text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
async def get_device_info(self, custom_attributes=None):
"""Get the local installed version."""
await self.get_geofences()
await self.get_devices()
await self.get_positions()
devinfo = {}
try: # pylint: disable=too-many-nested-blocks
for dev in self._devices ... | [
"async",
"def",
"get_device_info",
"(",
"self",
",",
"custom_attributes",
"=",
"None",
")",
":",
"await",
"self",
".",
"get_geofences",
"(",
")",
"await",
"self",
".",
"get_devices",
"(",
")",
"await",
"self",
".",
"get_positions",
"(",
")",
"devinfo",
"="... | 44.837209 | 0.001015 |
def image_import(self, image_name, url, image_meta, remote_host=None):
"""Import the image specified in url to SDK image repository, and
create a record in image db, the imported images are located in
image_repository/prov_method/os_version/image_name/, for example,
/opt/sdk/images/netbo... | [
"def",
"image_import",
"(",
"self",
",",
"image_name",
",",
"url",
",",
"image_meta",
",",
"remote_host",
"=",
"None",
")",
":",
"image_info",
"=",
"[",
"]",
"try",
":",
"image_info",
"=",
"self",
".",
"_ImageDbOperator",
".",
"image_query_record",
"(",
"i... | 53.976471 | 0.000428 |
def sigma_Silva_Liu_Macedo(Tc, Pc):
r'''Calculates Lennard-Jones molecular diameter.
Uses critical temperature and pressure. CSP method by [1]_.
.. math::
\sigma_{LJ}^3 = 0.17791 + 11.779 \left( \frac{T_c}{P_c}\right)
- 0.049029\left( \frac{T_c}{P_c}\right)^2
Parameters
----------
... | [
"def",
"sigma_Silva_Liu_Macedo",
"(",
"Tc",
",",
"Pc",
")",
":",
"Pc",
"=",
"Pc",
"/",
"1E5",
"# Pa to bar",
"term",
"=",
"0.17791",
"+",
"11.779",
"*",
"(",
"Tc",
"/",
"Pc",
")",
"-",
"0.049029",
"*",
"(",
"Tc",
"/",
"Pc",
")",
"**",
"2",
"if",
... | 28.222222 | 0.002283 |
def gather_metadata_statements(self, fos=None, context=''):
"""
Only gathers metadata statements and returns them.
:param fos: Signed metadata statements from these Federation Operators
should be added.
:param context: context of the metadata exchange
:return: Dictio... | [
"def",
"gather_metadata_statements",
"(",
"self",
",",
"fos",
"=",
"None",
",",
"context",
"=",
"''",
")",
":",
"if",
"not",
"context",
":",
"context",
"=",
"self",
".",
"context",
"_res",
"=",
"{",
"}",
"if",
"self",
".",
"metadata_statements",
":",
"... | 34.754717 | 0.001056 |
def build_table_schema(data, index=True, primary_key=None, version=True):
"""
Create a Table schema from ``data``.
Parameters
----------
data : Series, DataFrame
index : bool, default True
Whether to include ``data.index`` in the schema.
primary_key : bool or None, default True
... | [
"def",
"build_table_schema",
"(",
"data",
",",
"index",
"=",
"True",
",",
"primary_key",
"=",
"None",
",",
"version",
"=",
"True",
")",
":",
"if",
"index",
"is",
"True",
":",
"data",
"=",
"set_default_names",
"(",
"data",
")",
"schema",
"=",
"{",
"}",
... | 31.701299 | 0.000397 |
def replace_anc(dataset, parent_dataset):
"""Replace *dataset* the *parent_dataset*'s `ancillary_variables` field."""
if parent_dataset is None:
return
current_dsid = DatasetID.from_dict(dataset.attrs)
for idx, ds in enumerate(parent_dataset.attrs['ancillary_variables']):
if current_dsid... | [
"def",
"replace_anc",
"(",
"dataset",
",",
"parent_dataset",
")",
":",
"if",
"parent_dataset",
"is",
"None",
":",
"return",
"current_dsid",
"=",
"DatasetID",
".",
"from_dict",
"(",
"dataset",
".",
"attrs",
")",
"for",
"idx",
",",
"ds",
"in",
"enumerate",
"... | 48.444444 | 0.002252 |
def delete_task(name, location='\\'):
r'''
Delete a task from the task scheduler.
:param str name: The name of the task to delete.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\ta... | [
"def",
"delete_task",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing task",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
... | 26.710526 | 0.000951 |
def add_target_and_index(self, name, sig, signode):
"""Add objects to the domain list of objects
This uses the directive short name along with the full object name to
create objects and nodes that are type and name unique.
"""
full_name = name[0]
target_name = '{0}-{1}'.... | [
"def",
"add_target_and_index",
"(",
"self",
",",
"name",
",",
"sig",
",",
"signode",
")",
":",
"full_name",
"=",
"name",
"[",
"0",
"]",
"target_name",
"=",
"'{0}-{1}'",
".",
"format",
"(",
"self",
".",
"short_name",
",",
"full_name",
")",
"if",
"target_n... | 43.638889 | 0.001245 |
def render_variable(env, raw, cookiecutter_dict):
"""Inside the prompting taken from the cookiecutter.json file, this renders
the next variable. For example, if a project_name is "Peanut Butter
Cookie", the repo_name could be be rendered with:
`{{ cookiecutter.project_name.replace(" ", "_") }}`.
... | [
"def",
"render_variable",
"(",
"env",
",",
"raw",
",",
"cookiecutter_dict",
")",
":",
"if",
"raw",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"raw",
",",
"dict",
")",
":",
"return",
"{",
"render_variable",
"(",
"env",
",",
"k",
","... | 35.314286 | 0.000787 |
def predict(self, x):
"""
Predict labels for provided features.
Using a piecewise linear function.
1) If x exactly matches a boundary then associated prediction
is returned. In case there are multiple predictions with the
same boundary then one of them is returned. Which ... | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"RDD",
")",
":",
"return",
"x",
".",
"map",
"(",
"lambda",
"v",
":",
"self",
".",
"predict",
"(",
"v",
")",
")",
"return",
"np",
".",
"interp",
"(",
"x",
",... | 46.666667 | 0.00175 |
def _make_eof_intr():
"""Set constants _EOF and _INTR.
This avoids doing potentially costly operations on module load.
"""
global _EOF, _INTR
if (_EOF is not None) and (_INTR is not None):
return
# inherit EOF and INTR definitions from controlling process.
try:
from ter... | [
"def",
"_make_eof_intr",
"(",
")",
":",
"global",
"_EOF",
",",
"_INTR",
"if",
"(",
"_EOF",
"is",
"not",
"None",
")",
"and",
"(",
"_INTR",
"is",
"not",
"None",
")",
":",
"return",
"# inherit EOF and INTR definitions from controlling process.",
"try",
":",
"from... | 35.205128 | 0.002126 |
def send_invoice(self):
"""
Pay and send the customer's latest invoice.
:returns: True if an invoice was able to be created and paid, False otherwise
(typically if there was nothing to invoice).
"""
from .billing import Invoice
try:
invoice = Invoice._api_create(customer=self.id)
invoice.pay()
... | [
"def",
"send_invoice",
"(",
"self",
")",
":",
"from",
".",
"billing",
"import",
"Invoice",
"try",
":",
"invoice",
"=",
"Invoice",
".",
"_api_create",
"(",
"customer",
"=",
"self",
".",
"id",
")",
"invoice",
".",
"pay",
"(",
")",
"return",
"True",
"exce... | 27.933333 | 0.034642 |
def HEAD(self, *args, **kwargs):
""" HEAD request """
return self._handle_api(self.API_HEAD, args, kwargs) | [
"def",
"HEAD",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_handle_api",
"(",
"self",
".",
"API_HEAD",
",",
"args",
",",
"kwargs",
")"
] | 40 | 0.016393 |
def add_relation(self, parent, child, level, parent_func=None,
child_func=None):
"""
Manually add relations to the database.
Parameters
----------
parent : str or Feature instance
Parent feature to add.
child : str or Feature instance
... | [
"def",
"add_relation",
"(",
"self",
",",
"parent",
",",
"child",
",",
"level",
",",
"parent_func",
"=",
"None",
",",
"child_func",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"parent",
",",
"six",
".",
"string_types",
")",
":",
"parent",
"=",
"self... | 34.446429 | 0.001512 |
def append(self, lines):
"""
Args:
lines (list): List of line strings to append to the end of the editor
"""
if isinstance(lines, list):
self._lines = self._lines + lines
elif isinstance(lines, str):
lines = lines.split('\n')
self._... | [
"def",
"append",
"(",
"self",
",",
"lines",
")",
":",
"if",
"isinstance",
"(",
"lines",
",",
"list",
")",
":",
"self",
".",
"_lines",
"=",
"self",
".",
"_lines",
"+",
"lines",
"elif",
"isinstance",
"(",
"lines",
",",
"str",
")",
":",
"lines",
"=",
... | 36.083333 | 0.009009 |
def apply_patch(self, patch_path):
"""Applies the patch located at *patch_path*. Returns the return code of
the patch command.
"""
# Do not create .orig backup files, and merge files in place.
return self._execute('patch -p1 --no-backup-if-mismatch --merge', stdout=open(os.devnul... | [
"def",
"apply_patch",
"(",
"self",
",",
"patch_path",
")",
":",
"# Do not create .orig backup files, and merge files in place.",
"return",
"self",
".",
"_execute",
"(",
"'patch -p1 --no-backup-if-mismatch --merge'",
",",
"stdout",
"=",
"open",
"(",
"os",
".",
"devnull",
... | 59.166667 | 0.011111 |
def run(self, creds, override_etype = [23]):
"""
Requests TGT tickets for all users specified in the targets list
creds: list : the users to request the TGT tickets for
override_etype: list : list of supported encryption types
"""
tgts = []
for cred in creds:
try:
kcomm = KerbrosComm(cred, self.... | [
"def",
"run",
"(",
"self",
",",
"creds",
",",
"override_etype",
"=",
"[",
"23",
"]",
")",
":",
"tgts",
"=",
"[",
"]",
"for",
"cred",
"in",
"creds",
":",
"try",
":",
"kcomm",
"=",
"KerbrosComm",
"(",
"cred",
",",
"self",
".",
"ksoc",
")",
"kcomm",... | 29.590909 | 0.043155 |
def read_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None):
""" Read data
"""
self._setup_selection_range(f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop)
#check if selection is small enough.
if self.isheavy():
logger.warning("Selection ... | [
"def",
"read_data",
"(",
"self",
",",
"f_start",
"=",
"None",
",",
"f_stop",
"=",
"None",
",",
"t_start",
"=",
"None",
",",
"t_stop",
"=",
"None",
")",
":",
"self",
".",
"_setup_selection_range",
"(",
"f_start",
"=",
"f_start",
",",
"f_stop",
"=",
"f_s... | 51.166667 | 0.013859 |
def cmd_fft(args):
'''display fft from log'''
from MAVProxy.modules.lib import mav_fft
if len(args) > 0:
condition = args[0]
else:
condition = None
child = multiproc.Process(target=mav_fft.mavfft_display, args=[mestate.filename,condition])
child.start() | [
"def",
"cmd_fft",
"(",
"args",
")",
":",
"from",
"MAVProxy",
".",
"modules",
".",
"lib",
"import",
"mav_fft",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"condition",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"condition",
"=",
"None",
"child",
"="... | 31.666667 | 0.010239 |
def _valid_request_body(
self, cert_chain, signature, serialized_request_env):
# type: (Certificate, str, str) -> None
"""Validate the request body hash with signature.
This method checks if the hash value of the request body
matches with the hash value of the signature, dec... | [
"def",
"_valid_request_body",
"(",
"self",
",",
"cert_chain",
",",
"signature",
",",
"serialized_request_env",
")",
":",
"# type: (Certificate, str, str) -> None",
"decoded_signature",
"=",
"base64",
".",
"b64decode",
"(",
"signature",
")",
"public_key",
"=",
"cert_chai... | 41.1 | 0.002377 |
def log_data_send(self, id, ofs, count, data, force_mavlink1=False):
'''
Reply to LOG_REQUEST_DATA
id : Log id (from LOG_ENTRY reply) (uint16_t)
ofs : Offset into the log (uint32_t)
count ... | [
"def",
"log_data_send",
"(",
"self",
",",
"id",
",",
"ofs",
",",
"count",
",",
"data",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"log_data_encode",
"(",
"id",
",",
"ofs",
",",
"count",
",",
"data"... | 51.363636 | 0.008696 |
def unit(session, py):
"""Run the unit test suite."""
# Run unit tests against all supported versions of Python.
session.interpreter = 'python{}'.format(py)
# Install all test dependencies.
session.install('-r', 'requirements-test.txt')
# Install dev packages.
_install_dev_packages(sessio... | [
"def",
"unit",
"(",
"session",
",",
"py",
")",
":",
"# Run unit tests against all supported versions of Python.",
"session",
".",
"interpreter",
"=",
"'python{}'",
".",
"format",
"(",
"py",
")",
"# Install all test dependencies.",
"session",
".",
"install",
"(",
"'-r'... | 24.321429 | 0.001412 |
def _load(self, **kwargs):
'''Load python Service object with response JSON from BIG-IP®.
:params kwargs: keyword arguments for talking to the device
:returns: populated Service object
'''
# Some kwargs should be popped before we do a load
for key in self._meta_data['dis... | [
"def",
"_load",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Some kwargs should be popped before we do a load",
"for",
"key",
"in",
"self",
".",
"_meta_data",
"[",
"'disallowed_load_parameters'",
"]",
":",
"if",
"key",
"in",
"kwargs",
":",
"kwargs",
".",
... | 41.85 | 0.002336 |
def demo(self, *args, **kwargs):
"""
Simple run method
"""
print('* calling: self.dp.qprint("Why hello there, world!"):')
self.dp.qprint("Why hello there, world!")
print('* calling: self.dp2.qprint("Why hello there, world! In a debugging file!"):')
self.dp2.qpri... | [
"def",
"demo",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"'* calling: self.dp.qprint(\"Why hello there, world!\"):'",
")",
"self",
".",
"dp",
".",
"qprint",
"(",
"\"Why hello there, world!\"",
")",
"print",
"(",
"'* calling:... | 41.933333 | 0.013986 |
def parse_log_messages(self, text):
"""Will parse git log messages in the 'short' format"""
regex = r"commit ([0-9a-f]+)\nAuthor: (.*?)\n\n(.*?)(?:\n\n|$)"
messages = re.findall(regex, text, re.DOTALL)
parsed = []
for commit, author, message in messages:
pars... | [
"def",
"parse_log_messages",
"(",
"self",
",",
"text",
")",
":",
"regex",
"=",
"r\"commit ([0-9a-f]+)\\nAuthor: (.*?)\\n\\n(.*?)(?:\\n\\n|$)\"",
"messages",
"=",
"re",
".",
"findall",
"(",
"regex",
",",
"text",
",",
"re",
".",
"DOTALL",
")",
"parsed",
"=",
"[",
... | 38.461538 | 0.009766 |
def uniform_validator(validator):
""" unify validator
Args:
validator (dict): validator maybe in two formats:
format1: this is kept for compatiblity with the previous versions.
{"check": "status_code", "comparator": "eq", "expect": 201}
{"check": "$resp_body... | [
"def",
"uniform_validator",
"(",
"validator",
")",
":",
"if",
"not",
"isinstance",
"(",
"validator",
",",
"dict",
")",
":",
"raise",
"exceptions",
".",
"ParamsError",
"(",
"\"invalid validator: {}\"",
".",
"format",
"(",
"validator",
")",
")",
"if",
"\"check\"... | 32.037736 | 0.002286 |
def process_settings(self, settings):
"""A lazy way of feeding Dharma with configuration settings."""
logging.debug("Using configuration from: %s", settings.name)
exec(compile(settings.read(), settings.name, 'exec'), globals(), locals()) | [
"def",
"process_settings",
"(",
"self",
",",
"settings",
")",
":",
"logging",
".",
"debug",
"(",
"\"Using configuration from: %s\"",
",",
"settings",
".",
"name",
")",
"exec",
"(",
"compile",
"(",
"settings",
".",
"read",
"(",
")",
",",
"settings",
".",
"n... | 64.5 | 0.011494 |
def rst2pub(source, source_path=None, source_class=None,
destination_path=None,
reader=None, reader_name='standalone',
parser=None, parser_name='restructuredtext',
writer=None, writer_name='pseudoxml',
settings=None, settings_spec=None,
settings_ov... | [
"def",
"rst2pub",
"(",
"source",
",",
"source_path",
"=",
"None",
",",
"source_class",
"=",
"None",
",",
"destination_path",
"=",
"None",
",",
"reader",
"=",
"None",
",",
"reader_name",
"=",
"'standalone'",
",",
"parser",
"=",
"None",
",",
"parser_name",
"... | 37.512195 | 0.001267 |
def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(shebang_parts + cmd,
... | [
"def",
"_run_cmd",
"(",
"cmd",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cmd",
"[",
"0",
"]",
")",
":",
"cmd",
"[",
"0",
"]",
"=",
"shutil",
".",
"which",
"(",
"cmd",
"[",
"0",
"]",
")",
"assert",
"cmd",
"[",
"0",
"]",
... | 31.235294 | 0.001828 |
def action(
self,
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
kwargs=None
):
'''
Execute a single action via the cloud plugin backend
Examples:
.. code-block:: python
client.action(fun='show... | [
"def",
"action",
"(",
"self",
",",
"fun",
"=",
"None",
",",
"cloudmap",
"=",
"None",
",",
"names",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"instance",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"kwargs",
"is",
"None",
":",
"... | 30.313725 | 0.00188 |
def get_keybinding(self, mode, key):
"""look up keybinding from `MODE-maps` sections
:param mode: mode identifier
:type mode: str
:param key: urwid-style key identifier
:type key: str
:returns: a command line to be applied upon keypress
:rtype: str
"""
... | [
"def",
"get_keybinding",
"(",
"self",
",",
"mode",
",",
"key",
")",
":",
"cmdline",
"=",
"None",
"bindings",
"=",
"self",
".",
"_bindings",
"if",
"key",
"in",
"bindings",
".",
"scalars",
":",
"cmdline",
"=",
"bindings",
"[",
"key",
"]",
"if",
"mode",
... | 35.62963 | 0.002024 |
def parse(requirements):
"""
Parses given requirements line-by-line.
"""
transformer = RTransformer()
return map(transformer.transform, filter(None, map(_parse, requirements.splitlines()))) | [
"def",
"parse",
"(",
"requirements",
")",
":",
"transformer",
"=",
"RTransformer",
"(",
")",
"return",
"map",
"(",
"transformer",
".",
"transform",
",",
"filter",
"(",
"None",
",",
"map",
"(",
"_parse",
",",
"requirements",
".",
"splitlines",
"(",
")",
"... | 34 | 0.009569 |
def getDwordAtOffset(self, offset):
"""
Returns a C{DWORD} from a given offset.
@type offset: int
@param offset: The offset to get the C{DWORD} from.
@rtype: L{DWORD}
@return: The L{DWORD} obtained at the given offset.
"""
return datatyp... | [
"def",
"getDwordAtOffset",
"(",
"self",
",",
"offset",
")",
":",
"return",
"datatypes",
".",
"DWORD",
".",
"parse",
"(",
"utils",
".",
"ReadData",
"(",
"self",
".",
"getDataAtOffset",
"(",
"offset",
",",
"4",
")",
")",
")"
] | 34 | 0.015625 |
def get_activities(self, before=None, after=None, limit=None):
"""
Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date... | [
"def",
"get_activities",
"(",
"self",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"before",
":",
"before",
"=",
"self",
".",
"_utc_datetime_to_epoch",
"(",
"before",
")",
"if",
"after",
":",
"after"... | 37.297297 | 0.002119 |
async def terminate(self):
"""Terminate a running script."""
# Workaround for pylint issue #1469
# (https://github.com/PyCQA/pylint/issues/1469).
cmd = await subprocess.create_subprocess_exec( # pylint: disable=no-member
*shlex.split('{} rm -f {}'.format(self.command, self._... | [
"async",
"def",
"terminate",
"(",
"self",
")",
":",
"# Workaround for pylint issue #1469",
"# (https://github.com/PyCQA/pylint/issues/1469).",
"cmd",
"=",
"await",
"subprocess",
".",
"create_subprocess_exec",
"(",
"# pylint: disable=no-member",
"*",
"shlex",
".",
"split",
"... | 39.818182 | 0.008929 |
def build(self):
'''Builds Depoyed Classifier
'''
if self._clf is None:
raise NeedToTrainExceptionBeforeDeployingException()
return DeployedClassifier(self._category,
self._term_doc_matrix._category_idx_store,
self._term_doc_matrix._term_idx_store,
... | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"self",
".",
"_clf",
"is",
"None",
":",
"raise",
"NeedToTrainExceptionBeforeDeployingException",
"(",
")",
"return",
"DeployedClassifier",
"(",
"self",
".",
"_category",
",",
"self",
".",
"_term_doc_matrix",
".",
"_... | 40.666667 | 0.034759 |
def user_in_any_group(user, groups):
"""Returns True if the given user is in at least 1 of the given groups"""
return user_is_superuser(user) or any(user_in_group(user, group) for group in groups) | [
"def",
"user_in_any_group",
"(",
"user",
",",
"groups",
")",
":",
"return",
"user_is_superuser",
"(",
"user",
")",
"or",
"any",
"(",
"user_in_group",
"(",
"user",
",",
"group",
")",
"for",
"group",
"in",
"groups",
")"
] | 67.333333 | 0.009804 |
def pause(self, id, when=None): # pylint: disable=invalid-name,redefined-builtin
"""Pause a running result.
:param id: Result ID as an int.
:param when: Must be string `end-of-test` or `end-of-loop`.
"""
return self.service.post(self.base+str(id)+'/pause/', params={'when': when}... | [
"def",
"pause",
"(",
"self",
",",
"id",
",",
"when",
"=",
"None",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/pause/'",
",",
"p... | 45 | 0.015576 |
def process_one(self, item:ItemBase, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `item`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: item = p.process_one(item)
return item | [
"def",
"process_one",
"(",
"self",
",",
"item",
":",
"ItemBase",
",",
"processor",
":",
"PreProcessors",
"=",
"None",
")",
":",
"if",
"processor",
"is",
"not",
"None",
":",
"self",
".",
"processor",
"=",
"processor",
"self",
".",
"processor",
"=",
"listi... | 51.833333 | 0.025316 |
def _write_min_norm(self, norms:[])->None:
"Writes the minimum norm of the gradients to Tensorboard."
min_norm = min(norms)
self._add_gradient_scalar('min_norm', scalar_value=min_norm) | [
"def",
"_write_min_norm",
"(",
"self",
",",
"norms",
":",
"[",
"]",
")",
"->",
"None",
":",
"min_norm",
"=",
"min",
"(",
"norms",
")",
"self",
".",
"_add_gradient_scalar",
"(",
"'min_norm'",
",",
"scalar_value",
"=",
"min_norm",
")"
] | 51.25 | 0.019231 |
def ensure_size(
self,
size = None
):
"""
This function removes the least frequent elements until the size
constraint is met.
"""
if size is None:
size = self.size_constraint
while sys.getsizeof(self) > size:
element_frequen... | [
"def",
"ensure_size",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"self",
".",
"size_constraint",
"while",
"sys",
".",
"getsizeof",
"(",
"self",
")",
">",
"size",
":",
"element_frequencies",
"=",
"coll... | 32.928571 | 0.008439 |
def add_child(self, child, logical_block_size, allow_duplicate=False):
# type: (DirectoryRecord, int, bool) -> bool
'''
A method to add a new child to this directory record.
Parameters:
child - The child directory record object to add.
logical_block_size - The size of ... | [
"def",
"add_child",
"(",
"self",
",",
"child",
",",
"logical_block_size",
",",
"allow_duplicate",
"=",
"False",
")",
":",
"# type: (DirectoryRecord, int, bool) -> bool",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalE... | 47.333333 | 0.008055 |
def perm(A, p):
"""
Symmetric permutation of a symmetric sparse matrix.
:param A: :py:class:`spmatrix`
:param p: :py:class:`matrix` or :class:`list` of length `A.size[0]`
"""
assert isinstance(A,spmatrix), "argument must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be ... | [
"def",
"perm",
"(",
"A",
",",
"p",
")",
":",
"assert",
"isinstance",
"(",
"A",
",",
"spmatrix",
")",
",",
"\"argument must be a sparse matrix\"",
"assert",
"A",
".",
"size",
"[",
"0",
"]",
"==",
"A",
".",
"size",
"[",
"1",
"]",
",",
"\"A must be a squa... | 35.083333 | 0.009259 |
def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires t... | [
"def",
"create",
"(",
"vm_info",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_info",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
... | 34.19469 | 0.002012 |
def NRTL(xs, taus, alphas):
r'''Calculates the activity coefficients of each species in a mixture
using the Non-Random Two-Liquid (NRTL) method, given their mole fractions,
dimensionless interaction parameters, and nonrandomness constants. Those
are normally correlated with temperature in some form, and... | [
"def",
"NRTL",
"(",
"xs",
",",
"taus",
",",
"alphas",
")",
":",
"gammas",
"=",
"[",
"]",
"cmps",
"=",
"range",
"(",
"len",
"(",
"xs",
")",
")",
"Gs",
"=",
"[",
"[",
"exp",
"(",
"-",
"alphas",
"[",
"i",
"]",
"[",
"j",
"]",
"*",
"taus",
"["... | 35.753086 | 0.001008 |
def Power(base: vertex_constructor_param_types, exponent: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Raises a vertex to the power of another
:param base: the base vertex
:param exponent: the exponent vertex
"""
return Double(context.jvm_view().PowerVertex, lab... | [
"def",
"Power",
"(",
"base",
":",
"vertex_constructor_param_types",
",",
"exponent",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"jvm_vie... | 47.25 | 0.015584 |
def _include_misc(self,name,value):
"""Handle 'include()' for list/tuple attrs without a special handler"""
if not isinstance(value,sequence):
raise DistutilsSetupError(
"%s: setting must be a list (%r)" % (name, value)
)
try:
old = getattr(se... | [
"def",
"_include_misc",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"sequence",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"%s: setting must be a list (%r)\"",
"%",
"(",
"name",
",",
"value",
")",
")"... | 36.952381 | 0.013819 |
def __sum_stats(self, key, indice=None, mmm=None):
"""Return the sum of the stats value for the given key.
* indice: If indice is set, get the p[key][indice]
* mmm: display min, max, mean or current (if mmm=None)
"""
# Compute stats summary
ret = 0
for p in self.... | [
"def",
"__sum_stats",
"(",
"self",
",",
"key",
",",
"indice",
"=",
"None",
",",
"mmm",
"=",
"None",
")",
":",
"# Compute stats summary",
"ret",
"=",
"0",
"for",
"p",
"in",
"self",
".",
"stats",
":",
"if",
"key",
"not",
"in",
"p",
":",
"# Correct issu... | 32.613636 | 0.00203 |
def filter_tess_lcdict(lcdict,
filterqualityflags=True,
nanfilter='sap,pdc,time',
timestoignore=None,
quiet=False):
'''This filters the provided TESS `lcdict`, removing nans and bad
observations.
By default, this fu... | [
"def",
"filter_tess_lcdict",
"(",
"lcdict",
",",
"filterqualityflags",
"=",
"True",
",",
"nanfilter",
"=",
"'sap,pdc,time'",
",",
"timestoignore",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"cols",
"=",
"lcdict",
"[",
"'columns'",
"]",
"# filter all ba... | 30.627737 | 0.001154 |
def wrap(function_to_trace=None, **trace_options):
"""
Functions decorated with this will be traced.
Use ``local=True`` to only trace local code, eg::
@hunter.wrap(local=True)
def my_function():
...
Keyword arguments are allowed, eg::
@hunter.wrap(action=hunter.Ca... | [
"def",
"wrap",
"(",
"function_to_trace",
"=",
"None",
",",
"*",
"*",
"trace_options",
")",
":",
"def",
"tracing_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"tracing_wrapper",
"(",
"*",
"args",
",",
"*",
"... | 27.682927 | 0.001702 |
def exception(self, timeout=None):
"""Return a exception raised by the call that the future
represents.
:param timeout: The number of seconds to wait for the exception
if the future has not been completed. None, the default,
sets no limit.
:returns: The exception ... | [
"def",
"exception",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# with self.__condition:",
"if",
"self",
".",
"__state",
"==",
"FINISHED",
":",
"return",
"self",
".",
"__exception",
"self",
".",
"__condition",
".",
"wait",
"(",
"timeout",
")",
"if... | 38.761905 | 0.002398 |
def set_level(self, level):
"""Set device level."""
if self._json_state['control_url']:
url = CONST.BASE_URL + self._json_state['control_url']
level_data = {
'level': str(level)
}
response = self._abode.send_request(
"put"... | [
"def",
"set_level",
"(",
"self",
",",
"level",
")",
":",
"if",
"self",
".",
"_json_state",
"[",
"'control_url'",
"]",
":",
"url",
"=",
"CONST",
".",
"BASE_URL",
"+",
"self",
".",
"_json_state",
"[",
"'control_url'",
"]",
"level_data",
"=",
"{",
"'level'"... | 30.285714 | 0.002286 |
def fit_exp(y,graphToo=False):
"""Exponential fit. Returns [multiplier, t, offset, time constant]"""
x=np.arange(len(y))
try:
params, cv = scipy.optimize.curve_fit(algo_exp, x, y, p0=(1,1e-6,1))
except:
print(" !! curve fit failed (%.02f points)"%len(x))
return np.nan,np.nan,np.n... | [
"def",
"fit_exp",
"(",
"y",
",",
"graphToo",
"=",
"False",
")",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"y",
")",
")",
"try",
":",
"params",
",",
"cv",
"=",
"scipy",
".",
"optimize",
".",
"curve_fit",
"(",
"algo_exp",
",",
"x",
","... | 34.277778 | 0.047319 |
def free_cells(self):
"""Returns a list of empty cells."""
return [(x, y)
for x in range(self.COUNT_X)
for y in range(self.COUNT_Y)
if not self.grid[y][x]] | [
"def",
"free_cells",
"(",
"self",
")",
":",
"return",
"[",
"(",
"x",
",",
"y",
")",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"COUNT_X",
")",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"COUNT_Y",
")",
"if",
"not",
"self",
".",
"grid",
"[",... | 35.666667 | 0.009132 |
def closest_common_ancestor(self, other):
"""
Find the common ancestor between this history node and 'other'.
:param other: the PathHistory to find a common ancestor with.
:return: the common ancestor SimStateHistory, or None if there isn't one
"""
our_history_... | [
"def",
"closest_common_ancestor",
"(",
"self",
",",
"other",
")",
":",
"our_history_iter",
"=",
"reversed",
"(",
"HistoryIter",
"(",
"self",
")",
")",
"their_history_iter",
"=",
"reversed",
"(",
"HistoryIter",
"(",
"other",
")",
")",
"sofar",
"=",
"set",
"("... | 34.131579 | 0.002249 |
def ds2json(ds, u_var, v_var, lat_dim='latitude', lon_dim='longitude', units=None):
"""
Assumes that the velocity components are given on a regular grid
(fixed spacing in latitude and longitude).
Parameters
----------
u_var : str
Name of the U-component (zonal) variable.
v_var : str... | [
"def",
"ds2json",
"(",
"ds",
",",
"u_var",
",",
"v_var",
",",
"lat_dim",
"=",
"'latitude'",
",",
"lon_dim",
"=",
"'longitude'",
",",
"units",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"ds",
"=",
"ds",
".",
"copy",
"(",
")",
"for",
"var_... | 31.0625 | 0.00065 |
def greatCircleDistance(self, lat1, long1, lat2, long2, radius):
"""
Returns the great circle distance between two points.
Useful when using the SAS_NG solution in lat/lon coordinates
Modified from http://www.johndcook.com/blog/python_longitude_latitude/
It should be able to take numpy arrays.
"... | [
"def",
"greatCircleDistance",
"(",
"self",
",",
"lat1",
",",
"long1",
",",
"lat2",
",",
"long2",
",",
"radius",
")",
":",
"# Convert latitude and longitude to",
"# spherical coordinates in radians.",
"degrees_to_radians",
"=",
"np",
".",
"pi",
"/",
"180.0",
"# theta... | 35.888889 | 0.009043 |
def safeReadJSON(url, logger, max_check=6, waittime=30):
'''Return JSON object from URL'''
counter = 0
# try, try and try again ....
while counter < max_check:
try:
with contextlib.closing(urllib.request.urlopen(url)) as f:
res = json.loads(f.read().decode('utf8'))
... | [
"def",
"safeReadJSON",
"(",
"url",
",",
"logger",
",",
"max_check",
"=",
"6",
",",
"waittime",
"=",
"30",
")",
":",
"counter",
"=",
"0",
"# try, try and try again ....",
"while",
"counter",
"<",
"max_check",
":",
"try",
":",
"with",
"contextlib",
".",
"clo... | 38.866667 | 0.001675 |
def __filter_non_working_providers(self):
'''
Remove any mis-configured cloud providers from the available listing
'''
for alias, drivers in six.iteritems(self.opts['providers'].copy()):
for driver in drivers.copy():
fun = '{0}.get_configured_provider'.format(... | [
"def",
"__filter_non_working_providers",
"(",
"self",
")",
":",
"for",
"alias",
",",
"drivers",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"opts",
"[",
"'providers'",
"]",
".",
"copy",
"(",
")",
")",
":",
"for",
"driver",
"in",
"drivers",
".",
"c... | 46.914894 | 0.000888 |
def pipe(cmd, *arguments, **kwargs):
"""
Pipe many commands::
>>> noop = pipe(['gzip'], ['gzip'], ['zcat'], ['zcat'])
>>> _ = noop.stdin.write('foo'.encode()) # Ignore output in Python 3
>>> noop.stdin.close()
>>> print(noop.stdout.read().decode())
foo
Returns a Su... | [
"def",
"pipe",
"(",
"cmd",
",",
"*",
"arguments",
",",
"*",
"*",
"kwargs",
")",
":",
"acc",
"=",
"run",
"(",
"*",
"cmd",
",",
"*",
"*",
"kwargs",
")",
"for",
"cmd",
"in",
"arguments",
":",
"if",
"isinstance",
"(",
"cmd",
",",
"Subprocess",
")",
... | 27.315789 | 0.001862 |
def editable(parsed, context, token):
"""
Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
mod... | [
"def",
"editable",
"(",
"parsed",
",",
"context",
",",
"token",
")",
":",
"def",
"parse_field",
"(",
"field",
")",
":",
"field",
"=",
"field",
".",
"split",
"(",
"\".\"",
")",
"obj",
"=",
"context",
".",
"get",
"(",
"field",
".",
"pop",
"(",
"0",
... | 38.783784 | 0.00068 |
def get_complex_coefficients(self, params):
"""
Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` given th... | [
"def",
"get_complex_coefficients",
"(",
"self",
",",
"params",
")",
":",
"return",
"np",
".",
"empty",
"(",
"0",
")",
",",
"np",
".",
"empty",
"(",
"0",
")",
",",
"np",
".",
"empty",
"(",
"0",
")",
",",
"np",
".",
"empty",
"(",
"0",
")"
] | 44.055556 | 0.002469 |
def has_custom_queryset(manager):
"Check whether manager (or its parents) has declared some custom get_queryset method."
old_diff = getattr(manager, 'get_query_set', None) != getattr(Manager, 'get_query_set', None)
new_diff = getattr(manager, 'get_queryset', None) != getattr(Manager, 'get_queryset', None)
... | [
"def",
"has_custom_queryset",
"(",
"manager",
")",
":",
"old_diff",
"=",
"getattr",
"(",
"manager",
",",
"'get_query_set'",
",",
"None",
")",
"!=",
"getattr",
"(",
"Manager",
",",
"'get_query_set'",
",",
"None",
")",
"new_diff",
"=",
"getattr",
"(",
"manager... | 69.2 | 0.011429 |
def update_placeholders(self, format_string, placeholders):
"""
Update a format string renaming placeholders.
"""
# Tokenize the format string and process them
output = []
for token in self.tokens(format_string):
if token.group("key") in placeholders:
... | [
"def",
"update_placeholders",
"(",
"self",
",",
"format_string",
",",
"placeholders",
")",
":",
"# Tokenize the format string and process them",
"output",
"=",
"[",
"]",
"for",
"token",
"in",
"self",
".",
"tokens",
"(",
"format_string",
")",
":",
"if",
"token",
... | 46.897959 | 0.001705 |
def convert(input_ops, output_ops, byte_order, bigdl_type):
"""
Convert tensorflow model to bigdl model
:param input_ops: operation list used for input, should be placeholders
:param output_ops: operations list used for output
:return: bigdl model
"""
input_names = map(lambda x: x.name.spli... | [
"def",
"convert",
"(",
"input_ops",
",",
"output_ops",
",",
"byte_order",
",",
"bigdl_type",
")",
":",
"input_names",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
",",
"input_ops",
")",
"outpu... | 30.307692 | 0.00123 |
def _CheckFieldMaskMessage(message):
"""Raises ValueError if message is not a FieldMask."""
message_descriptor = message.DESCRIPTOR
if (message_descriptor.name != 'FieldMask' or
message_descriptor.file.name != 'google/protobuf/field_mask.proto'):
raise ValueError('Message {0} is not a FieldMask.'.format... | [
"def",
"_CheckFieldMaskMessage",
"(",
"message",
")",
":",
"message_descriptor",
"=",
"message",
".",
"DESCRIPTOR",
"if",
"(",
"message_descriptor",
".",
"name",
"!=",
"'FieldMask'",
"or",
"message_descriptor",
".",
"file",
".",
"name",
"!=",
"'google/protobuf/field... | 50.571429 | 0.013889 |
def customize_base_cfg(cfgname, cfgopt_strs, base_cfg, cfgtype,
alias_keys=None, valid_keys=None, offset=0,
strict=True):
"""
Args:
cfgname (str): config name
cfgopt_strs (str): mini-language defining key variations
base_cfg (dict): specifies... | [
"def",
"customize_base_cfg",
"(",
"cfgname",
",",
"cfgopt_strs",
",",
"base_cfg",
",",
"cfgtype",
",",
"alias_keys",
"=",
"None",
",",
"valid_keys",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"strict",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut"... | 37.363636 | 0.000677 |
def remove_directories(list_of_paths):
"""
Removes non-leafs from a list of directory paths
"""
found_dirs = set('/')
for path in list_of_paths:
dirs = path.strip().split('/')
for i in range(2,len(dirs)):
found_dirs.add( '/'.join(dirs[:i]) )
paths = [ path for path i... | [
"def",
"remove_directories",
"(",
"list_of_paths",
")",
":",
"found_dirs",
"=",
"set",
"(",
"'/'",
")",
"for",
"path",
"in",
"list_of_paths",
":",
"dirs",
"=",
"path",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"for",
"i",
"in",
"range",
... | 32.153846 | 0.016279 |
def update_collision_rect(self):
""" 获取外接矩形 """
self.min_x = min(self.points[::2])
self.max_x = max(self.points[::2])
self.min_y = min(self.points[1::2])
self.max_y = max(self.points[1::2]) | [
"def",
"update_collision_rect",
"(",
"self",
")",
":",
"self",
".",
"min_x",
"=",
"min",
"(",
"self",
".",
"points",
"[",
":",
":",
"2",
"]",
")",
"self",
".",
"max_x",
"=",
"max",
"(",
"self",
".",
"points",
"[",
":",
":",
"2",
"]",
")",
"self... | 37.333333 | 0.008734 |
def output_results(results, metric, options):
"""
Output the results to stdout.
TODO: add AMPQ support for efficiency
"""
formatter = options['Formatter']
context = metric.copy() # XXX might need to sanitize this
try:
context['dimension'] = list(metric['Dimensions'].values())[0]
... | [
"def",
"output_results",
"(",
"results",
",",
"metric",
",",
"options",
")",
":",
"formatter",
"=",
"options",
"[",
"'Formatter'",
"]",
"context",
"=",
"metric",
".",
"copy",
"(",
")",
"# XXX might need to sanitize this",
"try",
":",
"context",
"[",
"'dimensio... | 38 | 0.001833 |
def write_checktime (self, url_data):
"""Write url_data.checktime."""
self.writeln(u"<tr><td>"+self.part("checktime")+u"</td><td>"+
(_("%.3f seconds") % url_data.checktime)+u"</td></tr>") | [
"def",
"write_checktime",
"(",
"self",
",",
"url_data",
")",
":",
"self",
".",
"writeln",
"(",
"u\"<tr><td>\"",
"+",
"self",
".",
"part",
"(",
"\"checktime\"",
")",
"+",
"u\"</td><td>\"",
"+",
"(",
"_",
"(",
"\"%.3f seconds\"",
")",
"%",
"url_data",
".",
... | 55.25 | 0.017857 |
def _update_service_context(self, resp, **kwargs):
"""
Deal with Provider Config Response. Based on the provider info
response a set of parameters in different places needs to be set.
:param resp: The provider info response
:param service_context: Information collected/used by s... | [
"def",
"_update_service_context",
"(",
"self",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
":",
"issuer",
"=",
"self",
".",
"service_context",
".",
"issuer",
"# Verify that the issuer value received is the same as the",
"# url that was used as service endpoint (without the .we... | 40.684211 | 0.000632 |
def _tree_line(self, no_type: bool = False) -> str:
"""Return the receiver's contribution to tree diagram."""
return self._tree_line_prefix() + " " + self.iname() | [
"def",
"_tree_line",
"(",
"self",
",",
"no_type",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"self",
".",
"_tree_line_prefix",
"(",
")",
"+",
"\" \"",
"+",
"self",
".",
"iname",
"(",
")"
] | 58.666667 | 0.011236 |
def is_child_uri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri.
This function accounts for the fact that '/a/b/c' and 'a/b/c/' are
children of '/a/b' (and also of '/a/b/').
Note that '/a/b/cd' is NOT a child of 'a/b/c'.
"""
return (
parentUri
and chil... | [
"def",
"is_child_uri",
"(",
"parentUri",
",",
"childUri",
")",
":",
"return",
"(",
"parentUri",
"and",
"childUri",
"and",
"childUri",
".",
"rstrip",
"(",
"\"/\"",
")",
".",
"startswith",
"(",
"parentUri",
".",
"rstrip",
"(",
"\"/\"",
")",
"+",
"\"/\"",
"... | 32.666667 | 0.002481 |
def call(self, inputs):
"""Runs the model to generate a distribution `q(f | x_{1:T})`.
This generates a list of batched MultivariateNormalDiag
distributions using the output of the recurrent model at each
timestep to parameterize each distribution.
Args:
inputs: A batch of intermediate repre... | [
"def",
"call",
"(",
"self",
",",
"inputs",
")",
":",
"# TODO(dusenberrymw): Remove these reshaping commands after b/113126249 is",
"# fixed.",
"collapsed_shape",
"=",
"tf",
".",
"concat",
"(",
"(",
"[",
"-",
"1",
"]",
",",
"tf",
".",
"shape",
"(",
"input",
"=",
... | 47.785714 | 0.000733 |
def update_pypsa_generator_timeseries(network, generators_to_update=None,
timesteps=None):
"""
Updates generator time series in pypsa representation.
This function overwrites p_set and q_set of generators_t attribute of
pypsa network.
Be aware that if you call ... | [
"def",
"update_pypsa_generator_timeseries",
"(",
"network",
",",
"generators_to_update",
"=",
"None",
",",
"timesteps",
"=",
"None",
")",
":",
"_update_pypsa_timeseries_by_type",
"(",
"network",
",",
"type",
"=",
"'generator'",
",",
"components_to_update",
"=",
"gener... | 51.382353 | 0.001124 |
async def contains_tracks(self, *tracks: Sequence[Union[str, Track]]) -> List[bool]:
"""Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library.
Parameters
----------
tracks : Union[Track, str]
A sequence of track objects or spotify ID... | [
"async",
"def",
"contains_tracks",
"(",
"self",
",",
"*",
"tracks",
":",
"Sequence",
"[",
"Union",
"[",
"str",
",",
"Track",
"]",
"]",
")",
"->",
"List",
"[",
"bool",
"]",
":",
"_tracks",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
... | 46.4 | 0.008457 |
def parseAcceptHeader(value):
"""Parse an accept header, ignoring any accept-extensions
returns a list of tuples containing main MIME type, MIME subtype,
and quality markdown.
str -> [(str, str, float)]
"""
chunks = [chunk.strip() for chunk in value.split(',')]
accept = []
for chunk in... | [
"def",
"parseAcceptHeader",
"(",
"value",
")",
":",
"chunks",
"=",
"[",
"chunk",
".",
"strip",
"(",
")",
"for",
"chunk",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"accept",
"=",
"[",
"]",
"for",
"chunk",
"in",
"chunks",
":",
"parts",
"=",
... | 27.315789 | 0.00093 |
def array_addunique(path, value, create_parents=False, **kwargs):
"""
Add a new value to an array if the value does not exist.
:param path: The path to the array
:param value: Value to add to the array if it does not exist.
Currently the value is restricted to primitives: strings, numbers,
... | [
"def",
"array_addunique",
"(",
"path",
",",
"value",
",",
"create_parents",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gen_4spec",
"(",
"LCB_SDCMD_ARRAY_ADD_UNIQUE",
",",
"path",
",",
"value",
",",
"create_path",
"=",
"create_parents",
",",
... | 36.863636 | 0.001202 |
def move(self, external_index, new_priority):
"""
Change the priority of a leaf node
"""
index = external_index + (self._capacity - 1)
return self._move(index, new_priority) | [
"def",
"move",
"(",
"self",
",",
"external_index",
",",
"new_priority",
")",
":",
"index",
"=",
"external_index",
"+",
"(",
"self",
".",
"_capacity",
"-",
"1",
")",
"return",
"self",
".",
"_move",
"(",
"index",
",",
"new_priority",
")"
] | 34.666667 | 0.00939 |
def to_XML(self, xml_declaration=True, xmlns=True):
"""
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
XMLNS prefix... | [
"def",
"to_XML",
"(",
"self",
",",
"xml_declaration",
"=",
"True",
",",
"xmlns",
"=",
"True",
")",
":",
"root_node",
"=",
"self",
".",
"_to_DOM",
"(",
")",
"if",
"xmlns",
":",
"xmlutils",
".",
"annotate_with_XMLNS",
"(",
"root_node",
",",
"LOCATION_XMLNS_P... | 42.571429 | 0.002188 |
def read_from_hdx(identifier, configuration=None):
# type: (str, Optional[Configuration]) -> Optional['Organization']
"""Reads the organization given by identifier from HDX and returns Organization object
Args:
identifier (str): Identifier of organization
configuration (... | [
"def",
"read_from_hdx",
"(",
"identifier",
",",
"configuration",
"=",
"None",
")",
":",
"# type: (str, Optional[Configuration]) -> Optional['Organization']",
"organization",
"=",
"Organization",
"(",
"configuration",
"=",
"configuration",
")",
"result",
"=",
"organization",... | 41.764706 | 0.008264 |
def cylsph(r, lonc, z):
"""
Convert from cylindrical to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylsph_c.html
:param r: Rectangular coordinates of the point.
:type r: float
:param lonc: Angle (radians) of point from XZ plane.
:type lonc: float
:pa... | [
"def",
"cylsph",
"(",
"r",
",",
"lonc",
",",
"z",
")",
":",
"r",
"=",
"ctypes",
".",
"c_double",
"(",
"r",
")",
"lonc",
"=",
"ctypes",
".",
"c_double",
"(",
"lonc",
")",
"z",
"=",
"ctypes",
".",
"c_double",
"(",
"z",
")",
"radius",
"=",
"ctypes... | 33.111111 | 0.001087 |
def retrieve_collection(collection, query_arguments=None):
"""Return the resources in *collection*, possibly filtered by a series of
values to use in a 'where' clause search.
:param string collection: a :class:`sandman.model.Model` endpoint
:param dict query_arguments: a list of filter query arguments
... | [
"def",
"retrieve_collection",
"(",
"collection",
",",
"query_arguments",
"=",
"None",
")",
":",
"session",
"=",
"_get_session",
"(",
")",
"cls",
"=",
"endpoint_class",
"(",
"collection",
")",
"if",
"query_arguments",
":",
"filters",
"=",
"[",
"]",
"order",
"... | 35.903226 | 0.000875 |
def feedparser_render(url, *args, **kwargs):
"""
Render a feed and return its builded html
Usage: ::
{% feedparser_render 'http://localhost/sample.xml' %}
Or with all accepted arguments: ::
{% feedparser_render 'http://localhost/sample.xml' renderer='CustomRenderer' t... | [
"def",
"feedparser_render",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer_name",
"=",
"kwargs",
".",
"get",
"(",
"'renderer'",
",",
"settings",
".",
"FEED_DEFAULT_RENDERER_ENGINE",
")",
"renderer_template",
"=",
"kwargs",
".",
"g... | 39.055556 | 0.0125 |
def sci(self):
"""Property providing access to the :class:`.ServerCommandInterfaceAPI`"""
if self._sci_api is None:
self._sci_api = self.get_sci_api()
return self._sci_api | [
"def",
"sci",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sci_api",
"is",
"None",
":",
"self",
".",
"_sci_api",
"=",
"self",
".",
"get_sci_api",
"(",
")",
"return",
"self",
".",
"_sci_api"
] | 40.6 | 0.014493 |
def getidfobjectlist(idf):
"""return a list of all idfobjects in idf"""
idfobjects = idf.idfobjects
# idfobjlst = [idfobjects[key] for key in idfobjects if idfobjects[key]]
idfobjlst = [idfobjects[key] for key in idf.model.dtls if idfobjects[key]]
# `for key in idf.model.dtls` maintains the or... | [
"def",
"getidfobjectlist",
"(",
"idf",
")",
":",
"idfobjects",
"=",
"idf",
".",
"idfobjects",
"# idfobjlst = [idfobjects[key] for key in idfobjects if idfobjects[key]]",
"idfobjlst",
"=",
"[",
"idfobjects",
"[",
"key",
"]",
"for",
"key",
"in",
"idf",
".",
"model",
"... | 47.8 | 0.008214 |
def public_notes(self, key, value):
"""Populate the ``public_notes`` key.
Also populates the ``curated`` and ``thesis_info`` keys through side effects.
"""
def _means_not_curated(public_note):
return public_note in [
'*Brief entry*',
'* Brief entry *',
'*Temp... | [
"def",
"public_notes",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"def",
"_means_not_curated",
"(",
"public_note",
")",
":",
"return",
"public_note",
"in",
"[",
"'*Brief entry*'",
",",
"'* Brief entry *'",
",",
"'*Temporary entry*'",
",",
"'* Temporary entry... | 33.475 | 0.002177 |
def _wrapinit(init):
"""Wrap an existing initialize function by thawing self for the duration
of the init.
Parameters
----------
init : callable
The user-provided init.
Returns
-------
wrapped : callable
The wrapped init method.
"""
try:
spec = getfullar... | [
"def",
"_wrapinit",
"(",
"init",
")",
":",
"try",
":",
"spec",
"=",
"getfullargspec",
"(",
"init",
")",
"except",
"TypeError",
":",
"# we cannot preserve the type signature.",
"def",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
... | 27.329412 | 0.000415 |
def worker(self):
"""
Calculates the quartet weights for the test at a random
subsampled chunk of loci.
"""
## subsample loci
fullseqs = self.sample_loci()
## find all iterations of samples for this quartet
liters = itertools.product(*self.imap.values())
## run tree inference fo... | [
"def",
"worker",
"(",
"self",
")",
":",
"## subsample loci ",
"fullseqs",
"=",
"self",
".",
"sample_loci",
"(",
")",
"## find all iterations of samples for this quartet",
"liters",
"=",
"itertools",
".",
"product",
"(",
"*",
"self",
".",
"imap",
".",
"values",
"... | 31.216667 | 0.01294 |
def unpack(source_array, mask, dtype=np.uint8):
""" Unpack sub field using its mask
Parameters:
----------
source_array : numpy.ndarray
The source array
mask : mask (ie: 0b00001111)
Mask of the sub field to be extracted from the source array
Returns
-------
numpy.ndarray... | [
"def",
"unpack",
"(",
"source_array",
",",
"mask",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
":",
"lsb",
"=",
"least_significant_bit",
"(",
"mask",
")",
"return",
"(",
"(",
"source_array",
"&",
"mask",
")",
">>",
"lsb",
")",
".",
"astype",
"(",
"dt... | 27.1875 | 0.002222 |
def exists(self, **kwargs):
"""Check for the existence of the named object on the BIG-IP
Tries to `load()` the object and if it fails checks the exception
for 404. If the `load()` is successful it returns `True` if the
exception is :exc:`requests.HTTPError` and the
``status_cod... | [
"def",
"exists",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"requests_params",
"=",
"self",
".",
"_handle_requests_params",
"(",
"kwargs",
")",
"self",
".",
"_check_load_parameters",
"(",
"*",
"*",
"kwargs",
")",
"load_uri",
"=",
"self",
".",
"_create... | 43.28125 | 0.001412 |
def sort_languages(self, order=Qt.AscendingOrder):
"""
Sorts the Model languages.
:param order: Order. ( Qt.SortOrder )
"""
self.beginResetModel()
self.__languages = sorted(self.__languages, key=lambda x: (x.name), reverse=order)
self.endResetModel() | [
"def",
"sort_languages",
"(",
"self",
",",
"order",
"=",
"Qt",
".",
"AscendingOrder",
")",
":",
"self",
".",
"beginResetModel",
"(",
")",
"self",
".",
"__languages",
"=",
"sorted",
"(",
"self",
".",
"__languages",
",",
"key",
"=",
"lambda",
"x",
":",
"... | 29.9 | 0.00974 |
def pair_is_consistent(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> Optional[str]:
"""Return if the edges between the given nodes are consistent, meaning they all have the same relation.
:return: If the edges aren't consistent, return false, otherwise return the relation type
"""
relations = {data... | [
"def",
"pair_is_consistent",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"relations",
"=",
"{",
"data",
"[",
"RELATION",
"]",
"for",
"data",
"in",
"graph",
"[",
... | 39 | 0.009112 |
def json_call(cls, method, url, **kwargs):
""" Call a remote api using json format """
# retrieve api key if needed
empty_key = kwargs.pop('empty_key', False)
send_key = kwargs.pop('send_key', True)
return_header = kwargs.pop('return_header', False)
try:
apike... | [
"def",
"json_call",
"(",
"cls",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# retrieve api key if needed",
"empty_key",
"=",
"kwargs",
".",
"pop",
"(",
"'empty_key'",
",",
"False",
")",
"send_key",
"=",
"kwargs",
".",
"pop",
"(",
"'sen... | 40.71875 | 0.001499 |
def build_segment_list(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0):
"""Optains a list of segments for the given ifo, name and version between the
specified times. If a version is given the request is straightforward and is
passed on to build_segment_... | [
"def",
"build_segment_list",
"(",
"engine",
",",
"gps_start_time",
",",
"gps_end_time",
",",
"ifo",
",",
"segment_name",
",",
"version",
"=",
"None",
",",
"start_pad",
"=",
"0",
",",
"end_pad",
"=",
"0",
")",
":",
"if",
"version",
"is",
"not",
"None",
":... | 56.555556 | 0.013527 |
def send_no_servlet_response(self):
"""
Default response sent when no servlet is found for the requested path
"""
# Use the helper to send the error page
response = _HTTPServletResponse(self)
response.send_content(404, self._service.make_not_found_page(self.path)) | [
"def",
"send_no_servlet_response",
"(",
"self",
")",
":",
"# Use the helper to send the error page",
"response",
"=",
"_HTTPServletResponse",
"(",
"self",
")",
"response",
".",
"send_content",
"(",
"404",
",",
"self",
".",
"_service",
".",
"make_not_found_page",
"(",
... | 43.714286 | 0.009615 |
def unpack_rsp(cls, rsp_pb):
"""Convert from PLS response to user response"""
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
return RET_OK, "", None | [
"def",
"unpack_rsp",
"(",
"cls",
",",
"rsp_pb",
")",
":",
"if",
"rsp_pb",
".",
"retType",
"!=",
"RET_OK",
":",
"return",
"RET_ERROR",
",",
"rsp_pb",
".",
"retMsg",
",",
"None",
"return",
"RET_OK",
",",
"\"\"",
",",
"None"
] | 33.333333 | 0.009756 |
def parse_template(self, tmp, reset=False, only_body=False):
"""parses a template or user edited string to fills this envelope.
:param tmp: the string to parse.
:type tmp: str
:param reset: remove previous envelope content
:type reset: bool
"""
logging.debug('GoT... | [
"def",
"parse_template",
"(",
"self",
",",
"tmp",
",",
"reset",
"=",
"False",
",",
"only_body",
"=",
"False",
")",
":",
"logging",
".",
"debug",
"(",
"'GoT: \"\"\"\\n%s\\n\"\"\"'",
",",
"tmp",
")",
"if",
"self",
".",
"sent_time",
":",
"self",
".",
"modif... | 38.517857 | 0.000904 |
def saveFormatFileEnc(self, filename, encoding, format):
"""Dump an XML document to a file or an URL. """
ret = libxml2mod.xmlSaveFormatFileEnc(filename, self._o, encoding, format)
return ret | [
"def",
"saveFormatFileEnc",
"(",
"self",
",",
"filename",
",",
"encoding",
",",
"format",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlSaveFormatFileEnc",
"(",
"filename",
",",
"self",
".",
"_o",
",",
"encoding",
",",
"format",
")",
"return",
"ret"
] | 53 | 0.013953 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.