text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _generate_anchors(base_size, scales, aspect_ratios):
"""Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, base_size - 1, base_size - 1) window.
"""
anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1
anchors = _ratio_enum(anchor, asp... | [
"def",
"_generate_anchors",
"(",
"base_size",
",",
"scales",
",",
"aspect_ratios",
")",
":",
"anchor",
"=",
"np",
".",
"array",
"(",
"[",
"1",
",",
"1",
",",
"base_size",
",",
"base_size",
"]",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"-",
"1",
... | 46.8 | 0.002096 |
def check_semidefinite_positiveness(A):
"""Check if ``A`` is a semi-definite positive matrix.
Args:
A (array_like): Matrix.
Returns:
bool: ``True`` if ``A`` is definite positive; ``False`` otherwise.
"""
B = empty_like(A)
B[:] = A
B[diag_indices_from(B)] += sqrt(finfo(float... | [
"def",
"check_semidefinite_positiveness",
"(",
"A",
")",
":",
"B",
"=",
"empty_like",
"(",
"A",
")",
"B",
"[",
":",
"]",
"=",
"A",
"B",
"[",
"diag_indices_from",
"(",
"B",
")",
"]",
"+=",
"sqrt",
"(",
"finfo",
"(",
"float",
")",
".",
"eps",
")",
... | 23.529412 | 0.002404 |
def create(src, dest, **kwargs):
"""Inefficient comparison of src and dest dicts.
Recurses through dict and lists.
returns (is_identical, modifications, additions, deletions)
where each
is_identical is a boolean True if the dicts have
contents that compare equ... | [
"def",
"create",
"(",
"src",
",",
"dest",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"src",
"==",
"dest",
":",
"return",
"None",
"trivial_order",
"=",
"[",
"(",
"i",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"len",
"(",
"src",
... | 40.783333 | 0.001197 |
def dump_dict_of_nested_lists_to_h5(fname, data):
"""
Take nested list structure and dump it in hdf5 file.
Parameters
----------
fname : str
Filename
data : dict(list(numpy.ndarray))
Dict of nested lists with variable len arrays.
Returns
-------
None
... | [
"def",
"dump_dict_of_nested_lists_to_h5",
"(",
"fname",
",",
"data",
")",
":",
"# Open file",
"print",
"(",
"'writing to file: %s'",
"%",
"fname",
")",
"f",
"=",
"h5py",
".",
"File",
"(",
"fname",
")",
"# Iterate over values",
"for",
"i",
",",
"ivalue",
"in",
... | 28.833333 | 0.003728 |
def load_configuration(self, configuration_file):
'''Loading configuration
Parameters
----------
configuration_file : string
Path to the configuration file (text or HDF5 file).
'''
if os.path.isfile(configuration_file):
if not isinstance(... | [
"def",
"load_configuration",
"(",
"self",
",",
"configuration_file",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"configuration_file",
")",
":",
"if",
"not",
"isinstance",
"(",
"configuration_file",
",",
"tb",
".",
"file",
".",
"File",
")",
"and... | 46.066667 | 0.005674 |
def replacing_symlink(source, link_name):
"""Create symlink that overwrites any existing target.
"""
with make_tmp_name(link_name) as tmp_link_name:
os.symlink(source, tmp_link_name)
replace_file_or_dir(link_name, tmp_link_name) | [
"def",
"replacing_symlink",
"(",
"source",
",",
"link_name",
")",
":",
"with",
"make_tmp_name",
"(",
"link_name",
")",
"as",
"tmp_link_name",
":",
"os",
".",
"symlink",
"(",
"source",
",",
"tmp_link_name",
")",
"replace_file_or_dir",
"(",
"link_name",
",",
"tm... | 41.833333 | 0.003906 |
def port_is_open():
"""
Determine if the default port and user is open for business.
"""
with settings(hide('aborts'), warn_only=True ):
try:
if env.verbosity:
print "Testing node for previous installation on port %s:"% env.port
distribution = lsb_release(... | [
"def",
"port_is_open",
"(",
")",
":",
"with",
"settings",
"(",
"hide",
"(",
"'aborts'",
")",
",",
"warn_only",
"=",
"True",
")",
":",
"try",
":",
"if",
"env",
".",
"verbosity",
":",
"print",
"\"Testing node for previous installation on port %s:\"",
"%",
"env",... | 41.777778 | 0.014304 |
def run_node(cls, node, inputs, device='CPU'): # pylint: disable=arguments-differ
"""Running individual node inference on mxnet engine and
return the result to onnx test infrastructure.
Parameters
----------
node : onnx node object
loaded onnx node (individual lay... | [
"def",
"run_node",
"(",
"cls",
",",
"node",
",",
"inputs",
",",
"device",
"=",
"'CPU'",
")",
":",
"# pylint: disable=arguments-differ",
"graph",
"=",
"GraphProto",
"(",
")",
"sym",
",",
"_",
"=",
"graph",
".",
"from_onnx",
"(",
"MXNetBackend",
".",
"make_g... | 40.984848 | 0.00361 |
def delete(cls, global_, key):
""" Delete key/value pair from configuration file. """
# first retrieve current configuration
scope = 'global' if global_ else 'local'
config = cls._conffiles.get(scope, {})
cls._del(scope, key)
conf_file = cls.home_config if global_ else cl... | [
"def",
"delete",
"(",
"cls",
",",
"global_",
",",
"key",
")",
":",
"# first retrieve current configuration",
"scope",
"=",
"'global'",
"if",
"global_",
"else",
"'local'",
"config",
"=",
"cls",
".",
"_conffiles",
".",
"get",
"(",
"scope",
",",
"{",
"}",
")"... | 46.555556 | 0.004684 |
def __add_class_views(self):
"""
Include any custom class views on the Sanic JWT Blueprint
"""
config = self.config
if "class_views" in self.kwargs:
class_views = self.kwargs.pop("class_views")
for route, view in class_views:
if issubclass... | [
"def",
"__add_class_views",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"config",
"if",
"\"class_views\"",
"in",
"self",
".",
"kwargs",
":",
"class_views",
"=",
"self",
".",
"kwargs",
".",
"pop",
"(",
"\"class_views\"",
")",
"for",
"route",
",",
"... | 36.695652 | 0.002309 |
def hash_password(plain_text):
"""Hash a plain text password"""
# NOTE: despite the name this is a one-way hash not a reversible cypher
hashed = pbkdf2_sha256.encrypt(plain_text, rounds=8000, salt_size=10)
return unicode(hashed) | [
"def",
"hash_password",
"(",
"plain_text",
")",
":",
"# NOTE: despite the name this is a one-way hash not a reversible cypher",
"hashed",
"=",
"pbkdf2_sha256",
".",
"encrypt",
"(",
"plain_text",
",",
"rounds",
"=",
"8000",
",",
"salt_size",
"=",
"10",
")",
"return",
"... | 51.2 | 0.007692 |
def maximum_notifiers(self, value):
"""
Setter for **self.__maximum_notifiers** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("maximum_notifi... | [
"def",
"maximum_notifiers",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"int",
",",
"\"'{0}' attribute: '{1}' type is not 'int'!\"",
".",
"format",
"(",
"\"maximum_notifiers\"",
",",
... | 43.846154 | 0.008591 |
def _set_vlanoper(self, v, load=False):
"""
Setter method for vlanoper, mapped from YANG variable /interface/ethernet/switchport/trunk/allowed/vlanoper (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlanoper is considered as a private
method. Backends lo... | [
"def",
"_set_vlanoper",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | 64.923077 | 0.005838 |
def get_app_name(mod_name):
"""
Retrieve application name from models.py module path
>>> get_app_name('testapp.models.foo')
'testapp'
'testapp' instead of 'some.testapp' for compatibility:
>>> get_app_name('some.testapp.models.foo')
'testapp'
>>> get_app_name('some.models.testapp.model... | [
"def",
"get_app_name",
"(",
"mod_name",
")",
":",
"rparts",
"=",
"list",
"(",
"reversed",
"(",
"mod_name",
".",
"split",
"(",
"'.'",
")",
")",
")",
"try",
":",
"try",
":",
"return",
"rparts",
"[",
"rparts",
".",
"index",
"(",
"MODELS_MODULE_NAME",
")",... | 29.148148 | 0.00123 |
def v_res(self, nodes=None, level=None):
"""
Get resulting voltage level at node.
Parameters
----------
nodes : :obj:`list`
List of string representatives of grid topology components, e.g.
:class:`~.grid.components.Generator`. If not provided defaults to
... | [
"def",
"v_res",
"(",
"self",
",",
"nodes",
"=",
"None",
",",
"level",
"=",
"None",
")",
":",
"# check if voltages are available:",
"if",
"hasattr",
"(",
"self",
",",
"'pfa_v_mag_pu'",
")",
":",
"self",
".",
"pfa_v_mag_pu",
".",
"sort_index",
"(",
"axis",
"... | 39.727273 | 0.001117 |
def shared_dataset_ids(self):
"""Dataset IDs shared by all children."""
shared_ids = set(self.scenes[0].keys())
for scene in self.scenes[1:]:
shared_ids &= set(scene.keys())
return shared_ids | [
"def",
"shared_dataset_ids",
"(",
"self",
")",
":",
"shared_ids",
"=",
"set",
"(",
"self",
".",
"scenes",
"[",
"0",
"]",
".",
"keys",
"(",
")",
")",
"for",
"scene",
"in",
"self",
".",
"scenes",
"[",
"1",
":",
"]",
":",
"shared_ids",
"&=",
"set",
... | 38.333333 | 0.008511 |
def processes_with_env_ps(env_name, env_value):
"""
Find PIDs of processes having environment variable matching given one.
It uses `$ ps xe -o pid,cmd` command so it works only on systems
having such command available (Linux, MacOS). If not available function
will just log error.
:param str en... | [
"def",
"processes_with_env_ps",
"(",
"env_name",
",",
"env_value",
")",
":",
"pids",
"=",
"set",
"(",
")",
"ps_xe",
"=",
"''",
"try",
":",
"cmd",
"=",
"'ps'",
",",
"'xe'",
",",
"'-o'",
",",
"'pid,cmd'",
"ps_xe",
"=",
"subprocess",
".",
"check_output",
... | 38.527778 | 0.000703 |
def postproc (stats_result):
"""Simple helper to postprocess angular outputs from StatsCollectors in the
way we want.
"""
n, mean, scat = stats_result
mean *= 180 / np.pi # rad => deg
scat /= n # variance-of-samples => variance-of-mean
scat **= 0.5 # variance => stddev
scat *= 180 / np.... | [
"def",
"postproc",
"(",
"stats_result",
")",
":",
"n",
",",
"mean",
",",
"scat",
"=",
"stats_result",
"mean",
"*=",
"180",
"/",
"np",
".",
"pi",
"# rad => deg",
"scat",
"/=",
"n",
"# variance-of-samples => variance-of-mean",
"scat",
"**=",
"0.5",
"# variance =... | 31.545455 | 0.016807 |
def get_all_aminames(i_info):
"""Get Image_Name for each instance in i_info.
Args:
i_info (dict): information on instances and details.
Returns:
i_info (dict): i_info is returned with the aminame
added for each instance.
"""
for i in i_info:
try:
... | [
"def",
"get_all_aminames",
"(",
"i_info",
")",
":",
"for",
"i",
"in",
"i_info",
":",
"try",
":",
"# pylint: disable=maybe-no-member",
"i_info",
"[",
"i",
"]",
"[",
"'aminame'",
"]",
"=",
"EC2R",
".",
"Image",
"(",
"i_info",
"[",
"i",
"]",
"[",
"'ami'",
... | 29.882353 | 0.001908 |
async def save(self):
"""Save the machine in MAAS."""
orig_owner_data = self._orig_data['owner_data']
new_owner_data = dict(self._data['owner_data'])
self._changed_data.pop('owner_data', None)
await super(Machine, self).save()
params_diff = calculate_dict_diff(orig_owner_... | [
"async",
"def",
"save",
"(",
"self",
")",
":",
"orig_owner_data",
"=",
"self",
".",
"_orig_data",
"[",
"'owner_data'",
"]",
"new_owner_data",
"=",
"dict",
"(",
"self",
".",
"_data",
"[",
"'owner_data'",
"]",
")",
"self",
".",
"_changed_data",
".",
"pop",
... | 49.454545 | 0.00361 |
def lock(self):
'''
Place an lock file and report on the success/failure. This is an
interface to be used by the fileserver runner, so it is hard-coded to
perform an update lock. We aren't using the gen_lock()
contextmanager here because the lock is meant to stay and not be
... | [
"def",
"lock",
"(",
"self",
")",
":",
"success",
"=",
"[",
"]",
"failed",
"=",
"[",
"]",
"try",
":",
"result",
"=",
"self",
".",
"_lock",
"(",
"lock_type",
"=",
"'update'",
")",
"except",
"GitLockError",
"as",
"exc",
":",
"failed",
".",
"append",
"... | 35.611111 | 0.00304 |
def get_go2nt(self, usr_go2nt):
"""Combine user namedtuple fields, GO object fields, and format_txt."""
gos_all = self.get_gos_all()
# Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs
prt_flds_all = get_hdridx_flds() + self.gosubdag.prt_attr['flds']
... | [
"def",
"get_go2nt",
"(",
"self",
",",
"usr_go2nt",
")",
":",
"gos_all",
"=",
"self",
".",
"get_gos_all",
"(",
")",
"# Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs",
"prt_flds_all",
"=",
"get_hdridx_flds",
"(",
")",
"+",
"self",
".",
... | 61.384615 | 0.004938 |
def fit(self, X, y):
"""Scikit-learn required: Computes the feature importance scores from the training data.
Parameters
----------
X: array-like {n_samples, n_features}
Training instances to compute the feature importance scores from
y: array-like {n_samples}
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"self",
".",
"_X",
"=",
"X",
"# matrix of predictive variables ('independent variables')",
"self",
".",
"_y",
"=",
"y",
"# vector of values for outcome variable ('dependent variable')",
"# Set up the properties for ... | 48.171875 | 0.005403 |
def do_describe(self, line):
"describe [-c] {tablename}..."
args = self.getargs(line)
if '-c' in args:
create_info = True
args.remove('-c')
else:
create_info = False
if not args:
if self.table:
args = [self.table.n... | [
"def",
"do_describe",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"getargs",
"(",
"line",
")",
"if",
"'-c'",
"in",
"args",
":",
"create_info",
"=",
"True",
"args",
".",
"remove",
"(",
"'-c'",
")",
"else",
":",
"create_info",
"=",
... | 32.105263 | 0.003182 |
def StatResultFromStatEntry(
stat_entry):
"""Returns a `os.stat_result` with most information from `StatEntry`.
This is a lossy conversion, only the 10 first stat_result fields are
populated, because the os.stat_result constructor is inflexible.
Args:
stat_entry: An instance of rdf_client_fs.StatEntry... | [
"def",
"StatResultFromStatEntry",
"(",
"stat_entry",
")",
":",
"values",
"=",
"[",
"]",
"for",
"attr",
"in",
"_STAT_ATTRS",
"[",
":",
"10",
"]",
":",
"values",
".",
"append",
"(",
"stat_entry",
".",
"Get",
"(",
"attr",
")",
")",
"return",
"os",
".",
... | 29.764706 | 0.011494 |
def get_plugin_and_folder(inputzip=None, inputdir=None, inputfile=None):
""" Main function. """
if (inputzip and inputdir) \
or (inputzip and inputfile) \
or (inputdir and inputfile):
raise MQ2Exception('You must provide either a zip file or a '
'direc... | [
"def",
"get_plugin_and_folder",
"(",
"inputzip",
"=",
"None",
",",
"inputdir",
"=",
"None",
",",
"inputfile",
"=",
"None",
")",
":",
"if",
"(",
"inputzip",
"and",
"inputdir",
")",
"or",
"(",
"inputzip",
"and",
"inputfile",
")",
"or",
"(",
"inputdir",
"an... | 38.291667 | 0.000531 |
def rooms(self, sid, namespace=None):
"""Return the rooms a client is in.
:param sid: Session ID of the client.
:param namespace: The Socket.IO namespace for the event. If this
argument is omitted the default namespace is used.
"""
namespace = namespace... | [
"def",
"rooms",
"(",
"self",
",",
"sid",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"or",
"'/'",
"return",
"self",
".",
"manager",
".",
"get_rooms",
"(",
"sid",
",",
"namespace",
")"
] | 41.444444 | 0.005249 |
def generate_response(chaldict,uri,username,passwd,method='GET',cnonce=None):
"""
Generate an authorization response dictionary. chaldict should contain the digest
challenge in dict form. Use fetch_challenge to create a chaldict from a HTTPResponse
object like this: fetch_challenge(res.getheaders()).
returns... | [
"def",
"generate_response",
"(",
"chaldict",
",",
"uri",
",",
"username",
",",
"passwd",
",",
"method",
"=",
"'GET'",
",",
"cnonce",
"=",
"None",
")",
":",
"authdict",
"=",
"{",
"}",
"qop",
"=",
"dict_fetch",
"(",
"chaldict",
",",
"'qop'",
")",
"domain... | 32.071429 | 0.042507 |
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElem... | [
"def",
"get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_priority",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_brief_info",
"=",
"ET",
".",
"Element",
"(",
"\... | 49.529412 | 0.004662 |
def _safe_call(obj, methname, *args, **kwargs):
"""
Safely calls the method with the given methname on the given
object. Remaining positional and keyword arguments are passed to
the method. The return value is None, if the method is not
available, or the return value of the method.
"""
me... | [
"def",
"_safe_call",
"(",
"obj",
",",
"methname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"meth",
"=",
"getattr",
"(",
"obj",
",",
"methname",
",",
"None",
")",
"if",
"meth",
"is",
"None",
"or",
"not",
"callable",
"(",
"meth",
")",
"... | 33.307692 | 0.002247 |
def single(self):
"""Whether or not the user is only interested in people that are single.
"""
return 'display: none;' not in self._looking_for_xpb.li(id='ajax_single').\
one_(self._profile.profile_tree).attrib['style'] | [
"def",
"single",
"(",
"self",
")",
":",
"return",
"'display: none;'",
"not",
"in",
"self",
".",
"_looking_for_xpb",
".",
"li",
"(",
"id",
"=",
"'ajax_single'",
")",
".",
"one_",
"(",
"self",
".",
"_profile",
".",
"profile_tree",
")",
".",
"attrib",
"[",
... | 50.2 | 0.015686 |
def get_file_list(opts):
"""
Returns a list containing file paths of requested files to be parsed
using AnchorHub options.
:param opts: Namespace containing AnchorHub options, usually created from
command line arguments
:return: a list of absolute string file paths of files that should be
... | [
"def",
"get_file_list",
"(",
"opts",
")",
":",
"if",
"opts",
".",
"is_dir",
":",
"# Input is a directory, get a list of files",
"return",
"get_files",
"(",
"opts",
".",
"abs_input",
",",
"opts",
".",
"extensions",
",",
"exclude",
"=",
"[",
"opts",
".",
"abs_ou... | 35.3 | 0.001379 |
def _call(self, coeffs):
"""Return the inverse wavelet transform of ``coeffs``."""
if self.impl == 'pywt':
coeffs = pywt.unravel_coeffs(coeffs,
coeff_slices=self._coeff_slices,
coeff_shapes=self._coeff_shapes,
... | [
"def",
"_call",
"(",
"self",
",",
"coeffs",
")",
":",
"if",
"self",
".",
"impl",
"==",
"'pywt'",
":",
"coeffs",
"=",
"pywt",
".",
"unravel_coeffs",
"(",
"coeffs",
",",
"coeff_slices",
"=",
"self",
".",
"_coeff_slices",
",",
"coeff_shapes",
"=",
"self",
... | 53.815789 | 0.000961 |
def delete_field_value(self, name):
"""
Mark this field to be deleted
"""
name = self.get_real_name(name)
if name and self._can_write_field(name):
if name in self.__modified_data__:
self.__modified_data__.pop(name)
if name in self.__origi... | [
"def",
"delete_field_value",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"get_real_name",
"(",
"name",
")",
"if",
"name",
"and",
"self",
".",
"_can_write_field",
"(",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"__modified_data__... | 34.416667 | 0.007075 |
def _prepare_ingest(self):
"""If the RDF datastream refers to the object by the default dummy
uriref then we need to replace that dummy reference with a real one
before we ingest the object."""
# see also commentary on DigitalObject.DUMMY_URIREF
self.replace_uri(self.obj.DUMMY_U... | [
"def",
"_prepare_ingest",
"(",
"self",
")",
":",
"# see also commentary on DigitalObject.DUMMY_URIREF",
"self",
".",
"replace_uri",
"(",
"self",
".",
"obj",
".",
"DUMMY_URIREF",
",",
"self",
".",
"obj",
".",
"uriref",
")"
] | 48.142857 | 0.005831 |
def get_toolbar_buttons(self):
"""Return toolbar buttons list."""
buttons = []
# Code to add the stop button
if self.stop_button is None:
self.stop_button = create_toolbutton(
self,
text=_("Stop"),... | [
"def",
"get_toolbar_buttons",
"(",
"self",
")",
":",
"buttons",
"=",
"[",
"]",
"# Code to add the stop button\r",
"if",
"self",
".",
"stop_button",
"is",
"None",
":",
"self",
".",
"stop_button",
"=",
"create_toolbutton",
"(",
"self",
",",
"text",
"=",
"_",
"... | 43.933333 | 0.001484 |
def read(self, size=-1):
"""Read at most `size` bytes from the file (less if there
isn't enough data).
The bytes are returned as an instance of :class:`str` (:class:`bytes`
in python 3). If `size` is negative or omitted all data is read.
:Parameters:
- `size` (optiona... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"self",
".",
"_ensure_file",
"(",
")",
"if",
"size",
"==",
"0",
":",
"return",
"EMPTY",
"remainder",
"=",
"int",
"(",
"self",
".",
"length",
")",
"-",
"self",
".",
"__position",
"i... | 33.604651 | 0.001345 |
def equal(self, line1, line2):
'''
return true if exactly equal or if equal but modified,
otherwise return false
return type: BooleanPlus
'''
eqLine = line1 == line2
if eqLine:
return BooleanPlus(True, False)
else:
unchanged_count ... | [
"def",
"equal",
"(",
"self",
",",
"line1",
",",
"line2",
")",
":",
"eqLine",
"=",
"line1",
"==",
"line2",
"if",
"eqLine",
":",
"return",
"BooleanPlus",
"(",
"True",
",",
"False",
")",
"else",
":",
"unchanged_count",
"=",
"self",
".",
"count_similar_words... | 32.947368 | 0.003106 |
def define_wide_deep_flags():
"""Add supervised learning flags, as well as wide-deep model type."""
flags_core.define_base()
flags_core.define_benchmark()
flags_core.define_performance(
num_parallel_calls=False, inter_op=True, intra_op=True,
synthetic_data=False, max_train_steps=False, dtype=False,
... | [
"def",
"define_wide_deep_flags",
"(",
")",
":",
"flags_core",
".",
"define_base",
"(",
")",
"flags_core",
".",
"define_benchmark",
"(",
")",
"flags_core",
".",
"define_performance",
"(",
"num_parallel_calls",
"=",
"False",
",",
"inter_op",
"=",
"True",
",",
"int... | 39.666667 | 0.010944 |
def make_sentences(self, stream_item):
'assemble Sentence and Token objects'
self.make_label_index(stream_item)
sentences = []
token_num = 0
new_mention_id = 0
for sent_start, sent_end, sent_str in self._sentences(
stream_item.body.clean_visible):
... | [
"def",
"make_sentences",
"(",
"self",
",",
"stream_item",
")",
":",
"self",
".",
"make_label_index",
"(",
"stream_item",
")",
"sentences",
"=",
"[",
"]",
"token_num",
"=",
"0",
"new_mention_id",
"=",
"0",
"for",
"sent_start",
",",
"sent_end",
",",
"sent_str"... | 41.8 | 0.000935 |
def expm1(x, context=None):
"""
Return one less than the exponential of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_expm1,
(BigFloat._implicit_convert(x),),
context,
) | [
"def",
"expm1",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_expm1",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
... | 21.454545 | 0.004065 |
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
lhs = self.children[1].sym(nested_scope)
rhs = self.children[2].sym(nested_scope)
return operation(lhs, rhs) | [
"def",
"sym",
"(",
"self",
",",
"nested_scope",
"=",
"None",
")",
":",
"operation",
"=",
"self",
".",
"children",
"[",
"0",
"]",
".",
"operation",
"(",
")",
"lhs",
"=",
"self",
".",
"children",
"[",
"1",
"]",
".",
"sym",
"(",
"nested_scope",
")",
... | 43.833333 | 0.007463 |
def use_plenary_grade_entry_view(self):
"""Pass through to provider GradeEntryLookupSession.use_plenary_grade_entry_view"""
self._object_views['grade_entry'] = PLENARY
# self._get_provider_session('grade_entry_lookup_session') # To make sure the session is tracked
for session in self._ge... | [
"def",
"use_plenary_grade_entry_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'grade_entry'",
"]",
"=",
"PLENARY",
"# self._get_provider_session('grade_entry_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_ge... | 51.333333 | 0.008511 |
def _mangle_prefix(res):
""" Mangle prefix result
"""
# fugly cast from large numbers to string to deal with XML-RPC
res['total_addresses'] = unicode(res['total_addresses'])
res['used_addresses'] = unicode(res['used_addresses'])
res['free_addresses'] = unicode(res['free_addresses'])
# postg... | [
"def",
"_mangle_prefix",
"(",
"res",
")",
":",
"# fugly cast from large numbers to string to deal with XML-RPC",
"res",
"[",
"'total_addresses'",
"]",
"=",
"unicode",
"(",
"res",
"[",
"'total_addresses'",
"]",
")",
"res",
"[",
"'used_addresses'",
"]",
"=",
"unicode",
... | 39.705882 | 0.001447 |
def __request_finish(self, queue_item, new_requests, request_failed=False):
"""Called when the crawler finished the given queue item.
Args:
queue_item (:class:`nyawc.QueueItem`): The request/response pair that finished.
new_requests list(:class:`nyawc.http.Request`): All the req... | [
"def",
"__request_finish",
"(",
"self",
",",
"queue_item",
",",
"new_requests",
",",
"request_failed",
"=",
"False",
")",
":",
"if",
"self",
".",
"__stopping",
":",
"return",
"del",
"self",
".",
"__threads",
"[",
"queue_item",
".",
"get_hash",
"(",
")",
"]... | 38 | 0.005548 |
def _infer_interval_breaks(coord, axis=0, check_monotonic=False):
"""
>>> _infer_interval_breaks(np.arange(5))
array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])
>>> _infer_interval_breaks([[0, 1], [3, 4]], axis=1)
array([[-0.5, 0.5, 1.5],
[ 2.5, 3.5, 4.5]])
"""
coord = np.asarray(co... | [
"def",
"_infer_interval_breaks",
"(",
"coord",
",",
"axis",
"=",
"0",
",",
"check_monotonic",
"=",
"False",
")",
":",
"coord",
"=",
"np",
".",
"asarray",
"(",
"coord",
")",
"if",
"check_monotonic",
"and",
"not",
"_is_monotonic",
"(",
"coord",
",",
"axis",
... | 49.384615 | 0.000764 |
def absent(name, keys=None, **connection_args):
'''
Ensure key absent from redis
name
Key to ensure absent from redis
keys
list of keys to ensure absent, name will be ignored if this is used
'''
ret = {'name': name,
'changes': {},
'result': True,
... | [
"def",
"absent",
"(",
"name",
",",
"keys",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'Key(s) specified already... | 31.323529 | 0.000911 |
def obj_to_grid(self, file_path=None, delim=None, tab=None,
quote_numbers=True, quote_empty_str=False):
"""
This will return a str of a grid table.
:param file_path: path to data file, defaults to
self's contents if left alone
:pa... | [
"def",
"obj_to_grid",
"(",
"self",
",",
"file_path",
"=",
"None",
",",
"delim",
"=",
"None",
",",
"tab",
"=",
"None",
",",
"quote_numbers",
"=",
"True",
",",
"quote_empty_str",
"=",
"False",
")",
":",
"div_delims",
"=",
"{",
"\"top\"",
":",
"[",
"'top ... | 48.946429 | 0.001788 |
def regressionplot(x, y, poly=None):
"""
Plot a 2-D linear regression (y = slope * x + offset) overlayed over the raw data samples
"""
if not isinstance(x[0], (float, int, np.float64, np.float32)):
x = [row[0] for row in x]
y_regression = poly[0] * np.array(x) + poly[-1]
try:
plt... | [
"def",
"regressionplot",
"(",
"x",
",",
"y",
",",
"poly",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
"[",
"0",
"]",
",",
"(",
"float",
",",
"int",
",",
"np",
".",
"float64",
",",
"np",
".",
"float32",
")",
")",
":",
"x",
"=",... | 34.166667 | 0.004747 |
def html(self, groups='all', template=None, **context):
"""Return an html string of the routes specified by the doc() method
A template can be specified. A list of routes is available under the
'autodoc' value (refer to the documentation for the generate() for a
description of available... | [
"def",
"html",
"(",
"self",
",",
"groups",
"=",
"'all'",
",",
"template",
"=",
"None",
",",
"*",
"*",
"context",
")",
":",
"context",
"[",
"'autodoc'",
"]",
"=",
"context",
"[",
"'autodoc'",
"]",
"if",
"'autodoc'",
"in",
"context",
"else",
"self",
".... | 43.740741 | 0.001657 |
def _check_cronjob(self):
"""Check projects cronjob tick, return True when a new tick is sended"""
now = time.time()
self._last_tick = int(self._last_tick)
if now - self._last_tick < 1:
return False
self._last_tick += 1
for project in itervalues(self.projects)... | [
"def",
"_check_cronjob",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_last_tick",
"=",
"int",
"(",
"self",
".",
"_last_tick",
")",
"if",
"now",
"-",
"self",
".",
"_last_tick",
"<",
"1",
":",
"return",
"False",
"s... | 34.064516 | 0.002762 |
def flexifunction_directory_encode(self, target_system, target_component, directory_type, start_index, count, directory_data):
'''
Acknowldge sucess or failure of a flexifunction command
target_system : System ID (uint8_t)
target_component ... | [
"def",
"flexifunction_directory_encode",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"directory_type",
",",
"start_index",
",",
"count",
",",
"directory_data",
")",
":",
"return",
"MAVLink_flexifunction_directory_message",
"(",
"target_system",
",",
... | 64 | 0.007109 |
def generate_layout(bpmn_graph):
"""
:param bpmn_graph: an instance of BPMNDiagramGraph class.
"""
classification = generate_elements_clasification(bpmn_graph)
(sorted_nodes_with_classification, backward_flows) = topological_sort(bpmn_graph, classification[0])
grid = grid_layout(bpmn_graph, sort... | [
"def",
"generate_layout",
"(",
"bpmn_graph",
")",
":",
"classification",
"=",
"generate_elements_clasification",
"(",
"bpmn_graph",
")",
"(",
"sorted_nodes_with_classification",
",",
"backward_flows",
")",
"=",
"topological_sort",
"(",
"bpmn_graph",
",",
"classification",... | 47.222222 | 0.004619 |
def create_directory(self, path=None):
"""Create the directory for the given path. If path is None use the path of this instance
:param path: the path to create
:type path: str
:returns: None
:rtype: None
:raises: OSError
"""
if path is None:
... | [
"def",
"create_directory",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"get_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedir... | 30.538462 | 0.007335 |
def add_member(self, service_name, servicegroup_name):
"""Add a member (service) to this servicegroup
:param service_name: member (service) name
:type service_name: str
:param servicegroup_name: servicegroup name
:type servicegroup_name: str
:return: None
"""
... | [
"def",
"add_member",
"(",
"self",
",",
"service_name",
",",
"servicegroup_name",
")",
":",
"servicegroup",
"=",
"self",
".",
"find_by_name",
"(",
"servicegroup_name",
")",
"if",
"not",
"servicegroup",
":",
"servicegroup",
"=",
"Servicegroup",
"(",
"{",
"'service... | 41.529412 | 0.004155 |
def unassign_assessment_part_from_bank(self, assessment_part_id, bank_id):
"""Removes an ``AssessmentPart`` from an ``Bank``.
arg: assessment_part_id (osid.id.Id): the ``Id`` of the
``AssessmentPart``
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
raise: No... | [
"def",
"unassign_assessment_part_from_bank",
"(",
"self",
",",
"assessment_part_id",
",",
"bank_id",
")",
":",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'ASSESSMENT'",
",",
"local",
"=",
"True",
")",
"lookup_session",
"=",
"mgr",
".",
"get_bank_looku... | 50.6 | 0.00194 |
def _summarize_explored_parameters(self):
"""Summarizes the parameter settings.
:param run_name: Name of the single run
:param paramlist: List of explored parameters
:param add_table: Whether to add the overview table
:param create_run_group:
If a group with the ... | [
"def",
"_summarize_explored_parameters",
"(",
"self",
")",
":",
"runsummary",
"=",
"''",
"for",
"idx",
",",
"expparam",
"in",
"enumerate",
"(",
"self",
".",
"_explored_parameters",
".",
"values",
"(",
")",
")",
":",
"# Create the run summary for the `run` overview",... | 30.540541 | 0.003431 |
def add_var_opt(self,opt,value,short=False):
"""
Add a variable (macro) option for this node. If the option
specified does not exist in the CondorJob, it is added so the submit
file will be correct when written.
@param opt: option name.
@param value: value of the option for this node in the DAG.... | [
"def",
"add_var_opt",
"(",
"self",
",",
"opt",
",",
"value",
",",
"short",
"=",
"False",
")",
":",
"macro",
"=",
"self",
".",
"__bad_macro_chars",
".",
"sub",
"(",
"r''",
",",
"opt",
")",
"self",
".",
"__opts",
"[",
"'macro'",
"+",
"macro",
"]",
"=... | 40.727273 | 0.015284 |
def cli(env, sortby, columns, datacenter, username, storage_type):
"""List file storage."""
file_manager = SoftLayer.FileStorageManager(env.client)
file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
username=username,
... | [
"def",
"cli",
"(",
"env",
",",
"sortby",
",",
"columns",
",",
"datacenter",
",",
"username",
",",
"storage_type",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"file_volumes",
"=",
"file_manager",
".",... | 42.25 | 0.001447 |
def __validInterval(self, start, finish):
"""Check if the interval is correct.
An interval is correct if it has less than 1001
users. If the interval is correct, it will be added
to '_intervals' attribute. Else, interval will be
split in two news intervals and these intervals
... | [
"def",
"__validInterval",
"(",
"self",
",",
"start",
",",
"finish",
")",
":",
"url",
"=",
"self",
".",
"__getURL",
"(",
"1",
",",
"start",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
",",
"finish",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
")",
"data",... | 39.612903 | 0.00159 |
def rotations(self, region):
"""
Returns champion rotations, including free-to-play and low-level free-to-play rotations.
:returns: ChampionInfo
"""
url, query = ChampionApiV3Urls.rotations(region=region)
return self._raw_request(self.rotations.__name__, region, url, que... | [
"def",
"rotations",
"(",
"self",
",",
"region",
")",
":",
"url",
",",
"query",
"=",
"ChampionApiV3Urls",
".",
"rotations",
"(",
"region",
"=",
"region",
")",
"return",
"self",
".",
"_raw_request",
"(",
"self",
".",
"rotations",
".",
"__name__",
",",
"reg... | 39.5 | 0.009288 |
def update_installed_extension(self, extension):
"""UpdateInstalledExtension.
[Preview API] Update an installed extension. Typically this API is used to enable or disable an extension.
:param :class:`<InstalledExtension> <azure.devops.v5_0.extension_management.models.InstalledExtension>` extensi... | [
"def",
"update_installed_extension",
"(",
"self",
",",
"extension",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"extension",
",",
"'InstalledExtension'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'PATCH'",... | 67.416667 | 0.007317 |
def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``chain_id`` for the chain class.
"""
return chain_class.configure(chain_id=chain_id) | [
"def",
"chain_id",
"(",
"chain_id",
":",
"int",
",",
"chain_class",
":",
"Type",
"[",
"BaseChain",
"]",
")",
"->",
"Type",
"[",
"BaseChain",
"]",
":",
"return",
"chain_class",
".",
"configure",
"(",
"chain_id",
"=",
"chain_id",
")"
] | 37.4 | 0.005236 |
def onchange_dates(self):
'''
This method gives the duration between check in and checkout
if customer will leave only for some hour it would be considers
as a whole day.If customer will check in checkout for more or equal
hours, which configured in company as additional hours th... | [
"def",
"onchange_dates",
"(",
"self",
")",
":",
"configured_addition_hours",
"=",
"0",
"wid",
"=",
"self",
".",
"warehouse_id",
"whouse_com_id",
"=",
"wid",
"or",
"wid",
".",
"company_id",
"if",
"whouse_com_id",
":",
"configured_addition_hours",
"=",
"wid",
".",... | 45.694444 | 0.00119 |
def manual_argument_parsing(argv):
"""sadness because argparse doesn't quite do what we want."""
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
... | [
"def",
"manual_argument_parsing",
"(",
"argv",
")",
":",
"# Special case these for a better error message",
"if",
"not",
"argv",
"or",
"argv",
"==",
"[",
"'-h'",
"]",
"or",
"argv",
"==",
"[",
"'--help'",
"]",
":",
"print_help_and_exit",
"(",
")",
"try",
":",
"... | 31.117647 | 0.000917 |
def _client_data(self, client):
""" Returns a dict that represents the client specified
Keys: obj, id, url, name
"""
data = {}
if client:
data['obj'] = client
data['id'] = client.id
data['url'] = client.absolute_url()
data['name... | [
"def",
"_client_data",
"(",
"self",
",",
"client",
")",
":",
"data",
"=",
"{",
"}",
"if",
"client",
":",
"data",
"[",
"'obj'",
"]",
"=",
"client",
"data",
"[",
"'id'",
"]",
"=",
"client",
".",
"id",
"data",
"[",
"'url'",
"]",
"=",
"client",
".",
... | 32.727273 | 0.005405 |
def enabled_logical_ids(self):
"""
:return: only the logical id's for the deployment preferences in this collection which are enabled
"""
return [logical_id for logical_id, preference in self._resource_preferences.items() if preference.enabled] | [
"def",
"enabled_logical_ids",
"(",
"self",
")",
":",
"return",
"[",
"logical_id",
"for",
"logical_id",
",",
"preference",
"in",
"self",
".",
"_resource_preferences",
".",
"items",
"(",
")",
"if",
"preference",
".",
"enabled",
"]"
] | 54.4 | 0.014493 |
def get_hex_color(layer_type):
"""
Determines the hex color for a layer.
:parameters:
- layer_type : string
Class name of the layer
:returns:
- color : string containing a hex color for filling block.
"""
COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B'... | [
"def",
"get_hex_color",
"(",
"layer_type",
")",
":",
"COLORS",
"=",
"[",
"'#4A88B3'",
",",
"'#98C1DE'",
",",
"'#6CA2C8'",
",",
"'#3173A2'",
",",
"'#17649B'",
",",
"'#FFBB60'",
",",
"'#FFDAA9'",
",",
"'#FFC981'",
",",
"'#FCAC41'",
",",
"'#F29416'",
",",
"'#C5... | 35.083333 | 0.001156 |
def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
**httplib_request_kw):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param ... | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"chunked",
"=",
"False",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",... | 44.285714 | 0.002367 |
def load_edbfile(file=None):
"""Load the targets from a file"""
import ephem,string,math
if file is None:
import tkFileDialog
try:
file=tkFileDialog.askopenfilename()
except:
return
if file is None or file == '':
return
f=open(file)
lines=f.readl... | [
"def",
"load_edbfile",
"(",
"file",
"=",
"None",
")",
":",
"import",
"ephem",
",",
"string",
",",
"math",
"if",
"file",
"is",
"None",
":",
"import",
"tkFileDialog",
"try",
":",
"file",
"=",
"tkFileDialog",
".",
"askopenfilename",
"(",
")",
"except",
":",... | 33.4 | 0.046566 |
def self_uri(soup):
"""
self-uri tags
"""
self_uri = []
self_uri_tags = raw_parser.self_uri(soup)
position = 1
for tag in self_uri_tags:
item = {}
copy_attribute(tag.attrs, 'xlink:href', item, 'xlink_href')
copy_attribute(tag.attrs, 'content-type', item)
# ... | [
"def",
"self_uri",
"(",
"soup",
")",
":",
"self_uri",
"=",
"[",
"]",
"self_uri_tags",
"=",
"raw_parser",
".",
"self_uri",
"(",
"soup",
")",
"position",
"=",
"1",
"for",
"tag",
"in",
"self_uri_tags",
":",
"item",
"=",
"{",
"}",
"copy_attribute",
"(",
"t... | 25.296296 | 0.00141 |
def naturaldate(date, include_seconds=False):
"""Convert datetime into a human natural date string."""
if not date:
return ''
right_now = now()
today = datetime(right_now.year, right_now.month,
right_now.day, tzinfo=right_now.tzinfo)
delta = right_now - date
delta_... | [
"def",
"naturaldate",
"(",
"date",
",",
"include_seconds",
"=",
"False",
")",
":",
"if",
"not",
"date",
":",
"return",
"''",
"right_now",
"=",
"now",
"(",
")",
"today",
"=",
"datetime",
"(",
"right_now",
".",
"year",
",",
"right_now",
".",
"month",
","... | 31.25 | 0.000646 |
def _load(self, event):
"""
Processes a load event by setting the properties of this record
to the data restored from the database.
:param event: <orb.events.LoadEvent>
"""
if not event.data:
return
context = self.context()
schema = self.sche... | [
"def",
"_load",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"event",
".",
"data",
":",
"return",
"context",
"=",
"self",
".",
"context",
"(",
")",
"schema",
"=",
"self",
".",
"schema",
"(",
")",
"dbname",
"=",
"schema",
".",
"dbname",
"(",
... | 31.857143 | 0.001865 |
def _contains_array(self, val):
"""Checks whether exactly this array is in the list"""
arr = self(arr_name=val.psy.arr_name)[0]
is_not_list = any(
map(lambda a: not isinstance(a, InteractiveList),
[arr, val]))
is_list = any(map(lambda a: isinstance(a, Interact... | [
"def",
"_contains_array",
"(",
"self",
",",
"val",
")",
":",
"arr",
"=",
"self",
"(",
"arr_name",
"=",
"val",
".",
"psy",
".",
"arr_name",
")",
"[",
"0",
"]",
"is_not_list",
"=",
"any",
"(",
"map",
"(",
"lambda",
"a",
":",
"not",
"isinstance",
"(",... | 44.375 | 0.002759 |
def to_etree(self):
"""
creates an etree element of a ``SaltNode`` that mimicks a SaltXMI
<nodes> element
"""
layers_attrib_val = ' '.join('//@layers.{}'.format(layer_id)
for layer_id in self.layers)
attribs = {
'{{{pre}}}... | [
"def",
"to_etree",
"(",
"self",
")",
":",
"layers_attrib_val",
"=",
"' '",
".",
"join",
"(",
"'//@layers.{}'",
".",
"format",
"(",
"layer_id",
")",
"for",
"layer_id",
"in",
"self",
".",
"layers",
")",
"attribs",
"=",
"{",
"'{{{pre}}}type'",
".",
"format",
... | 34.352941 | 0.003333 |
def import_key(key_name, public_key_material, region=None, key=None,
keyid=None, profile=None):
'''
Imports the public key from an RSA key pair that you created with a third-party tool.
Supported formats:
- OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)
- Base6... | [
"def",
"import_key",
"(",
"key_name",
",",
"public_key_material",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",... | 36.192308 | 0.003106 |
def _read_para_seq_data(self, code, cbit, clen, *, desc, length, version):
"""Read HIP SEQ_DATA parameter.
Structure of HIP SEQ_DATA parameter [RFC 6078]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 ... | [
"def",
"_read_para_seq_data",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"if",
"clen",
"!=",
"4",
":",
"raise",
"ProtocolError",
"(",
"f'HIPv{version}: [Parano {code}] invalid format'",
... | 43.625 | 0.002803 |
def continuous_subpaths(self):
"""Breaks self into its continuous components, returning a list of
continuous subpaths.
I.e.
(all(subpath.iscontinuous() for subpath in self.continuous_subpaths())
and self == concatpaths(self.continuous_subpaths()))
)
"""
s... | [
"def",
"continuous_subpaths",
"(",
"self",
")",
":",
"subpaths",
"=",
"[",
"]",
"subpath_start",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
"-",
"1",
")",
":",
"if",
"self",
"[",
"i",
"]",
".",
"end",
"!=",
"self",
"[",
... | 39.4375 | 0.003096 |
def open(self, external_dir=None):
"""
Open the smart object as binary IO.
:param external_dir: Path to the directory of the external file.
Example::
with layer.smart_object.open() as f:
data = f.read()
"""
if self.kind == 'data':
... | [
"def",
"open",
"(",
"self",
",",
"external_dir",
"=",
"None",
")",
":",
"if",
"self",
".",
"kind",
"==",
"'data'",
":",
"with",
"io",
".",
"BytesIO",
"(",
"self",
".",
"_data",
".",
"data",
")",
"as",
"f",
":",
"yield",
"f",
"elif",
"self",
".",
... | 37.821429 | 0.001842 |
def at_index(iterable, index):
# type: (Iterable[T], int) -> T
"""" Return the item at the index of this iterable or raises IndexError.
WARNING: this will consume generators.
Negative indices are allowed but be aware they will cause n items to
be held in memory, where n = abs(index)
... | [
"def",
"at_index",
"(",
"iterable",
",",
"index",
")",
":",
"# type: (Iterable[T], int) -> T",
"try",
":",
"if",
"index",
"<",
"0",
":",
"return",
"deque",
"(",
"iterable",
",",
"maxlen",
"=",
"abs",
"(",
"index",
")",
")",
".",
"popleft",
"(",
")",
"r... | 36.625 | 0.001664 |
def from_dict(cls, tag):
"""
Create a tag object from a dictionary. This method is intended for internal use, to construct a
:class:`Tag` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response to an AP... | [
"def",
"from_dict",
"(",
"cls",
",",
"tag",
")",
":",
"return",
"Tag",
"(",
"name",
"=",
"tag",
".",
"get",
"(",
"'name'",
")",
",",
"id",
"=",
"tag",
".",
"get",
"(",
"'guid'",
")",
",",
"enclave_id",
"=",
"tag",
".",
"get",
"(",
"'enclaveId'",
... | 43.769231 | 0.008606 |
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
whi... | [
"def",
"count",
"(",
"self",
",",
"area",
"=",
"None",
",",
"date",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"area_relation",
"=",
"'Intersects'",
",",
"*",
"*",
"keywords",
")",
":",
"for",
"kw",
"in",
"[",
"'order_by'",
",",
"'limit'",
",",
"'o... | 41.952381 | 0.006659 |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(... | [
"def",
"rouge_l_summary_level",
"(",
"evaluated_sentences",
",",
"reference_sentences",
")",
":",
"if",
"len",
"(",
"evaluated_sentences",
")",
"<=",
"0",
"or",
"len",
"(",
"reference_sentences",
")",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Collections must... | 37.166667 | 0.001248 |
def stop(self):
"""
Stops this router.
"""
status = yield from self.get_status()
if status != "inactive":
try:
yield from self._hypervisor.send('vm stop "{name}"'.format(name=self._name))
except DynamipsError as e:
log.warn... | [
"def",
"stop",
"(",
"self",
")",
":",
"status",
"=",
"yield",
"from",
"self",
".",
"get_status",
"(",
")",
"if",
"status",
"!=",
"\"inactive\"",
":",
"try",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm stop \"{name}\"'",
".",
... | 37.705882 | 0.006088 |
def start_evaluating(self, n: Node, s: ShExJ.shapeExpr) -> Optional[bool]:
"""Indicate that we are beginning to evaluate n according to shape expression s.
If we are already in the process of evaluating (n,s), as indicated self.evaluating, we return our current
guess as to the result.
:... | [
"def",
"start_evaluating",
"(",
"self",
",",
"n",
":",
"Node",
",",
"s",
":",
"ShExJ",
".",
"shapeExpr",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"not",
"s",
".",
"id",
":",
"s",
".",
"id",
"=",
"str",
"(",
"BNode",
"(",
")",
")",
... | 40.347826 | 0.005263 |
def run(self, args):
"""
Prints out non deprecated project-type auth roles.
:param args Namespace arguments parsed from the command line
"""
auth_roles = self.remote_store.get_active_auth_roles(RemoteAuthRole.PROJECT_CONTEXT)
if auth_roles:
for auth_role in au... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"auth_roles",
"=",
"self",
".",
"remote_store",
".",
"get_active_auth_roles",
"(",
"RemoteAuthRole",
".",
"PROJECT_CONTEXT",
")",
"if",
"auth_roles",
":",
"for",
"auth_role",
"in",
"auth_roles",
":",
"print",
... | 40.727273 | 0.00655 |
def to_shape_list(region_list, coordinate_system='fk5'):
"""
Converts a list of regions into a `regions.ShapeList` object.
Parameters
----------
region_list: python list
Lists of `regions.Region` objects
format_type: str ('DS9' or 'CRTF')
The format type of the Shape object. Def... | [
"def",
"to_shape_list",
"(",
"region_list",
",",
"coordinate_system",
"=",
"'fk5'",
")",
":",
"shape_list",
"=",
"ShapeList",
"(",
")",
"for",
"region",
"in",
"region_list",
":",
"coord",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"region",
",",
"SkyRegion",
... | 32.333333 | 0.001305 |
def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs):
"""
Decorator for inline query handler
Example:
.. code-block:: python3
@dp.inline_handler(lambda inline_query: True)
async def some_inline_handler(inline_query: types.InlineQuery)
... | [
"def",
"inline_handler",
"(",
"self",
",",
"*",
"custom_filters",
",",
"state",
"=",
"None",
",",
"run_task",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"callback",
")",
":",
"self",
".",
"register_inline_handler",
"(",
"cal... | 30.73913 | 0.004115 |
def feed_parser(self, data):
"""Parse received message."""
assert isinstance(data, bytes)
self.controller.feed_parser(data) | [
"def",
"feed_parser",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"controller",
".",
"feed_parser",
"(",
"data",
")"
] | 36 | 0.013605 |
def trades(symbol=None, token='', version=''):
'''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.
https://iexcloud.io/docs/api/#deep-trades
Args:
symbol (string); Ticker to request
... | [
"def",
"trades",
"(",
"symbol",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"symbol",
":",
"return",
"_getJson",
"(",
"'deep/trades?symbols='",
"+",
"symbol",
",",
"token",
",",
... | 34.294118 | 0.003339 |
def write_branch_data(self, file):
""" Writes branch data to file.
"""
branch_attr = ["r", "x", "b", "rate_a", "rate_b", "rate_c",
"ratio", "phase_shift", "online", "ang_min", "ang_max", "p_from",
"q_from", "p_to", "q_to", "mu_s_from", "mu_s_to", "mu_angmin",
... | [
"def",
"write_branch_data",
"(",
"self",
",",
"file",
")",
":",
"branch_attr",
"=",
"[",
"\"r\"",
",",
"\"x\"",
",",
"\"b\"",
",",
"\"rate_a\"",
",",
"\"rate_b\"",
",",
"\"rate_c\"",
",",
"\"ratio\"",
",",
"\"phase_shift\"",
",",
"\"online\"",
",",
"\"ang_mi... | 40.481481 | 0.004468 |
def CreateEvent(self, EventId, Caption, Hint):
"""Creates a custom event displayed in Skype client's events pane.
:Parameters:
EventId : unicode
Unique identifier for the event.
Caption : unicode
Caption text.
Hint : unicode
Hint text. S... | [
"def",
"CreateEvent",
"(",
"self",
",",
"EventId",
",",
"Caption",
",",
"Hint",
")",
":",
"self",
".",
"_Skype",
".",
"_DoCommand",
"(",
"'CREATE EVENT %s CAPTION %s HINT %s'",
"%",
"(",
"tounicode",
"(",
"EventId",
")",
",",
"quote",
"(",
"tounicode",
"(",
... | 36.529412 | 0.006279 |
def vcenter_activate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id_key = ET.SubElement(vcenter, "id")
id_key.text = kwargs.pop('id')
activate = ... | [
"def",
"vcenter_activate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"vcenter",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"vcenter\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:b... | 39.545455 | 0.006742 |
def ema_growth(eqdata, **kwargs):
"""
Growth of exponential moving average.
Parameters
----------
eqdata : DataFrame
span : int, optional
Span for exponential moving average. Defaults to 20.
outputcol : str, optional.
Column to use for output. Defaults to 'EMA Growth'.
s... | [
"def",
"ema_growth",
"(",
"eqdata",
",",
"*",
"*",
"kwargs",
")",
":",
"_growth_outputcol",
"=",
"kwargs",
".",
"get",
"(",
"'outputcol'",
",",
"'EMA Growth'",
")",
"_ema_outputcol",
"=",
"'EMA'",
"kwargs",
"[",
"'outputcol'",
"]",
"=",
"_ema_outputcol",
"_e... | 33.333333 | 0.00216 |
async def create_pool_ledger_config(config_name: str,
config: Optional[str]) -> None:
"""
Creates a new local pool ledger configuration that can be used later to connect pool nodes.
:param config_name: Name of the pool ledger configuration.
:param config: (optional) ... | [
"async",
"def",
"create_pool_ledger_config",
"(",
"config_name",
":",
"str",
",",
"config",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"None",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"create_p... | 42.636364 | 0.003475 |
def on_line(client, line):
"""Default handling for incoming lines.
This handler will automatically manage the following IRC messages:
PING:
Responds with a PONG.
PRIVMSG:
Dispatches the PRIVMSG event.
NOTICE:
Dispatches the NOTICE event.
MOTDSTART:
Initi... | [
"def",
"on_line",
"(",
"client",
",",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"PING\"",
")",
":",
"client",
".",
"send",
"(",
"\"PONG\"",
"+",
"line",
"[",
"4",
":",
"]",
")",
"return",
"True",
"if",
"line",
".",
"startswith",
"("... | 28.108108 | 0.000929 |
def create_ticket(self, service):
"""Create an AuthTicket for a given service."""
ticket = AuthTicket(owner=self, service=service)
ticket.authorize()
return ticket | [
"def",
"create_ticket",
"(",
"self",
",",
"service",
")",
":",
"ticket",
"=",
"AuthTicket",
"(",
"owner",
"=",
"self",
",",
"service",
"=",
"service",
")",
"ticket",
".",
"authorize",
"(",
")",
"return",
"ticket"
] | 38.2 | 0.010256 |
def what_task(self, token_id, presented_pronunciation, index, phonemes, phonemes_probability,
warn=True, default=True):
"""Provide the prediction of the what task.
This function is used to predict the probability of a given phoneme being reported at a given index
for a given t... | [
"def",
"what_task",
"(",
"self",
",",
"token_id",
",",
"presented_pronunciation",
",",
"index",
",",
"phonemes",
",",
"phonemes_probability",
",",
"warn",
"=",
"True",
",",
"default",
"=",
"True",
")",
":",
"if",
"phonemes_probability",
"is",
"not",
"None",
... | 52.595745 | 0.007943 |
def parse_params(self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs):
"""
Take in a dictionary of parameters and applies attack-spec... | [
"def",
"parse_params",
"(",
"self",
",",
"eps",
"=",
"2.0",
",",
"nb_iter",
"=",
"None",
",",
"xi",
"=",
"1e-6",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"num_iterations",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# S... | 37.142857 | 0.009369 |
def validate_conversion_arguments(to_wrap):
"""
Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type
"""
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs... | [
"def",
"validate_conversion_arguments",
"(",
"to_wrap",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_assert_one_val",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | 31.157895 | 0.001639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.