text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
#... | [
"def",
"get_versions",
"(",
")",
":",
"# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have",
"# __file__, we can work backwards from there to the root. Some",
"# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which",
"# case we can only use expanded keywords.... | 33.327586 | 22.172414 |
def require_auth(view_func):
"""Performs user authentication check.
Similar to Django's `login_required` decorator, except that this throws
:exc:`~horizon.exceptions.NotAuthenticated` exception if the user is not
signed-in.
"""
from horizon.exceptions import NotAuthenticated
@functools.wra... | [
"def",
"require_auth",
"(",
"view_func",
")",
":",
"from",
"horizon",
".",
"exceptions",
"import",
"NotAuthenticated",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"dec",
"(",
"... | 38.066667 | 19.6 |
def wrsamp(self, expanded=False, write_dir=''):
"""
Write a wfdb header file and any associated dat files from this
object.
Parameters
----------
expanded : bool, optional
Whether to write the expanded signal (e_d_signal) instead
of the uniform si... | [
"def",
"wrsamp",
"(",
"self",
",",
"expanded",
"=",
"False",
",",
"write_dir",
"=",
"''",
")",
":",
"# Perform field validity and cohesion checks, and write the",
"# header file.",
"self",
".",
"wrheader",
"(",
"write_dir",
"=",
"write_dir",
")",
"if",
"self",
"."... | 35.857143 | 17.666667 |
def inverse_transform(self, X):
"""Undo the scaling of X according to feature_range.
Note that if truncate is true, any truncated points will not
be restored exactly.
Parameters
----------
X : array-like with shape [n_samples, n_features]
Input data that wil... | [
"def",
"inverse_transform",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
",",
"copy",
"=",
"self",
".",
"copy",
")",
"X",
"-=",
"self",
".",
"min_",
"X",
"/=",
"self",
".",
"scale_",
"return",
"X"
] | 29.533333 | 17.2 |
def fpopen(*args, **kwargs):
'''
Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, i... | [
"def",
"fpopen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove uid, gid and mode from kwargs if present",
"uid",
"=",
"kwargs",
".",
"pop",
"(",
"'uid'",
",",
"-",
"1",
")",
"# -1 means no change to current uid",
"gid",
"=",
"kwargs",
".",
"po... | 35.619048 | 23.380952 |
def next(self):
"""
This method is deprecated, a holdover from when queries were iterators,
rather than iterables.
@return: one element of massaged data.
"""
if self._selfiter is None:
warnings.warn(
"Calling 'next' directly on a query is depr... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_selfiter",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Calling 'next' directly on a query is deprecated. \"",
"\"Perhaps you want to use iter(query).next(), or something \"",
"\"more expressive like store.findFi... | 40.133333 | 17.2 |
def to_json(self, depth=-1, **kwargs):
"""Returns a JSON representation of the object."""
return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs) | [
"def",
"to_json",
"(",
"self",
",",
"depth",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
"depth",
"=",
"depth",
",",
"ordered",
"=",
"True",
")",
",",
"*",
"*",
"kwargs",
"... | 57.333333 | 12.666667 |
def __snake_case(self, descriptor):
"""
Utility method to convert camelcase to snake
:param descriptor: The dictionary to convert
"""
newdict = {}
for i, (k, v) in enumerate(descriptor.items()):
newkey = ""
for j, c in enumerate(k):
... | [
"def",
"__snake_case",
"(",
"self",
",",
"descriptor",
")",
":",
"newdict",
"=",
"{",
"}",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"enumerate",
"(",
"descriptor",
".",
"items",
"(",
")",
")",
":",
"newkey",
"=",
"\"\"",
"for",
"j",
",",
... | 30.444444 | 10.666667 |
def snapshots_delete(container, name, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Delete a snapshot for a container
container :
The name of the container to get.
name :
The name of the snapshot.
remote_addr :
An URL to a remote server... | [
"def",
"snapshots_delete",
"(",
"container",
",",
"name",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"cont",
"=",
"container_get",
"(",
"container",
",",
"remote_addr",
"... | 21.886792 | 23.509434 |
def configure(filename=None):
"""This function gives to the user application a chance to define where
configuration file should live. Subsequent calls to this function will have
no effect, unless you call :func:`reconfigure`.
:param str filename: Full path to configuration file.
"""
global ret... | [
"def",
"configure",
"(",
"filename",
"=",
"None",
")",
":",
"global",
"retry",
"if",
"getattr",
"(",
"configure",
",",
"'_configured'",
",",
"False",
")",
":",
"return",
"filename",
"=",
"filename",
"or",
"DEFAULT_CONFIG_FILENAME",
"_ensure_directory",
"(",
"f... | 34.052632 | 21.631579 |
def wait_until_clickable(self, timeout=None):
"""Search element and wait until it is clickable
:param timeout: max time to wait
:returns: page element instance
"""
try:
self.utils.wait_until_element_clickable(self, timeout)
except TimeoutException as exceptio... | [
"def",
"wait_until_clickable",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"utils",
".",
"wait_until_element_clickable",
"(",
"self",
",",
"timeout",
")",
"except",
"TimeoutException",
"as",
"exception",
":",
"parent_msg",
"=",... | 52.5 | 26.1875 |
def delete_user(self, user_descriptor):
"""DeleteUser.
[Preview API] Disables a user.
:param str user_descriptor: The descriptor of the user to delete.
"""
route_values = {}
if user_descriptor is not None:
route_values['userDescriptor'] = self._serialize.url('... | [
"def",
"delete_user",
"(",
"self",
",",
"user_descriptor",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"user_descriptor",
"is",
"not",
"None",
":",
"route_values",
"[",
"'userDescriptor'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'user_descr... | 46 | 13.083333 |
def get_saved_policy(table='filter', chain=None, conf_file=None, family='ipv4'):
'''
Return the current policy for the specified table/chain
CLI Examples:
.. code-block:: bash
salt '*' iptables.get_saved_policy filter INPUT
salt '*' iptables.get_saved_policy filter INPUT \\
... | [
"def",
"get_saved_policy",
"(",
"table",
"=",
"'filter'",
",",
"chain",
"=",
"None",
",",
"conf_file",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"if",
"not",
"chain",
":",
"return",
"'Error: Chain needs to be specified'",
"rules",
"=",
"_parse_conf"... | 28.730769 | 24.730769 |
def show_address_scope(self, address_scope, **_params):
"""Fetches information of a certain address scope."""
return self.get(self.address_scope_path % (address_scope),
params=_params) | [
"def",
"show_address_scope",
"(",
"self",
",",
"address_scope",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"address_scope_path",
"%",
"(",
"address_scope",
")",
",",
"params",
"=",
"_params",
")"
] | 55.25 | 10.5 |
def dist_abs(self, src, tar, gap_cost=1, sim_func=sim_ident):
"""Return the Smith-Waterman score of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
gap_cost : float
The c... | [
"def",
"dist_abs",
"(",
"self",
",",
"src",
",",
"tar",
",",
"gap_cost",
"=",
"1",
",",
"sim_func",
"=",
"sim_ident",
")",
":",
"d_mat",
"=",
"np_zeros",
"(",
"(",
"len",
"(",
"src",
")",
"+",
"1",
",",
"len",
"(",
"tar",
")",
"+",
"1",
")",
... | 31.108696 | 18.086957 |
def setLocalityGroups(self, login, tableName, groups):
"""
Parameters:
- login
- tableName
- groups
"""
self.send_setLocalityGroups(login, tableName, groups)
self.recv_setLocalityGroups() | [
"def",
"setLocalityGroups",
"(",
"self",
",",
"login",
",",
"tableName",
",",
"groups",
")",
":",
"self",
".",
"send_setLocalityGroups",
"(",
"login",
",",
"tableName",
",",
"groups",
")",
"self",
".",
"recv_setLocalityGroups",
"(",
")"
] | 23.777778 | 15.777778 |
def cbpdn_ystep(k):
"""Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
AXU = mp_Z_X[k] + mp_Z_U[k]
mp_Z_Y[k] = sp.prox_l1(AXU, (mp_lmbda/mp_xrho)) | [
"def",
"cbpdn_ystep",
"(",
"k",
")",
":",
"AXU",
"=",
"mp_Z_X",
"[",
"k",
"]",
"+",
"mp_Z_U",
"[",
"k",
"]",
"mp_Z_Y",
"[",
"k",
"]",
"=",
"sp",
".",
"prox_l1",
"(",
"AXU",
",",
"(",
"mp_lmbda",
"/",
"mp_xrho",
")",
")"
] | 35.625 | 15 |
def rpc_get_names(self, filename, source, offset):
"""Return the list of possible names"""
names = jedi.api.names(source=source,
path=filename, encoding='utf-8',
all_scopes=True,
definitions=True,
... | [
"def",
"rpc_get_names",
"(",
"self",
",",
"filename",
",",
"source",
",",
"offset",
")",
":",
"names",
"=",
"jedi",
".",
"api",
".",
"names",
"(",
"source",
"=",
"source",
",",
"path",
"=",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"all_scopes"... | 43.65 | 13.2 |
def update_path(self, path):
"""
There are EXTENDED messages which don't include any routers at
all, and any of the EXTENDED messages may have some arbitrary
flags in them. So far, they're all upper-case and none start
with $ luckily. The routers in the path should all be
... | [
"def",
"update_path",
"(",
"self",
",",
"path",
")",
":",
"oldpath",
"=",
"self",
".",
"path",
"self",
".",
"path",
"=",
"[",
"]",
"for",
"p",
"in",
"path",
":",
"if",
"p",
"[",
"0",
"]",
"!=",
"'$'",
":",
"break",
"# this will create a Router if we ... | 38.677419 | 19 |
def sign_transaction(self, tx_data, unspents=None): # pragma: no cover
"""Creates a signed P2PKH transaction using previously prepared
transaction data.
:param tx_data: Hex-encoded transaction or output of :func:`~bit.Key.prepare_transaction`.
:type tx_data: ``str``
:param unsp... | [
"def",
"sign_transaction",
"(",
"self",
",",
"tx_data",
",",
"unspents",
"=",
"None",
")",
":",
"# pragma: no cover",
"try",
":",
"# Json-tx-data from :func:`~bit.Key.prepare_transaction`",
"data",
"=",
"json",
".",
"loads",
"(",
"tx_data",
")",
"assert",
"(",
"un... | 46.066667 | 22.133333 |
def get_barycenter(self):
"""Return the mass weighted average location.
Args:
None
Returns:
:class:`numpy.ndarray`:
"""
try:
mass = self['mass'].values
except KeyError:
mass = self.add_data('mass')['mass'].values
p... | [
"def",
"get_barycenter",
"(",
"self",
")",
":",
"try",
":",
"mass",
"=",
"self",
"[",
"'mass'",
"]",
".",
"values",
"except",
"KeyError",
":",
"mass",
"=",
"self",
".",
"add_data",
"(",
"'mass'",
")",
"[",
"'mass'",
"]",
".",
"values",
"pos",
"=",
... | 27.933333 | 18.466667 |
def localeselector():
"""Default locale selector used in abilian applications."""
# if a user is logged in, use the locale from the user settings
user = getattr(g, "user", None)
if user is not None:
locale = getattr(user, "locale", None)
if locale:
return locale
# Otherw... | [
"def",
"localeselector",
"(",
")",
":",
"# if a user is logged in, use the locale from the user settings",
"user",
"=",
"getattr",
"(",
"g",
",",
"\"user\"",
",",
"None",
")",
"if",
"user",
"is",
"not",
"None",
":",
"locale",
"=",
"getattr",
"(",
"user",
",",
... | 39.428571 | 19.5 |
def query_input(question, default=None, color=default_color):
"""Ask a question for input via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
The "answer" return value is a str.
"""
if de... | [
"def",
"query_input",
"(",
"question",
",",
"default",
"=",
"None",
",",
"color",
"=",
"default_color",
")",
":",
"if",
"default",
"is",
"None",
"or",
"default",
"==",
"''",
":",
"prompt",
"=",
"' '",
"elif",
"type",
"(",
"default",
")",
"==",
"str",
... | 32.772727 | 17.090909 |
def release(version):
"""Tags all submodules for a new release.
Ensures that git tags, as well as the version.py files in each submodule, agree and that the
new version is strictly greater than the current version. Will fail if the new version
is not an increment (following PEP 440). Creates a new git ... | [
"def",
"release",
"(",
"version",
")",
":",
"check_new_version",
"(",
"version",
")",
"set_new_version",
"(",
"version",
")",
"commit_new_version",
"(",
"version",
")",
"set_git_tag",
"(",
"version",
")"
] | 40.909091 | 22.727273 |
def can(self):
"""Grant permission if owner or admin."""
return str(current_user.get_id()) == str(self.community.id_user) or \
DynamicPermission(ActionNeed('admin-access')).can() | [
"def",
"can",
"(",
"self",
")",
":",
"return",
"str",
"(",
"current_user",
".",
"get_id",
"(",
")",
")",
"==",
"str",
"(",
"self",
".",
"community",
".",
"id_user",
")",
"or",
"DynamicPermission",
"(",
"ActionNeed",
"(",
"'admin-access'",
")",
")",
"."... | 50.75 | 21.5 |
def request_leadership(self, opt_count, skip_brokers, skip_partitions):
"""Under-balanced broker requests leadership from current leader, on the
pretext that it recursively can maintain its leadership count as optimal.
:key_terms:
leader-balanced: Count of brokers as leader is at least ... | [
"def",
"request_leadership",
"(",
"self",
",",
"opt_count",
",",
"skip_brokers",
",",
"skip_partitions",
")",
":",
"# Possible partitions which can grant leadership to broker",
"owned_partitions",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"p",
":",
"self",
"is",
"not... | 52.676471 | 22.044118 |
def read_file(filename):
""" return the contents of the file named filename or None if file not found """
if os.path.isfile(filename):
with open(filename, 'r') as f:
return f.read() | [
"def",
"read_file",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | 41 | 7.8 |
def json_tuple(col, *fields):
"""Creates a new row for a json column according to the given field names.
:param col: string column in json format
:param fields: list of fields to extract
>>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')]
>>> df = spark.creat... | [
"def",
"json_tuple",
"(",
"col",
",",
"*",
"fields",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"jc",
"=",
"sc",
".",
"_jvm",
".",
"functions",
".",
"json_tuple",
"(",
"_to_java_column",
"(",
"col",
")",
",",
"_to_seq",
"(",
"sc",... | 46.928571 | 22.285714 |
def set_units(self, unit):
"""Set the unit for this data point
Unit, as with data_type, are actually associated with the stream and not
the individual data point. As such, changing this within a stream is
not encouraged. Setting the unit on the data point is useful when the
st... | [
"def",
"set_units",
"(",
"self",
",",
"unit",
")",
":",
"self",
".",
"_units",
"=",
"validate_type",
"(",
"unit",
",",
"type",
"(",
"None",
")",
",",
"*",
"six",
".",
"string_types",
")"
] | 45 | 26.4 |
def merge(infiles, outfile, same_run, templatefile):
"""
Merge multiple OSW files and (for large experiments, it is recommended to subsample first).
"""
if len(infiles) < 1:
raise click.ClickException("At least one PyProphet input file needs to be provided.")
merge_osw(infiles, outfile, te... | [
"def",
"merge",
"(",
"infiles",
",",
"outfile",
",",
"same_run",
",",
"templatefile",
")",
":",
"if",
"len",
"(",
"infiles",
")",
"<",
"1",
":",
"raise",
"click",
".",
"ClickException",
"(",
"\"At least one PyProphet input file needs to be provided.\"",
")",
"me... | 37 | 25.666667 |
def ApplyEdits(self, adds=None, updates=None, deletes=None):
"""This operation adds, updates and deletes features to the associated
feature layer or table in a single call (POST only). The apply edits
operation is performed on a feature service layer resource. The
result of this... | [
"def",
"ApplyEdits",
"(",
"self",
",",
"adds",
"=",
"None",
",",
"updates",
"=",
"None",
",",
"deletes",
"=",
"None",
")",
":",
"add_str",
",",
"update_str",
"=",
"None",
",",
"None",
"if",
"adds",
":",
"add_str",
"=",
"\",\"",
".",
"join",
"(",
"j... | 64.92 | 25.6 |
def create_diskgroup(cache_disk_id, capacity_disk_ids, safety_checks=True,
service_instance=None):
'''
Creates disk group on an ESXi host with the specified cache and
capacity disks.
cache_disk_id
The canonical name of the disk to be used as a cache. The disk must be
... | [
"def",
"create_diskgroup",
"(",
"cache_disk_id",
",",
"capacity_disk_ids",
",",
"safety_checks",
"=",
"True",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Validating diskgroup input'",
")",
"schema",
"=",
"DiskGroupsDiskIdSchema",
".",... | 41.825397 | 22.714286 |
def _parse_downloadcount(self, text):
""" parse download count
text format maybe:
- pure number: 1000
- number + unit: 1万
"""
unit_map = {
'千': 1000,
'万': 10000,
'百万': 1000000,
}
m = re.match(r'^(\d+(?:\.\d+)?)(\w{0,2})... | [
"def",
"_parse_downloadcount",
"(",
"self",
",",
"text",
")",
":",
"unit_map",
"=",
"{",
"'千': ",
"1",
"00,",
"",
"'万': ",
"1",
"000,",
"",
"'百万': 10",
"0",
"000,",
"",
"}",
"m",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+(?:\\.\\d+)?)(\\w{0,2})$'",
",",
"... | 24.85 | 16.2 |
def get_tl(self):
"""Returns the top left border of the cell"""
cell_above_left = CellBorders(self.cell_attributes,
*self.cell.get_above_left_key_rect())
return cell_above_left.get_r() | [
"def",
"get_tl",
"(",
"self",
")",
":",
"cell_above_left",
"=",
"CellBorders",
"(",
"self",
".",
"cell_attributes",
",",
"*",
"self",
".",
"cell",
".",
"get_above_left_key_rect",
"(",
")",
")",
"return",
"cell_above_left",
".",
"get_r",
"(",
")"
] | 40.333333 | 19.833333 |
def prepare_params(self):
"""
Prepare the parameters passed to the templatetag
"""
if self.options.resolve_fragment:
self.fragment_name = self.node.fragment_name.resolve(self.context)
else:
self.fragment_name = str(self.node.fragment_name)
# Re... | [
"def",
"prepare_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"options",
".",
"resolve_fragment",
":",
"self",
".",
"fragment_name",
"=",
"self",
".",
"node",
".",
"fragment_name",
".",
"resolve",
"(",
"self",
".",
"context",
")",
"else",
":",
"self... | 44.695652 | 24.782609 |
def get_attributes(self, sids, flds, **overrides):
"""Check cache first, then defer to data manager
:param sids: security identifiers
:param flds: fields to retrieve
:param overrides: key-value pairs to pass to the mgr get_attributes method
:return: DataFrame with flds as columns... | [
"def",
"get_attributes",
"(",
"self",
",",
"sids",
",",
"flds",
",",
"*",
"*",
"overrides",
")",
":",
"# Unfortunately must be inefficient with request",
"flds",
"=",
"_force_array",
"(",
"flds",
")",
"sids",
"=",
"_force_array",
"(",
"sids",
")",
"cached",
"=... | 48.071429 | 19.107143 |
def _sign_single(self, payload, signing_key):
"""
Make a single-signature JWT.
Returns the serialized token (compact form), as a string
"""
if not isinstance(payload, Mapping):
raise TypeError('Expecting a mapping object, as only '
'JSON ob... | [
"def",
"_sign_single",
"(",
"self",
",",
"payload",
",",
"signing_key",
")",
":",
"if",
"not",
"isinstance",
"(",
"payload",
",",
"Mapping",
")",
":",
"raise",
"TypeError",
"(",
"'Expecting a mapping object, as only '",
"'JSON objects can be used as payloads.'",
")",
... | 38.478261 | 21.956522 |
def _get_node_parent(self, age, pos):
"""Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node.
"""
return self.nodes[age][int(pos / self.comp)] | [
"def",
"_get_node_parent",
"(",
"self",
",",
"age",
",",
"pos",
")",
":",
"return",
"self",
".",
"nodes",
"[",
"age",
"]",
"[",
"int",
"(",
"pos",
"/",
"self",
".",
"comp",
")",
"]"
] | 32.571429 | 11.857143 |
def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | [
"def",
"_visible",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"name",
"in",
"self",
".",
"_disallowed_names",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"u'<!--.*-->'",
",",
"six",
".",
"text_type",
"(",
"element",
".",
... | 37.875 | 13.125 |
def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node` as keyword arg."""
arg = node.arg
if arg is None:
return f"**{self.visit(node.value)}"
else:
return f"{arg}={self.visit(node.value)}" | [
"def",
"visit_keyword",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"arg",
"=",
"node",
".",
"arg",
"if",
"arg",
"is",
"None",
":",
"return",
"f\"**{self.visit(node.value)}\"",
"else",
":",
... | 41.142857 | 15.857143 |
def spawn_agent(self, agent_definition, location):
"""Queues a spawn agent command. It will be applied when `tick` or `step` is called next.
The agent won't be able to be used until the next frame.
Args:
agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn... | [
"def",
"spawn_agent",
"(",
"self",
",",
"agent_definition",
",",
"location",
")",
":",
"self",
".",
"_should_write_to_command_buffer",
"=",
"True",
"self",
".",
"_add_agents",
"(",
"agent_definition",
")",
"command_to_send",
"=",
"SpawnAgentCommand",
"(",
"location"... | 57.5 | 26.333333 |
def backwards(self, orm):
"Write your backwards methods here."
from django.contrib.auth.models import Group
projects = orm['samples.Project'].objects.all()
names = [PROJECT_GROUP_TEMPLATE.format(p.name) for p in projects]
# Remove groups named after these teams
Group.ob... | [
"def",
"backwards",
"(",
"self",
",",
"orm",
")",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"models",
"import",
"Group",
"projects",
"=",
"orm",
"[",
"'samples.Project'",
"]",
".",
"objects",
".",
"all",
"(",
")",
"names",
"=",
"[",
"P... | 38.777778 | 19.888889 |
def evaluate(self, env):
"""Evaluate the function call in the environment, returning a
Unicode string.
"""
if self.ident in env.functions:
arg_vals = [expr.evaluate(env) for expr in self.args]
try:
out = env.functions[self.ident](*arg_vals)
... | [
"def",
"evaluate",
"(",
"self",
",",
"env",
")",
":",
"if",
"self",
".",
"ident",
"in",
"env",
".",
"functions",
":",
"arg_vals",
"=",
"[",
"expr",
".",
"evaluate",
"(",
"env",
")",
"for",
"expr",
"in",
"self",
".",
"args",
"]",
"try",
":",
"out"... | 38.2 | 12.866667 |
def _hash_filter_fn(self, filter_fn, **kwargs):
""" Construct string representing state of filter_fn
Used to cache filtered variants or effects uniquely depending on filter fn values
"""
filter_fn_name = self._get_function_name(filter_fn, default="filter-none")
logger.debug("... | [
"def",
"_hash_filter_fn",
"(",
"self",
",",
"filter_fn",
",",
"*",
"*",
"kwargs",
")",
":",
"filter_fn_name",
"=",
"self",
".",
"_get_function_name",
"(",
"filter_fn",
",",
"default",
"=",
"\"filter-none\"",
")",
"logger",
".",
"debug",
"(",
"\"Computing hash ... | 52.69697 | 21.515152 |
def container_setting(name, container, settings=None):
'''
Set the value of the setting for an IIS container.
:param str name: The name of the IIS container.
:param str container: The type of IIS container. The container types are:
AppPools, Sites, SslBindings
:param str settings: A diction... | [
"def",
"container_setting",
"(",
"name",
",",
"container",
",",
"settings",
"=",
"None",
")",
":",
"identityType_map2string",
"=",
"{",
"0",
":",
"'LocalSystem'",
",",
"1",
":",
"'LocalService'",
",",
"2",
":",
"'NetworkService'",
",",
"3",
":",
"'SpecificUs... | 38.861702 | 23.968085 |
def add_role(self, service_name, deployment_name, role_name, system_config,
os_virtual_hard_disk, network_config=None,
availability_set_name=None, data_virtual_hard_disks=None,
role_size=None, role_type='PersistentVMRole',
resource_extension_references... | [
"def",
"add_role",
"(",
"self",
",",
"service_name",
",",
"deployment_name",
",",
"role_name",
",",
"system_config",
",",
"os_virtual_hard_disk",
",",
"network_config",
"=",
"None",
",",
"availability_set_name",
"=",
"None",
",",
"data_virtual_hard_disks",
"=",
"Non... | 49.833333 | 20.880952 |
def gap_index_map(sequence, gap_chars='-'):
"""
Opposite of ungap_index_map: returns mapping from gapped index to ungapped
index.
>>> gap_index_map('AC-TG-')
{0: 0, 1: 1, 3: 2, 4: 3}
"""
return dict(
(v, k) for k, v in list(ungap_index_map(sequence, gap_chars).items())) | [
"def",
"gap_index_map",
"(",
"sequence",
",",
"gap_chars",
"=",
"'-'",
")",
":",
"return",
"dict",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"ungap_index_map",
"(",
"sequence",
",",
"gap_chars",
")",
".",
"items",
"(",
... | 29.8 | 19.4 |
def const_shuffle(arr, seed=23980):
""" Shuffle an array in-place with a fixed seed.
"""
old_seed = np.random.seed()
np.random.seed(seed)
np.random.shuffle(arr)
np.random.seed(old_seed) | [
"def",
"const_shuffle",
"(",
"arr",
",",
"seed",
"=",
"23980",
")",
":",
"old_seed",
"=",
"np",
".",
"random",
".",
"seed",
"(",
")",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"arr",
")",
"np",
... | 29 | 8 |
def update(self, json_state):
"""Update the json data from a dictionary.
Only updates if it already exists in the device.
"""
self._json_state.update(
{k: json_state[k] for k in json_state if self._json_state.get(k)})
self._update_name() | [
"def",
"update",
"(",
"self",
",",
"json_state",
")",
":",
"self",
".",
"_json_state",
".",
"update",
"(",
"{",
"k",
":",
"json_state",
"[",
"k",
"]",
"for",
"k",
"in",
"json_state",
"if",
"self",
".",
"_json_state",
".",
"get",
"(",
"k",
")",
"}",... | 35.375 | 15.75 |
def handler(self, scheme_name=None):
""" Return handler which scheme name matches the specified one
:param scheme_name: scheme name to search for
:return: WSchemeHandler class or None (if matching handler was not found)
"""
if scheme_name is None:
return self.__default_handler_cls
for handler in self.__... | [
"def",
"handler",
"(",
"self",
",",
"scheme_name",
"=",
"None",
")",
":",
"if",
"scheme_name",
"is",
"None",
":",
"return",
"self",
".",
"__default_handler_cls",
"for",
"handler",
"in",
"self",
".",
"__handlers_cls",
":",
"if",
"handler",
".",
"scheme_specif... | 37.181818 | 14.181818 |
def matrix(self):
"""Build matrix representation of Householder transformation.
Builds the matrix representation
:math:`H = I - \\beta vv^*`.
**Use with care!** This routine may be helpful for testing purposes but
should not be used in production codes for high dimensions since... | [
"def",
"matrix",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"v",
".",
"shape",
"[",
"0",
"]",
"return",
"numpy",
".",
"eye",
"(",
"n",
",",
"n",
")",
"-",
"self",
".",
"beta",
"*",
"numpy",
".",
"dot",
"(",
"self",
".",
"v",
",",
"self",... | 39 | 19.333333 |
def with_organisation(self, organisation):
"""Add an organisation segment.
Args:
organisation (str): Official name of an administrative body
holding an election.
Returns:
IdBuilder
Raises:
ValueError
"""
if organisati... | [
"def",
"with_organisation",
"(",
"self",
",",
"organisation",
")",
":",
"if",
"organisation",
"is",
"None",
":",
"organisation",
"=",
"''",
"organisation",
"=",
"slugify",
"(",
"organisation",
")",
"self",
".",
"_validate_organisation",
"(",
"organisation",
")",... | 26.263158 | 17 |
def add_category(self, category):
"""Add a category assigned to this message
:rtype: Category
"""
self._categories = self._ensure_append(category, self._categories) | [
"def",
"add_category",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"_categories",
"=",
"self",
".",
"_ensure_append",
"(",
"category",
",",
"self",
".",
"_categories",
")"
] | 32 | 16.166667 |
def isVideo(self):
"""
Is the stream labelled as a video stream.
"""
val=False
if self.__dict__['codec_type']:
if self.codec_type == 'video':
val=True
return val | [
"def",
"isVideo",
"(",
"self",
")",
":",
"val",
"=",
"False",
"if",
"self",
".",
"__dict__",
"[",
"'codec_type'",
"]",
":",
"if",
"self",
".",
"codec_type",
"==",
"'video'",
":",
"val",
"=",
"True",
"return",
"val"
] | 25.444444 | 10.555556 |
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=con... | [
"def",
"put_blob",
"(",
"kwargs",
"=",
"None",
",",
"storage_conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The put_blob function must be called with -f or --function.'",
")",
"... | 35.219178 | 25.082192 |
def _backup_file(self, file, patch):
""" Creates a backup of file """
dest_dir = self.quilt_pc + patch.get_name()
file_dir = file.get_directory()
if file_dir:
#TODO get relative path
dest_dir = dest_dir + file_dir
backup = Backup()
backup.backup_fi... | [
"def",
"_backup_file",
"(",
"self",
",",
"file",
",",
"patch",
")",
":",
"dest_dir",
"=",
"self",
".",
"quilt_pc",
"+",
"patch",
".",
"get_name",
"(",
")",
"file_dir",
"=",
"file",
".",
"get_directory",
"(",
")",
"if",
"file_dir",
":",
"#TODO get relativ... | 38.555556 | 8.555556 |
def _get(self, target, alias):
"""
Internal method to get a specific alias.
"""
if target not in self._aliases:
return
return self._aliases[target].get(alias) | [
"def",
"_get",
"(",
"self",
",",
"target",
",",
"alias",
")",
":",
"if",
"target",
"not",
"in",
"self",
".",
"_aliases",
":",
"return",
"return",
"self",
".",
"_aliases",
"[",
"target",
"]",
".",
"get",
"(",
"alias",
")"
] | 29.142857 | 6.857143 |
def get_json_tuples(self, prettyprint=False, translate=True):
"""
Get the data as JSON tuples
"""
j = self.get_json(prettyprint, translate)
if len(j) > 2:
if prettyprint:
j = j[1:-2] + ",\n"
else:
j = j[1:-1] + ","
e... | [
"def",
"get_json_tuples",
"(",
"self",
",",
"prettyprint",
"=",
"False",
",",
"translate",
"=",
"True",
")",
":",
"j",
"=",
"self",
".",
"get_json",
"(",
"prettyprint",
",",
"translate",
")",
"if",
"len",
"(",
"j",
")",
">",
"2",
":",
"if",
"prettypr... | 26.769231 | 13.384615 |
def fill_superseqs(data, samples):
"""
Fills the superseqs array with seq data from cat.clust
and fill the edges array with information about paired split locations.
"""
## load super to get edges
io5 = h5py.File(data.clust_database, 'r+')
superseqs = io5["seqs"]
splits = io5["splits"]
... | [
"def",
"fill_superseqs",
"(",
"data",
",",
"samples",
")",
":",
"## load super to get edges",
"io5",
"=",
"h5py",
".",
"File",
"(",
"data",
".",
"clust_database",
",",
"'r+'",
")",
"superseqs",
"=",
"io5",
"[",
"\"seqs\"",
"]",
"splits",
"=",
"io5",
"[",
... | 34.405941 | 19.277228 |
def fd_solve(self):
"""
w = fd_solve()
where coeff is the sparse coefficient matrix output from function
coeff_matrix and qs is the array of loads (stresses)
Sparse solver for one-dimensional flexure of an elastic plate
"""
if self.Debug:
print("qs", self.qs.shape)
... | [
"def",
"fd_solve",
"(",
"self",
")",
":",
"if",
"self",
".",
"Debug",
":",
"print",
"(",
"\"qs\"",
",",
"self",
".",
"qs",
".",
"shape",
")",
"print",
"(",
"\"Te\"",
",",
"self",
".",
"Te",
".",
"shape",
")",
"self",
".",
"calc_max_flexural_wavelengt... | 40.52381 | 23.761905 |
def get_sessionmaker(sqlalchemy_url, engine=None):
"""
Create session with database to work in
"""
if engine is None:
engine = create_engine(sqlalchemy_url)
return sessionmaker(bind=engine) | [
"def",
"get_sessionmaker",
"(",
"sqlalchemy_url",
",",
"engine",
"=",
"None",
")",
":",
"if",
"engine",
"is",
"None",
":",
"engine",
"=",
"create_engine",
"(",
"sqlalchemy_url",
")",
"return",
"sessionmaker",
"(",
"bind",
"=",
"engine",
")"
] | 30.142857 | 5.857143 |
def _logpdf(self, **kwargs):
"""
Returns the logpdf at the given angles.
Parameters
----------
\**kwargs:
The keyword arguments should specify the value for each angle,
using the names of the polar and azimuthal angles as the keywords.
Unrecog... | [
"def",
"_logpdf",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_polardist",
".",
"_logpdf",
"(",
"*",
"*",
"kwargs",
")",
"+",
"self",
".",
"_azimuthaldist",
".",
"_logpdf",
"(",
"*",
"*",
"kwargs",
")"
] | 30.333333 | 19.666667 |
def prune_taxonomy(taxF, level):
"""
:type taxF: file
:param taxF: The taxonomy output file to parse
:type level: string
:param level: The level of the phylogenetic assignment at which to cut off
every assigned taxonomic string.
:rtype: dict
:return: A dictionary of taxon... | [
"def",
"prune_taxonomy",
"(",
"taxF",
",",
"level",
")",
":",
"uniqueTax",
"=",
"{",
"}",
"nuTax",
"=",
"{",
"}",
"# non-unique taxonomies",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"taxF",
")",
":",
"try",
":",
"otuID",
",",
"tax",
",",
"flo... | 34 | 20.387097 |
def draw_frame(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
"""Similar to L{draw_rect} but only draws the outline of the rectangle.
`width or `height` can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total s... | [
"def",
"draw_frame",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"string",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"self",
".",
"_normalizeRect",
"(... | 47.589744 | 23.74359 |
def generate_and_write_ed25519_keypair(filepath=None, password=None):
"""
<Purpose>
Generate an Ed25519 keypair, where the encrypted key (using 'password' as
the passphrase) is saved to <'filepath'>. The public key portion of the
generated Ed25519 key is saved to <'filepath'>.pub. If the filepath is n... | [
"def",
"generate_and_write_ed25519_keypair",
"(",
"filepath",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"# Generate a new Ed25519 key object.",
"ed25519_key",
"=",
"securesystemslib",
".",
"keys",
".",
"generate_ed25519_key",
"(",
")",
"if",
"not",
"filepat... | 38.443478 | 25.852174 |
def BC_selector_and_coeff_matrix_creator(self):
"""
Selects the boundary conditions
E-W is for inside each panel
N-S is for the block diagonal matrix ("with fringes")
Then calls the function to build the diagonal matrix
The current method of coefficient matrix construction utilizes longer-range... | [
"def",
"BC_selector_and_coeff_matrix_creator",
"(",
"self",
")",
":",
"# Zeroth, start the timer and print the boundary conditions to the screen",
"self",
".",
"coeff_start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"Verbose",
":",
"print",
"(",
"\"Bo... | 43.77551 | 25.367347 |
def setup_parameters(self):
"""Add any CloudFormation parameters to the template"""
t = self.template
parameters = self.get_parameter_definitions()
if not parameters:
logger.debug("No parameters defined.")
return
for name, attrs in parameters.items():
... | [
"def",
"setup_parameters",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"template",
"parameters",
"=",
"self",
".",
"get_parameter_definitions",
"(",
")",
"if",
"not",
"parameters",
":",
"logger",
".",
"debug",
"(",
"\"No parameters defined.\"",
")",
"return"... | 31.833333 | 15.583333 |
def line(self, sentences, line_number=None):
""" Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
"""
if line_number is None:
line_number = self.current_line + 10
self.current_line = ... | [
"def",
"line",
"(",
"self",
",",
"sentences",
",",
"line_number",
"=",
"None",
")",
":",
"if",
"line_number",
"is",
"None",
":",
"line_number",
"=",
"self",
".",
"current_line",
"+",
"10",
"self",
".",
"current_line",
"=",
"line_number",
"sep",
"=",
"[",... | 32.1 | 16.45 |
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and... | [
"def",
"_wrap_chunks",
"(",
"self",
",",
"chunks",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"self",
".",
"width",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"invalid width %r (must be > 0)\"",
"%",
"self",
".",
"width",
")",
"# Arrange in reverse order so it... | 38.661972 | 22.929577 |
def param_names(scipy_dist):
"""Get names of fit parameters from a ``scipy.rv_*`` distribution."""
if not isinstance(scipy_dist, rv_continuous):
raise TypeError
names = ['loc', 'scale']
if scipy_dist.shapes is not None:
names += scipy_dist.shapes.split()
return names | [
"def",
"param_names",
"(",
"scipy_dist",
")",
":",
"if",
"not",
"isinstance",
"(",
"scipy_dist",
",",
"rv_continuous",
")",
":",
"raise",
"TypeError",
"names",
"=",
"[",
"'loc'",
",",
"'scale'",
"]",
"if",
"scipy_dist",
".",
"shapes",
"is",
"not",
"None",
... | 37 | 9.875 |
def download_and_expand(self):
"""Download and expand RPM Python binding."""
top_dir_name = None
if self.git_branch:
# Download a source by git clone.
top_dir_name = self._download_and_expand_by_git()
else:
# Download a source from the arcihve URL.
... | [
"def",
"download_and_expand",
"(",
"self",
")",
":",
"top_dir_name",
"=",
"None",
"if",
"self",
".",
"git_branch",
":",
"# Download a source by git clone.",
"top_dir_name",
"=",
"self",
".",
"_download_and_expand_by_git",
"(",
")",
"else",
":",
"# Download a source fr... | 45.529412 | 17.117647 |
def init_api(self, instance_config, custom_tags):
"""
Guarantees a valid auth scope for this instance, and returns it
Communicates with the identity server and initializes a new scope when one is absent, or has been forcibly
removed due to token expiry
"""
custom_tags = ... | [
"def",
"init_api",
"(",
"self",
",",
"instance_config",
",",
"custom_tags",
")",
":",
"custom_tags",
"=",
"custom_tags",
"or",
"[",
"]",
"keystone_server_url",
"=",
"instance_config",
".",
"get",
"(",
"\"keystone_server_url\"",
")",
"proxy_config",
"=",
"self",
... | 48.086957 | 23.73913 |
def noise_from_psd(length, delta_t, psd, seed=None):
""" Create noise with a given psd.
Return noise with a given psd. Note that if unique noise is desired
a unique seed should be provided.
Parameters
----------
length : int
The length of noise to generate in samples.
delta_t : flo... | [
"def",
"noise_from_psd",
"(",
"length",
",",
"delta_t",
",",
"psd",
",",
"seed",
"=",
"None",
")",
":",
"noise_ts",
"=",
"TimeSeries",
"(",
"zeros",
"(",
"length",
")",
",",
"delta_t",
"=",
"delta_t",
")",
"if",
"seed",
"is",
"None",
":",
"seed",
"="... | 28.207547 | 22.301887 |
def stop_NoteContainer(self, notecontainer):
"""Add note_off events for each note in the NoteContainer to the
track_data."""
# if there is more than one note in the container, the deltatime should
# be set back to zero after the first one has been stopped
if len(notecontainer) <=... | [
"def",
"stop_NoteContainer",
"(",
"self",
",",
"notecontainer",
")",
":",
"# if there is more than one note in the container, the deltatime should",
"# be set back to zero after the first one has been stopped",
"if",
"len",
"(",
"notecontainer",
")",
"<=",
"1",
":",
"[",
"self"... | 47.272727 | 13.090909 |
def visit_Alt(self, node: parsing.Alt) -> [ast.stmt]:
"""Generates python code for alternatives.
try:
try:
<code for clause> #raise AltFalse when alternative is False
raise AltTrue()
except AltFalse:
pass
return False
... | [
"def",
"visit_Alt",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Alt",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
":",
"clauses",
"=",
"[",
"self",
".",
"visit",
"(",
"clause",
")",
"for",
"clause",
"in",
"node",
".",
"ptlist",
"]",
"for",
"clau... | 36.484848 | 16.333333 |
def _add_potential(self, potential, parent_tag):
"""
Adds Potentials to the ProbModelXML.
Parameters
----------
potential: dict
Dictionary containing Potential data.
For example: {'role': 'Utility',
'Variables': ['D0', 'D1', 'C0'... | [
"def",
"_add_potential",
"(",
"self",
",",
"potential",
",",
"parent_tag",
")",
":",
"potential_type",
"=",
"potential",
"[",
"'type'",
"]",
"try",
":",
"potential_tag",
"=",
"etree",
".",
"SubElement",
"(",
"parent_tag",
",",
"'Potential'",
",",
"attrib",
"... | 57 | 23.833333 |
def make_similar_sized_bins(x, n):
"""Utility function to create a set of bins over the range of values in `x`
such that each bin contains roughly the same number of values.
Parameters
----------
x : array_like
The values to be binned.
n : int
The number of bins to create.
... | [
"def",
"make_similar_sized_bins",
"(",
"x",
",",
"n",
")",
":",
"# copy and sort the array",
"y",
"=",
"np",
".",
"array",
"(",
"x",
")",
".",
"flatten",
"(",
")",
"y",
".",
"sort",
"(",
")",
"# setup bins",
"bins",
"=",
"[",
"y",
"[",
"0",
"]",
"]... | 20.957447 | 23.680851 |
def escalation_date(self, escalation_date):
"""
Sets the task escalation_date
Args:
escalation_date: Converted to %Y-%m-%dT%H:%M:%SZ date format
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
escalation_date = self._utils.... | [
"def",
"escalation_date",
"(",
"self",
",",
"escalation_date",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"escalation_date",
"=",
"sel... | 40.066667 | 18.333333 |
def get_refs(self, location):
"""Return map of named refs (branches or tags) to commit hashes."""
output = call_subprocess([self.cmd, 'show-ref'],
show_stdout=False, cwd=location)
rv = {}
for line in output.strip().splitlines():
commit, ref = ... | [
"def",
"get_refs",
"(",
"self",
",",
"location",
")",
":",
"output",
"=",
"call_subprocess",
"(",
"[",
"self",
".",
"cmd",
",",
"'show-ref'",
"]",
",",
"show_stdout",
"=",
"False",
",",
"cwd",
"=",
"location",
")",
"rv",
"=",
"{",
"}",
"for",
"line",... | 43.333333 | 11.055556 |
def indicator_pivot(self, indicator_resource):
"""Pivot point on indicators for this resource.
This method will return all *resources* (groups, tasks, victims, etc)
for this resource that are associated with the provided resource id
(indicator value).
**Example Endpoints URI's*... | [
"def",
"indicator_pivot",
"(",
"self",
",",
"indicator_resource",
")",
":",
"resource",
"=",
"self",
".",
"copy",
"(",
")",
"resource",
".",
"_request_uri",
"=",
"'{}/{}'",
".",
"format",
"(",
"indicator_resource",
".",
"request_uri",
",",
"resource",
".",
"... | 63.911765 | 39.852941 |
def extract_paths(self, paths, ignore_nopath):
"""
Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try ex... | [
"def",
"extract_paths",
"(",
"self",
",",
"paths",
",",
"ignore_nopath",
")",
":",
"try",
":",
"super",
"(",
")",
".",
"extract_paths",
"(",
"paths",
"=",
"paths",
",",
"ignore_nopath",
"=",
"ignore_nopath",
",",
")",
"except",
"ExtractPathError",
"as",
"e... | 33.891892 | 23.459459 |
def _get_policies(self):
"""Returns all the policy names for a given user"""
username = self._get_username_for_key()
policies = self.client.list_user_policies(
UserName=username
)
return policies | [
"def",
"_get_policies",
"(",
"self",
")",
":",
"username",
"=",
"self",
".",
"_get_username_for_key",
"(",
")",
"policies",
"=",
"self",
".",
"client",
".",
"list_user_policies",
"(",
"UserName",
"=",
"username",
")",
"return",
"policies"
] | 34.428571 | 13.142857 |
def quaternion_from_euler(angles, order='yzy'):
"""Generate a quaternion from a set of Euler angles.
Args:
angles (array_like): Array of Euler angles.
order (str): Order of Euler rotations. 'yzy' is default.
Returns:
Quaternion: Quaternion representation of Euler rotation.
"""... | [
"def",
"quaternion_from_euler",
"(",
"angles",
",",
"order",
"=",
"'yzy'",
")",
":",
"angles",
"=",
"np",
".",
"asarray",
"(",
"angles",
",",
"dtype",
"=",
"float",
")",
"quat",
"=",
"quaternion_from_axis_rotation",
"(",
"angles",
"[",
"0",
"]",
",",
"or... | 36.8125 | 19.375 |
def data_factory(value, encoding='UTF-8'):
"""Wrap a Python type in the equivalent C AMQP type.
If the Python type has already been wrapped in a ~uamqp.types.AMQPType
object - then this will be used to select the appropriate C type.
- bool => c_uamqp.BoolValue
- int => c_uamqp.IntValue, LongValue, D... | [
"def",
"data_factory",
"(",
"value",
",",
"encoding",
"=",
"'UTF-8'",
")",
":",
"result",
"=",
"None",
"if",
"value",
"is",
"None",
":",
"result",
"=",
"c_uamqp",
".",
"null_value",
"(",
")",
"elif",
"hasattr",
"(",
"value",
",",
"'c_data'",
")",
":",
... | 41.075472 | 10.415094 |
def transform_point(self, x, y):
"""Transforms the point ``(x, y)`` by this matrix.
:param x: X position.
:param y: Y position.
:type x: float
:type y: float
:returns: A ``(new_x, new_y)`` tuple of floats.
"""
xy = ffi.new('double[2]', [x, y])
ca... | [
"def",
"transform_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"xy",
"=",
"ffi",
".",
"new",
"(",
"'double[2]'",
",",
"[",
"x",
",",
"y",
"]",
")",
"cairo",
".",
"cairo_matrix_transform_point",
"(",
"self",
".",
"_pointer",
",",
"xy",
"+",
"0... | 30.461538 | 16.230769 |
def clean_features(df):
"""Fixes up columns of the passed DataFrame, such as casting T/F columns to
boolean and filling in NaNs for team and opp.
:param df: DataFrame of play-by-play data.
:returns: Dataframe with cleaned columns.
"""
df = pd.DataFrame(df)
bool_vals = set([True, False, Non... | [
"def",
"clean_features",
"(",
"df",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"df",
")",
"bool_vals",
"=",
"set",
"(",
"[",
"True",
",",
"False",
",",
"None",
",",
"np",
".",
"nan",
"]",
")",
"sparse_cols",
"=",
"sparse_lineup_cols",
"(",
"... | 33.032258 | 16.774194 |
def logout_view(self):
"""Process the logout link."""
""" Sign the user out."""
# Send user_logged_out signal
signals.user_logged_out.send(current_app._get_current_object(), user=current_user)
# Use Flask-Login to sign out user
logout_user()
# Flash a system me... | [
"def",
"logout_view",
"(",
"self",
")",
":",
"\"\"\" Sign the user out.\"\"\"",
"# Send user_logged_out signal",
"signals",
".",
"user_logged_out",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"current_user",
")",
"# Use Fla... | 34.625 | 21.4375 |
def unmonitor_instances(self, instance_ids):
"""
Disable CloudWatch monitoring for the supplied instance.
:type instance_id: list of string
:param instance_id: The instance id
:rtype: list
:return: A list of :class:`boto.ec2.instanceinfo.InstanceInfo`
"""
... | [
"def",
"unmonitor_instances",
"(",
"self",
",",
"instance_ids",
")",
":",
"params",
"=",
"{",
"}",
"self",
".",
"build_list_params",
"(",
"params",
",",
"instance_ids",
",",
"'InstanceId'",
")",
"return",
"self",
".",
"get_list",
"(",
"'UnmonitorInstances'",
"... | 36.714286 | 18.142857 |
def plotAccuracyAndMCsDuringDecrementChange(results, title="", yaxis=""):
"""
Plot accuracy vs decrement value
"""
decrementRange = []
mcRange = []
for r in results:
if r["basalPredictedSegmentDecrement"] not in decrementRange:
decrementRange.append(r["basalPredictedSegmentDecrement"])
if r["... | [
"def",
"plotAccuracyAndMCsDuringDecrementChange",
"(",
"results",
",",
"title",
"=",
"\"\"",
",",
"yaxis",
"=",
"\"\"",
")",
":",
"decrementRange",
"=",
"[",
"]",
"mcRange",
"=",
"[",
"]",
"for",
"r",
"in",
"results",
":",
"if",
"r",
"[",
"\"basalPredicted... | 35.157895 | 21.421053 |
def _pair_samples_with_pipelines(run_info_yaml, config):
"""Map samples defined in input file to pipelines to run.
"""
samples = config_utils.load_config(run_info_yaml)
if isinstance(samples, dict):
resources = samples.pop("resources")
samples = samples["details"]
else:
resou... | [
"def",
"_pair_samples_with_pipelines",
"(",
"run_info_yaml",
",",
"config",
")",
":",
"samples",
"=",
"config_utils",
".",
"load_config",
"(",
"run_info_yaml",
")",
"if",
"isinstance",
"(",
"samples",
",",
"dict",
")",
":",
"resources",
"=",
"samples",
".",
"p... | 37.9375 | 11.125 |
def get_responses(self):
"""Gets list of the latest responses"""
response_list = []
for question_map in self._my_map['questions']:
response_list.append(self._get_response_from_question_map(question_map))
return ResponseList(response_list) | [
"def",
"get_responses",
"(",
"self",
")",
":",
"response_list",
"=",
"[",
"]",
"for",
"question_map",
"in",
"self",
".",
"_my_map",
"[",
"'questions'",
"]",
":",
"response_list",
".",
"append",
"(",
"self",
".",
"_get_response_from_question_map",
"(",
"questio... | 46.166667 | 15 |
def write_to_datastore(self):
"""Writes all image batches to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
for batch_id, batch_data in iteritems(self._data):
batch_key = client.key(self._entity_kind_batches, batch_id)
batch_entity = ... | [
"def",
"write_to_datastore",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_datastore_client",
"with",
"client",
".",
"no_transact_batch",
"(",
")",
"as",
"client_batch",
":",
"for",
"batch_id",
",",
"batch_data",
"in",
"iteritems",
"(",
"self",
".",
"... | 45.666667 | 11.333333 |
def _initPermConnected(self):
"""
Returns a randomly generated permanence value for a synapses that is
initialized in a connected state. The basic idea here is to initialize
permanence values very close to synPermConnected so that a small number of
learning steps could make it disconnected or connec... | [
"def",
"_initPermConnected",
"(",
"self",
")",
":",
"p",
"=",
"self",
".",
"_synPermConnected",
"+",
"(",
"self",
".",
"_synPermMax",
"-",
"self",
".",
"_synPermConnected",
")",
"*",
"self",
".",
"_random",
".",
"getReal64",
"(",
")",
"# Ensure we don't have... | 45.166667 | 25.722222 |
def bleakest_moves(self, start_game, end_game):
"""Given a range of games, return the bleakest moves.
Returns a list of (game, move, q) sorted by q.
"""
bleak = b'bleakest_q'
rows = self.bt_table.read_rows(
ROW_PREFIX.format(start_game),
ROW_PREFIX.format... | [
"def",
"bleakest_moves",
"(",
"self",
",",
"start_game",
",",
"end_game",
")",
":",
"bleak",
"=",
"b'bleakest_q'",
"rows",
"=",
"self",
".",
"bt_table",
".",
"read_rows",
"(",
"ROW_PREFIX",
".",
"format",
"(",
"start_game",
")",
",",
"ROW_PREFIX",
".",
"fo... | 38.722222 | 11.5 |
def strip_qos_cntrl(self, idx, prot_type):
"""strip(2 byte) wlan.qos
:idx: int
:prot_type: string
802.11 protocol type(.11ac, .11a, .11n, etc)
:return: int
number of processed bytes
:return: int
qos priority
:return: int
qos... | [
"def",
"strip_qos_cntrl",
"(",
"self",
",",
"idx",
",",
"prot_type",
")",
":",
"qos_cntrl",
",",
"=",
"struct",
".",
"unpack",
"(",
"'H'",
",",
"self",
".",
"_packet",
"[",
"idx",
":",
"idx",
"+",
"2",
"]",
")",
"qos_cntrl_bits",
"=",
"format",
"(",
... | 34.36 | 12.92 |
def get(self, request, bot_id, id, format=None):
"""
Get list of source state of a handler
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(SourceStateList, self).get(request, bot_i... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"SourceStateList",
",",
"self",
")",
".",
"get",
"(",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
")"
] | 32.5 | 11.5 |
def _handle_mouse(self, ev):
"""
Handle mouse events. Return a list of KeyPress instances.
"""
FROM_LEFT_1ST_BUTTON_PRESSED = 0x1
result = []
# Check event type.
if ev.ButtonState == FROM_LEFT_1ST_BUTTON_PRESSED:
# On a key press, generate both the m... | [
"def",
"_handle_mouse",
"(",
"self",
",",
"ev",
")",
":",
"FROM_LEFT_1ST_BUTTON_PRESSED",
"=",
"0x1",
"result",
"=",
"[",
"]",
"# Check event type.",
"if",
"ev",
".",
"ButtonState",
"==",
"FROM_LEFT_1ST_BUTTON_PRESSED",
":",
"# On a key press, generate both the mouse do... | 33.6 | 18.9 |
def cleanup(self):
"""
Attempt to set a new current symlink if it is broken. If no other
prefixes exist and the workdir is empty, try to delete the entire
workdir.
Raises:
:exc:`~MalformedWorkdir`: if no prefixes were found, but the
workdir is not emp... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"join",
"(",
"'current'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"current",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'found broken current symlink, removing: %s'",
",",
... | 38.1 | 16.833333 |
def parse_superbox(self, fptr):
"""Parse a superbox (box consisting of nothing but other boxes.
Parameters
----------
fptr : file
Open file object.
Returns
-------
list
List of top-level boxes in the JPEG 2000 file.
"""
s... | [
"def",
"parse_superbox",
"(",
"self",
",",
"fptr",
")",
":",
"superbox",
"=",
"[",
"]",
"start",
"=",
"fptr",
".",
"tell",
"(",
")",
"while",
"True",
":",
"# Are we at the end of the superbox?",
"if",
"start",
">=",
"self",
".",
"offset",
"+",
"self",
".... | 34.565217 | 21.666667 |
def hist(table, field=-1, class_column=None,
title='', verbosity=2, **kwargs):
"""Plot discrete PDFs
>>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC'))
>>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0)
>>> len(hist(df, verbosity=0, class_column='... | [
"def",
"hist",
"(",
"table",
",",
"field",
"=",
"-",
"1",
",",
"class_column",
"=",
"None",
",",
"title",
"=",
"''",
",",
"verbosity",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"field",
"=",
"fuzzy_index_match",
"(",
"table",
",",
"field",
")",
... | 36.476744 | 19.895349 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.