text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def invoice(request, invoice_id, access_code=None):
''' Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): The invoic... | [
"def",
"invoice",
"(",
"request",
",",
"invoice_id",
",",
"access_code",
"=",
"None",
")",
":",
"current_invoice",
"=",
"InvoiceController",
".",
"for_id_or_404",
"(",
"invoice_id",
")",
"if",
"not",
"current_invoice",
".",
"can_view",
"(",
"user",
"=",
"reque... | 26.139535 | 27.255814 |
def read_inifile (self, noexistok=False, typed=False):
"""Open assuming an “ini-file” format and return a generator yielding data
records using either :func:`pwkit.inifile.read_stream` (if *typed* is
false) or :func:`pwkit.tinifile.read_stream` (if it’s true). The
latter version is desig... | [
"def",
"read_inifile",
"(",
"self",
",",
"noexistok",
"=",
"False",
",",
"typed",
"=",
"False",
")",
":",
"if",
"typed",
":",
"from",
".",
"tinifile",
"import",
"read_stream",
"else",
":",
"from",
".",
"inifile",
"import",
"read_stream",
"try",
":",
"wit... | 40.136364 | 18.090909 |
def make_downsampled_type(cls, other_base):
"""
Factory for making Downsampled{Filter,Factor,Classifier}.
"""
docstring = dedent(
"""
A {t} that defers to another {t} at lower-than-daily frequency.
Parameters
----------
term : ... | [
"def",
"make_downsampled_type",
"(",
"cls",
",",
"other_base",
")",
":",
"docstring",
"=",
"dedent",
"(",
"\"\"\"\n A {t} that defers to another {t} at lower-than-daily frequency.\n\n Parameters\n ----------\n term : {t}\n {{frequency}}\... | 28.407407 | 16.333333 |
def init(quick):
# type: () -> None
""" Create an empty pelconf.yaml from template """
config_file = 'pelconf.yaml'
prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file)
if exists(config_file) and not click.confirm(shell.fmt(prompt)):
log.info("Canceled")
return
... | [
"def",
"init",
"(",
"quick",
")",
":",
"# type: () -> None",
"config_file",
"=",
"'pelconf.yaml'",
"prompt",
"=",
"\"-- <35>{} <32>already exists. Wipe it?<0>\"",
".",
"format",
"(",
"config_file",
")",
"if",
"exists",
"(",
"config_file",
")",
"and",
"not",
"click",... | 35 | 22.066667 |
def _set_tacacs_server(self, v, load=False):
"""
Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tacacs_server is considered as a private
method. Backends looking to populate this v... | [
"def",
"_set_tacacs_server",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 78.590909 | 36.136364 |
def b64_from(val):
"""Returns base64 encoded bytes for a given int/long/bytes value.
:param int|long|bytes val:
:rtype: bytes|str
"""
if isinstance(val, integer_types):
val = int_to_bytes(val)
return b64encode(val).decode('ascii') | [
"def",
"b64_from",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"integer_types",
")",
":",
"val",
"=",
"int_to_bytes",
"(",
"val",
")",
"return",
"b64encode",
"(",
"val",
")",
".",
"decode",
"(",
"'ascii'",
")"
] | 28.333333 | 11.444444 |
def get(self, id, service='facebook', type='analysis'):
""" Get a given Pylon task
:param id: The ID of the task
:type id: str
:param service: The PYLON service (facebook)
:type service: str
:return: dict of REST API output with headers attached
... | [
"def",
"get",
"(",
"self",
",",
"id",
",",
"service",
"=",
"'facebook'",
",",
"type",
"=",
"'analysis'",
")",
":",
"return",
"self",
".",
"request",
".",
"get",
"(",
"service",
"+",
"'/task/'",
"+",
"type",
"+",
"'/'",
"+",
"id",
")"
] | 44 | 16.692308 |
def scan_prefix_ids(self, prefix):
'''Scan for ids with a given prefix.
:param str prefix: Identifier prefix.
:param [str] feature_names:
A list of feature names to retrieve. When ``None``, all
features are retrieved. Wildcards are allowed.
:rtype: Iterable of ``cont... | [
"def",
"scan_prefix_ids",
"(",
"self",
",",
"prefix",
")",
":",
"resp",
"=",
"self",
".",
"_scan_prefix",
"(",
"prefix",
",",
"feature_names",
"=",
"False",
")",
"for",
"hit",
"in",
"resp",
":",
"yield",
"did",
"(",
"hit",
"[",
"'_id'",
"]",
")"
] | 37.5 | 14.666667 |
def _execShowCmd(self, showcmd):
"""Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dictionary.
"""
result = None
lines = self._execCmd("show", showcmd)
if lines and len(lines) >= 2 and... | [
"def",
"_execShowCmd",
"(",
"self",
",",
"showcmd",
")",
":",
"result",
"=",
"None",
"lines",
"=",
"self",
".",
"_execCmd",
"(",
"\"show\"",
",",
"showcmd",
")",
"if",
"lines",
"and",
"len",
"(",
"lines",
")",
">=",
"2",
"and",
"lines",
"[",
"0",
"... | 33.315789 | 12.473684 |
def protocol_authenticate(self, account=None):
"""
Low-level API to perform protocol-level authentication on protocols
that support it.
.. HINT::
In most cases, you want to use the login() method instead, as
it automatically chooses the best login method for each p... | [
"def",
"protocol_authenticate",
"(",
"self",
",",
"account",
"=",
"None",
")",
":",
"with",
"self",
".",
"_get_account",
"(",
"account",
")",
"as",
"account",
":",
"user",
"=",
"account",
".",
"get_name",
"(",
")",
"password",
"=",
"account",
".",
"get_p... | 40.130435 | 17.695652 |
def push(self, vs):
'Move given sheet `vs` to index 0 of list `sheets`.'
if vs:
vs.vd = self
if vs in self.sheets:
self.sheets.remove(vs)
self.sheets.insert(0, vs)
elif not vs.loaded:
self.sheets.insert(0, vs)
... | [
"def",
"push",
"(",
"self",
",",
"vs",
")",
":",
"if",
"vs",
":",
"vs",
".",
"vd",
"=",
"self",
"if",
"vs",
"in",
"self",
".",
"sheets",
":",
"self",
".",
"sheets",
".",
"remove",
"(",
"vs",
")",
"self",
".",
"sheets",
".",
"insert",
"(",
"0"... | 32.588235 | 13.294118 |
def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff':
"""
Join several DBDiff objects into a single DBDiff object.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes.
"""
tracker = DBDiffTracker()
for ... | [
"def",
"join",
"(",
"cls",
",",
"diffs",
":",
"Iterable",
"[",
"'DBDiff'",
"]",
")",
"->",
"'DBDiff'",
":",
"tracker",
"=",
"DBDiffTracker",
"(",
")",
"for",
"diff",
"in",
"diffs",
":",
"diff",
".",
"apply_to",
"(",
"tracker",
")",
"return",
"tracker",... | 35.363636 | 14.818182 |
def centroid_2dg(data, error=None, mask=None):
"""
Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus
a constant) to the array.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the combinati... | [
"def",
"centroid_2dg",
"(",
"data",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"gfit",
"=",
"fit_2dgaussian",
"(",
"data",
",",
"error",
"=",
"error",
",",
"mask",
"=",
"mask",
")",
"return",
"np",
".",
"array",
"(",
"[",
"gfit"... | 30.967742 | 22.709677 |
def queryEx(self, viewcls, *args, **kwargs):
"""
Query a view, with the ``viewcls`` instance receiving events
of the query as they arrive.
:param type viewcls: A class (derived from :class:`AsyncViewBase`)
to instantiate
Other arguments are passed to the standard `que... | [
"def",
"queryEx",
"(",
"self",
",",
"viewcls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'itercls'",
"]",
"=",
"viewcls",
"o",
"=",
"super",
"(",
"AsyncBucket",
",",
"self",
")",
".",
"query",
"(",
"*",
"args",
",",
"*"... | 33.478261 | 22.869565 |
def prep_for_deserialize(model, record, using, init_list=None): # pylint:disable=unused-argument
"""
Convert a record from SFDC (decoded JSON) to dict(model string, pk, fields)
If fixes fields of some types. If names of required fields `init_list `are
specified, then only these fields are processed.
... | [
"def",
"prep_for_deserialize",
"(",
"model",
",",
"record",
",",
"using",
",",
"init_list",
"=",
"None",
")",
":",
"# pylint:disable=unused-argument",
"# TODO the parameter 'using' is not currently important.",
"attribs",
"=",
"record",
".",
"pop",
"(",
"'attributes'",
... | 40.352941 | 24.588235 |
def request_permissions(self, permissions):
""" Return a future that resolves with the results
of the permission requests
"""
f = self.create_future()
#: Old versions of android did permissions at install time
if self.api_level < 23:
f.set_result({p... | [
"def",
"request_permissions",
"(",
"self",
",",
"permissions",
")",
":",
"f",
"=",
"self",
".",
"create_future",
"(",
")",
"#: Old versions of android did permissions at install time",
"if",
"self",
".",
"api_level",
"<",
"23",
":",
"f",
".",
"set_result",
"(",
... | 34.121212 | 20.909091 |
def FSeek(params, ctxt, scope, stream, coord):
"""Returns 0 if successful or -1 if the address is out of range
"""
if len(params) != 1:
raise errors.InvalidArguments(coord, "{} args".format(len(params)), "FSeek accepts only one argument")
pos = PYVAL(params[0])
curr_pos = stream.tell()
... | [
"def",
"FSeek",
"(",
"params",
",",
"ctxt",
",",
"scope",
",",
"stream",
",",
"coord",
")",
":",
"if",
"len",
"(",
"params",
")",
"!=",
"1",
":",
"raise",
"errors",
".",
"InvalidArguments",
"(",
"coord",
",",
"\"{} args\"",
".",
"format",
"(",
"len",... | 30.619048 | 23.047619 |
def Print(self, output_writer):
"""Prints a human readable version of the filter.
Args:
output_writer (CLIOutputWriter): output writer.
"""
if self._names:
output_writer.Write('\tnames: {0:s}\n'.format(
', '.join(self._names))) | [
"def",
"Print",
"(",
"self",
",",
"output_writer",
")",
":",
"if",
"self",
".",
"_names",
":",
"output_writer",
".",
"Write",
"(",
"'\\tnames: {0:s}\\n'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"self",
".",
"_names",
")",
")",
")"
] | 28.666667 | 14.666667 |
def download(self, version=None, tags=None, ext=None, overwrite=False,
verbose=False, **kwargs):
"""Downloads the given instance of this dataset from dataset store.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
... | [
"def",
"download",
"(",
"self",
",",
"version",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"ext",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"fpath",
"=",
"self",
".",
"fpath",
"... | 42.307692 | 17.846154 |
def datetimes(self):
"""A sorted list of datetimes in this analysis period."""
if self._timestamps_data is None:
self._calculate_timestamps()
return tuple(DateTime.from_moy(moy, self.is_leap_year)
for moy in self._timestamps_data) | [
"def",
"datetimes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timestamps_data",
"is",
"None",
":",
"self",
".",
"_calculate_timestamps",
"(",
")",
"return",
"tuple",
"(",
"DateTime",
".",
"from_moy",
"(",
"moy",
",",
"self",
".",
"is_leap_year",
")",
"... | 47 | 9.5 |
def placeCursor(self, pos):
"""
Try to place the cursor in ``line`` at ``col`` if possible.
If this is not possible, then place it at the end.
"""
if pos > len(self.qteWidget.toPlainText()):
pos = len(self.qteWidget.toPlainText())
tc = self.qteWidget.textCurs... | [
"def",
"placeCursor",
"(",
"self",
",",
"pos",
")",
":",
"if",
"pos",
">",
"len",
"(",
"self",
".",
"qteWidget",
".",
"toPlainText",
"(",
")",
")",
":",
"pos",
"=",
"len",
"(",
"self",
".",
"qteWidget",
".",
"toPlainText",
"(",
")",
")",
"tc",
"=... | 34.818182 | 12.090909 |
def span_path(cls, project, trace, span):
"""Return a fully-qualified span string."""
return google.api_core.path_template.expand(
"projects/{project}/traces/{trace}/spans/{span}",
project=project,
trace=trace,
span=span,
) | [
"def",
"span_path",
"(",
"cls",
",",
"project",
",",
"trace",
",",
"span",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/traces/{trace}/spans/{span}\"",
",",
"project",
"=",
"project",
",",
"trace"... | 36 | 13.875 |
def foreachPartition(self, f):
"""
Applies a function to each partition of this RDD.
>>> def f(iterator):
... for x in iterator:
... print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f)
"""
def func(it):
r = f(it)
... | [
"def",
"foreachPartition",
"(",
"self",
",",
"f",
")",
":",
"def",
"func",
"(",
"it",
")",
":",
"r",
"=",
"f",
"(",
"it",
")",
"try",
":",
"return",
"iter",
"(",
"r",
")",
"except",
"TypeError",
":",
"return",
"iter",
"(",
"[",
"]",
")",
"self"... | 28.1875 | 13.1875 |
def calculate_mean(samples, weights):
r'''Calculate the mean of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importance weights.
'''
... | [
"def",
"calculate_mean",
"(",
"samples",
",",
"weights",
")",
":",
"assert",
"len",
"(",
"samples",
")",
"==",
"len",
"(",
"weights",
")",
",",
"\"The number of samples (got %i) must equal the number of weights (got %i).\"",
"%",
"(",
"len",
"(",
"samples",
")",
"... | 33.933333 | 32.466667 |
def GET_AUTH(self): # pylint: disable=arguments-differ
""" GET request """
auth_methods = self.user_manager.get_auth_methods()
user_data = self.database.users.find_one({"username": self.user_manager.session_username()})
bindings = user_data.get("bindings", {})
return self.templa... | [
"def",
"GET_AUTH",
"(",
"self",
")",
":",
"# pylint: disable=arguments-differ",
"auth_methods",
"=",
"self",
".",
"user_manager",
".",
"get_auth_methods",
"(",
")",
"user_data",
"=",
"self",
".",
"database",
".",
"users",
".",
"find_one",
"(",
"{",
"\"username\"... | 65.833333 | 28 |
def repartition(self, numPartitions):
"""Repartition every RDD.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([['h... | [
"def",
"repartition",
"(",
"self",
",",
"numPartitions",
")",
":",
"return",
"self",
".",
"transform",
"(",
"lambda",
"rdd",
":",
"(",
"rdd",
".",
"repartition",
"(",
"numPartitions",
")",
"if",
"not",
"isinstance",
"(",
"rdd",
",",
"EmptyRDD",
")",
"els... | 25.481481 | 21.037037 |
def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset... | [
"def",
"_convert_angle_limit",
"(",
"angle",
",",
"joint",
",",
"*",
"*",
"kwargs",
")",
":",
"angle_pypot",
"=",
"angle",
"# No need to take care of orientation",
"if",
"joint",
"[",
"\"orientation\"",
"]",
"==",
"\"indirect\"",
":",
"angle_pypot",
"=",
"1",
"*... | 31.636364 | 14.181818 |
def handle_authorized_event(self, event):
"""Request roster upon login."""
self.server = event.authorized_jid.bare()
if "versioning" in self.server_features:
if self.roster is not None and self.roster.version is not None:
version = self.roster.version
else... | [
"def",
"handle_authorized_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"server",
"=",
"event",
".",
"authorized_jid",
".",
"bare",
"(",
")",
"if",
"\"versioning\"",
"in",
"self",
".",
"server_features",
":",
"if",
"self",
".",
"roster",
"is",
... | 38.090909 | 12.454545 |
def getRepositories(self):
"""Returns a list of repositories for this directory.
"""
if self.srcdir and not self.duplicate:
return self.srcdir.get_all_rdirs() + self.repositories
return self.repositories | [
"def",
"getRepositories",
"(",
"self",
")",
":",
"if",
"self",
".",
"srcdir",
"and",
"not",
"self",
".",
"duplicate",
":",
"return",
"self",
".",
"srcdir",
".",
"get_all_rdirs",
"(",
")",
"+",
"self",
".",
"repositories",
"return",
"self",
".",
"reposito... | 40.333333 | 9 |
def normalize_value(self, value, transform=True):
"""Prepare the given value to be stored in the index
For the parameters, see BaseIndex.normalize_value
Raises
------
ValueError
If ``raise_if_not_float`` is True and the value cannot
be casted to a float.... | [
"def",
"normalize_value",
"(",
"self",
",",
"value",
",",
"transform",
"=",
"True",
")",
":",
"if",
"transform",
":",
"value",
"=",
"self",
".",
"transform_value",
"(",
"value",
")",
"try",
":",
"return",
"float",
"(",
"value",
")",
"except",
"(",
"Val... | 31.045455 | 18.818182 |
def get_templates(self, limit=100, offset=0):
"""
Get all account templates
"""
url = self.TEMPLATES_URL + "?limit=%s&offset=%s" % (limit, offset)
connection = Connection(self.token)
connection.set_url(self.production, url)
return connection.get_request() | [
"def",
"get_templates",
"(",
"self",
",",
"limit",
"=",
"100",
",",
"offset",
"=",
"0",
")",
":",
"url",
"=",
"self",
".",
"TEMPLATES_URL",
"+",
"\"?limit=%s&offset=%s\"",
"%",
"(",
"limit",
",",
"offset",
")",
"connection",
"=",
"Connection",
"(",
"self... | 27.636364 | 16.181818 |
def calc_q0_perc_uz_v1(self):
"""Perform the upper zone layer routine which determines percolation
to the lower zone layer and the fast response of the hland model.
Note that the system behaviour of this method depends strongly on the
specifications of the options |RespArea| and |RecStep|.
Required... | [
"def",
"calc_q0_perc_uz_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
"... | 29.918478 | 21.391304 |
def _update_partition_dci_id(self, tenant_name, dci_id,
vrf_prof=None, part_name=None):
"""Function to update DCI ID of partition. """
self.dcnm_obj.update_project(tenant_name, part_name, dci_id=dci_id,
vrf_prof=vrf_prof) | [
"def",
"_update_partition_dci_id",
"(",
"self",
",",
"tenant_name",
",",
"dci_id",
",",
"vrf_prof",
"=",
"None",
",",
"part_name",
"=",
"None",
")",
":",
"self",
".",
"dcnm_obj",
".",
"update_project",
"(",
"tenant_name",
",",
"part_name",
",",
"dci_id",
"="... | 60.6 | 17.8 |
def _load_hooks_settings(self):
"""load hooks settings"""
log.debug("executing _load_hooks_settings")
hook_show_widget = self.get_widget("hook_show")
hook_show_setting = self.settings.hooks.get_string("show")
if hook_show_widget is not None:
if hook_show_setting is no... | [
"def",
"_load_hooks_settings",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"executing _load_hooks_settings\"",
")",
"hook_show_widget",
"=",
"self",
".",
"get_widget",
"(",
"\"hook_show\"",
")",
"hook_show_setting",
"=",
"self",
".",
"settings",
".",
"hooks... | 47.625 | 10.75 |
def delete_river(self, river, river_name=None):
"""
Delete a river
"""
if isinstance(river, River):
river_name = river.name
return self._send_request('DELETE', '/_river/%s/' % river_name) | [
"def",
"delete_river",
"(",
"self",
",",
"river",
",",
"river_name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"river",
",",
"River",
")",
":",
"river_name",
"=",
"river",
".",
"name",
"return",
"self",
".",
"_send_request",
"(",
"'DELETE'",
",",
... | 33.285714 | 9.285714 |
def assembly_cleanup(data):
""" cleanup for assembly object """
## build s2 results data frame
data.stats_dfs.s2 = data._build_stat("s2")
data.stats_files.s2 = os.path.join(data.dirs.edits, 's2_rawedit_stats.txt')
## write stats for all samples
with io.open(data.stats_files.s2, 'w', encoding='... | [
"def",
"assembly_cleanup",
"(",
"data",
")",
":",
"## build s2 results data frame",
"data",
".",
"stats_dfs",
".",
"s2",
"=",
"data",
".",
"_build_stat",
"(",
"\"s2\"",
")",
"data",
".",
"stats_files",
".",
"s2",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | 40.6 | 21.7 |
def update(self, webhook_url=values.unset, friendly_name=values.unset,
reachability_webhooks_enabled=values.unset,
acl_enabled=values.unset):
"""
Update the ServiceInstance
:param unicode webhook_url: A URL that will receive event updates when objects are manipulat... | [
"def",
"update",
"(",
"self",
",",
"webhook_url",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"reachability_webhooks_enabled",
"=",
"values",
".",
"unset",
",",
"acl_enabled",
"=",
"values",
".",
"unset",
")",
":",
... | 44.5 | 28.214286 |
def from_file(self, fname, comment_lead=['c'], compressed_with='use_ext'):
"""
Read a CNF formula from a file in the DIMACS format. A file name is
expected as an argument. A default argument is ``comment_lead`` for
parsing comment lines. A given file can be compressed by eith... | [
"def",
"from_file",
"(",
"self",
",",
"fname",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
",",
"compressed_with",
"=",
"'use_ext'",
")",
":",
"with",
"FileObject",
"(",
"fname",
",",
"mode",
"=",
"'r'",
",",
"compression",
"=",
"compressed_with",
")",
"a... | 43 | 24.657143 |
def get_md5sum(src_file):
"""Returns md5sum of file"""
with open(src_file, 'rb') as src_data:
src_content = src_data.read()
return hashlib.md5(src_content).hexdigest() | [
"def",
"get_md5sum",
"(",
"src_file",
")",
":",
"with",
"open",
"(",
"src_file",
",",
"'rb'",
")",
"as",
"src_data",
":",
"src_content",
"=",
"src_data",
".",
"read",
"(",
")",
"return",
"hashlib",
".",
"md5",
"(",
"src_content",
")",
".",
"hexdigest",
... | 37.4 | 6.2 |
def compose_capability(base, *classes):
"""Create a new class starting with the base and adding capabilities."""
if _debug: compose_capability._debug("compose_capability %r %r", base, classes)
# make sure the base is a Collector
if not issubclass(base, Collector):
raise TypeError("base must be ... | [
"def",
"compose_capability",
"(",
"base",
",",
"*",
"classes",
")",
":",
"if",
"_debug",
":",
"compose_capability",
".",
"_debug",
"(",
"\"compose_capability %r %r\"",
",",
"base",
",",
"classes",
")",
"# make sure the base is a Collector",
"if",
"not",
"issubclass"... | 33.26087 | 18.913043 |
def _do_get(self, uri, **kwargs):
"""
Convinient method for GET requests
Returns http request status value from a POST request
"""
#TODO:
# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method
scaleioapi_get_head... | [
"def",
"_do_get",
"(",
"self",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"#TODO:",
"# Add error handling. Check for HTTP status here would be much more conveinent than in each calling method",
"scaleioapi_get_headers",
"=",
"{",
"'Content-type'",
":",
"'application/json'",... | 49 | 29.153846 |
def is_available(workshift_profile, shift):
"""
Check whether a specified user is able to do a specified workshift.
Parameters:
workshift_profile is the workshift profile for a user
shift is a weekly recurring workshift
Returns:
True if the user has enough free time between the s... | [
"def",
"is_available",
"(",
"workshift_profile",
",",
"shift",
")",
":",
"if",
"shift",
".",
"week_long",
":",
"return",
"True",
"start_time",
"=",
"(",
"shift",
".",
"start_time",
"if",
"shift",
".",
"start_time",
"is",
"not",
"None",
"else",
"time",
"(",... | 31.383562 | 21.493151 |
def _two_to_one(datadir):
"""After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintai... | [
"def",
"_two_to_one",
"(",
"datadir",
")",
":",
"_",
",",
"env_name",
"=",
"_split_path",
"(",
"datadir",
")",
"print",
"'Making sure that containers are stopped...'",
"# New-style names",
"remove_container",
"(",
"'datacats_web_{}_primary'",
".",
"format",
"(",
"env_na... | 37.896552 | 22.706897 |
def run_duplicated_samples(in_prefix, in_type, out_prefix, base_dir, options):
"""Runs step1 (duplicated samples).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param op... | [
"def",
"run_duplicated_samples",
"(",
"in_prefix",
",",
"in_type",
",",
"out_prefix",
",",
"base_dir",
",",
"options",
")",
":",
"# Creating the output directory",
"os",
".",
"mkdir",
"(",
"out_prefix",
")",
"# We know we need tfile",
"required_type",
"=",
"\"tfile\""... | 41.473214 | 20.491071 |
def TRM(f,a,b):
"""
Calculate TRM using tanh relationship
TRM(f)=a*math.tanh(b*f)
"""
m = float(a) * math.tanh(float(b) * float(f))
return float(m) | [
"def",
"TRM",
"(",
"f",
",",
"a",
",",
"b",
")",
":",
"m",
"=",
"float",
"(",
"a",
")",
"*",
"math",
".",
"tanh",
"(",
"float",
"(",
"b",
")",
"*",
"float",
"(",
"f",
")",
")",
"return",
"float",
"(",
"m",
")"
] | 24 | 9.714286 |
def reset(self):
"""
Reset the state of the sandbox.
http://docs.fiesta.cc/sandbox.html#post--reset
"""
path = 'reset'
request_data = {} # Need to put data into the request to force urllib2 to make it a POST request
response_data = self.request(path, request_dat... | [
"def",
"reset",
"(",
"self",
")",
":",
"path",
"=",
"'reset'",
"request_data",
"=",
"{",
"}",
"# Need to put data into the request to force urllib2 to make it a POST request",
"response_data",
"=",
"self",
".",
"request",
"(",
"path",
",",
"request_data",
")",
"succes... | 39.5 | 17.5 |
def aggregate_hazard_preparation(self):
"""This function is doing the aggregate hazard layer.
It will prepare the aggregate layer and intersect hazard polygons with
aggregation areas and assign hazard class.
"""
LOGGER.info('ANALYSIS : Aggregate hazard preparation')
self... | [
"def",
"aggregate_hazard_preparation",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'ANALYSIS : Aggregate hazard preparation'",
")",
"self",
".",
"set_state_process",
"(",
"'hazard'",
",",
"'Make hazard layer valid'",
")",
"self",
".",
"hazard",
"=",
"clean_lay... | 43.529412 | 18.117647 |
def __nt_relpath(path, start=os.curdir):
"""Return a relative version of a path"""
if not path: raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.sep)
path_list = os.path.abspath(path).split(os.sep)
if start_list[0].lower() != path_list[0].lower():
unc_path... | [
"def",
"__nt_relpath",
"(",
"path",
",",
"start",
"=",
"os",
".",
"curdir",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"no path specified\"",
")",
"start_list",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"start",
")",
".",
"spl... | 42.4 | 18.2 |
def generate_dep_names(self, target: Target):
"""Generate names of all dependencies (descendants) of `target`."""
yield from sorted(get_descendants(self.target_graph, target.name)) | [
"def",
"generate_dep_names",
"(",
"self",
",",
"target",
":",
"Target",
")",
":",
"yield",
"from",
"sorted",
"(",
"get_descendants",
"(",
"self",
".",
"target_graph",
",",
"target",
".",
"name",
")",
")"
] | 64.666667 | 13 |
def init_mimedb():
"""Initialize the local MIME database."""
global mimedb
try:
mimedb = mimetypes.MimeTypes(strict=False)
except Exception as msg:
log.error(LOG_CHECK, "could not initialize MIME database: %s" % msg)
return
# For Opera bookmark files (opera6.adr)
add_mime... | [
"def",
"init_mimedb",
"(",
")",
":",
"global",
"mimedb",
"try",
":",
"mimedb",
"=",
"mimetypes",
".",
"MimeTypes",
"(",
"strict",
"=",
"False",
")",
"except",
"Exception",
"as",
"msg",
":",
"log",
".",
"error",
"(",
"LOG_CHECK",
",",
"\"could not initializ... | 38.571429 | 16.357143 |
def _check_file_exists_unix(self, remote_cmd=""):
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
self.ssh_ctl_chan._enter_shell()
remote_cmd = "ls {}".format(self.file_system)
remote_out = self.ssh_ctl_chan... | [
"def",
"_check_file_exists_unix",
"(",
"self",
",",
"remote_cmd",
"=",
"\"\"",
")",
":",
"if",
"self",
".",
"direction",
"==",
"\"put\"",
":",
"self",
".",
"ssh_ctl_chan",
".",
"_enter_shell",
"(",
")",
"remote_cmd",
"=",
"\"ls {}\"",
".",
"format",
"(",
"... | 47.333333 | 9.166667 |
def write(self, data: bytes) -> None:
"""
Write the data.
"""
if self.finished():
if self._exc:
raise self._exc
raise WriteAfterFinishedError
if not data:
return
try:
self._delegate.write_data(data, finish... | [
"def",
"write",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"None",
":",
"if",
"self",
".",
"finished",
"(",
")",
":",
"if",
"self",
".",
"_exc",
":",
"raise",
"self",
".",
"_exc",
"raise",
"WriteAfterFinishedError",
"if",
"not",
"data",
":",
... | 21.136364 | 18.045455 |
def gates_in_isa(isa):
"""
Generate the full gateset associated with an ISA.
:param ISA isa: The instruction set architecture for a QPU.
:return: A sequence of Gate objects encapsulating all gates compatible with the ISA.
:rtype: Sequence[Gate]
"""
gates = []
for q in isa.qubits:
... | [
"def",
"gates_in_isa",
"(",
"isa",
")",
":",
"gates",
"=",
"[",
"]",
"for",
"q",
"in",
"isa",
".",
"qubits",
":",
"if",
"q",
".",
"dead",
":",
"# TODO: dead qubits may in the future lead to some implicit re-indexing",
"continue",
"if",
"q",
".",
"type",
"in",
... | 39.078947 | 18.973684 |
def relations(cls):
"""Return a `list` of relationship names or the given model
"""
return [c.key for c in cls.__mapper__.iterate_properties
if isinstance(c, RelationshipProperty)] | [
"def",
"relations",
"(",
"cls",
")",
":",
"return",
"[",
"c",
".",
"key",
"for",
"c",
"in",
"cls",
".",
"__mapper__",
".",
"iterate_properties",
"if",
"isinstance",
"(",
"c",
",",
"RelationshipProperty",
")",
"]"
] | 43.2 | 12 |
def kuhn_munkres(G): # maximum profit bipartite matching in O(n^4)
"""Maximum profit perfect matching
for minimum cost perfect matching just inverse the weights
:param G: squared weight matrix of a complete bipartite graph
:complexity: :math:`O(n^4)`
"""
assert len(G) == len(G[0])
n =... | [
"def",
"kuhn_munkres",
"(",
"G",
")",
":",
"# maximum profit bipartite matching in O(n^4)",
"assert",
"len",
"(",
"G",
")",
"==",
"len",
"(",
"G",
"[",
"0",
"]",
")",
"n",
"=",
"len",
"(",
"G",
")",
"mu",
"=",
"[",
"None",
"]",
"*",
"n",
"# Empty mat... | 35.565217 | 17.26087 |
def fallback_schema_from_field(self, field):
""" Fallback schema for field that isn't inspected properly by DRF
and probably won't land in upstream canon due to its hacky nature only for doc purposes
"""
title = force_text(field.label) if field.label else ''
description = force_t... | [
"def",
"fallback_schema_from_field",
"(",
"self",
",",
"field",
")",
":",
"title",
"=",
"force_text",
"(",
"field",
".",
"label",
")",
"if",
"field",
".",
"label",
"else",
"''",
"description",
"=",
"force_text",
"(",
"field",
".",
"help_text",
")",
"if",
... | 47.266667 | 21.066667 |
def _set_state(self, state, force=True):
"""
Setting force to True allows for changing a state after it
COMPLETED. This would otherwise be invalid.
"""
self._setstate(state, True)
self.last_state_change = time.time() | [
"def",
"_set_state",
"(",
"self",
",",
"state",
",",
"force",
"=",
"True",
")",
":",
"self",
".",
"_setstate",
"(",
"state",
",",
"True",
")",
"self",
".",
"last_state_change",
"=",
"time",
".",
"time",
"(",
")"
] | 36.857143 | 6.571429 |
def split_overlays(self):
"Deprecated method to split overlays inside the HoloMap."
if util.config.future_deprecations:
self.param.warning("split_overlays is deprecated and is now "
"a private method.")
return self._split_overlays() | [
"def",
"split_overlays",
"(",
"self",
")",
":",
"if",
"util",
".",
"config",
".",
"future_deprecations",
":",
"self",
".",
"param",
".",
"warning",
"(",
"\"split_overlays is deprecated and is now \"",
"\"a private method.\"",
")",
"return",
"self",
".",
"_split_over... | 49 | 15 |
def list_metrics(self, include=None, interval="1d", **kwargs):
"""Get statistics.
:param list[str] include: List of fields included in response.
None, or an empty list will return all fields.
Fields: transactions, successful_api_calls, failed_api_calls, successful_handshakes,
... | [
"def",
"list_metrics",
"(",
"self",
",",
"include",
"=",
"None",
",",
"interval",
"=",
"\"1d\"",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_verify_arguments",
"(",
"interval",
",",
"kwargs",
")",
"include",
"=",
"Metric",
".",
"_map_includes",
"("... | 61.785714 | 26.964286 |
def load_rabit_checkpoint(self):
"""Initialize the model by load from rabit checkpoint.
Returns
-------
version: integer
The version number of the model.
"""
version = ctypes.c_int()
_check_call(_LIB.XGBoosterLoadRabitCheckpoint(
self.hand... | [
"def",
"load_rabit_checkpoint",
"(",
"self",
")",
":",
"version",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"XGBoosterLoadRabitCheckpoint",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"version",
")",
")",
")"... | 30.416667 | 13.333333 |
def submit(self, func, *args, **kwargs):
"""Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`"""
with self._shutdown_lock:
if PY3 and self._broken:
raise BrokenProcessPool(
"A child process terminated "
"abruptly,... | [
"def",
"submit",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_shutdown_lock",
":",
"if",
"PY3",
"and",
"self",
".",
"_broken",
":",
"raise",
"BrokenProcessPool",
"(",
"\"A child process terminated \"... | 40.448276 | 13.172414 |
def parse_multi_object_delete_response(data):
"""Parser for Multi-Object Delete API response.
:param data: XML response body content from service.
:return: Returns list of error objects for each delete object that
had an error.
"""
root = S3Element.fromstring('MultiObjectDeleteResult', data)
... | [
"def",
"parse_multi_object_delete_response",
"(",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'MultiObjectDeleteResult'",
",",
"data",
")",
"return",
"[",
"MultiDeleteError",
"(",
"errtag",
".",
"get_child_text",
"(",
"'Key'",
")",
",",
... | 33.5625 | 20.6875 |
def weekdays(first_day=None):
"""Returns a list of weekday names.
Arguments
---------
first_day : str, default None
The first day of the week. If not given, 'Monday' is used.
Returns
-------
list
A list of weekday names.
"""
if first_day is None:
first_day =... | [
"def",
"weekdays",
"(",
"first_day",
"=",
"None",
")",
":",
"if",
"first_day",
"is",
"None",
":",
"first_day",
"=",
"'Monday'",
"ix",
"=",
"_lower_weekdays",
"(",
")",
".",
"index",
"(",
"first_day",
".",
"lower",
"(",
")",
")",
"return",
"_double_weekda... | 23.764706 | 18.588235 |
def to_wire(self, origin=None, max_size=0, **kw):
"""Return a string containing the message in DNS compressed wire
format.
Additional keyword arguments are passed to the rrset to_wire()
method.
@param origin: The origin to be appended to any relative names.
@type origin... | [
"def",
"to_wire",
"(",
"self",
",",
"origin",
"=",
"None",
",",
"max_size",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"if",
"max_size",
"==",
"0",
":",
"if",
"self",
".",
"request_payload",
"!=",
"0",
":",
"max_size",
"=",
"self",
".",
"request_payl... | 39.888889 | 17.6 |
def print_callback(val):
"""
Internal function.
This function is called via a call back returning from IPC to Cython
to Python. It tries to perform incremental printing to IPython Notebook or
Jupyter Notebook and when all else fails, just prints locally.
"""
success = False
try:
... | [
"def",
"print_callback",
"(",
"val",
")",
":",
"success",
"=",
"False",
"try",
":",
"# for reasons I cannot fathom, regular printing, even directly",
"# to io.stdout does not work.",
"# I have to intrude rather deep into IPython to make it behave",
"if",
"have_ipython",
":",
"if",
... | 35.227273 | 22.772727 |
def wait(self, condition, interval, *args):
"""
:Description: Create an interval in vm.window, will clear interval after condition met.
:param condition: Condition in javascript to pass to interval.
:example: '$el.innerText == "cheesecake"'
:example: '$el[0].disabled && $el[1].di... | [
"def",
"wait",
"(",
"self",
",",
"condition",
",",
"interval",
",",
"*",
"args",
")",
":",
"hid",
"=",
"lambda",
":",
"'$'",
"+",
"str",
"(",
"uuid",
".",
"uuid1",
"(",
")",
")",
"[",
":",
"8",
"]",
"handle",
"=",
"hid",
"(",
")",
"if",
"len"... | 50.45283 | 22.226415 |
def issubclass(cls, ifaces):
"""Check if the given class is an implementation of the given iface."""
ifaces = _ensure_ifaces_tuple(ifaces)
for iface in ifaces:
return all((
_check_for_definition(
iface,
cls,
'__iclassattribute__',
... | [
"def",
"issubclass",
"(",
"cls",
",",
"ifaces",
")",
":",
"ifaces",
"=",
"_ensure_ifaces_tuple",
"(",
"ifaces",
")",
"for",
"iface",
"in",
"ifaces",
":",
"return",
"all",
"(",
"(",
"_check_for_definition",
"(",
"iface",
",",
"cls",
",",
"'__iclassattribute__... | 26.16129 | 15.032258 |
def get_record(self, msg_id):
"""Get a specific Task Record, by msg_id."""
cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,))
line = cursor.fetchone()
if line is None:
raise KeyError("No such msg: %r"%msg_id)
return self._list_to_d... | [
"def",
"get_record",
"(",
"self",
",",
"msg_id",
")",
":",
"cursor",
"=",
"self",
".",
"_db",
".",
"execute",
"(",
"\"\"\"SELECT * FROM %s WHERE msg_id==?\"\"\"",
"%",
"self",
".",
"table",
",",
"(",
"msg_id",
",",
")",
")",
"line",
"=",
"cursor",
".",
"... | 46.142857 | 6.857143 |
def match(self, query=None, **kwargs):
"""Try to match the current record to the database."""
from invenio.search_engine import perform_request_search
if not query:
# We use default setup
recid = self.record["001"][0][3]
return perform_request_search(p="035:%s... | [
"def",
"match",
"(",
"self",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"invenio",
".",
"search_engine",
"import",
"perform_request_search",
"if",
"not",
"query",
":",
"# We use default setup",
"recid",
"=",
"self",
".",
"record",
... | 45.692308 | 12.769231 |
def directories(self):
""" Get a generator that yields all subdirectories in the directory.
"""
dirlist_p = new_gp_object("CameraList")
lib.gp_camera_folder_list_folders(self._cam._cam, self.path.encode(),
dirlist_p, self._cam._ctx)
for i... | [
"def",
"directories",
"(",
"self",
")",
":",
"dirlist_p",
"=",
"new_gp_object",
"(",
"\"CameraList\"",
")",
"lib",
".",
"gp_camera_folder_list_folders",
"(",
"self",
".",
"_cam",
".",
"_cam",
",",
"self",
".",
"path",
".",
"encode",
"(",
")",
",",
"dirlist... | 51.636364 | 16.636364 |
def calcAspectRatioFromCorners(corners, in_plane=False):
'''
simple and better alg. than below
in_plane -> whether object has no tilt, but only rotation and translation
'''
q = corners
l0 = [q[0, 0], q[0, 1], q[1, 0], q[1, 1]]
l1 = [q[0, 0], q[0, 1], q[-1, 0], q[-1, 1]]
l2 = ... | [
"def",
"calcAspectRatioFromCorners",
"(",
"corners",
",",
"in_plane",
"=",
"False",
")",
":",
"q",
"=",
"corners",
"l0",
"=",
"[",
"q",
"[",
"0",
",",
"0",
"]",
",",
"q",
"[",
"0",
",",
"1",
"]",
",",
"q",
"[",
"1",
",",
"0",
"]",
",",
"q",
... | 30.44 | 21.16 |
def indexes(self, indexes):
""" :type indexes: list[int] """
self._indexes = indexes
self._index = len(indexes) / 2 | [
"def",
"indexes",
"(",
"self",
",",
"indexes",
")",
":",
"self",
".",
"_indexes",
"=",
"indexes",
"self",
".",
"_index",
"=",
"len",
"(",
"indexes",
")",
"/",
"2"
] | 34 | 6 |
def get_prep_value(self, value):
"""
Convert an Enum value into a string for the database
"""
if value is None:
return None
if isinstance(value, self.enum):
return value.name
raise ValueError("Unknown value {value:r} of type {cls}".format(
... | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"self",
".",
"enum",
")",
":",
"return",
"value",
".",
"name",
"raise",
"ValueError",
"(",
"\"Unkno... | 34.5 | 10.5 |
def _last_of_quarter(self, day_of_week=None):
"""
Modify to the last occurrence of a given day of the week
in the current quarter. If no day_of_week is provided,
modify to the last day of the quarter. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDA... | [
"def",
"_last_of_quarter",
"(",
"self",
",",
"day_of_week",
"=",
"None",
")",
":",
"return",
"self",
".",
"on",
"(",
"self",
".",
"year",
",",
"self",
".",
"quarter",
"*",
"3",
",",
"1",
")",
".",
"last_of",
"(",
"\"month\"",
",",
"day_of_week",
")"
... | 39.5 | 20.666667 |
def registerkbevent(self, keys, modifiers, fn_name, *args):
"""
Register keystroke events
@param keys: key to listen
@type keys: string
@param modifiers: control / alt combination using gtk MODIFIERS
@type modifiers: int
@param fn_name: Callback function
... | [
"def",
"registerkbevent",
"(",
"self",
",",
"keys",
",",
"modifiers",
",",
"fn_name",
",",
"*",
"args",
")",
":",
"event_name",
"=",
"\"kbevent%s%s\"",
"%",
"(",
"keys",
",",
"modifiers",
")",
"self",
".",
"_pollEvents",
".",
"_callback",
"[",
"event_name"... | 37.684211 | 17.157895 |
def confd_state_internal_callpoints_snmp_notification_subscription_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state... | [
"def",
"confd_state_internal_callpoints_snmp_notification_subscription_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state... | 51.692308 | 23.615385 |
def edit_user_push_restrictions(self, *users):
"""
:calls: `POST /repos/:owner/:repo/branches/:branch/protection/restrictions <https://developer.github.com/v3/repos/branches>`_
:users: list of strings
"""
assert all(isinstance(element, (str, unicode)) or isinstance(element, (str,... | [
"def",
"edit_user_push_restrictions",
"(",
"self",
",",
"*",
"users",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"element",
",",
"(",
"str",
",",
"unicode",
")",
")",
"or",
"isinstance",
"(",
"element",
",",
"(",
"str",
",",
"unicode",
")",
")"... | 43.416667 | 27.916667 |
def get_sdb_secret_version_paths(self, sdb_id):
""" Get SDB secret version paths. This function takes the sdb_id """
sdb_resp = get_with_retry(str.join('', [self.cerberus_url, '/v1/sdb-secret-version-paths/', sdb_id]),
headers=self.HEADERS)
throw_if_bad_response... | [
"def",
"get_sdb_secret_version_paths",
"(",
"self",
",",
"sdb_id",
")",
":",
"sdb_resp",
"=",
"get_with_retry",
"(",
"str",
".",
"join",
"(",
"''",
",",
"[",
"self",
".",
"cerberus_url",
",",
"'/v1/sdb-secret-version-paths/'",
",",
"sdb_id",
"]",
")",
",",
"... | 44.375 | 22.5 |
def clean_email(self):
""" ensure email is in the database """
if EMAIL_CONFIRMATION:
from .models import EmailAddress
condition = EmailAddress.objects.filter(
email__iexact=self.cleaned_data["email"],
verified=True
).count() == 0
... | [
"def",
"clean_email",
"(",
"self",
")",
":",
"if",
"EMAIL_CONFIRMATION",
":",
"from",
".",
"models",
"import",
"EmailAddress",
"condition",
"=",
"EmailAddress",
".",
"objects",
".",
"filter",
"(",
"email__iexact",
"=",
"self",
".",
"cleaned_data",
"[",
"\"emai... | 35 | 13.789474 |
def on_select(self, item, action):
"""
Add an action to make when an object is selected.
Only one action can be stored this way.
"""
if not isinstance(item, int):
item = self.items.index(item)
self._on_select[item] = action | [
"def",
"on_select",
"(",
"self",
",",
"item",
",",
"action",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"int",
")",
":",
"item",
"=",
"self",
".",
"items",
".",
"index",
"(",
"item",
")",
"self",
".",
"_on_select",
"[",
"item",
"]",
"... | 27.6 | 11.6 |
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_ty... | [
"def",
"_build_type_validator",
"(",
"value_type",
")",
":",
"def",
"type_validator",
"(",
"data",
")",
":",
"\"\"\"Validate instances of a particular type.\"\"\"",
"if",
"isinstance",
"(",
"data",
",",
"value_type",
")",
":",
"return",
"data",
"raise",
"NotValid",
... | 31 | 17.454545 |
def u2open(self, u2request):
"""
Open a connection.
@param u2request: A urllib2 request.
@type u2request: urllib2.Requet.
@return: The opened file-like urllib2 object.
@rtype: fp
"""
tm = self.options.timeout
url = build_opener(HTTPSClientAuthHandl... | [
"def",
"u2open",
"(",
"self",
",",
"u2request",
")",
":",
"tm",
"=",
"self",
".",
"options",
".",
"timeout",
"url",
"=",
"build_opener",
"(",
"HTTPSClientAuthHandler",
"(",
"self",
".",
"context",
")",
")",
"if",
"self",
".",
"u2ver",
"(",
")",
"<",
... | 33.266667 | 9.666667 |
def _generate_ordered_structures(self, sanitized_input_structure, transformations):
"""
Apply our input structure to our list of transformations and output a list
of ordered structures that have been pruned for duplicates and for those
with low symmetry (optional).
Args:
... | [
"def",
"_generate_ordered_structures",
"(",
"self",
",",
"sanitized_input_structure",
",",
"transformations",
")",
":",
"ordered_structures",
"=",
"self",
".",
"ordered_structures",
"ordered_structures_origins",
"=",
"self",
".",
"ordered_structure_origins",
"# utility functi... | 41.209302 | 22.337209 |
def base_url(self):
'''The public URL for this storage'''
config_value = self.config.get('url')
if config_value:
return self._clean_url(config_value)
default_url = current_app.config.get('FS_URL')
default_url = current_app.config.get('{0}URL'.format(self.backend_prefi... | [
"def",
"base_url",
"(",
"self",
")",
":",
"config_value",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'url'",
")",
"if",
"config_value",
":",
"return",
"self",
".",
"_clean_url",
"(",
"config_value",
")",
"default_url",
"=",
"current_app",
".",
"config",... | 47.363636 | 17.363636 |
def clickable(self):
"""
Property used for determining if the widget should be clickable by the user.
This is only true if the submenu of this widget is active and this widget is enabled.
The widget may be either disabled by setting this property or the :py:attr:`enable... | [
"def",
"clickable",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"submenu",
",",
"Container",
")",
":",
"return",
"self",
".",
"submenu",
".",
"name",
"==",
"self",
".",
"submenu",
".",
"menu",
".",
"activeSubMenu",
"and",
"self"... | 50 | 33.333333 |
def check_get_revoked(self):
"""
Create a CRL object with 100 Revoked objects, then call the
get_revoked method repeatedly.
"""
crl = CRL()
for i in xrange(100):
crl.add_revoked(Revoked())
for i in xrange(self.iterations):
crl.get_revoked() | [
"def",
"check_get_revoked",
"(",
"self",
")",
":",
"crl",
"=",
"CRL",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",
"100",
")",
":",
"crl",
".",
"add_revoked",
"(",
"Revoked",
"(",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"iterations",
... | 31.1 | 8.7 |
def get_default_pandas_parsers() -> List[AnyParser]:
"""
Utility method to return the default parsers able to parse a dictionary from a file.
:return:
"""
return [SingleFileParserFunction(parser_function=read_dataframe_from_xls,
streaming_mode=False,
... | [
"def",
"get_default_pandas_parsers",
"(",
")",
"->",
"List",
"[",
"AnyParser",
"]",
":",
"return",
"[",
"SingleFileParserFunction",
"(",
"parser_function",
"=",
"read_dataframe_from_xls",
",",
"streaming_mode",
"=",
"False",
",",
"supported_exts",
"=",
"{",
"'.xls'"... | 57.0625 | 28.0625 |
def _create_run_ini(self, port, production, output='development.ini',
source='development.ini', override_site_url=True):
"""
Create run/development.ini in datadir with debug and site_url overridden
and with correct db passwords inserted
"""
cp = SafeConfig... | [
"def",
"_create_run_ini",
"(",
"self",
",",
"port",
",",
"production",
",",
"output",
"=",
"'development.ini'",
",",
"source",
"=",
"'development.ini'",
",",
"override_site_url",
"=",
"True",
")",
":",
"cp",
"=",
"SafeConfigParser",
"(",
")",
"try",
":",
"cp... | 44.162791 | 21.511628 |
def create_message_set(messages, codec=CODEC_NONE, key=None, compresslevel=None):
"""Create a message set using the given codec.
If codec is CODEC_NONE, return a list of raw Kafka messages. Otherwise,
return a list containing a single codec-encoded message.
"""
if codec == CODEC_NONE:
retur... | [
"def",
"create_message_set",
"(",
"messages",
",",
"codec",
"=",
"CODEC_NONE",
",",
"key",
"=",
"None",
",",
"compresslevel",
"=",
"None",
")",
":",
"if",
"codec",
"==",
"CODEC_NONE",
":",
"return",
"[",
"create_message",
"(",
"m",
",",
"k",
")",
"for",
... | 44.285714 | 20.785714 |
def _set_reg(cls, reg):
"""The writing complement of _get_reg
"""
cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS] | [
"def",
"_set_reg",
"(",
"cls",
",",
"reg",
")",
":",
"cls",
".",
"_reg",
"=",
"[",
"task_cls",
"for",
"task_cls",
"in",
"reg",
".",
"values",
"(",
")",
"if",
"task_cls",
"is",
"not",
"cls",
".",
"AMBIGUOUS_CLASS",
"]"
] | 44 | 18.5 |
def getActiveProperties(self):
""" Returns the non-zero accidental dignities. """
score = self.getScoreProperties()
return {key: value for (key, value) in score.items()
if value != 0} | [
"def",
"getActiveProperties",
"(",
"self",
")",
":",
"score",
"=",
"self",
".",
"getScoreProperties",
"(",
")",
"return",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"score",
".",
"items",
"(",
")",
"if",
"value",
"!=",
"0",... | 43.8 | 8.2 |
def file_contents(file_name):
"""Given a file name to a valid file returns the file object."""
curr_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(curr_dir, file_name)) as the_file:
contents = the_file.read()
return contents | [
"def",
"file_contents",
"(",
"file_name",
")",
":",
"curr_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_dir",
",",
"f... | 44.666667 | 12.666667 |
def add_package(package,
ignore_check=False,
prevent_pending=False,
image=None,
restart=False):
'''
Install a package using DISM
Args:
package (str):
The package to install. Can be a .cab file, a .msu file, or a folder
... | [
"def",
"add_package",
"(",
"package",
",",
"ignore_check",
"=",
"False",
",",
"prevent_pending",
"=",
"False",
",",
"image",
"=",
"None",
",",
"restart",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'DISM'",
",",
"'/Quiet'",
",",
"'/Image:{0}'",
".",
"forma... | 28.833333 | 22.87037 |
def normalize_datum(self, datum):
"""
Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:... | [
"def",
"normalize_datum",
"(",
"self",
",",
"datum",
")",
":",
"if",
"datum",
"is",
"None",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
"self",
".",
"PACKABLE_TYPES",
")",
":",
"return",
"datum",
"if",
"isinstance",
"(",
"datum",
",",
... | 50.347368 | 26.115789 |
def collect_string_fields(format_string) -> Iterable[Optional[str]]:
""" Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
"""
formatter = string.Formatter()
try:
parseiterator = formatter.parse(format_string)
for result i... | [
"def",
"collect_string_fields",
"(",
"format_string",
")",
"->",
"Iterable",
"[",
"Optional",
"[",
"str",
"]",
"]",
":",
"formatter",
"=",
"string",
".",
"Formatter",
"(",
")",
"try",
":",
"parseiterator",
"=",
"formatter",
".",
"parse",
"(",
"format_string"... | 40.903226 | 16.193548 |
def update_role_config_group(self, name, apigroup):
"""
Update a role config group.
@param name: Role config group name.
@param apigroup: The updated role config group.
@return: The updated ApiRoleConfigGroup object.
@since: API v3
"""
return role_config_groups.update_role_config_group(... | [
"def",
"update_role_config_group",
"(",
"self",
",",
"name",
",",
"apigroup",
")",
":",
"return",
"role_config_groups",
".",
"update_role_config_group",
"(",
"self",
".",
"_get_resource_root",
"(",
")",
",",
"self",
".",
"name",
",",
"name",
",",
"apigroup",
"... | 33.75 | 12.25 |
def workers(ctx, account, top):
""" List all workers (of an account)
"""
workers = Workers(account)
t = [["id", "name/url", "daily_pay", "votes", "time", "account"]]
workers_sorted = sorted(
workers, key=lambda x: int(x["total_votes_for"]), reverse=True
)
if top:
workers_sort... | [
"def",
"workers",
"(",
"ctx",
",",
"account",
",",
"top",
")",
":",
"workers",
"=",
"Workers",
"(",
"account",
")",
"t",
"=",
"[",
"[",
"\"id\"",
",",
"\"name/url\"",
",",
"\"daily_pay\"",
",",
"\"votes\"",
",",
"\"time\"",
",",
"\"account\"",
"]",
"]"... | 36.071429 | 20.25 |
def archive_wheelfile(base_name, base_dir):
"""Archive all files under `base_dir` in a whl file and name it like
`base_name`.
"""
olddir = os.path.abspath(os.curdir)
base_name = os.path.abspath(base_name)
try:
os.chdir(base_dir)
return make_wheelfile_inner(base_name)
finally:... | [
"def",
"archive_wheelfile",
"(",
"base_name",
",",
"base_dir",
")",
":",
"olddir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"curdir",
")",
"base_name",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"base_name",
")",
"try",
":",
"os",
".... | 30.454545 | 11.454545 |
def refresh_cache(self, if_want_update=False):
"""Update all threads currently stored in our cache."""
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update() | [
"def",
"refresh_cache",
"(",
"self",
",",
"if_want_update",
"=",
"False",
")",
":",
"for",
"thread",
"in",
"tuple",
"(",
"self",
".",
"_thread_cache",
".",
"values",
"(",
")",
")",
":",
"if",
"if_want_update",
":",
"if",
"not",
"thread",
".",
"want_updat... | 41.857143 | 8.571429 |
def schema_term(self):
"""Return the Table term for this resource, which is referenced either by the `table` property or the
`schema` property"""
if not self.name:
raise MetapackError("Resource for url '{}' doe not have name".format(self.url))
t = self.doc.find_first('Root.... | [
"def",
"schema_term",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"raise",
"MetapackError",
"(",
"\"Resource for url '{}' doe not have name\"",
".",
"format",
"(",
"self",
".",
"url",
")",
")",
"t",
"=",
"self",
".",
"doc",
".",
"find_fir... | 30.5 | 26.777778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.