text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def p_CommentOrEmptyLineList(p):
'''
CommentOrEmptyLineList :
| CommentOrEmptyLine
| CommentOrEmptyLineList CommentOrEmptyLine
'''
if len(p) <= 1:
p[0] = CommentOrEmptyLineList(None, None)
elif len(p) <= 2:
p[0] = CommentOrEmptyL... | [
"def",
"p_CommentOrEmptyLineList",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"<=",
"1",
":",
"p",
"[",
"0",
"]",
"=",
"CommentOrEmptyLineList",
"(",
"None",
",",
"None",
")",
"elif",
"len",
"(",
"p",
")",
"<=",
"2",
":",
"p",
"[",
"0",
"]... | 32.333333 | 18.5 |
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.cancelar_ultima_venda`.
:return: Uma resposta SAT especializada em ``CancelarUltimaVenda``.
:rtype: satcfe.resposta.cancelarultimavenda.RespostaCancelarUltimaVenda
"""
resp... | [
"def",
"cancelar_ultima_venda",
"(",
"self",
",",
"chave_cfe",
",",
"dados_cancelamento",
")",
":",
"resp",
"=",
"self",
".",
"_http_post",
"(",
"'cancelarultimavenda'",
",",
"chave_cfe",
"=",
"chave_cfe",
",",
"dados_cancelamento",
"=",
"dados_cancelamento",
".",
... | 51.181818 | 20.545455 |
def get(self, key, value):
"""Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multip... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'id'",
":",
"# Server returns 204 instead of 404 for a non-existent app id",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'app/{}'",
".",
"form... | 32.857143 | 20.485714 |
def parse(cls, querydict):
""" Parse querydict data.
There are expected agruments:
distinct, fields, filter, include, page, sort
Parameters
----------
querydict : django.http.request.QueryDict
MultiValueDict with query arguments.
Returns
... | [
"def",
"parse",
"(",
"cls",
",",
"querydict",
")",
":",
"for",
"key",
"in",
"querydict",
".",
"keys",
"(",
")",
":",
"if",
"not",
"any",
"(",
"(",
"key",
"in",
"JSONAPIQueryDict",
".",
"_fields",
",",
"cls",
".",
"RE_FIELDS",
".",
"match",
"(",
"ke... | 30 | 21.025641 |
def get_execution_engine(name):
"""Get the execution engine by name."""
manager = driver.DriverManager(
namespace='cosmic_ray.execution_engines',
name=name,
invoke_on_load=True,
on_load_failure_callback=_log_extension_loading_failure,
)
return manager.driver | [
"def",
"get_execution_engine",
"(",
"name",
")",
":",
"manager",
"=",
"driver",
".",
"DriverManager",
"(",
"namespace",
"=",
"'cosmic_ray.execution_engines'",
",",
"name",
"=",
"name",
",",
"invoke_on_load",
"=",
"True",
",",
"on_load_failure_callback",
"=",
"_log... | 29.8 | 17.1 |
def uid(self):
"""Return the user id that the process will run as
:rtype: int
"""
if not self._uid:
if self.config.daemon.user:
self._uid = pwd.getpwnam(self.config.daemon.user).pw_uid
else:
self._uid = os.getuid()
return ... | [
"def",
"uid",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_uid",
":",
"if",
"self",
".",
"config",
".",
"daemon",
".",
"user",
":",
"self",
".",
"_uid",
"=",
"pwd",
".",
"getpwnam",
"(",
"self",
".",
"config",
".",
"daemon",
".",
"user",
... | 26.5 | 17.916667 |
def names(self):
"""The names referenced in this code object.
Names come from instructions like LOAD_GLOBAL or STORE_ATTR
where the name of the global or attribute is needed at runtime.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to... | [
"def",
"names",
"(",
"self",
")",
":",
"# We must sort to preserve the order between calls.",
"# The set comprehension is to drop the duplicates.",
"return",
"tuple",
"(",
"sorted",
"(",
"{",
"instr",
".",
"arg",
"for",
"instr",
"in",
"self",
".",
"instrs",
"if",
"ins... | 39.909091 | 20.363636 |
def list(self, request, *args, **kwargs):
"""
Available request parameters:
- ?type=type_of_statistics_objects (required. Have to be from the list: 'customer', 'project')
- ?from=timestamp (default: now - 30 days, for example: 1415910025)
- ?to=timestamp (default: now, for examp... | [
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"CreationTimeStatsView",
",",
"self",
")",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 40.208333 | 26.541667 |
def mel(sr, n_fft, n_mels=128, fmin=0.0, fmax=None, htk=False,
norm=1, dtype=np.float32):
"""Create a Filterbank matrix to combine FFT bins into Mel-frequency bins
Parameters
----------
sr : number > 0 [scalar]
sampling rate of the incoming signal
n_fft : int > 0 [scalar... | [
"def",
"mel",
"(",
"sr",
",",
"n_fft",
",",
"n_mels",
"=",
"128",
",",
"fmin",
"=",
"0.0",
",",
"fmax",
"=",
"None",
",",
"htk",
"=",
"False",
",",
"norm",
"=",
"1",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
":",
"if",
"fmax",
"is",
"None... | 30.403509 | 20.508772 |
def proto_01_12_steps025(abf=exampleABF):
"""IC steps. Use to determine gain function."""
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in ['freq','downslope']:
swhlab.ap.plot_values(abf,feature,continuous=False) #plot AP info
swhlab.plot.save(abf,tag='A_'+feature)
... | [
"def",
"proto_01_12_steps025",
"(",
"abf",
"=",
"exampleABF",
")",
":",
"swhlab",
".",
"ap",
".",
"detect",
"(",
"abf",
")",
"standard_groupingForInj",
"(",
"abf",
",",
"200",
")",
"for",
"feature",
"in",
"[",
"'freq'",
",",
"'downslope'",
"]",
":",
"swh... | 37.181818 | 14.363636 |
def build_key_bundle(key_conf, kid_template=""):
"""
Builds a :py:class:`oidcmsg.key_bundle.KeyBundle` instance based on a key
specification.
An example of such a specification::
keys = [
{"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]},
{"type": "EC", "... | [
"def",
"build_key_bundle",
"(",
"key_conf",
",",
"kid_template",
"=",
"\"\"",
")",
":",
"kid",
"=",
"0",
"tot_kb",
"=",
"KeyBundle",
"(",
")",
"for",
"spec",
"in",
"key_conf",
":",
"typ",
"=",
"spec",
"[",
"\"type\"",
"]",
".",
"upper",
"(",
")",
"if... | 29.24359 | 22.75641 |
def stop_all_tensorboards():
"""Terminate all TensorBoard instances."""
for process in Process.instances:
print("Process '%s', running %d" % (process.command[0],
process.is_running()))
if process.is_running() and process.command[0] == "tensorboard":
... | [
"def",
"stop_all_tensorboards",
"(",
")",
":",
"for",
"process",
"in",
"Process",
".",
"instances",
":",
"print",
"(",
"\"Process '%s', running %d\"",
"%",
"(",
"process",
".",
"command",
"[",
"0",
"]",
",",
"process",
".",
"is_running",
"(",
")",
")",
")"... | 49 | 15 |
def handle_sap(q):
question_votes = votes = Answer.objects.filter(question=q)
users = q.get_users_voted()
num_users_votes = {u.id: votes.filter(user=u).count() for u in users}
user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users}
choices = []
for c in q.choice_set.all().order_by("num")... | [
"def",
"handle_sap",
"(",
"q",
")",
":",
"question_votes",
"=",
"votes",
"=",
"Answer",
".",
"objects",
".",
"filter",
"(",
"question",
"=",
"q",
")",
"users",
"=",
"q",
".",
"get_users_voted",
"(",
")",
"num_users_votes",
"=",
"{",
"u",
".",
"id",
"... | 39.950617 | 23.82716 |
def _setup_crontab():
"""Sets up the crontab if it hasn't already been setup."""
from crontab import CronTab
#Since CI works out of a virtualenv anyway, the `ci.py` script will be
#installed in the bin already, so we can call it explicitly.
command = '/bin/bash -c "source ~/.cron_profile; workon {};... | [
"def",
"_setup_crontab",
"(",
")",
":",
"from",
"crontab",
"import",
"CronTab",
"#Since CI works out of a virtualenv anyway, the `ci.py` script will be",
"#installed in the bin already, so we can call it explicitly.",
"command",
"=",
"'/bin/bash -c \"source ~/.cron_profile; workon {}; ci.p... | 40.054054 | 20.702703 |
def _already_in(self, option):
"""
Check if an option is already in the message.
:type option: Option
:param option: the option to be checked
:return: True if already present, False otherwise
"""
for opt in self._options:
if option.number == opt.numbe... | [
"def",
"_already_in",
"(",
"self",
",",
"option",
")",
":",
"for",
"opt",
"in",
"self",
".",
"_options",
":",
"if",
"option",
".",
"number",
"==",
"opt",
".",
"number",
":",
"return",
"True",
"return",
"False"
] | 30 | 11.833333 |
def enable_disable(self):
"""
Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None
"""
if self.enabled:
self.data['enabled'] = False
else:
self.data['enabled'] = True
self.update() | [
"def",
"enable_disable",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
":",
"self",
".",
"data",
"[",
"'enabled'",
"]",
"=",
"False",
"else",
":",
"self",
".",
"data",
"[",
"'enabled'",
"]",
"=",
"True",
"self",
".",
"update",
"(",
")"
] | 25 | 15.5 |
def _GetSubFileEntries(self):
"""Retrieves sub file entries.
Yields:
ZipFileEntry: a sub file entry.
"""
if self._directory is None:
self._directory = self._GetDirectory()
zip_file = self._file_system.GetZipFile()
if self._directory and zip_file:
for path_spec in self._direct... | [
"def",
"_GetSubFileEntries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_directory",
"is",
"None",
":",
"self",
".",
"_directory",
"=",
"self",
".",
"_GetDirectory",
"(",
")",
"zip_file",
"=",
"self",
".",
"_file_system",
".",
"GetZipFile",
"(",
")",
"if... | 28.208333 | 17.416667 |
def svd(a, compute_uv=True, rcond=None):
""" svd decomposition of matrix ``a`` containing |GVar|\s.
Args:
a: Two-dimensional matrix/array of numbers
and/or :class:`gvar.GVar`\s.
compute_uv (bool): It ``True`` (default), returns
tuple ``(u,s,vT)`` where matrix ``a = u @ n... | [
"def",
"svd",
"(",
"a",
",",
"compute_uv",
"=",
"True",
",",
"rcond",
"=",
"None",
")",
":",
"a",
"=",
"numpy",
".",
"asarray",
"(",
"a",
")",
"if",
"a",
".",
"dtype",
"!=",
"object",
":",
"return",
"numpy",
".",
"linalg",
".",
"svd",
"(",
"a",... | 39.797297 | 18.432432 |
def convert_from_binary(self, binvalue, type, **kwargs):
"""
Convert binary data to type 'type'.
'type' must have a convert_binary function. If 'type'
supports size checking, the size function is called to ensure
that binvalue is the correct size for deserialization
"""... | [
"def",
"convert_from_binary",
"(",
"self",
",",
"binvalue",
",",
"type",
",",
"*",
"*",
"kwargs",
")",
":",
"size",
"=",
"self",
".",
"get_type_size",
"(",
"type",
")",
"if",
"size",
">",
"0",
"and",
"len",
"(",
"binvalue",
")",
"!=",
"size",
":",
... | 42.052632 | 26.578947 |
def edges(inputtiles, parsenames):
"""
For a stream of [<x>, <y>, <z>] tiles, return only those tiles that are on the edge.
"""
try:
inputtiles = click.open_file(inputtiles).readlines()
except IOError:
inputtiles = [inputtiles]
# parse the input stream into an array
tiles = ... | [
"def",
"edges",
"(",
"inputtiles",
",",
"parsenames",
")",
":",
"try",
":",
"inputtiles",
"=",
"click",
".",
"open_file",
"(",
"inputtiles",
")",
".",
"readlines",
"(",
")",
"except",
"IOError",
":",
"inputtiles",
"=",
"[",
"inputtiles",
"]",
"# parse the ... | 28.857143 | 18.857143 |
def GetClientConfig(self, context, validate=True, deploy_timestamp=True):
"""Generates the client config file for inclusion in deployable binaries."""
with utils.TempDirectory() as tmp_dir:
# Make sure we write the file in yaml format.
filename = os.path.join(
tmp_dir,
config.CON... | [
"def",
"GetClientConfig",
"(",
"self",
",",
"context",
",",
"validate",
"=",
"True",
",",
"deploy_timestamp",
"=",
"True",
")",
":",
"with",
"utils",
".",
"TempDirectory",
"(",
")",
"as",
"tmp_dir",
":",
"# Make sure we write the file in yaml format.",
"filename",... | 39.945455 | 20.745455 |
def set_profiling_level(self, level, slow_ms=None, session=None):
"""Set the database's profiling level.
:Parameters:
- `level`: Specifies a profiling level, see list of possible values
below.
- `slow_ms`: Optionally modify the threshold for the profile to
co... | [
"def",
"set_profiling_level",
"(",
"self",
",",
"level",
",",
"slow_ms",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
"or",
"level",
"<",
"0",
"or",
"level",
">",
"2",
":",
"raise",
"... | 45.255814 | 26.255814 |
def garbage_cycle(index):
"""Get reference cycle details."""
graph = _compute_garbage_graphs()[int(index)]
graph.reduce_to_cycles()
objects = graph.metadata
objects.sort(key=lambda x: -x.size)
return dict(objects=objects, index=index) | [
"def",
"garbage_cycle",
"(",
"index",
")",
":",
"graph",
"=",
"_compute_garbage_graphs",
"(",
")",
"[",
"int",
"(",
"index",
")",
"]",
"graph",
".",
"reduce_to_cycles",
"(",
")",
"objects",
"=",
"graph",
".",
"metadata",
"objects",
".",
"sort",
"(",
"key... | 36 | 7.714286 |
def parse_afterqc_log(self, f):
""" Parse the JSON output from AfterQC and save the summary statistics """
try:
parsed_json = json.load(f['f'])
except:
log.warn("Could not parse AfterQC JSON: '{}'".format(f['fn']))
return None
# AfterQC changed the na... | [
"def",
"parse_afterqc_log",
"(",
"self",
",",
"f",
")",
":",
"try",
":",
"parsed_json",
"=",
"json",
".",
"load",
"(",
"f",
"[",
"'f'",
"]",
")",
"except",
":",
"log",
".",
"warn",
"(",
"\"Could not parse AfterQC JSON: '{}'\"",
".",
"format",
"(",
"f",
... | 41.827586 | 23.344828 |
def orthorhombic(a: float, b: float, c: float):
"""
Convenience constructor for an orthorhombic lattice.
Args:
a (float): *a* lattice parameter of the orthorhombic cell.
b (float): *b* lattice parameter of the orthorhombic cell.
c (float): *c* lattice paramet... | [
"def",
"orthorhombic",
"(",
"a",
":",
"float",
",",
"b",
":",
"float",
",",
"c",
":",
"float",
")",
":",
"return",
"Lattice",
".",
"from_parameters",
"(",
"a",
",",
"b",
",",
"c",
",",
"90",
",",
"90",
",",
"90",
")"
] | 37.230769 | 21.846154 |
def download(self, local_port_path, key_names): # pragma: no cover
"""
download all files from a users account location
:param local_port_path: the local path where the data is to download to
:param key_name: can start with self.prefix or taken as relative to prefix.
Example:
... | [
"def",
"download",
"(",
"self",
",",
"local_port_path",
",",
"key_names",
")",
":",
"# pragma: no cover",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"local_port_path",
")",
":",
"raise",
"ValueError",
"(",
"\"Download path does not exist: %s\"",
"%",
"lo... | 42.822222 | 21.311111 |
def tracebacks_from_file(fileobj, reverse=False):
"""Generator that yields tracebacks found in a file object
With reverse=True, searches backwards from the end of the file.
"""
if reverse:
lines = deque()
for line in BackwardsReader(fileobj):
lines.appendleft(line)
... | [
"def",
"tracebacks_from_file",
"(",
"fileobj",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"reverse",
":",
"lines",
"=",
"deque",
"(",
")",
"for",
"line",
"in",
"BackwardsReader",
"(",
"fileobj",
")",
":",
"lines",
".",
"appendleft",
"(",
"line",
")",
... | 30 | 17.941176 |
def add_license(service_instance, key, description, license_manager=None):
'''
Adds a license.
service_instance
The Service Instance Object.
key
The key of the license to add.
description
The description of the license to add.
license_manager
The License Manag... | [
"def",
"add_license",
"(",
"service_instance",
",",
"key",
",",
"description",
",",
"license_manager",
"=",
"None",
")",
":",
"if",
"not",
"license_manager",
":",
"license_manager",
"=",
"get_license_manager",
"(",
"service_instance",
")",
"label",
"=",
"vim",
"... | 31.702703 | 18.72973 |
def local_attention1d_spatial_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
"""Image Transformer decoder with local1D spatial layers."""
batch_dim, length_dim, model_dim = x.shape.dims
blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length)
num_w_blocks_dim... | [
"def",
"local_attention1d_spatial_decoder",
"(",
"x",
",",
"kv_dim",
",",
"heads_dim",
",",
"feedforward_dim",
",",
"hparams",
")",
":",
"batch_dim",
",",
"length_dim",
",",
"model_dim",
"=",
"x",
".",
"shape",
".",
"dims",
"blocks_w_dim",
"=",
"mtf",
".",
"... | 44.40625 | 15.59375 |
def psd(data, dt, ndivide=1, window=hanning, overlap_half=False):
"""Calculate power spectrum density of data.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
ax (m... | [
"def",
"psd",
"(",
"data",
",",
"dt",
",",
"ndivide",
"=",
"1",
",",
"window",
"=",
"hanning",
",",
"overlap_half",
"=",
"False",
")",
":",
"logger",
"=",
"getLogger",
"(",
"'decode.utils.ndarray.psd'",
")",
"if",
"overlap_half",
":",
"step",
"=",
"int",... | 33.795918 | 20.265306 |
def set_conditions(self, variables, constraints):
"""Problem provided data.
variables = {variable-name: list-of-domain-values}
constraints = [(constraint_function, variable-names, default-variable-values)]
"""
self._vars, self._constraints = variables, []
# build constra... | [
"def",
"set_conditions",
"(",
"self",
",",
"variables",
",",
"constraints",
")",
":",
"self",
".",
"_vars",
",",
"self",
".",
"_constraints",
"=",
"variables",
",",
"[",
"]",
"# build constraint objects",
"for",
"func",
",",
"variables",
",",
"values",
"in",... | 44.615385 | 15.846154 |
def _collapse_edge_passing_predicates(graph: BELGraph, edge_predicates: EdgePredicates = None) -> None:
"""Collapse all edges passing the given edge predicates."""
for u, v, _ in filter_edges(graph, edge_predicates=edge_predicates):
collapse_pair(graph, survivor=u, victim=v) | [
"def",
"_collapse_edge_passing_predicates",
"(",
"graph",
":",
"BELGraph",
",",
"edge_predicates",
":",
"EdgePredicates",
"=",
"None",
")",
"->",
"None",
":",
"for",
"u",
",",
"v",
",",
"_",
"in",
"filter_edges",
"(",
"graph",
",",
"edge_predicates",
"=",
"e... | 72 | 26.25 |
def is_in_intervall(value, min_value, max_value, name='variable'):
"""
Raise an exception if value is not in an interval.
Parameters
----------
value : orderable
min_value : orderable
max_value : orderable
name : str
Name of the variable to print in exception.
"""
if not... | [
"def",
"is_in_intervall",
"(",
"value",
",",
"min_value",
",",
"max_value",
",",
"name",
"=",
"'variable'",
")",
":",
"if",
"not",
"(",
"min_value",
"<=",
"value",
"<=",
"max_value",
")",
":",
"raise",
"ValueError",
"(",
"'{}={} is not in [{}, {}]'",
".",
"f... | 30.8 | 17.466667 |
def which_roles_can(self, name):
"""Which role can SendMail? """
targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first()
return [{'role': group.role} for group in targetPermissionRecords.groups] | [
"def",
"which_roles_can",
"(",
"self",
",",
"name",
")",
":",
"targetPermissionRecords",
"=",
"AuthPermission",
".",
"objects",
"(",
"creator",
"=",
"self",
".",
"client",
",",
"name",
"=",
"name",
")",
".",
"first",
"(",
")",
"return",
"[",
"{",
"'role'... | 62 | 26.25 |
def check_label_shape(self, label_shape):
"""Checks if the new label shape is valid"""
if not len(label_shape) == 2:
raise ValueError('label_shape should have length 2')
if label_shape[0] < self.label_shape[0]:
msg = 'Attempts to reduce label count from %d to %d, not allo... | [
"def",
"check_label_shape",
"(",
"self",
",",
"label_shape",
")",
":",
"if",
"not",
"len",
"(",
"label_shape",
")",
"==",
"2",
":",
"raise",
"ValueError",
"(",
"'label_shape should have length 2'",
")",
"if",
"label_shape",
"[",
"0",
"]",
"<",
"self",
".",
... | 52.75 | 14.583333 |
def read_and_redirect(request, notification_id):
"""
Marks the supplied notification as read and then redirects
to the supplied URL from the ``next`` URL parameter.
**IMPORTANT**: This is CSRF - unsafe method.
Only use it if its okay for you to mark notifications \
as read without a robust chec... | [
"def",
"read_and_redirect",
"(",
"request",
",",
"notification_id",
")",
":",
"notification_page",
"=",
"reverse",
"(",
"'notifications:all'",
")",
"next_page",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"notification_page",
")",
"if",
"is_safe_... | 31.827586 | 18.103448 |
def get_query(query_name):
"""Find file matching query_name, read and return query object
"""
query_file_match = list(
filter(lambda i: query_name == i.stem, FLAT_QUERIES))
if not query_file_match:
return None
# TODO: Log warning if more than one match
query_file = query_file_mat... | [
"def",
"get_query",
"(",
"query_name",
")",
":",
"query_file_match",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"i",
":",
"query_name",
"==",
"i",
".",
"stem",
",",
"FLAT_QUERIES",
")",
")",
"if",
"not",
"query_file_match",
":",
"return",
"None",
"# TODO: ... | 33.238095 | 11.857143 |
def jenkins(self):
"""Generate jenkins job details."""
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job | [
"def",
"jenkins",
"(",
"self",
")",
":",
"job_name",
"=",
"self",
".",
"format",
"[",
"'jenkins_job_name'",
"]",
".",
"format",
"(",
"*",
"*",
"self",
".",
"data",
")",
"job",
"=",
"{",
"'name'",
":",
"job_name",
"}",
"return",
"job"
] | 30.166667 | 20.333333 |
def _get_elements(complex_type, root):
"""Get attribute elements
"""
found_elements = []
element = findall(root, '{%s}complexType' % XS_NAMESPACE,
attribute_name='name', attribute_value=complex_type)[0]
found_elements = findall(element, '{%s}element' % XS_NAMESPACE)
retu... | [
"def",
"_get_elements",
"(",
"complex_type",
",",
"root",
")",
":",
"found_elements",
"=",
"[",
"]",
"element",
"=",
"findall",
"(",
"root",
",",
"'{%s}complexType'",
"%",
"XS_NAMESPACE",
",",
"attribute_name",
"=",
"'name'",
",",
"attribute_value",
"=",
"comp... | 32.8 | 20 |
def data_filler_user_agent(self, number_of_rows, db):
'''creates and fills the table with user agent data
'''
try:
user_agent = db
data_list = list()
for i in range(0, number_of_rows):
post_uo_reg = {
"id": rnd_id_generator... | [
"def",
"data_filler_user_agent",
"(",
"self",
",",
"number_of_rows",
",",
"db",
")",
":",
"try",
":",
"user_agent",
"=",
"db",
"data_list",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number_of_rows",
")",
":",
"post_uo_reg",
"=",
... | 34.571429 | 16.952381 |
def exists(self):
"""Check whether the AppProfile already exists.
:rtype: bool
:returns: True if the AppProfile exists, else False.
"""
try:
self.instance_admin_client.get_app_profile(self.name)
return True
# NOTE: There could be other exceptions ... | [
"def",
"exists",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"instance_admin_client",
".",
"get_app_profile",
"(",
"self",
".",
"name",
")",
"return",
"True",
"# NOTE: There could be other exceptions that are returned to the user.",
"except",
"NotFound",
":",
"ret... | 32.416667 | 20.25 |
def list(self, **params):
"""
Retrieve all notes
Returns all notes available to the user, according to the parameters provided
:calls: ``get /notes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which ... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"notes",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/notes\"",
",",
"params",
"=",
"params",
")",
"return",
"notes"
] | 32.857143 | 25.428571 |
def __frontend_limit_rules_descriptor(self, api_info):
"""Builds a frontend limit rules descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A list of dictionaries with frontend limit rules information.
"""
if not api_info.frontend_limits.rules:
return None
... | [
"def",
"__frontend_limit_rules_descriptor",
"(",
"self",
",",
"api_info",
")",
":",
"if",
"not",
"api_info",
".",
"frontend_limits",
".",
"rules",
":",
"return",
"None",
"rules",
"=",
"[",
"]",
"for",
"rule",
"in",
"api_info",
".",
"frontend_limits",
".",
"r... | 32.038462 | 18.923077 |
def install(name=None,
refresh=False,
sysupgrade=None,
pkgs=None,
sources=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which mod... | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"sysupgrade",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pkg_params",
",",
"pkg_type",
"=",
"__s... | 35.609375 | 23.317708 |
def shift_by_n_processors(self, x, mesh_axis, offset, wrap):
"""Receive the slice from processor pcoord - offset.
Args:
x: a LaidOutTensor
mesh_axis: an integer
offset: an integer
wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
"""
n = self.shape[mesh_axis... | [
"def",
"shift_by_n_processors",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"offset",
",",
"wrap",
")",
":",
"n",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"source_pcoord",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"n",
... | 27.45 | 18.5 |
def get_http_method_arg_name(self):
"""
Return the HTTP function to call and the params/data argument name
"""
if self.method == 'get':
arg_name = 'params'
else:
arg_name = 'data'
return getattr(requests, self.method), arg_name | [
"def",
"get_http_method_arg_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"'get'",
":",
"arg_name",
"=",
"'params'",
"else",
":",
"arg_name",
"=",
"'data'",
"return",
"getattr",
"(",
"requests",
",",
"self",
".",
"method",
")",
",",
"a... | 32.333333 | 12.111111 |
def update_job_libraries(
logger,
job_list,
match,
new_library_path,
token,
host,
):
"""
update libraries on jobs using same major version
Parameters
----------
logger: logging object
configured in cli_commands.py
job_list: list of strings
output of get_j... | [
"def",
"update_job_libraries",
"(",
"logger",
",",
"job_list",
",",
"match",
",",
"new_library_path",
",",
"token",
",",
"host",
",",
")",
":",
"for",
"job",
"in",
"job_list",
":",
"get_res",
"=",
"requests",
".",
"get",
"(",
"host",
"+",
"'/api/2.0/jobs/g... | 30.564516 | 16.306452 |
def chunks(raw):
"""Yield successive EVENT_SIZE sized chunks from raw."""
for i in range(0, len(raw), EVENT_SIZE):
yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_SIZE]) | [
"def",
"chunks",
"(",
"raw",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"raw",
")",
",",
"EVENT_SIZE",
")",
":",
"yield",
"struct",
".",
"unpack",
"(",
"EVENT_FORMAT",
",",
"raw",
"[",
"i",
":",
"i",
"+",
"EVENT_SIZE",
"]",
... | 45.5 | 12.5 |
def identification_field_factory(label, error_required):
"""
A simple identification field factory which enable you to set the label.
:param label:
String containing the label for this field.
:param error_required:
String containing the error message if the field is left empty.
""... | [
"def",
"identification_field_factory",
"(",
"label",
",",
"error_required",
")",
":",
"return",
"forms",
".",
"CharField",
"(",
"label",
"=",
"label",
",",
"widget",
"=",
"forms",
".",
"TextInput",
"(",
"attrs",
"=",
"attrs_dict",
")",
",",
"max_length",
"="... | 35.333333 | 20.8 |
def training_data(self):
""" Returns data dictionary from training.pkl """
data = pickle.load(open(os.path.join(self.repopath, 'training.pkl')))
return data.keys(), data.values() | [
"def",
"training_data",
"(",
"self",
")",
":",
"data",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"repopath",
",",
"'training.pkl'",
")",
")",
")",
"return",
"data",
".",
"keys",
"(",
")",
",",
... | 39.8 | 18.8 |
def newDocTextLen(self, content, len):
"""Creation of a new text node with an extra content length
parameter. The text node pertain to a given document. """
ret = libxml2mod.xmlNewDocTextLen(self._o, content, len)
if ret is None:raise treeError('xmlNewDocTextLen() failed')
__t... | [
"def",
"newDocTextLen",
"(",
"self",
",",
"content",
",",
"len",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewDocTextLen",
"(",
"self",
".",
"_o",
",",
"content",
",",
"len",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewDo... | 51 | 11.428571 |
def ekm_log(logstr, priority=3):
""" Send string to module level log
Args:
logstr (str): string to print.
priority (int): priority, supports 3 (default) and 4 (special).
"""
if priority <= ekmmeters_log_level:
dt = datetime.datetime
stamp = datetime.datetime.now().strfti... | [
"def",
"ekm_log",
"(",
"logstr",
",",
"priority",
"=",
"3",
")",
":",
"if",
"priority",
"<=",
"ekmmeters_log_level",
":",
"dt",
"=",
"datetime",
".",
"datetime",
"stamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"... | 35.416667 | 18.916667 |
def print_stat(x, message=None):
""" A simple print Op that might be easier to use than :meth:`tf.Print`.
Use it like: ``x = print_stat(x, message='This is x')``.
"""
if message is None:
message = x.op.name
lst = [tf.shape(x), tf.reduce_mean(x)]
if x.dtype.is_floating:
lst.ap... | [
"def",
"print_stat",
"(",
"x",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"x",
".",
"op",
".",
"name",
"lst",
"=",
"[",
"tf",
".",
"shape",
"(",
"x",
")",
",",
"tf",
".",
"reduce_mean",
"(",
"x",
... | 39.454545 | 11 |
def encode_params(self, data=None, **kwargs):
"""
Build the body for a text/plain request.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
... | [
"def",
"encode_params",
"(",
"self",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"charset",
"=",
"kwargs",
".",
"get",
"(",
"\"charset\"",
",",
"self",
".",
"charset",
")",
"collection_format",
"=",
"kwargs",
".",
"get",
"(",
"\"collec... | 49.2 | 23.511111 |
def get_favorite_radio_stations(self, *args, **kwargs):
"""Convenience method for `get_music_library_information`
with ``search_type='radio_stations'``. For details of other arguments,
see `that method
<#soco.music_library.MusicLibrary.get_music_library_information>`_.
"""
... | [
"def",
"get_favorite_radio_stations",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"tuple",
"(",
"[",
"'radio_stations'",
"]",
"+",
"list",
"(",
"args",
")",
")",
"return",
"self",
".",
"get_music_library_information",
"("... | 53.375 | 17.875 |
def calc_multi_exp_unc(sys_unc, n, mean, std, dof, confidence=0.95):
"""Calculate expanded uncertainty using values from multiple runs.
Note that this function assumes the statistic is a mean value, therefore
the combined standard deviation is divided by `sqrt(N)`.
Parameters
----------
... | [
"def",
"calc_multi_exp_unc",
"(",
"sys_unc",
",",
"n",
",",
"mean",
",",
"std",
",",
"dof",
",",
"confidence",
"=",
"0.95",
")",
":",
"sys_unc",
"=",
"sys_unc",
".",
"mean",
"(",
")",
"std_combined",
"=",
"combine_std",
"(",
"n",
",",
"mean",
",",
"s... | 41.409091 | 17.363636 |
def send_capabilties_request(self, vehicle, name, m):
'''An alias for send_capabilities_request.
The word "capabilities" was misspelled in previous versions of this code. This is simply
an alias to send_capabilities_request using the legacy name.
'''
return self.send_capabilitie... | [
"def",
"send_capabilties_request",
"(",
"self",
",",
"vehicle",
",",
"name",
",",
"m",
")",
":",
"return",
"self",
".",
"send_capabilities_request",
"(",
"vehicle",
",",
"name",
",",
"m",
")"
] | 48.714286 | 28.428571 |
def _extract_units(self, obj, value):
''' Internal helper for dealing with units associated units properties
when setting values on |UnitsSpec| properties.
When ``value`` is a dict, this function may mutate the value of the
associated units property.
Args:
obj (HasP... | [
"def",
"_extract_units",
"(",
"self",
",",
"obj",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"'units'",
"in",
"value",
":",
"value",
"=",
"copy",
"(",
"value",
")",
"# so we can modify it",
"units",
"=",
"val... | 35.043478 | 22.782609 |
def _select_ftdi_channel(channel):
"""Select multiplexer channel. Currently uses a FTDI chip via pylibftdi"""
if channel < 0 or channel > 8:
raise ArgumentError("FTDI-selected multiplexer only has channels 0-7 valid, "
"make sure you specify channel with -c channel=number", c... | [
"def",
"_select_ftdi_channel",
"(",
"channel",
")",
":",
"if",
"channel",
"<",
"0",
"or",
"channel",
">",
"8",
":",
"raise",
"ArgumentError",
"(",
"\"FTDI-selected multiplexer only has channels 0-7 valid, \"",
"\"make sure you specify channel with -c channel=number\"",
",",
... | 50.666667 | 17.111111 |
def _mse_converged(self):
"""Check convergence based on mean squared error
Returns
-------
converged : boolean
Whether the parameter estimation converged.
mse : float
Mean squared error between prior and posterior.
"""
mse = mean_squar... | [
"def",
"_mse_converged",
"(",
"self",
")",
":",
"mse",
"=",
"mean_squared_error",
"(",
"self",
".",
"local_prior",
",",
"self",
".",
"local_posterior_",
",",
"multioutput",
"=",
"'uniform_average'",
")",
"if",
"mse",
">",
"self",
".",
"threshold",
":",
"retu... | 26 | 22.35 |
def _get_ami_dict(json_url):
"""Get ami from a web url.
Args:
region (str): AWS Region to find AMI ID.
Returns:
dict: Contents in dictionary format.
"""
LOG.info("Getting AMI from %s", json_url)
response = requests.get(json_url)
assert response.ok, "Error getting ami info ... | [
"def",
"_get_ami_dict",
"(",
"json_url",
")",
":",
"LOG",
".",
"info",
"(",
"\"Getting AMI from %s\"",
",",
"json_url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"json_url",
")",
"assert",
"response",
".",
"ok",
",",
"\"Error getting ami info from {}\""... | 26.875 | 17.6875 |
def off_coordinator(self, year):
"""Returns the coach ID for the team's OC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the OC.
"""
try:
oc_anchor = self._year_info_pq(year, 'Offensive Coordinator')('a')
... | [
"def",
"off_coordinator",
"(",
"self",
",",
"year",
")",
":",
"try",
":",
"oc_anchor",
"=",
"self",
".",
"_year_info_pq",
"(",
"year",
",",
"'Offensive Coordinator'",
")",
"(",
"'a'",
")",
"if",
"oc_anchor",
":",
"return",
"oc_anchor",
".",
"attr",
"[",
... | 35.25 | 15.833333 |
def order_queryset(self, queryset):
"""
Orders the passed in queryset, returning a new queryset in response. By default uses the _order query
parameter.
"""
order = self.derive_ordering()
# if we get our order from the request
# make sure it is a valid field in ... | [
"def",
"order_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"order",
"=",
"self",
".",
"derive_ordering",
"(",
")",
"# if we get our order from the request",
"# make sure it is a valid field in the list",
"if",
"'_order'",
"in",
"self",
".",
"request",
".",
"GET"... | 32.285714 | 18.952381 |
def start(self):
"""Start websocket connection."""
if self.state != STATE_RUNNING:
conn = self.loop.create_connection(
lambda: self, self.host, self.port)
task = self.loop.create_task(conn)
task.add_done_callback(self.init_done)
self.state ... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"!=",
"STATE_RUNNING",
":",
"conn",
"=",
"self",
".",
"loop",
".",
"create_connection",
"(",
"lambda",
":",
"self",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"task",
... | 41.125 | 7.5 |
def has_printout(
state, index, not_printed_msg=None, pre_code=None, name=None, copy=False
):
"""Check if the right printouts happened.
``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
the solution proce... | [
"def",
"has_printout",
"(",
"state",
",",
"index",
",",
"not_printed_msg",
"=",
"None",
",",
"pre_code",
"=",
"None",
",",
"name",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"extra_msg",
"=",
"\"If you want to check printouts done in e.g. a for loop, you ha... | 36.840336 | 32.10084 |
def _get_request_content(self, message=None):
'''Updates message with default message paramaters.
:param message: Postmark message data
:type message: `dict`
:rtype: JSON encoded `unicode`
'''
message = self._cast_message(message=message)
return message.json() | [
"def",
"_get_request_content",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"message",
"=",
"self",
".",
"_cast_message",
"(",
"message",
"=",
"message",
")",
"return",
"message",
".",
"json",
"(",
")"
] | 34.333333 | 15 |
def _execute_and_seal_error(method, arg, method_name):
"""Execute method with arg and return the result.
If the method fails, return a RayTaskError so it can be sealed in the
resultOID and retried by user.
"""
try:
return method(arg)
except Exception:
return ray.worker.RayTaskEr... | [
"def",
"_execute_and_seal_error",
"(",
"method",
",",
"arg",
",",
"method_name",
")",
":",
"try",
":",
"return",
"method",
"(",
"arg",
")",
"except",
"Exception",
":",
"return",
"ray",
".",
"worker",
".",
"RayTaskError",
"(",
"method_name",
",",
"traceback",... | 35.1 | 19.3 |
def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"if",
"not",
"self",
".",
"done",
"(",
")",
":",
"raise",
"TransferNotDoneError",
"(",
"'set_exception can only be called once the transfer is '",
"'complete.'",
")",
"self",
".",
"_coordinator",
".",
... | 44.714286 | 12.571429 |
def hasColumn(self, column, recurse=True, flags=0):
"""
Returns whether or not this column exists within the list of columns
for this schema.
:return <bool>
"""
return column in self.columns(recurse=recurse, flags=flags) | [
"def",
"hasColumn",
"(",
"self",
",",
"column",
",",
"recurse",
"=",
"True",
",",
"flags",
"=",
"0",
")",
":",
"return",
"column",
"in",
"self",
".",
"columns",
"(",
"recurse",
"=",
"recurse",
",",
"flags",
"=",
"flags",
")"
] | 34.25 | 17 |
def cee_map_remap_lossless_priority_lossless_remapped_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name... | [
"def",
"cee_map_remap_lossless_priority_lossless_remapped_priority",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"cee_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"cee-map\"",
",",
"... | 52.071429 | 22.285714 |
def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
super(HTTPSConnectionPool, self)._validate_conn(conn)
# Force connect early to allow us to validate the connection.
if not getattr(conn, 'sock', None): # AppEngin... | [
"def",
"_validate_conn",
"(",
"self",
",",
"conn",
")",
":",
"super",
"(",
"HTTPSConnectionPool",
",",
"self",
")",
".",
"_validate_conn",
"(",
"conn",
")",
"# Force connect early to allow us to validate the connection.",
"if",
"not",
"getattr",
"(",
"conn",
",",
... | 41.9375 | 21.1875 |
def get(self,dimlist):
'''
get dimensions
:parameter dimlist: list of dimensions
'''
out=()
for i,d in enumerate(dimlist):
out+=(super(dimStr, self).get(d,None),)
return out | [
"def",
"get",
"(",
"self",
",",
"dimlist",
")",
":",
"out",
"=",
"(",
")",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"dimlist",
")",
":",
"out",
"+=",
"(",
"super",
"(",
"dimStr",
",",
"self",
")",
".",
"get",
"(",
"d",
",",
"None",
")",
... | 25.1 | 18.7 |
def start(debug=False, host='127.0.0.1'):
""" starts a nago agent (daemon) process """
if debug:
debug = True
nago.protocols.httpserver.app.run(debug=debug, host=host) | [
"def",
"start",
"(",
"debug",
"=",
"False",
",",
"host",
"=",
"'127.0.0.1'",
")",
":",
"if",
"debug",
":",
"debug",
"=",
"True",
"nago",
".",
"protocols",
".",
"httpserver",
".",
"app",
".",
"run",
"(",
"debug",
"=",
"debug",
",",
"host",
"=",
"hos... | 36.6 | 13.8 |
def Residual(*layers, **kwargs):
"""Constructs a residual version of layers, summing input to layers output."""
shortcut = kwargs.get('shortcut', Identity()) # pylint: disable=no-value-for-parameter
if len(layers) > 1:
return Serial(
Branch(), # pylint: disable=no-value-for-parameter
Paralle... | [
"def",
"Residual",
"(",
"*",
"layers",
",",
"*",
"*",
"kwargs",
")",
":",
"shortcut",
"=",
"kwargs",
".",
"get",
"(",
"'shortcut'",
",",
"Identity",
"(",
")",
")",
"# pylint: disable=no-value-for-parameter",
"if",
"len",
"(",
"layers",
")",
">",
"1",
":"... | 39.705882 | 19.941176 |
def protocolise(url):
"""
Given a URL, check to see if there is an assocaited protocol.
If not, set the protocol to HTTP and return the protocolised URL
"""
# Use the regex to match http//localhost/something
protore = re.compile(r'https?:{0,1}/{1,2}')
parsed = urlparse.urlparse(url)
if ... | [
"def",
"protocolise",
"(",
"url",
")",
":",
"# Use the regex to match http//localhost/something",
"protore",
"=",
"re",
".",
"compile",
"(",
"r'https?:{0,1}/{1,2}'",
")",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"s... | 34.083333 | 14.916667 |
def WriteVcard(filename, vcard, fopen=codecs.open):
"""Writes a vCard into the given filename."""
if os.access(filename, os.F_OK):
logger.warning('File exists at "{}", skipping.'.format(filename))
return False
try:
with fopen(filename, 'w', encoding='utf-8') as f:
logger.... | [
"def",
"WriteVcard",
"(",
"filename",
",",
"vcard",
",",
"fopen",
"=",
"codecs",
".",
"open",
")",
":",
"if",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"F_OK",
")",
":",
"logger",
".",
"warning",
"(",
"'File exists at \"{}\", skipping.'",
"."... | 42.230769 | 20.307692 |
def start(self):
"""
Starts the TCP server.
:return: Method success.
:rtype: bool
"""
if self.__online:
raise foundations.exceptions.ServerOperationError(
"{0} | '{1}' TCP Server is already online!".format(self.__class__.__name__, self))
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"__online",
":",
"raise",
"foundations",
".",
"exceptions",
".",
"ServerOperationError",
"(",
"\"{0} | '{1}' TCP Server is already online!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
... | 42.068966 | 26.206897 |
def _name_to_index(self, channels):
"""
Return the channel indices for the specified channel names.
Integers contained in `channel` are returned unmodified, if they
are within the range of ``self.channels``.
Parameters
----------
channels : int or str or list of... | [
"def",
"_name_to_index",
"(",
"self",
",",
"channels",
")",
":",
"# Check if list, then run recursively",
"if",
"hasattr",
"(",
"channels",
",",
"'__iter__'",
")",
"and",
"not",
"isinstance",
"(",
"channels",
",",
"six",
".",
"string_types",
")",
":",
"return",
... | 34.634146 | 19.463415 |
def get_backbuffer_size(self):
"""Get the width and height of the backbuffer as a Vector2."""
vec = Vector2()
vec.X = self.backbuffer.get_width()
vec.Y = self.backbuffer.get_height()
return vec | [
"def",
"get_backbuffer_size",
"(",
"self",
")",
":",
"vec",
"=",
"Vector2",
"(",
")",
"vec",
".",
"X",
"=",
"self",
".",
"backbuffer",
".",
"get_width",
"(",
")",
"vec",
".",
"Y",
"=",
"self",
".",
"backbuffer",
".",
"get_height",
"(",
")",
"return",... | 38 | 9.333333 |
def from_json(self, json_data):
"""
Load JSON data into this Task
"""
try:
data = json_data.decode()
except Exception:
data = json_data
self.__dict__ = json.loads(data) | [
"def",
"from_json",
"(",
"self",
",",
"json_data",
")",
":",
"try",
":",
"data",
"=",
"json_data",
".",
"decode",
"(",
")",
"except",
"Exception",
":",
"data",
"=",
"json_data",
"self",
".",
"__dict__",
"=",
"json",
".",
"loads",
"(",
"data",
")"
] | 25.777778 | 7.777778 |
def use_federated_objective_bank_view(self):
"""Pass through to provider ObjectiveLookupSession.use_federated_objective_bank_view"""
self._objective_bank_view = FEDERATED
# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked
for session in self._g... | [
"def",
"use_federated_objective_bank_view",
"(",
"self",
")",
":",
"self",
".",
"_objective_bank_view",
"=",
"FEDERATED",
"# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",... | 52 | 17 |
def add_intersecting(self, division, intersection=None, symm=True):
"""
Adds paired relationships between intersecting divisions.
Optional intersection represents the portion of the area of the related
division intersecting this division. You can only specify an
intersection on ... | [
"def",
"add_intersecting",
"(",
"self",
",",
"division",
",",
"intersection",
"=",
"None",
",",
"symm",
"=",
"True",
")",
":",
"relationship",
",",
"created",
"=",
"IntersectRelationship",
".",
"objects",
".",
"update_or_create",
"(",
"from_division",
"=",
"se... | 42.25 | 21.375 |
def init_structure(self, total_num_bonds, total_num_atoms,
total_num_groups, total_num_chains, total_num_models,
structure_id):
"""Initialise the structure object.
:param total_num_bonds: the number of bonds in the structure
:param total_num_atoms: t... | [
"def",
"init_structure",
"(",
"self",
",",
"total_num_bonds",
",",
"total_num_atoms",
",",
"total_num_groups",
",",
"total_num_chains",
",",
"total_num_models",
",",
"structure_id",
")",
":",
"self",
".",
"mmtf_version",
"=",
"constants",
".",
"MMTF_VERSION",
"self"... | 40.619048 | 10.619048 |
def cget(self, key):
"""
Query widget option.
:param key: option name
:type key: str
:return: value of the option
To get the list of options for this widget, call the method :meth:`~Balloon.keys`.
"""
if key == "headertext":
return self.__hea... | [
"def",
"cget",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"==",
"\"headertext\"",
":",
"return",
"self",
".",
"__headertext",
"elif",
"key",
"==",
"\"text\"",
":",
"return",
"self",
".",
"__text",
"elif",
"key",
"==",
"\"width\"",
":",
"return",
"... | 28.181818 | 14.090909 |
def ensure_berksfile_cookbooks_are_installed():
"""Run 'berks vendor' to berksfile cookbooks directory"""
msg = "Vendoring cookbooks from Berksfile {0} to directory {1}..."
print(msg.format(env.berksfile, env.berksfile_cookbooks_directory))
run_vendor = True
cookbooks_dir = env.berksfile_cookbooks_... | [
"def",
"ensure_berksfile_cookbooks_are_installed",
"(",
")",
":",
"msg",
"=",
"\"Vendoring cookbooks from Berksfile {0} to directory {1}...\"",
"print",
"(",
"msg",
".",
"format",
"(",
"env",
".",
"berksfile",
",",
"env",
".",
"berksfile_cookbooks_directory",
")",
")",
... | 41.962963 | 20.296296 |
def _process_fields(self):
"""Default info massage to appropiate format/style.
This processing is called on preprocess and postprocess, AKA
before and after conversion of fields to appropiate
format/style.
Perfect example: custom fields on certain objects is a mess
(IMH... | [
"def",
"_process_fields",
"(",
"self",
")",
":",
"try",
":",
"try",
":",
"if",
"self",
".",
"has_key",
"(",
"self",
".",
"customFieldName",
")",
":",
"self",
"[",
"self",
".",
"customFieldName",
"]",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
"[",
"s... | 46.275862 | 24.275862 |
def _make_request_data(self, teststep_dict, entry_json):
""" parse HAR entry request data, and make teststep request data
Args:
entry_json (dict):
{
"request": {
"method": "POST",
"postData": {
... | [
"def",
"_make_request_data",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"method",
"=",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"method\"",
")",
"if",
"method",
"in",
"[",
"\"POST\"",
",",
"\"PUT\"",
",",
"\"PATCH\"",
... | 34.912281 | 18.754386 |
def azimintpix(data, dataerr, bcx, bcy, mask=None, Ntheta=100, pixmin=0,
pixmax=np.inf, returnmask=False, errorpropagation=2):
"""Azimuthal integration (averaging) on the detector plane
Inputs:
data: scattering pattern matrix (np.ndarray, dtype: np.double)
dataerr: error matrix (... | [
"def",
"azimintpix",
"(",
"data",
",",
"dataerr",
",",
"bcx",
",",
"bcy",
",",
"mask",
"=",
"None",
",",
"Ntheta",
"=",
"100",
",",
"pixmin",
"=",
"0",
",",
"pixmax",
"=",
"np",
".",
"inf",
",",
"returnmask",
"=",
"False",
",",
"errorpropagation",
... | 44.448276 | 16.206897 |
def fix_flags(self, flags):
"""Fixes standard TensorBoard CLI flags to parser."""
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
if flags.logdir and flags.event_file:
raise FlagsError(
'Must specify either --logdir or --event_file, but n... | [
"def",
"fix_flags",
"(",
"self",
",",
"flags",
")",
":",
"FlagsError",
"=",
"base_plugin",
".",
"FlagsError",
"if",
"flags",
".",
"version_tb",
":",
"pass",
"elif",
"flags",
".",
"inspect",
":",
"if",
"flags",
".",
"logdir",
"and",
"flags",
".",
"event_f... | 44.947368 | 18.052632 |
def set_inasafe_default_value_qsetting(
qsetting, category, inasafe_field_key, value):
"""Helper method to set inasafe default value to qsetting.
:param qsetting: QSettings.
:type qsetting: QSettings
:param category: Category of the default value. It can be global or
recent. Global mea... | [
"def",
"set_inasafe_default_value_qsetting",
"(",
"qsetting",
",",
"category",
",",
"inasafe_field_key",
",",
"value",
")",
":",
"key",
"=",
"'inasafe/default_value/%s/%s'",
"%",
"(",
"category",
",",
"inasafe_field_key",
")",
"qsetting",
".",
"setValue",
"(",
"key"... | 35.95 | 19.1 |
def listDatasetArray(self, **kwargs):
"""
API to list datasets in DBS.
:param dataset: list of datasets [dataset1,dataset2,..,dataset n] (Required if dataset_id is not presented), Max length 1000.
:type dataset: list
:param dataset_id: list of dataset_ids that are the primary ke... | [
"def",
"listDatasetArray",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"validParameters",
"=",
"[",
"'dataset'",
",",
"'dataset_access_type'",
",",
"'detail'",
",",
"'dataset_id'",
"]",
"requiredParameters",
"=",
"{",
"'multiple'",
":",
"[",
"'dataset'",
"... | 60.481481 | 43.592593 |
def disable_ap_port(self, apid, port):
"""临时关闭接入点端口
临时关闭接入点端口,仅对公网域名,公网ip有效。
Args:
- apid: 接入点ID
- port: 要设置的端口号
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
... | [
"def",
"disable_ap_port",
"(",
"self",
",",
"apid",
",",
"port",
")",
":",
"url",
"=",
"'{0}/v3/aps/{1}/{2}/disable'",
".",
"format",
"(",
"self",
".",
"host",
",",
"apid",
",",
"port",
")",
"return",
"self",
".",
"__post",
"(",
"url",
")"
] | 28.5 | 18.8125 |
def _periodicfeatures_worker(task):
'''
This is a parallel worker for the drivers below.
'''
pfpickle, lcbasedir, outdir, starfeatures, kwargs = task
try:
return get_periodicfeatures(pfpickle,
lcbasedir,
outdir,
... | [
"def",
"_periodicfeatures_worker",
"(",
"task",
")",
":",
"pfpickle",
",",
"lcbasedir",
",",
"outdir",
",",
"starfeatures",
",",
"kwargs",
"=",
"task",
"try",
":",
"return",
"get_periodicfeatures",
"(",
"pfpickle",
",",
"lcbasedir",
",",
"outdir",
",",
"starfe... | 26.736842 | 24.315789 |
def add_directory(self, relativePath, info=None):
"""
Adds a directory in the repository and creates its
attribute in the Repository with utc timestamp.
It insures adding all the missing directories in the path.
:Parameters:
#. relativePath (string): The relative to ... | [
"def",
"add_directory",
"(",
"self",
",",
"relativePath",
",",
"info",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"relativePath",
")",
"# create directories",
"currentDir",
"=",
"self",
".",
"path",
"currentDict",
"=",
"se... | 39.170732 | 18.390244 |
def get_instance(self, payload):
"""
Build an instance of ReservationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.reservation.R... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"ReservationInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
"worker_sid",
"=",
"self",
"."... | 36.133333 | 21.066667 |
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
"""Returns the times when this search is scheduled to run.
By default this method returns the times in the next hour. For different
time ranges, set *earliest_time* and *latest_time*. For example,
for all times in the la... | [
"def",
"scheduled_times",
"(",
"self",
",",
"earliest_time",
"=",
"'now'",
",",
"latest_time",
"=",
"'+1h'",
")",
":",
"response",
"=",
"self",
".",
"get",
"(",
"\"scheduled_times\"",
",",
"earliest_time",
"=",
"earliest_time",
",",
"latest_time",
"=",
"latest... | 41.478261 | 15.608696 |
def pop(self,
num_items: int,
type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]:
"""
Pop an item off the stack.
Note: This function is optimized for speed over readability.
"""
try:
if num_items == 1:
return n... | [
"def",
"pop",
"(",
"self",
",",
"num_items",
":",
"int",
",",
"type_hint",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"bytes",
",",
"Tuple",
"[",
"Union",
"[",
"int",
",",
"bytes",
"]",
",",
"...",
"]",
"]",
":",
"try",
":",
"if",
"num_it... | 33.533333 | 18.866667 |
def est_kl_divergence(self, other, kernel=None, delta=1e-2):
"""
Finds the KL divergence between this and another particle
distribution by using a kernel density estimator to smooth over the
other distribution's particles.
:param SMCUpdater other:
"""
return self... | [
"def",
"est_kl_divergence",
"(",
"self",
",",
"other",
",",
"kernel",
"=",
"None",
",",
"delta",
"=",
"1e-2",
")",
":",
"return",
"self",
".",
"_kl_divergence",
"(",
"other",
".",
"particle_locations",
",",
"other",
".",
"particle_weights",
",",
"kernel",
... | 33.384615 | 14.461538 |
def insert_query_m(data, table, conn, columns=None, db_type='mysql'):
""" Insert python list of tuples into SQL table
Args:
data (list): List of tuples
table (str): Name of database table
conn (connection object): database connection object
columns (str): String of column names ... | [
"def",
"insert_query_m",
"(",
"data",
",",
"table",
",",
"conn",
",",
"columns",
"=",
"None",
",",
"db_type",
"=",
"'mysql'",
")",
":",
"# if length of data is very large we need to break into chunks the insert_query_m is then used recursively untill",
"# all data has been inse... | 39.333333 | 23.333333 |
def _process_status(self, status):
""" Process latest status update. """
self._screen_id = status.get(ATTR_SCREEN_ID)
self.status_update_event.set() | [
"def",
"_process_status",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"_screen_id",
"=",
"status",
".",
"get",
"(",
"ATTR_SCREEN_ID",
")",
"self",
".",
"status_update_event",
".",
"set",
"(",
")"
] | 42.25 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.