text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def read_file(filename):
"""Reads a file which matches the pattern `filename`.
Args:
filename The filename pattern
Returns:
The file content or the empty string, if the file is not found.
"""
hits = glob.glob('**/{}'.format(filename), recursive=True)
if not len(hits):
p... | [
"def",
"read_file",
"(",
"filename",
")",
":",
"hits",
"=",
"glob",
".",
"glob",
"(",
"'**/{}'",
".",
"format",
"(",
"filename",
")",
",",
"recursive",
"=",
"True",
")",
"if",
"not",
"len",
"(",
"hits",
")",
":",
"pf",
".",
"debug",
"(",
"'No file ... | 29.444444 | 0.001828 |
def home_mode_set_state(self, state, **kwargs):
"""Set the state of Home Mode"""
# It appears that surveillance station needs lowercase text
# true/false for the on switch
if state not in (HOME_MODE_ON, HOME_MODE_OFF):
raise ValueError('Invalid home mode state')
api... | [
"def",
"home_mode_set_state",
"(",
"self",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"# It appears that surveillance station needs lowercase text",
"# true/false for the on switch",
"if",
"state",
"not",
"in",
"(",
"HOME_MODE_ON",
",",
"HOME_MODE_OFF",
")",
":",
... | 30.863636 | 0.002857 |
def __apply_mask(address_packed, mask_packed, nr_bytes):
"""
Perform a bitwise AND operation on all corresponding bytes between the
mask and the provided address. Mask parts set to 0 will become 0 in the
anonymized IP address as well
:param bytes address_packed: Binary representation of the IP addre... | [
"def",
"__apply_mask",
"(",
"address_packed",
",",
"mask_packed",
",",
"nr_bytes",
")",
":",
"anon_packed",
"=",
"bytearray",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"nr_bytes",
")",
":",
"anon_packed",
".",
"append",
"(",
"ord",
"(",
"mask_p... | 40.368421 | 0.001274 |
def ppo_opt_step(i,
opt_state,
ppo_opt_update,
policy_net_apply,
old_policy_params,
value_net_apply,
value_net_params,
padded_observations,
padded_actions,
padded_rewa... | [
"def",
"ppo_opt_step",
"(",
"i",
",",
"opt_state",
",",
"ppo_opt_update",
",",
"policy_net_apply",
",",
"old_policy_params",
",",
"value_net_apply",
",",
"value_net_params",
",",
"padded_observations",
",",
"padded_actions",
",",
"padded_rewards",
",",
"reward_mask",
... | 29.064516 | 0.005371 |
def get_group_by_id(self, group_id) -> typing.Optional['Group']:
"""
Args:
group_id: group id
Returns: Group
"""
for group in self.groups:
if group.group_id == group_id:
return group
return None | [
"def",
"get_group_by_id",
"(",
"self",
",",
"group_id",
")",
"->",
"typing",
".",
"Optional",
"[",
"'Group'",
"]",
":",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"if",
"group",
".",
"group_id",
"==",
"group_id",
":",
"return",
"group",
"return",
... | 21 | 0.007018 |
def getWidth(self):
"""
Get the width of the text output for the table.
@rtype: int
@return: Width in characters for the text output,
including the newline character.
"""
width = 0
if self.__width:
width = sum( abs(x) for x in self.__widt... | [
"def",
"getWidth",
"(",
"self",
")",
":",
"width",
"=",
"0",
"if",
"self",
".",
"__width",
":",
"width",
"=",
"sum",
"(",
"abs",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"__width",
")",
"width",
"=",
"width",
"+",
"len",
"(",
"self",
".",
... | 30.769231 | 0.009709 |
def get_arrays(self, lines, personalities=[]):
"""Return a dict of arrays."""
ret = {}
i = 0
while i < len(lines):
try:
# First array line: get the md device
md_device = self.get_md_device_name(lines[i])
except IndexError:
... | [
"def",
"get_arrays",
"(",
"self",
",",
"lines",
",",
"personalities",
"=",
"[",
"]",
")",
":",
"ret",
"=",
"{",
"}",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"lines",
")",
":",
"try",
":",
"# First array line: get the md device",
"md_device",
"=",... | 32.130435 | 0.003942 |
def mute(self):
"""get/set the current mute state"""
response = self.rendering_control.GetMute(InstanceID=1, Channel=1)
return response.CurrentMute == 1 | [
"def",
"mute",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"rendering_control",
".",
"GetMute",
"(",
"InstanceID",
"=",
"1",
",",
"Channel",
"=",
"1",
")",
"return",
"response",
".",
"CurrentMute",
"==",
"1"
] | 43.25 | 0.011364 |
def _decode(obj): # type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821
"""Decode an object to unicode.
Args:
obj (bytes or str or unicode or anything serializable): object to be decoded
Returns:
object decoded in unicode.
"""
if obj is None:
return u''
... | [
"def",
"_decode",
"(",
"obj",
")",
":",
"# type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821",
"if",
"obj",
"is",
"None",
":",
"return",
"u''",
"if",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"obj",
",",
"six",
".",
"binary_type",
")",
"... | 33.714286 | 0.002747 |
def _render_hs_label(self, hs):
"""Return the label of the given Hilbert space as a string"""
if isinstance(hs.__class__, Singleton):
return self._render_str(hs.label)
else:
return self._tensor_sym.join(
[self._render_str(ls.label) for ls in hs.local_facto... | [
"def",
"_render_hs_label",
"(",
"self",
",",
"hs",
")",
":",
"if",
"isinstance",
"(",
"hs",
".",
"__class__",
",",
"Singleton",
")",
":",
"return",
"self",
".",
"_render_str",
"(",
"hs",
".",
"label",
")",
"else",
":",
"return",
"self",
".",
"_tensor_s... | 45.428571 | 0.006173 |
def add_expiration_rule(self, criterion, value, timeout, use_mod_time=False):
"""Adds statics expiration rule based on a criterion.
:param str|unicode criterion: Criterion (subject) to base expiration on.
See ``.expiration_criteria``.
:param str|unicode|list[str|unicode] value: Va... | [
"def",
"add_expiration_rule",
"(",
"self",
",",
"criterion",
",",
"value",
",",
"timeout",
",",
"use_mod_time",
"=",
"False",
")",
":",
"command",
"=",
"'static-expires'",
"separator",
"=",
"' '",
"if",
"criterion",
"!=",
"self",
".",
"expiration_criteria",
".... | 28.514286 | 0.005814 |
def ingest_config_obj(ctx, *, silent=True):
""" Ingest the configuration object into the click context. """
try:
ctx.obj['config'] = Config.from_file(ctx.obj['config_path'])
except ConfigLoadError as err:
click.echo(_style(ctx.obj['show_color'], str(err), fg='red', bold=True))
if not... | [
"def",
"ingest_config_obj",
"(",
"ctx",
",",
"*",
",",
"silent",
"=",
"True",
")",
":",
"try",
":",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"=",
"Config",
".",
"from_file",
"(",
"ctx",
".",
"obj",
"[",
"'config_path'",
"]",
")",
"except",
"ConfigLoa... | 44.125 | 0.005556 |
def fromSchedulerConstructorArgs(change_filter=None,
branch=NotABranch, categories=None):
"""
Static method to create a filter based on constructor args
change_filter, branch, and categories; use default values @code{None},
@code{NotABranch}, and @cod... | [
"def",
"fromSchedulerConstructorArgs",
"(",
"change_filter",
"=",
"None",
",",
"branch",
"=",
"NotABranch",
",",
"categories",
"=",
"None",
")",
":",
"# use a change_filter, if given one",
"if",
"change_filter",
":",
"if",
"(",
"branch",
"is",
"not",
"NotABranch",
... | 42.448276 | 0.002383 |
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
dateti... | [
"def",
"convert_utc_time",
"(",
"datetime_str",
")",
":",
"if",
"not",
"datetime_str",
":",
"return",
"None",
"if",
"not",
"set",
"(",
"[",
"'-'",
",",
"':'",
"]",
")",
"&",
"set",
"(",
"datetime_str",
")",
":",
"_date",
"=",
"datetime",
".",
"datetime... | 32.175 | 0.000754 |
def clean(self):
"""
Authenticate the given username/email and password. If the fields
are valid, store the authenticated user for returning via save().
"""
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
self._user = auth... | [
"def",
"clean",
"(",
"self",
")",
":",
"username",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"\"username\"",
")",
"password",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"\"password\"",
")",
"self",
".",
"_user",
"=",
"authenticate",
"(",... | 46.642857 | 0.003003 |
def getsz(self, addr):
"""Get zero-terminated bytes string from given address. Will raise
NotEnoughDataError exception if a hole is encountered before a 0.
"""
i = 0
try:
while True:
if self._buf[addr+i] == 0:
break
... | [
"def",
"getsz",
"(",
"self",
",",
"addr",
")",
":",
"i",
"=",
"0",
"try",
":",
"while",
"True",
":",
"if",
"self",
".",
"_buf",
"[",
"addr",
"+",
"i",
"]",
"==",
"0",
":",
"break",
"i",
"+=",
"1",
"except",
"KeyError",
":",
"raise",
"NotEnoughD... | 36.5 | 0.005725 |
def del_action_role(ctx):
"""Deletes a role from an action on objects"""
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or role is None:
log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
... | [
"def",
"del_action_role",
"(",
"ctx",
")",
":",
"objects",
"=",
"ctx",
".",
"obj",
"[",
"'objects'",
"]",
"action",
"=",
"ctx",
".",
"obj",
"[",
"'action'",
"]",
"role",
"=",
"ctx",
".",
"obj",
"[",
"'role'",
"]",
"if",
"action",
"is",
"None",
"or"... | 27.294118 | 0.004167 |
def from_linearized(first, second, intersections):
"""Determine curve-curve intersection from pair of linearizations.
.. note::
This assumes that at least one of ``first`` and ``second`` is
not a line. The line-line case should be handled "early"
by :func:`check_lines`.
.. note::
... | [
"def",
"from_linearized",
"(",
"first",
",",
"second",
",",
"intersections",
")",
":",
"# NOTE: There is no corresponding \"enable\", but the disable only applies",
"# in this lexical scope.",
"# pylint: disable=too-many-return-statements",
"s",
",",
"t",
",",
"success",
"=... | 36.75 | 0.000368 |
def from_molecule(cls, mol, theory, charge=None, spin_multiplicity=None,
basis_set="6-31g", basis_set_option="cartesian",
title=None, operation="optimize", theory_directives=None,
alternate_directives=None):
"""
Very flexible arguments to... | [
"def",
"from_molecule",
"(",
"cls",
",",
"mol",
",",
"theory",
",",
"charge",
"=",
"None",
",",
"spin_multiplicity",
"=",
"None",
",",
"basis_set",
"=",
"\"6-31g\"",
",",
"basis_set_option",
"=",
"\"cartesian\"",
",",
"title",
"=",
"None",
",",
"operation",
... | 52.096774 | 0.001519 |
def title(self):
"""
Returns the title for this axis.
:return <str>
"""
if not self._title:
return projex.text.pretty(self.name())
return self._title | [
"def",
"title",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_title",
":",
"return",
"projex",
".",
"text",
".",
"pretty",
"(",
"self",
".",
"name",
"(",
")",
")",
"return",
"self",
".",
"_title"
] | 24.666667 | 0.013043 |
def get_fmt_results(results, limit=5, sep='::', fmt=None):
"""
Return a list of formatted strings representation on a result dictionary.
The elements of the key are divided by a separator string. The result is
appended after the key between parentheses. Apply a format transformation
to odd elements ... | [
"def",
"get_fmt_results",
"(",
"results",
",",
"limit",
"=",
"5",
",",
"sep",
"=",
"'::'",
",",
"fmt",
"=",
"None",
")",
":",
"result_list",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"results",
",",
"key",
"=",
"lambda",
"x",
":",
"results"... | 43 | 0.003249 |
def _set_optimizer_param(optimizer, param_group, param_name, value):
"""Set a parameter on an all or a specific parameter group of an
optimizer instance. To select all param groups, use ``param_group='all'``.
"""
if param_group == 'all':
groups = optimizer.param_groups
else:
groups =... | [
"def",
"_set_optimizer_param",
"(",
"optimizer",
",",
"param_group",
",",
"param_name",
",",
"value",
")",
":",
"if",
"param_group",
"==",
"'all'",
":",
"groups",
"=",
"optimizer",
".",
"param_groups",
"else",
":",
"groups",
"=",
"[",
"optimizer",
".",
"para... | 37.545455 | 0.002364 |
def fit_var(self):
""" Fit a VAR model to the source activations.
Returns
-------
self : Workspace
The Workspace object.
Raises
------
RuntimeError
If the :class:`Workspace` instance does not contain source activations.
"""
... | [
"def",
"fit_var",
"(",
"self",
")",
":",
"if",
"self",
".",
"activations_",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"VAR fitting requires source activations (run do_mvarica first)\"",
")",
"self",
".",
"var_",
".",
"fit",
"(",
"data",
"=",
"self",
"."... | 33.833333 | 0.007987 |
def save_state(self, fname: str):
"""
Saves the current state of iterator to a file, so that iteration can be
continued. Note that the data is not saved, i.e. the iterator must be
initialized with the same parameters as in the first call.
:param fname: File name to save the info... | [
"def",
"save_state",
"(",
"self",
",",
"fname",
":",
"str",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"wb\"",
")",
"as",
"fp",
":",
"pickle",
".",
"dump",
"(",
"self",
".",
"batch_indices",
",",
"fp",
")",
"pickle",
".",
"dump",
"(",
"self",
... | 47.538462 | 0.003175 |
def reset(self):
"""!
\~english Reset display
\~chinese 复位显示屏
"""
if self._spi_reset == None: return
GPIO.output( self._spi_reset, 1 )
time.sleep(0.002)
GPIO.output( self._spi_reset, 0 )
time.sleep(0.015)
GPIO.output( self._spi_reset, 1 ) | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_spi_reset",
"==",
"None",
":",
"return",
"GPIO",
".",
"output",
"(",
"self",
".",
"_spi_reset",
",",
"1",
")",
"time",
".",
"sleep",
"(",
"0.002",
")",
"GPIO",
".",
"output",
"(",
"self",
... | 28 | 0.037736 |
def is_shutting_down(
self,
shutdown_event):
"""is_shutting_down
Determine if the parent is shutting down or this was
triggered to shutdown
:param shutdown_event: shutdown event
"""
return bool(
shutdown_event.is_set()
or... | [
"def",
"is_shutting_down",
"(",
"self",
",",
"shutdown_event",
")",
":",
"return",
"bool",
"(",
"shutdown_event",
".",
"is_set",
"(",
")",
"or",
"self",
".",
"shutdown_now",
"or",
"self",
".",
"run_once",
")"
] | 23.6 | 0.005435 |
def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None):
""" Create a CAS login URL .
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas)
service -- (ex. http://localhost:5000/login)
r... | [
"def",
"create_cas_login_url",
"(",
"cas_url",
",",
"cas_route",
",",
"service",
",",
"renew",
"=",
"None",
",",
"gateway",
"=",
"None",
")",
":",
"return",
"create_url",
"(",
"cas_url",
",",
"cas_route",
",",
"(",
"'service'",
",",
"service",
")",
",",
... | 29.24 | 0.002649 |
def _CopyTimeFromString(self, time_string):
"""Copies a time from a string.
Args:
time_string (str): time value formatted as:
hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The seconds fraction a... | [
"def",
"_CopyTimeFromString",
"(",
"self",
",",
"time_string",
")",
":",
"time_string_length",
"=",
"len",
"(",
"time_string",
")",
"# The time string should at least contain 'hh:mm:ss'.",
"if",
"time_string_length",
"<",
"8",
":",
"raise",
"ValueError",
"(",
"'Time str... | 33.295652 | 0.008623 |
def remove_rows_containing(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the DataFrame.
... | [
"def",
"remove_rows_containing",
"(",
"df",
",",
"column",
",",
"match",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"mask",
"=",
"[",
"match",
"not",
"in",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"df",
"[",
"column",
"]",
".",
"values",
... | 38.2 | 0.005111 |
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
"""
Insert the language tabs.
"""
if self._has_translatable_model():
lang_code = self.get_form_language(request, obj)
lang = get_language_title(lang_code)
... | [
"def",
"render_change_form",
"(",
"self",
",",
"request",
",",
"context",
",",
"add",
"=",
"False",
",",
"change",
"=",
"False",
",",
"form_url",
"=",
"''",
",",
"obj",
"=",
"None",
")",
":",
"if",
"self",
".",
"_has_translatable_model",
"(",
")",
":",... | 47.794118 | 0.004222 |
def delete_token(self,
token_name,
project_name,
dataset_name):
"""
Delete a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Dataset name project is based on
... | [
"def",
"delete_token",
"(",
"self",
",",
"token_name",
",",
"project_name",
",",
"dataset_name",
")",
":",
"url",
"=",
"self",
".",
"url",
"(",
")",
"+",
"\"/nd/resource/dataset/{}\"",
".",
"format",
"(",
"dataset_name",
")",
"+",
"\"/project/{}\"",
".",
"fo... | 37.88 | 0.005149 |
def _rebuild_indicator(self):
""" update the indicator """
indicator = {'term':np.array([]),
'row':np.array([]),
'col':np.array([])}
for term in range(self.n_terms):
L = self.A[term].shape[0]
K = self.F[term].shape[1]
... | [
"def",
"_rebuild_indicator",
"(",
"self",
")",
":",
"indicator",
"=",
"{",
"'term'",
":",
"np",
".",
"array",
"(",
"[",
"]",
")",
",",
"'row'",
":",
"np",
".",
"array",
"(",
"[",
"]",
")",
",",
"'col'",
":",
"np",
".",
"array",
"(",
"[",
"]",
... | 46.466667 | 0.02391 |
def create_vault_ec2_certificate_configuration(self, cert_name, aws_public_cert, mount_point='aws-ec2'):
"""POST /auth/<mount_point>/config/certificate/<cert_name>
:param cert_name:
:type cert_name:
:param aws_public_cert:
:type aws_public_cert:
:param mount_point:
... | [
"def",
"create_vault_ec2_certificate_configuration",
"(",
"self",
",",
"cert_name",
",",
"aws_public_cert",
",",
"mount_point",
"=",
"'aws-ec2'",
")",
":",
"params",
"=",
"{",
"'cert_name'",
":",
"cert_name",
",",
"'aws_public_cert'",
":",
"aws_public_cert",
"}",
"r... | 35.235294 | 0.006504 |
def add_child_resource_client(self, res_name, res_spec):
"""Add a resource client to the container and start the resource connection"""
res_spec = dict(res_spec)
res_spec['name'] = res_name
res = self.client_resource_factory(
res_spec, parent=self, logger=self._logger)
... | [
"def",
"add_child_resource_client",
"(",
"self",
",",
"res_name",
",",
"res_spec",
")",
":",
"res_spec",
"=",
"dict",
"(",
"res_spec",
")",
"res_spec",
"[",
"'name'",
"]",
"=",
"res_name",
"res",
"=",
"self",
".",
"client_resource_factory",
"(",
"res_spec",
... | 43.545455 | 0.00818 |
def fix_reserved_word(word, is_module=False):
"""
Replaces words that may be problematic
In particular the term 'type' is used in the osid spec, primarily as an argument
parameter where a type is provided to a method. 'type' is a reserved word
in python, so we give ours a trailing underscore. If w... | [
"def",
"fix_reserved_word",
"(",
"word",
",",
"is_module",
"=",
"False",
")",
":",
"if",
"is_module",
":",
"if",
"word",
"==",
"'logging'",
":",
"word",
"=",
"'logging_'",
"# Still deciding this",
"else",
":",
"if",
"keyword",
".",
"iskeyword",
"(",
"word",
... | 36.47619 | 0.005089 |
def inline(self) -> str:
"""
Return inline document string
:return:
"""
return "{0}:{1}:{2}:{3}".format(self.pubkey_from, self.pubkey_to,
self.timestamp.number, self.signatures[0]) | [
"def",
"inline",
"(",
"self",
")",
"->",
"str",
":",
"return",
"\"{0}:{1}:{2}:{3}\"",
".",
"format",
"(",
"self",
".",
"pubkey_from",
",",
"self",
".",
"pubkey_to",
",",
"self",
".",
"timestamp",
".",
"number",
",",
"self",
".",
"signatures",
"[",
"0",
... | 31.75 | 0.011494 |
def sizeHint(self, option, index):
"""
Returns the size hint for the inputed index.
:param option | <QStyleOptionViewItem>
index | <QModelIndex>
:return <QtCore.QSize>
"""
size = super(XTreeWidgetDelegate, self).s... | [
"def",
"sizeHint",
"(",
"self",
",",
"option",
",",
"index",
")",
":",
"size",
"=",
"super",
"(",
"XTreeWidgetDelegate",
",",
"self",
")",
".",
"sizeHint",
"(",
"option",
",",
"index",
")",
"tree",
"=",
"self",
".",
"parent",
"(",
")",
"item",
"=",
... | 27.347826 | 0.013825 |
def set_ie_mode():
"""
By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value
must be set for the executable.
See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this
behaviour.
"""
... | [
"def",
"set_ie_mode",
"(",
")",
":",
"try",
":",
"import",
"_winreg",
"as",
"winreg",
"# Python 2",
"except",
"ImportError",
":",
"import",
"winreg",
"# Python 3",
"def",
"get_ie_mode",
"(",
")",
":",
"\"\"\"\n Get the installed version of IE\n :return:\n ... | 40.015625 | 0.004192 |
def get_filename(self, *parts):
'''
Returns an absolute filename in the data-directory (standardized by StandardizePath).
@params parts: list(unicode)
Path parts. Each part is joined to form a path.
:rtype: unicode
:returns:
The full path prefixed with t... | [
"def",
"get_filename",
"(",
"self",
",",
"*",
"parts",
")",
":",
"from",
"zerotk",
".",
"easyfs",
"import",
"StandardizePath",
"result",
"=",
"[",
"self",
".",
"_data_dir",
"]",
"+",
"list",
"(",
"parts",
")",
"result",
"=",
"'/'",
".",
"join",
"(",
... | 30.789474 | 0.004975 |
def K_ball_valve_Crane(D1, D2, angle, fd=None):
r'''Returns the loss coefficient for a ball valve as shown in [1]_.
If β = 1:
.. math::
K = K_1 = K_2 = 3f_d
If β < 1 and θ <= 45°:
.. math::
K_2 = \frac{K + \sin \frac{\theta}{2} \left[0.8(1-\beta^2)
... | [
"def",
"K_ball_valve_Crane",
"(",
"D1",
",",
"D2",
",",
"angle",
",",
"fd",
"=",
"None",
")",
":",
"if",
"fd",
"is",
"None",
":",
"fd",
"=",
"ft_Crane",
"(",
"D2",
")",
"beta",
"=",
"D1",
"/",
"D2",
"K1",
"=",
"3",
"*",
"fd",
"angle",
"=",
"r... | 27.850746 | 0.008282 |
def convert_items(data, mapping):
"""
Input: list of dicts (each dict a record for one item),
mapping with column names to swap into the records.
Output: updated list of dicts.
"""
new_recs = []
for rec in data:
new_rec = map_magic.mapping(rec, mapping)
new_recs.append(new_re... | [
"def",
"convert_items",
"(",
"data",
",",
"mapping",
")",
":",
"new_recs",
"=",
"[",
"]",
"for",
"rec",
"in",
"data",
":",
"new_rec",
"=",
"map_magic",
".",
"mapping",
"(",
"rec",
",",
"mapping",
")",
"new_recs",
".",
"append",
"(",
"new_rec",
")",
"... | 30.181818 | 0.002924 |
def remove(self, point, **kwargs):
"""!
@brief Remove specified point from kd-tree.
@details It removes the first found node that satisfy to the input parameters. Make sure that
pair (point, payload) is unique for each node, othewise the first found is removed.
... | [
"def",
"remove",
"(",
"self",
",",
"point",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get required node\r",
"node_for_remove",
"=",
"None",
"if",
"'payload'",
"in",
"kwargs",
":",
"node_for_remove",
"=",
"self",
".",
"find_node_with_payload",
"(",
"point",
",",
... | 38.804878 | 0.00981 |
def generate(self):
"""
Generates the report
"""
self._setup()
header_html = self._generate_header()
footer_html = self._generate_footer()
results_topbar_html = self._generate_topbar("results")
summary_topbar_html = self._generate_topbar("summary")
logs_topbar_html = self._generate_... | [
"def",
"generate",
"(",
"self",
")",
":",
"self",
".",
"_setup",
"(",
")",
"header_html",
"=",
"self",
".",
"_generate_header",
"(",
")",
"footer_html",
"=",
"self",
".",
"_generate_footer",
"(",
")",
"results_topbar_html",
"=",
"self",
".",
"_generate_topba... | 46.789474 | 0.008264 |
def get_install_requirements_dockerfile(self, name: str, tag: str, repo_path: Path,
requirements_option: RequirementsOptions) -> str:
"""
Returns the content of a Dockerfile that will install requirements based on the repository,
prioritizing Pipfile o... | [
"def",
"get_install_requirements_dockerfile",
"(",
"self",
",",
"name",
":",
"str",
",",
"tag",
":",
"str",
",",
"repo_path",
":",
"Path",
",",
"requirements_option",
":",
"RequirementsOptions",
")",
"->",
"str",
":",
"if",
"requirements_option",
"==",
"Requirem... | 43.861111 | 0.006815 |
def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2):
'''
TT completion via Alternating Least Squares algorithm.
Parameters:
:dict: cooP
dictionary with two records
- 'indices': numpy.array of P x d shape,
... | [
"def",
"ttSparseALS",
"(",
"cooP",
",",
"shape",
",",
"x0",
"=",
"None",
",",
"ttRank",
"=",
"1",
",",
"tol",
"=",
"1e-5",
",",
"maxnsweeps",
"=",
"20",
",",
"verbose",
"=",
"True",
",",
"alpha",
"=",
"1e-2",
")",
":",
"indices",
"=",
"cooP",
"["... | 37.873134 | 0.005376 |
def initialize(self, id=None, text=None):
self.id = none_or(id, int)
"""
Contributing user's identifier : int | None
"""
self.text = none_or(text, str)
"""
Username or IP address of the user at the time of the edit : str | None
""" | [
"def",
"initialize",
"(",
"self",
",",
"id",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"self",
".",
"id",
"=",
"none_or",
"(",
"id",
",",
"int",
")",
"self",
".",
"text",
"=",
"none_or",
"(",
"text",
",",
"str",
")",
"\"\"\"\n Usernam... | 28.7 | 0.010135 |
def handle_range(schema, field, validator, parent_schema):
"""Adds validation logic for ``marshmallow.validate.Range``, setting the
values appropriately ``fields.Number`` and it's subclasses.
Args:
schema (dict): The original JSON schema we generated. This is what we
want to post-proces... | [
"def",
"handle_range",
"(",
"schema",
",",
"field",
",",
"validator",
",",
"parent_schema",
")",
":",
"if",
"not",
"isinstance",
"(",
"field",
",",
"fields",
".",
"Number",
")",
":",
"return",
"schema",
"if",
"validator",
".",
"min",
":",
"schema",
"[",
... | 34.242424 | 0.000861 |
def brightness_temp(self, band, temp_scale='K'):
"""Calculate brightness temperature of Landsat 8
as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php
T = K2 / log((K1 / L) + 1)
and
L = ML * Q + AL
where:
T = At-satellite brightness temperature (degrees kelvin)
... | [
"def",
"brightness_temp",
"(",
"self",
",",
"band",
",",
"temp_scale",
"=",
"'K'",
")",
":",
"if",
"band",
"in",
"self",
".",
"oli_bands",
":",
"raise",
"ValueError",
"(",
"'Landsat 8 brightness should be TIRS band (i.e. 10 or 11)'",
")",
"k1",
"=",
"getattr",
"... | 35.55102 | 0.002235 |
def _load_params_of(self, effect):
"""
Called only when a effect has created
Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()`
"""
for param in effect.params:
if param.value != param.default:
... | [
"def",
"_load_params_of",
"(",
"self",
",",
"effect",
")",
":",
"for",
"param",
"in",
"effect",
".",
"params",
":",
"if",
"param",
".",
"value",
"!=",
"param",
".",
"default",
":",
"self",
".",
"_set_param_value",
"(",
"param",
")"
] | 43.75 | 0.008403 |
def _populate_and_save_user_profile(self):
"""
Populates a User profile object with fields from the LDAP directory.
"""
try:
app_label, class_name = django.conf.settings.AUTH_PROFILE_MODULE.split('.')
profile_model = apps.get_model(app_label, class_name)
... | [
"def",
"_populate_and_save_user_profile",
"(",
"self",
")",
":",
"try",
":",
"app_label",
",",
"class_name",
"=",
"django",
".",
"conf",
".",
"settings",
".",
"AUTH_PROFILE_MODULE",
".",
"split",
"(",
"'.'",
")",
"profile_model",
"=",
"apps",
".",
"get_model",... | 50.423077 | 0.008234 |
def DbPutDeviceAttributeProperty2(self, argin):
""" Put device attribute property. This command adds the possibility to have attribute property
which are arrays. Not possible with the old DbPutDeviceAttributeProperty command.
This old command is not deleted for compatibility reasons.
:p... | [
"def",
"DbPutDeviceAttributeProperty2",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbPutDeviceAttributeProperty2()\"",
")",
"device_name",
"=",
"argin",
"[",
"0",
"]",
"nb_attributes",
"=",
"int",
"(",
"argin",
"[",
"1",... | 43.619048 | 0.005342 |
def _method_magic_marker(magic_kind):
"""Decorator factory for methods in Magics subclasses.
"""
validate_type(magic_kind)
# This is a closure to capture the magic_kind. We could also use a class,
# but it's overkill for just that one bit of state.
def magic_deco(arg):
call = lambda f... | [
"def",
"_method_magic_marker",
"(",
"magic_kind",
")",
":",
"validate_type",
"(",
"magic_kind",
")",
"# This is a closure to capture the magic_kind. We could also use a class,",
"# but it's overkill for just that one bit of state.",
"def",
"magic_deco",
"(",
"arg",
")",
":",
"ca... | 36.40625 | 0.002508 |
def update_lan(self, datacenter_id, lan_id, name=None,
public=None, ip_failover=None):
"""
Updates a LAN
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param lan_id: The unique ID of the LAN.
:typ... | [
"def",
"update_lan",
"(",
"self",
",",
"datacenter_id",
",",
"lan_id",
",",
"name",
"=",
"None",
",",
"public",
"=",
"None",
",",
"ip_failover",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"name... | 26.710526 | 0.002852 |
def confd_state_cli_listen_ssh_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
cli = ET.SubElement(confd_state, "cli")
listen = ET.SubElement... | [
"def",
"confd_state_cli_listen_ssh_port",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"xmlns",
"=",
"\... | 41.384615 | 0.005455 |
def _deploy_method(self, ret, resource_path, method_name, method_data, api_key_required,
lambda_integration_role, lambda_region, authorization_type):
'''
Method to create a method for the given resource path, along with its associated
request and response integrations.
... | [
"def",
"_deploy_method",
"(",
"self",
",",
"ret",
",",
"resource_path",
",",
"method_name",
",",
"method_data",
",",
"api_key_required",
",",
"lambda_integration_role",
",",
"lambda_region",
",",
"authorization_type",
")",
":",
"method",
"=",
"self",
".",
"_parse_... | 51.911504 | 0.007026 |
def get_if_raw_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned.
"""
ip6 = get_if_addr6(iff)
if ip6 is not None:
return inet_pton(socket.AF_INET6, ip6)
return None | [
"def",
"get_if_raw_addr6",
"(",
"iff",
")",
":",
"ip6",
"=",
"get_if_addr6",
"(",
"iff",
")",
"if",
"ip6",
"is",
"not",
"None",
":",
"return",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"ip6",
")",
"return",
"None"
] | 27.636364 | 0.003185 |
def api_orgas(request, key=None, hproPk=None):
"""Return the list of organizations pk"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
list_orgas = []
if settings.PIAPI_STANDALONE:
list_orgas = [{'id': -1, 'name': 'EBU', 'codops': 'ZZEBU'},
... | [
"def",
"api_orgas",
"(",
"request",
",",
"key",
"=",
"None",
",",
"hproPk",
"=",
"None",
")",
":",
"if",
"not",
"check_api_key",
"(",
"request",
",",
"key",
",",
"hproPk",
")",
":",
"return",
"HttpResponseForbidden",
"list_orgas",
"=",
"[",
"]",
"if",
... | 35.172414 | 0.001908 |
def post_internal_command(self, int_cmd, thread_id):
""" if thread_id is *, post to the '*' queue"""
queue = self.get_internal_queue(thread_id)
queue.put(int_cmd) | [
"def",
"post_internal_command",
"(",
"self",
",",
"int_cmd",
",",
"thread_id",
")",
":",
"queue",
"=",
"self",
".",
"get_internal_queue",
"(",
"thread_id",
")",
"queue",
".",
"put",
"(",
"int_cmd",
")"
] | 45.75 | 0.010753 |
def rollover(self, alias, new_index=None, body=None, params=None):
"""
The rollover index API rolls an alias over to a new index when the
existing index is considered to be too large or too old.
The API accepts a single alias name and a list of conditions. The alias
must point t... | [
"def",
"rollover",
"(",
"self",
",",
"alias",
",",
"new_index",
"=",
"None",
",",
"body",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"alias",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"Empty value passed for a required argument 'al... | 56.827586 | 0.00358 |
def read_stream(stream, output, prebuffer, chunk_size=8192):
"""Reads data from stream and then writes it to the output."""
is_player = isinstance(output, PlayerOutput)
is_http = isinstance(output, HTTPServer)
is_fifo = is_player and output.namedpipe
show_progress = isinstance(output, FileOutput) an... | [
"def",
"read_stream",
"(",
"stream",
",",
"output",
",",
"prebuffer",
",",
"chunk_size",
"=",
"8192",
")",
":",
"is_player",
"=",
"isinstance",
"(",
"output",
",",
"PlayerOutput",
")",
"is_http",
"=",
"isinstance",
"(",
"output",
",",
"HTTPServer",
")",
"i... | 41.446809 | 0.002006 |
def when_called_with(self, *some_args, **some_kwargs):
"""Asserts the val callable when invoked with the given args and kwargs raises the expected exception."""
if not self.expected:
raise TypeError('expected exception not set, raises() must be called first')
try:
self.va... | [
"def",
"when_called_with",
"(",
"self",
",",
"*",
"some_args",
",",
"*",
"*",
"some_kwargs",
")",
":",
"if",
"not",
"self",
".",
"expected",
":",
"raise",
"TypeError",
"(",
"'expected exception not set, raises() must be called first'",
")",
"try",
":",
"self",
"... | 50.608696 | 0.004216 |
def predict(self, date, obs_code=568):
"""
use the bk predict method to compute the location of the source on the given date.
"""
time = Time(date, scale='utc', precision=6)
jd = ctypes.c_double(time.jd)
# call predict with agbfile, jdate, obscode
self.orbfit.pred... | [
"def",
"predict",
"(",
"self",
",",
"date",
",",
"obs_code",
"=",
"568",
")",
":",
"time",
"=",
"Time",
"(",
"date",
",",
"scale",
"=",
"'utc'",
",",
"precision",
"=",
"6",
")",
"jd",
"=",
"ctypes",
".",
"c_double",
"(",
"time",
".",
"jd",
")",
... | 50 | 0.009298 |
def _write_header(self):
""" Write out the table header """
self._ostream.write(len(self._header) * "-" + "\n")
self._ostream.write(self._header)
self._ostream.write("\n")
self._ostream.write(len(self._header) * "-" + "\n") | [
"def",
"_write_header",
"(",
"self",
")",
":",
"self",
".",
"_ostream",
".",
"write",
"(",
"len",
"(",
"self",
".",
"_header",
")",
"*",
"\"-\"",
"+",
"\"\\n\"",
")",
"self",
".",
"_ostream",
".",
"write",
"(",
"self",
".",
"_header",
")",
"self",
... | 43 | 0.007605 |
def pipe_uniq(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that filters out non unique items according to the specified
field. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
kwargs -- othe... | [
"def",
"pipe_uniq",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"funcs",
"=",
"get_splits",
"(",
"None",
",",
"conf",
",",
"*",
"*",
"cdicts",
"(",
"opts",
",",
"kwargs",
"... | 36 | 0.001425 |
def SelfReferenceProperty(label=None, collection_name=None, **attrs):
"""Create a self reference.
"""
if 'reference_class' in attrs:
raise ConfigurationError(
'Do not provide reference_class to self-reference.')
return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **... | [
"def",
"SelfReferenceProperty",
"(",
"label",
"=",
"None",
",",
"collection_name",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"'reference_class'",
"in",
"attrs",
":",
"raise",
"ConfigurationError",
"(",
"'Do not provide reference_class to self-reference.'",
... | 45.714286 | 0.003067 |
def _GetEnableOsLoginValue(self, metadata_dict):
"""Get the value of the enable-oslogin metadata key.
Args:
metadata_dict: json, the deserialized contents of the metadata server.
Returns:
bool, True if OS Login is enabled for VM access.
"""
instance_data, project_data = self._GetInstan... | [
"def",
"_GetEnableOsLoginValue",
"(",
"self",
",",
"metadata_dict",
")",
":",
"instance_data",
",",
"project_data",
"=",
"self",
".",
"_GetInstanceAndProjectAttributes",
"(",
"metadata_dict",
")",
"instance_value",
"=",
"instance_data",
".",
"get",
"(",
"'enable-oslog... | 34.3125 | 0.001773 |
def validate(self, *args, **kwargs):
"""
Validates the form by calling `validate` on each field, passing any
extra `Form.validate_<fieldname>` validators to the field validator.
also calls `validate_ldap`
"""
valid = FlaskForm.validate(self, *args, **kwargs)
if ... | [
"def",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"valid",
"=",
"FlaskForm",
".",
"validate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"valid",
":",
"logging",
".",
"debug",
"(",... | 35.466667 | 0.003663 |
def changed_fields(self, from_db=False):
"""
Args:
from_db (bool): Check changes against actual db data
Returns:
list: List of fields names which their values changed.
"""
if self.exist:
current_dict = self.clean_value()
# `from_db`... | [
"def",
"changed_fields",
"(",
"self",
",",
"from_db",
"=",
"False",
")",
":",
"if",
"self",
".",
"exist",
":",
"current_dict",
"=",
"self",
".",
"clean_value",
"(",
")",
"# `from_db` attr is set False as default, when a `ListNode` is",
"# initialized just after above `c... | 45.428571 | 0.00616 |
def read_file(self):
'''if this is stored in a file, read it into self.column'''
column_selector = r'(.*)\[(\d+)\]$'
if self.column_file:
column = None
m = re.match(column_selector,self.column_file)
file = self.column_file
if m:
fil... | [
"def",
"read_file",
"(",
"self",
")",
":",
"column_selector",
"=",
"r'(.*)\\[(\\d+)\\]$'",
"if",
"self",
".",
"column_file",
":",
"column",
"=",
"None",
"m",
"=",
"re",
".",
"match",
"(",
"column_selector",
",",
"self",
".",
"column_file",
")",
"file",
"="... | 41.8 | 0.007018 |
def response_list(data, key):
"""Obtain the relevant response data in a list.
If the response does not already contain the result in a list, a new one
will be created to ease iteration in the parser methods.
Args:
data (dict): API response.
key (str): Attribute of the response that con... | [
"def",
"response_list",
"(",
"data",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"data",
":",
"return",
"None",
"if",
"isinstance",
"(",
"data",
"[",
"key",
"]",
",",
"list",
")",
":",
"return",
"data",
"[",
"key",
"]",
"else",
":",
"return",
... | 27.238095 | 0.005068 |
def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | [
"def",
"_convert_to_array",
"(",
"array_like",
",",
"dtype",
")",
":",
"if",
"isinstance",
"(",
"array_like",
",",
"bytes",
")",
":",
"return",
"np",
".",
"frombuffer",
"(",
"array_like",
",",
"dtype",
"=",
"dtype",
")",
"return",
"np",
".",
"asarray",
"... | 40.714286 | 0.006873 |
def trace_filter (patterns):
"""Add given patterns to trace filter set or clear set if patterns is
None."""
if patterns is None:
_trace_filter.clear()
else:
_trace_filter.update(re.compile(pat) for pat in patterns) | [
"def",
"trace_filter",
"(",
"patterns",
")",
":",
"if",
"patterns",
"is",
"None",
":",
"_trace_filter",
".",
"clear",
"(",
")",
"else",
":",
"_trace_filter",
".",
"update",
"(",
"re",
".",
"compile",
"(",
"pat",
")",
"for",
"pat",
"in",
"patterns",
")"... | 34.285714 | 0.00813 |
def rename(self, name):
"""Rename the table
"""
sql = """ALTER TABLE {s}.{t} RENAME TO {name}
""".format(
s=self.schema, t=self.name, name=name
)
self.engine.execute(sql)
self.table = SQLATable(name, self.metadata, schema=self.schema, autoload=Tr... | [
"def",
"rename",
"(",
"self",
",",
"name",
")",
":",
"sql",
"=",
"\"\"\"ALTER TABLE {s}.{t} RENAME TO {name}\n \"\"\"",
".",
"format",
"(",
"s",
"=",
"self",
".",
"schema",
",",
"t",
"=",
"self",
".",
"name",
",",
"name",
"=",
"name",
")",
"se... | 35 | 0.009288 |
def date(self):
""":return: datetime object"""
if self.commit_time:
return datetime.utcfromtimestamp(self.commit_time)
else:
return datetime.now() | [
"def",
"date",
"(",
"self",
")",
":",
"if",
"self",
".",
"commit_time",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"self",
".",
"commit_time",
")",
"else",
":",
"return",
"datetime",
".",
"now",
"(",
")"
] | 31.5 | 0.010309 |
def write_members(self):
"""
write_members
"""
s = ""
objattributes = list(self.m_reprdict["positional"].keys())
objattributes.extend(list(self.m_reprdict["options"].keys()))
objattributes.sort()
for objattr in objattributes:
s += 8 * " " + "s... | [
"def",
"write_members",
"(",
"self",
")",
":",
"s",
"=",
"\"\"",
"objattributes",
"=",
"list",
"(",
"self",
".",
"m_reprdict",
"[",
"\"positional\"",
"]",
".",
"keys",
"(",
")",
")",
"objattributes",
".",
"extend",
"(",
"list",
"(",
"self",
".",
"m_rep... | 27.931034 | 0.002387 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = engine_from_config(
winchester_config['database'],
prefix='',
poolclass=pool.NullPool)
connection = e... | [
"def",
"run_migrations_online",
"(",
")",
":",
"engine",
"=",
"engine_from_config",
"(",
"winchester_config",
"[",
"'database'",
"]",
",",
"prefix",
"=",
"''",
",",
"poolclass",
"=",
"pool",
".",
"NullPool",
")",
"connection",
"=",
"engine",
".",
"connect",
... | 23.565217 | 0.001773 |
def get_token(self, user_id):
"""
Get user token
Checks if a custom token implementation is registered and uses that.
Otherwise falls back to default token implementation. Returns a string
token on success.
:param user_id: int, user id
:return: str
"""
... | [
"def",
"get_token",
"(",
"self",
",",
"user_id",
")",
":",
"if",
"not",
"self",
".",
"jwt_implementation",
":",
"return",
"self",
".",
"default_token_implementation",
"(",
"user_id",
")",
"try",
":",
"implementation",
"=",
"import_string",
"(",
"self",
".",
... | 35.681818 | 0.002481 |
def get_associated(self, retrieve=False):
'''
get pcdm:hasRelatedFile for this resource
Args:
retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload
'''
if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasRelated... | [
"def",
"get_associated",
"(",
"self",
",",
"retrieve",
"=",
"False",
")",
":",
"if",
"self",
".",
"exists",
"and",
"hasattr",
"(",
"self",
".",
"rdf",
".",
"triples",
",",
"'pcdm'",
")",
"and",
"hasattr",
"(",
"self",
".",
"rdf",
".",
"triples",
".",... | 26.470588 | 0.038627 |
def begin(self, vccstate=SSD1306_SWITCHCAPVCC):
"""Initialize display."""
# Save vcc state.
self._vccstate = vccstate
# Reset and initialize display.
self.reset()
self._initialize()
# Turn on the display.
self.command(SSD1306_DISPLAYON) | [
"def",
"begin",
"(",
"self",
",",
"vccstate",
"=",
"SSD1306_SWITCHCAPVCC",
")",
":",
"# Save vcc state.",
"self",
".",
"_vccstate",
"=",
"vccstate",
"# Reset and initialize display.",
"self",
".",
"reset",
"(",
")",
"self",
".",
"_initialize",
"(",
")",
"# Turn ... | 32.444444 | 0.006667 |
def StructField(name, field_type): # pylint: disable=invalid-name
"""Construct a field description protobuf.
:type name: str
:param name: the name of the field
:type field_type: :class:`type_pb2.Type`
:param field_type: the type of the field
:rtype: :class:`type_pb2.StructType.Field`
:re... | [
"def",
"StructField",
"(",
"name",
",",
"field_type",
")",
":",
"# pylint: disable=invalid-name",
"return",
"type_pb2",
".",
"StructType",
".",
"Field",
"(",
"name",
"=",
"name",
",",
"type",
"=",
"field_type",
")"
] | 33.076923 | 0.002262 |
def interface_endpoints(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
"""
api_version = self._get_api_version('interface_endpoints')
if api_version == ... | [
"def",
"interface_endpoints",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'interface_endpoints'",
")",
"if",
"api_version",
"==",
"'2018-08-01'",
":",
"from",
".",
"v2018_08_01",
".",
"operations",
"import",
"InterfaceEndpointsO... | 61 | 0.008811 |
def t_ID(t):
r'[A-Za-z][A-Za-z0-9_]*'
if t.value in keywords:
t.type = t.value.upper()
return t | [
"def",
"t_ID",
"(",
"t",
")",
":",
"if",
"t",
".",
"value",
"in",
"keywords",
":",
"t",
".",
"type",
"=",
"t",
".",
"value",
".",
"upper",
"(",
")",
"return",
"t"
] | 22.2 | 0.008696 |
def get_proficiency_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the proficiency lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ProficiencyLookupSession) - a
``ProficiencyLookupSession``
raise: NullArgument -... | [
"def",
"get_proficiency_lookup_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_proficiency_lookup",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"Prof... | 46.166667 | 0.004717 |
def cmd(*args, **kwargs):
"""Decorate a callable to replace it with a manufactured command
class.
Extends the interface of ``CommandDecorator``, allowing the same
``cmd`` to be used as a decorator or as a decorator factory::
@cmd(root=True)
def build():
...
@build.... | [
"def",
"cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"(",
"first",
",",
"*",
"remainder",
")",
"=",
"args",
"except",
"ValueError",
":",
"pass",
"else",
":",
"if",
"callable",
"(",
"first",
")",
":",
"return",
"CommandDeco... | 23.517241 | 0.001408 |
def pmdec(self,*args,**kwargs):
"""
NAME:
pmdec
PURPOSE:
return proper motion in declination (in mas/yr)
INPUT:
t - (optional) time at which to get pmdec
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
... | [
"def",
"pmdec",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_roSet",
"(",
"self",
",",
"kwargs",
",",
"'pmdec'",
")",
"_check_voSet",
"(",
"self",
",",
"kwargs",
",",
"'pmdec'",
")",
"pmrapmdec",
"=",
"self",
".",
"_pmrap... | 41.25 | 0.014808 |
def writeFromDict(dataDict, headers, csvFile):
"""
Write dictionary to a CSV, where keys are row numbers and values are a list.
"""
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
for row in sorted(dataDict.keys()):
writer.writerow(dataDict[row]) | [
"def",
"writeFromDict",
"(",
"dataDict",
",",
"headers",
",",
"csvFile",
")",
":",
"with",
"open",
"(",
"csvFile",
",",
"\"wb\"",
")",
"as",
"f",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"delimiter",
"=",
"\",\"",
")",
"writer",
".",
... | 34.444444 | 0.012579 |
def delete_topic(self, topic):
"""Delete a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/delete', fields={'topic': topic}) | [
"def",
"delete_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/delete'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | 44.75 | 0.010989 |
def _SetupBotoConfig(self):
"""Set the boto config so GSUtil works with provisioned service accounts."""
project_id = self._GetNumericProjectId()
try:
boto_config.BotoConfig(project_id, debug=self.debug)
except (IOError, OSError) as e:
self.logger.warning(str(e)) | [
"def",
"_SetupBotoConfig",
"(",
"self",
")",
":",
"project_id",
"=",
"self",
".",
"_GetNumericProjectId",
"(",
")",
"try",
":",
"boto_config",
".",
"BotoConfig",
"(",
"project_id",
",",
"debug",
"=",
"self",
".",
"debug",
")",
"except",
"(",
"IOError",
","... | 40.714286 | 0.013746 |
def remove(self, item):
"""
Removes the specified element's first occurrence from the list if it exists in this list.
:param item: (object), the specified element.
:return: (bool), ``true`` if the specified element is present in this list.
"""
check_not_none(item, "Value... | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"check_not_none",
"(",
"item",
",",
"\"Value can't be None\"",
")",
"item_data",
"=",
"self",
".",
"_to_data",
"(",
"item",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"list_remove_codec",
",",
"val... | 43.8 | 0.008949 |
def del_attr(self, name):
"""Implementation of attribute deletion
``del space.name`` by user script
Called from ``StaticSpace.__delattr__``
"""
if name in self.namespace:
if name in self.cells:
self.del_cells(name)
elif name in self.spaces... | [
"def",
"del_attr",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"namespace",
":",
"if",
"name",
"in",
"self",
".",
"cells",
":",
"self",
".",
"del_cells",
"(",
"name",
")",
"elif",
"name",
"in",
"self",
".",
"spaces",
":",
... | 34 | 0.003367 |
def connect(self):
"""Initialize the database connection."""
self._client = self._create_client()
self._db = getattr(self._client, self._db_name)
self._generic_dao = GenericDAO(self._client, self._db_name) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"_client",
"=",
"self",
".",
"_create_client",
"(",
")",
"self",
".",
"_db",
"=",
"getattr",
"(",
"self",
".",
"_client",
",",
"self",
".",
"_db_name",
")",
"self",
".",
"_generic_dao",
"=",
"Gene... | 46.6 | 0.008439 |
def enter_position(self):
'''enter new position'''
state = self.state
dlg = wx.TextEntryDialog(self, 'Enter new position', 'Position')
dlg.SetValue("%f %f" % (state.lat, state.lon))
if dlg.ShowModal() == wx.ID_OK:
latlon = dlg.GetValue().split()
dlg.Destro... | [
"def",
"enter_position",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"state",
"dlg",
"=",
"wx",
".",
"TextEntryDialog",
"(",
"self",
",",
"'Enter new position'",
",",
"'Position'",
")",
"dlg",
".",
"SetValue",
"(",
"\"%f %f\"",
"%",
"(",
"state",
"... | 41.916667 | 0.005837 |
def oauth_dance(consumer_key, consumer_secret,
oauth_callback="oob", loop=None):
"""
OAuth dance to get the user's access token
It calls async_oauth_dance and create event loop of not given
Parameters
----------
consumer_key : str
Your consumer key
consumer_secr... | [
"def",
"oauth_dance",
"(",
"consumer_key",
",",
"consumer_secret",
",",
"oauth_callback",
"=",
"\"oob\"",
",",
"loop",
"=",
"None",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"if",
"loop",
"is",
"None",
"else",
"loop",
"coro",
"=",
... | 25.518519 | 0.001399 |
def inicap_string(string,
cleanse=False):
"""
Convert the first letter of each word to capital letter without
touching the rest of the word.
@param string: a string.
@param cleanse: ``True`` to remove any separator character from the
string, such as comma; ``False`` to keeps any ch... | [
"def",
"inicap_string",
"(",
"string",
",",
"cleanse",
"=",
"False",
")",
":",
"return",
"string",
"and",
"' '",
".",
"join",
"(",
"word",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"word",
"[",
"1",
":",
"]",
"for",
"word",
"in",
"(",
"string",... | 38.0625 | 0.004808 |
def nsl(h, use_threads=True):
"""Compute the unstandardized number of segregating sites by length (nSl)
for each variant, comparing the reference and alternate alleles,
after Ferrer-Admetlla et al. (2014).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplo... | [
"def",
"nsl",
"(",
"h",
",",
"use_threads",
"=",
"True",
")",
":",
"# check inputs",
"h",
"=",
"asarray_ndim",
"(",
"h",
",",
"2",
")",
"check_integer_dtype",
"(",
"h",
")",
"h",
"=",
"memoryview_safe",
"(",
"h",
")",
"# # check there are no invariant sites"... | 26.847059 | 0.000423 |
def _load_gui_setting(self, key, d=None):
"""
Safely reads the header setting and sets the appropriate control
value.
Parameters
----------
key
Key string of the format 'self.controlname'.
d = None
Databox instance or dictionary, ... | [
"def",
"_load_gui_setting",
"(",
"self",
",",
"key",
",",
"d",
"=",
"None",
")",
":",
"# Whether we should pop the value from the dictionary when we set it.",
"pop_value",
"=",
"False",
"# If d is None, assume we're using the lazy load settings.",
"if",
"d",
"==",
"None",
"... | 35.25641 | 0.011323 |
def coredump_configured(name, enabled, dump_ip, host_vnic='vmk0', dump_port=6500):
'''
Ensures a host's core dump configuration.
name
Name of the state.
enabled
Sets whether or not ESXi core dump collection should be enabled.
This is a boolean value set to ``True`` or ``False``... | [
"def",
"coredump_configured",
"(",
"name",
",",
"enabled",
",",
"dump_ip",
",",
"host_vnic",
"=",
"'vmk0'",
",",
"dump_port",
"=",
"6500",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",... | 36.426471 | 0.001179 |
def unflatten(columns):
"""Given a list of column dictionaries following this layout:
[{
'column_comment': None,
'column_index': Decimal('1'),
'column_name': 'id',
'column_type': 'integer',
'table_comment': None,
'table_name': 'test_ta... | [
"def",
"unflatten",
"(",
"columns",
")",
":",
"structured",
"=",
"{",
"}",
"for",
"entry",
"in",
"columns",
":",
"schema_name",
"=",
"entry",
"[",
"'table_schema'",
"]",
"table_name",
"=",
"entry",
"[",
"'table_name'",
"]",
"if",
"schema_name",
"not",
"in"... | 31.722222 | 0.000425 |
def input(self, input, song):
"""Input callback, handles key presses
"""
try:
cmd = getattr(self, self.CMD_MAP[input][1])
except (IndexError, KeyError):
return self.screen.print_error(
"Invalid command {!r}!".format(input))
cmd(song) | [
"def",
"input",
"(",
"self",
",",
"input",
",",
"song",
")",
":",
"try",
":",
"cmd",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"CMD_MAP",
"[",
"input",
"]",
"[",
"1",
"]",
")",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"return"... | 30.5 | 0.006369 |
def _load_bib_db(self):
r"""Load the BibTeX bibliography referenced by the document.
This method triggered by the `bib_db` attribute and populates the
`_bib_db` private attribute.
The ``\bibliography`` command is parsed to identify the bibliographies
referenced by the document.... | [
"def",
"_load_bib_db",
"(",
"self",
")",
":",
"# Get the names of custom bibtex files by parsing the",
"# \\bibliography command and filtering out the default lsstdoc",
"# bibliographies.",
"command",
"=",
"LatexCommand",
"(",
"'bibliography'",
",",
"{",
"'name'",
":",
"'bib_name... | 39.021739 | 0.001087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.