text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def canGoBack(self):
"""
Returns whether or not this wizard can move forward.
:return <bool>
"""
try:
backId = self._navigation.index(self.currentId())-1
if backId >= 0:
self._navigation[backId]
else:
return... | [
"def",
"canGoBack",
"(",
"self",
")",
":",
"try",
":",
"backId",
"=",
"self",
".",
"_navigation",
".",
"index",
"(",
"self",
".",
"currentId",
"(",
")",
")",
"-",
"1",
"if",
"backId",
">=",
"0",
":",
"self",
".",
"_navigation",
"[",
"backId",
"]",
... | 25.25 | 16.5 |
def release(ctx, type_, repo=None, prebump_to=PREBUMP):
"""Make a new release.
"""
unprebump(ctx)
if bump_release(ctx, type_=type_):
return
this_version = _read_version()
ctx.run('towncrier')
ctx.run(f'git commit -am "Release {this_version}"')
ctx.run(f'git tag -fa {this_version... | [
"def",
"release",
"(",
"ctx",
",",
"type_",
",",
"repo",
"=",
"None",
",",
"prebump_to",
"=",
"PREBUMP",
")",
":",
"unprebump",
"(",
"ctx",
")",
"if",
"bump_release",
"(",
"ctx",
",",
"type_",
"=",
"type_",
")",
":",
"return",
"this_version",
"=",
"_... | 27.136364 | 19.363636 |
def ToABMag(self, wave, flux, **kwargs):
"""Convert to ``abmag``.
.. math::
\\textnormal{AB}_{\\nu} = -2.5 \\; \\log(h \\lambda \\; \\textnormal{photlam}) - 48.6
where :math:`h` is as defined in :ref:`pysynphot-constants`.
Parameters
----------
wave, flux ... | [
"def",
"ToABMag",
"(",
"self",
",",
"wave",
",",
"flux",
",",
"*",
"*",
"kwargs",
")",
":",
"arg",
"=",
"H",
"*",
"flux",
"*",
"wave",
"return",
"-",
"1.085736",
"*",
"N",
".",
"log",
"(",
"arg",
")",
"+",
"ABZERO"
] | 25.48 | 22.4 |
def _authenticate(self, client):
"""Perform AMQP authentication."""
yield client.authenticate(
self._username, self._password, mechanism=self._auth_mechanism)
returnValue(client) | [
"def",
"_authenticate",
"(",
"self",
",",
"client",
")",
":",
"yield",
"client",
".",
"authenticate",
"(",
"self",
".",
"_username",
",",
"self",
".",
"_password",
",",
"mechanism",
"=",
"self",
".",
"_auth_mechanism",
")",
"returnValue",
"(",
"client",
")... | 42 | 12.4 |
def split_options(opts, validate=True, warn=False, normalize=True):
"""Takes the options portion of a MongoDB URI, validates each option
and returns the options in a dictionary.
:Parameters:
- `opt`: A string representing MongoDB URI options.
- `validate`: If ``True`` (the default), validat... | [
"def",
"split_options",
"(",
"opts",
",",
"validate",
"=",
"True",
",",
"warn",
"=",
"False",
",",
"normalize",
"=",
"True",
")",
":",
"and_idx",
"=",
"opts",
".",
"find",
"(",
"\"&\"",
")",
"semi_idx",
"=",
"opts",
".",
"find",
"(",
"\";\"",
")",
... | 34.763158 | 19.473684 |
def _wrap(x, serializeFunc, encodeFunc=base64.urlsafe_b64encode, compress=True):
"""
Wraps an element @x by serializing and then encoding the resulting bytes.
"""
return encodeFunc(serializeFunc(x, compress)) | [
"def",
"_wrap",
"(",
"x",
",",
"serializeFunc",
",",
"encodeFunc",
"=",
"base64",
".",
"urlsafe_b64encode",
",",
"compress",
"=",
"True",
")",
":",
"return",
"encodeFunc",
"(",
"serializeFunc",
"(",
"x",
",",
"compress",
")",
")"
] | 44 | 17.2 |
def handle(self, argv=None):
"""
Main function.
Parses command, load settings and dispatches accordingly.
"""
desc = ('Zappa - Deploy Python applications to AWS Lambda'
' and API Gateway.\n')
parser = argparse.ArgumentParser(description=desc)
pa... | [
"def",
"handle",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"desc",
"=",
"(",
"'Zappa - Deploy Python applications to AWS Lambda'",
"' and API Gateway.\\n'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"desc",
")",
"parser... | 34.718563 | 22.919162 |
def get_all_styles(document, style):
"""Returns list of styles on which specified style is based on.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Returns:
List of style objects.
"""
classes = []
while Tru... | [
"def",
"get_all_styles",
"(",
"document",
",",
"style",
")",
":",
"classes",
"=",
"[",
"]",
"while",
"True",
":",
"classes",
".",
"insert",
"(",
"0",
",",
"get_style_name",
"(",
"style",
")",
")",
"if",
"style",
".",
"based_on",
":",
"style",
"=",
"d... | 22.363636 | 23.363636 |
def max_ret_portfolio(exp_rets):
"""
Computes a long-only maximum return portfolio, i.e. selects
the assets with maximal return. If there is more than one
asset with maximal return, equally weight all of them.
Parameters
----------
exp_rets: pandas.Series
Expected asset returns ... | [
"def",
"max_ret_portfolio",
"(",
"exp_rets",
")",
":",
"if",
"not",
"isinstance",
"(",
"exp_rets",
",",
"pd",
".",
"Series",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected returns is not a Series\"",
")",
"weights",
"=",
"exp_rets",
"[",
":",
"]",
"weights"... | 27.32 | 18.76 |
def _findAll(self, **kwargs):
"""Return a list of all children that match the specified criteria."""
result = []
for item in self._generateFind(**kwargs):
result.append(item)
return result | [
"def",
"_findAll",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"_generateFind",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] | 37.833333 | 11.5 |
def process_module(self, node):
'''
process a module
the module's content is accessible via node.file_stream object
'''
nodepaths = []
if not isinstance(node.path, list):
nodepaths = [node.path]
else:
nodepaths = node.path
for nod... | [
"def",
"process_module",
"(",
"self",
",",
"node",
")",
":",
"nodepaths",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"node",
".",
"path",
",",
"list",
")",
":",
"nodepaths",
"=",
"[",
"node",
".",
"path",
"]",
"else",
":",
"nodepaths",
"=",
"no... | 43.928571 | 24.428571 |
def load(self, path):
"""Load sound from wave file.
Uses :attr:`Waveform.load`, but will set the Waveform's name based on
the sound filename.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
return Sound(name, Waveform.... | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"(",
"name",
",",
"extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"... | 32.2 | 17.8 |
def from_dict(cls, d):
"""
Generates an ion object from a dict created by as_dict().
Args:
d:
{symbol: amount} dict.
"""
charge = d.pop('charge')
composition = Composition(d)
return Ion(composition, charge) | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"charge",
"=",
"d",
".",
"pop",
"(",
"'charge'",
")",
"composition",
"=",
"Composition",
"(",
"d",
")",
"return",
"Ion",
"(",
"composition",
",",
"charge",
")"
] | 25.545455 | 13.727273 |
def drop_retention_policy(self, name, database=None):
"""Drop an existing retention policy for a database.
:param name: the name of the retention policy to drop
:type name: str
:param database: the database for which the retention policy is
dropped. Defaults to current clien... | [
"def",
"drop_retention_policy",
"(",
"self",
",",
"name",
",",
"database",
"=",
"None",
")",
":",
"query_string",
"=",
"(",
"\"DROP RETENTION POLICY {0} ON {1}\"",
")",
".",
"format",
"(",
"quote_ident",
"(",
"name",
")",
",",
"quote_ident",
"(",
"database",
"... | 42.846154 | 16.769231 |
def run(input_file, options):
"""Runs the Generator using parsed options."""
options.logger = log
generator.Generator(input_file, **options.__dict__).execute() | [
"def",
"run",
"(",
"input_file",
",",
"options",
")",
":",
"options",
".",
"logger",
"=",
"log",
"generator",
".",
"Generator",
"(",
"input_file",
",",
"*",
"*",
"options",
".",
"__dict__",
")",
".",
"execute",
"(",
")"
] | 33.6 | 18.4 |
def scan(backend, timeout=10):
"""Scan for miflora devices.
Note: this must be run as root!
"""
result = []
for (mac, name) in backend.scan_for_devices(timeout):
if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \
mac is not None and mac.upper().startswith(DEVI... | [
"def",
"scan",
"(",
"backend",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"[",
"]",
"for",
"(",
"mac",
",",
"name",
")",
"in",
"backend",
".",
"scan_for_devices",
"(",
"timeout",
")",
":",
"if",
"(",
"name",
"is",
"not",
"None",
"and",
"... | 34.363636 | 17.181818 |
def cancelReserveRN(self, CorpNum, RequestNum, UserID=None):
""" 문자 예약전송 취소
args
CorpNum : 팝빌회원 사업자번호
RequestNum : 전송요청시 할당한 전송요청번호
UserID : 팝빌회원 아이디
return
처리결과. consist of code and message
raise
... | [
"def",
"cancelReserveRN",
"(",
"self",
",",
"CorpNum",
",",
"RequestNum",
",",
"UserID",
"=",
"None",
")",
":",
"if",
"RequestNum",
"==",
"None",
"or",
"RequestNum",
"==",
"''",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"요청번호가 입력되지 않았습니다... | 36.466667 | 15.6 |
def uninstall(client):
"""Uninstall Git hooks."""
from git.index.fun import hook_path as get_hook_path
for hook in HOOKS:
hook_path = Path(get_hook_path(hook, client.repo.git_dir))
if hook_path.exists():
hook_path.unlink() | [
"def",
"uninstall",
"(",
"client",
")",
":",
"from",
"git",
".",
"index",
".",
"fun",
"import",
"hook_path",
"as",
"get_hook_path",
"for",
"hook",
"in",
"HOOKS",
":",
"hook_path",
"=",
"Path",
"(",
"get_hook_path",
"(",
"hook",
",",
"client",
".",
"repo"... | 32 | 17.25 |
def save(self, x509):
"""Persist this x509 object to disk"""
self.x509 = x509
with open_tls_file(self.file_path, 'w',
private=self.is_private()) as fh:
fh.write(str(self)) | [
"def",
"save",
"(",
"self",
",",
"x509",
")",
":",
"self",
".",
"x509",
"=",
"x509",
"with",
"open_tls_file",
"(",
"self",
".",
"file_path",
",",
"'w'",
",",
"private",
"=",
"self",
".",
"is_private",
"(",
")",
")",
"as",
"fh",
":",
"fh",
".",
"w... | 32.714286 | 15.857143 |
def figure_buffer(figs):
'''Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.'''
assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?'
buffers = []
w, h = figs[0].canvas.get_width_height()
for f in figs:
wf, hf = f.canvas.get_width_height()
... | [
"def",
"figure_buffer",
"(",
"figs",
")",
":",
"assert",
"len",
"(",
"figs",
")",
">",
"0",
",",
"'No figure buffers given. Forgot to return from draw call?'",
"buffers",
"=",
"[",
"]",
"w",
",",
"h",
"=",
"figs",
"[",
"0",
"]",
".",
"canvas",
".",
"get_wi... | 46.272727 | 27 |
def _clean_multiple_def(self, ready):
"""Cleans the list of variable definitions extracted from the definition text to
get hold of the dimensions and default values.
"""
result = []
for entry in ready:
if isinstance(entry, list):
#This variable declara... | [
"def",
"_clean_multiple_def",
"(",
"self",
",",
"ready",
")",
":",
"result",
"=",
"[",
"]",
"for",
"entry",
"in",
"ready",
":",
"if",
"isinstance",
"(",
"entry",
",",
"list",
")",
":",
"#This variable declaration has a default value specified, which is in the",
"#... | 39.433333 | 14.666667 |
def su(self) -> 'Gate':
"""Convert gate tensor to the special unitary group."""
rank = 2**self.qubit_nb
U = asarray(self.asoperator())
U /= np.linalg.det(U) ** (1/rank)
return Gate(tensor=U, qubits=self.qubits) | [
"def",
"su",
"(",
"self",
")",
"->",
"'Gate'",
":",
"rank",
"=",
"2",
"**",
"self",
".",
"qubit_nb",
"U",
"=",
"asarray",
"(",
"self",
".",
"asoperator",
"(",
")",
")",
"U",
"/=",
"np",
".",
"linalg",
".",
"det",
"(",
"U",
")",
"**",
"(",
"1"... | 40.833333 | 6.333333 |
def set_register(self, motors):
""" Gets the value from :class:`~pypot.dynamixel.motor.DxlMotor` and sets it to the specified register. """
if not motors:
return
ids = [m.id for m in motors]
values = (m.__dict__[self.varname] for m in motors)
getattr(self.io, 'set_{}... | [
"def",
"set_register",
"(",
"self",
",",
"motors",
")",
":",
"if",
"not",
"motors",
":",
"return",
"ids",
"=",
"[",
"m",
".",
"id",
"for",
"m",
"in",
"motors",
"]",
"values",
"=",
"(",
"m",
".",
"__dict__",
"[",
"self",
".",
"varname",
"]",
"for"... | 39.272727 | 19.545455 |
def do_node_set(self, element, decl, pseudo):
"""Implement node-set declaration."""
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
_, valstep = self.lookup('pending', target)
if not valstep:
... | [
"def",
"do_node_set",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"target",
"=",
"serialize",
"(",
"decl",
".",
"value",
")",
".",
"strip",
"(",
")",
"step",
"=",
"self",
".",
"state",
"[",
"self",
".",
"state",
"[",
"'curren... | 44.6 | 12.9 |
def desc(self):
"""return the description of this endpoint"""
doc = inspect.getdoc(self.controller_class)
if not doc: doc = ''
return doc | [
"def",
"desc",
"(",
"self",
")",
":",
"doc",
"=",
"inspect",
".",
"getdoc",
"(",
"self",
".",
"controller_class",
")",
"if",
"not",
"doc",
":",
"doc",
"=",
"''",
"return",
"doc"
] | 33 | 14 |
def analyze_text(input_text, apis=DEFAULT_APIS, **kwargs):
"""
Given input text, returns the results of specified text apis. Possible apis
include: [ 'text_tags', 'political', 'sentiment', 'language' ]
Example usage:
.. code-block:: python
>>> import indicoio
>>> text = 'M... | [
"def",
"analyze_text",
"(",
"input_text",
",",
"apis",
"=",
"DEFAULT_APIS",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"kwargs",
".",
"pop",
"(",
"'cloud'",
",",
"None",
")",
"batch",
"=",
"kwargs",
".",
"pop",
"(",
"'batch'",
",",
"False",
")"... | 31 | 19.057143 |
def snmp_server_group_write(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
group = ET.SubElement(snmp_server, "group")
group_name_key = ET.SubElement(g... | [
"def",
"snmp_server_group_write",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"snmp_server",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"snmp-server\"",
",",
"xmlns",
"=",
"\"urn:bro... | 45.666667 | 15.2 |
def extracting(self, *names, **kwargs):
"""Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given)."""
if not isinstance(self.val, Iterable):
raise TypeError('val is not iterable')
if isi... | [
"def",
"extracting",
"(",
"self",
",",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"val",
",",
"Iterable",
")",
":",
"raise",
"TypeError",
"(",
"'val is not iterable'",
")",
"if",
"isinstance",
"(",
"se... | 44.892308 | 17.307692 |
def iuwt_decomposition(in1, scale_count, scale_adjust=0, mode='ser', core_count=2, store_smoothed=False,
store_on_gpu=False):
"""
This function serves as a handler for the different implementations of the IUWT decomposition. It allows the
different methods to be used almost interchang... | [
"def",
"iuwt_decomposition",
"(",
"in1",
",",
"scale_count",
",",
"scale_adjust",
"=",
"0",
",",
"mode",
"=",
"'ser'",
",",
"core_count",
"=",
"2",
",",
"store_smoothed",
"=",
"False",
",",
"store_on_gpu",
"=",
"False",
")",
":",
"if",
"mode",
"==",
"'se... | 59.72 | 41.32 |
def _find_resources(resource, name=None, resource_id=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Get VPC resources based on resource type and name, id, or tags.
'''
if all((resource_id, name)):
raise SaltInvocationError('Only one of name or id may ... | [
"def",
"_find_resources",
"(",
"resource",
",",
"name",
"=",
"None",
",",
"resource_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"... | 33.513514 | 23.621622 |
def admin_view_reverse_fk_links(modeladmin: ModelAdmin,
obj,
reverse_fk_set_field: str,
missing: str = "(None)",
use_str: bool = True,
separator: str = "<br>",
... | [
"def",
"admin_view_reverse_fk_links",
"(",
"modeladmin",
":",
"ModelAdmin",
",",
"obj",
",",
"reverse_fk_set_field",
":",
"str",
",",
"missing",
":",
"str",
"=",
"\"(None)\"",
",",
"use_str",
":",
"bool",
"=",
"True",
",",
"separator",
":",
"str",
"=",
"\"<b... | 41.675676 | 16.702703 |
def startstop_bool(pack):
"""Make a bool array based on start and stop conditions.
pack:
pack.ChannelPack instance
If there is start conditions but no stop conditions, this is legal,
the True section will begin at first start and remain the rest of
the array. Likewise, if there is stop con... | [
"def",
"startstop_bool",
"(",
"pack",
")",
":",
"b_TRUE",
"=",
"np",
".",
"ones",
"(",
"pack",
".",
"rec_cnt",
")",
"==",
"True",
"# NOQA",
"start_list",
"=",
"pack",
".",
"conconf",
".",
"conditions_list",
"(",
"'startcond'",
")",
"stop_list",
"=",
"pac... | 29.3125 | 19.708333 |
def is_descriptor_class(desc, include_abstract=False):
r"""Check calculatable descriptor class or not.
Returns:
bool
"""
return (
isinstance(desc, type)
and issubclass(desc, Descriptor)
and (True if include_abstract else not inspect.isabstract(desc))
) | [
"def",
"is_descriptor_class",
"(",
"desc",
",",
"include_abstract",
"=",
"False",
")",
":",
"return",
"(",
"isinstance",
"(",
"desc",
",",
"type",
")",
"and",
"issubclass",
"(",
"desc",
",",
"Descriptor",
")",
"and",
"(",
"True",
"if",
"include_abstract",
... | 24.583333 | 21.25 |
def logout(self):
"""Logout of a vSphere server."""
if self._logged_in is True:
self.si.flush_cache()
self.sc.sessionManager.Logout()
self._logged_in = False | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_logged_in",
"is",
"True",
":",
"self",
".",
"si",
".",
"flush_cache",
"(",
")",
"self",
".",
"sc",
".",
"sessionManager",
".",
"Logout",
"(",
")",
"self",
".",
"_logged_in",
"=",
"False"
] | 34 | 7.166667 |
def tables_list(self, dataset_name, max_results=0, page_token=None):
"""Issues a request to retrieve a list of tables.
Args:
dataset_name: the name of the dataset to enumerate.
max_results: an optional maximum number of tables to retrieve.
page_token: an optional token to continue the retriev... | [
"def",
"tables_list",
"(",
"self",
",",
"dataset_name",
",",
"max_results",
"=",
"0",
",",
"page_token",
"=",
"None",
")",
":",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_TABLES_PATH",
"%",
"(",
"dataset_name",
".",
"project_id",
",",
... | 35.545455 | 23 |
def write(self, notifications):
"Connect to the APNS service and send notifications"
if not self.factory:
log.msg('APNSService write (connecting)')
server, port = ((APNS_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else APNS_SERVER_HOSTNAME), ... | [
"def",
"write",
"(",
"self",
",",
"notifications",
")",
":",
"if",
"not",
"self",
".",
"factory",
":",
"log",
".",
"msg",
"(",
"'APNSService write (connecting)'",
")",
"server",
",",
"port",
"=",
"(",
"(",
"APNS_SERVER_SANDBOX_HOSTNAME",
"if",
"self",
".",
... | 37.571429 | 16.071429 |
def clicky(parser, token):
"""
Clicky tracking template tag.
Renders Javascript code to track page visits. You must supply
your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' ta... | [
"def",
"clicky",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes no arguments\"",
"%",
"bits",
"[",
"0",
"]",
... | 30.083333 | 17.583333 |
def signal_transmit(self, fd):
""" Awake one process waiting to transmit data on fd """
connections = self.connections
if connections(fd) and self.rwait[connections(fd)]:
procid = random.sample(self.rwait[connections(fd)], 1)[0]
self.awake(procid) | [
"def",
"signal_transmit",
"(",
"self",
",",
"fd",
")",
":",
"connections",
"=",
"self",
".",
"connections",
"if",
"connections",
"(",
"fd",
")",
"and",
"self",
".",
"rwait",
"[",
"connections",
"(",
"fd",
")",
"]",
":",
"procid",
"=",
"random",
".",
... | 48.333333 | 11.666667 |
def getpolicyid(self, fuzzy=True, language=None, windowsversion=None):
"""
Return an identification string which can be used to find a policy.
This string is a combination of the manifest's processorArchitecture,
major and minor version, name, publicKeyToken and language.
... | [
"def",
"getpolicyid",
"(",
"self",
",",
"fuzzy",
"=",
"True",
",",
"language",
"=",
"None",
",",
"windowsversion",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"logger",
".",
"warn",
"(",
"\"Assembly metadata incomplete\"",
")",
"return",
... | 38.583333 | 20 |
def authorization_target(original_class):
""" Add bouncer goodness to the model. This is a class decorator, when added to your User model if will add
``can`` and ``cannot`` methods to the class
:param original_class: the User class to be decorated
"""
def can(self, action, subject):
a... | [
"def",
"authorization_target",
"(",
"original_class",
")",
":",
"def",
"can",
"(",
"self",
",",
"action",
",",
"subject",
")",
":",
"ability",
"=",
"Ability",
"(",
"self",
",",
"get_authorization_method",
"(",
")",
")",
"return",
"ability",
".",
"can",
"("... | 35.176471 | 14.411765 |
def download(self, target_relpath, download_in_toto_metadata=True):
'''
Returns:
If download over TUF and in-toto is successful, this function will
return the complete filepath to the desired target.
'''
return self.__get_target(target_relpath, download_in_toto_me... | [
"def",
"download",
"(",
"self",
",",
"target_relpath",
",",
"download_in_toto_metadata",
"=",
"True",
")",
":",
"return",
"self",
".",
"__get_target",
"(",
"target_relpath",
",",
"download_in_toto_metadata",
"=",
"download_in_toto_metadata",
")"
] | 49.571429 | 33 |
def get_variables_by_offset(self, start):
"""
Find variables covering the given region offset.
:param int start:
:return: A list of stack variables.
:rtype: set
"""
_, container = self._get_container(start)
if container is None:
return []
... | [
"def",
"get_variables_by_offset",
"(",
"self",
",",
"start",
")",
":",
"_",
",",
"container",
"=",
"self",
".",
"_get_container",
"(",
"start",
")",
"if",
"container",
"is",
"None",
":",
"return",
"[",
"]",
"else",
":",
"return",
"container",
".",
"inter... | 26 | 14.714286 |
def p_stmt_list(p):
"""
stmt_list : stmt
| stmt_list stmt
"""
if len(p) == 2:
p[0] = node.stmt_list([p[1]] if p[1] else [])
elif len(p) == 3:
p[0] = p[1]
if p[2]:
p[0].append(p[2])
else:
assert 0 | [
"def",
"p_stmt_list",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"node",
".",
"stmt_list",
"(",
"[",
"p",
"[",
"1",
"]",
"]",
"if",
"p",
"[",
"1",
"]",
"else",
"[",
"]",
")",
"elif",
"len",
... | 20.384615 | 16.538462 |
def validate(self):
"""
Verify that the contents of the PublicKey object are valid.
Raises:
TypeError: if the types of any PublicKey attributes are invalid.
"""
if not isinstance(self.value, bytes):
raise TypeError("key value must be bytes")
elif ... | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"value",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"key value must be bytes\"",
")",
"elif",
"not",
"isinstance",
"(",
"self",
".",
"cryptographic_algorithm",
"... | 45.5 | 19.4 |
def remove(self, *tokens: str) -> None:
"""Remove tokens from list."""
from wdom.web_node import WdomElement
_removed_tokens = []
for token in tokens:
self._validate_token(token)
if token in self:
self._list.remove(token)
_removed_t... | [
"def",
"remove",
"(",
"self",
",",
"*",
"tokens",
":",
"str",
")",
"->",
"None",
":",
"from",
"wdom",
".",
"web_node",
"import",
"WdomElement",
"_removed_tokens",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"self",
".",
"_validate_token",
"(",
... | 42 | 8.909091 |
def components(arg):
"""Converts a dict of components to the format expected by the Google Maps
server.
For example:
c = {"country": "US", "postal_code": "94043"}
convert.components(c)
# 'country:US|postal_code:94043'
:param arg: The component filter.
:type arg: dict
:rtype: bases... | [
"def",
"components",
"(",
"arg",
")",
":",
"# Components may have multiple values per type, here we",
"# expand them into individual key/value items, eg:",
"# {\"country\": [\"US\", \"AU\"], \"foo\": 1} -> \"country:AU\", \"country:US\", \"foo:1\"",
"def",
"expand",
"(",
"arg",
")",
":",... | 28.206897 | 18.241379 |
def set_cookie(self, name: str, value: str, *,
expires: Optional[str]=None,
domain: Optional[str]=None,
max_age: Optional[Union[int, str]]=None,
path: str='/',
secure: Optional[str]=None,
httponly: Optional... | [
"def",
"set_cookie",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
",",
"*",
",",
"expires",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"domain",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"max_age",
":",
"Opti... | 31.162791 | 14.883721 |
def _clear_inspect(self):
"""Clears inspect attributes when re-executing a pipeline"""
self.trace_info = defaultdict(list)
self.process_tags = {}
self.process_stats = {}
self.samples = []
self.stored_ids = []
self.stored_log_ids = []
self.time_start = Non... | [
"def",
"_clear_inspect",
"(",
"self",
")",
":",
"self",
".",
"trace_info",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"process_tags",
"=",
"{",
"}",
"self",
".",
"process_stats",
"=",
"{",
"}",
"self",
".",
"samples",
"=",
"[",
"]",
"self",
"... | 33.45 | 10.95 |
def transform(self, crs):
""" Transforms BBoxCollection from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: BBoxCollection in target CRS
:rtype: BBoxCollection
"""
return BBoxCollection([bbox.transform(crs) for bbox in self.bbo... | [
"def",
"transform",
"(",
"self",
",",
"crs",
")",
":",
"return",
"BBoxCollection",
"(",
"[",
"bbox",
".",
"transform",
"(",
"crs",
")",
"for",
"bbox",
"in",
"self",
".",
"bbox_list",
"]",
")"
] | 35.555556 | 14.111111 |
def iterable_source(iterable, target):
"""Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
it = iter(iterable)... | [
"def",
"iterable_source",
"(",
"iterable",
",",
"target",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"for",
"item",
"in",
"it",
":",
"try",
":",
"target",
".",
"send",
"(",
"item",
")",
"except",
"StopIteration",
":",
"return",
"prepend",
"(",
... | 26.941176 | 17.647059 |
def __check_extension(files, ignore_globs=None, include_globs=None):
"""
Internal method to filter a list of file changes by extension and ignore_dirs.
:param files:
:param ignore_globs: a list of globs to ignore (if none falls back to extensions and ignore_dir)
:param include_g... | [
"def",
"__check_extension",
"(",
"files",
",",
"ignore_globs",
"=",
"None",
",",
"include_globs",
"=",
"None",
")",
":",
"if",
"include_globs",
"is",
"None",
"or",
"include_globs",
"==",
"[",
"]",
":",
"include_globs",
"=",
"[",
"'*'",
"]",
"out",
"=",
"... | 40.965517 | 28.62069 |
def job_task(self, application_id, job_id, task_id):
"""
A Task resource contains information about a particular
task within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response ... | [
"def",
"job_task",
"(",
"self",
",",
"application_id",
",",
"job_id",
",",
"task_id",
")",
":",
"path",
"=",
"'/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'",
".",
"format",
"(",
"appid",
"=",
"application_id",
",",
"jobid",
"=",
"job_id",
",",
"task... | 38.666667 | 16.533333 |
def show_error_dialog(self, message, details=None):
"""
Convenience method for showing an error dialog.
"""
dlg = Gtk.MessageDialog(type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
message_format=message)
if details is not None:
... | [
"def",
"show_error_dialog",
"(",
"self",
",",
"message",
",",
"details",
"=",
"None",
")",
":",
"dlg",
"=",
"Gtk",
".",
"MessageDialog",
"(",
"type",
"=",
"Gtk",
".",
"MessageType",
".",
"ERROR",
",",
"buttons",
"=",
"Gtk",
".",
"ButtonsType",
".",
"OK... | 38.6 | 14.6 |
def columnCount(self, parent):
""" Returns the number of columns for the children of the given parent.
"""
# print("columnCount:",self)
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.root.columnCount() | [
"def",
"columnCount",
"(",
"self",
",",
"parent",
")",
":",
"# print(\"columnCount:\",self)",
"if",
"parent",
".",
"isValid",
"(",
")",
":",
"return",
"parent",
".",
"internalPointer",
"(",
")",
".",
"columnCount",
"(",
")",
"else",
":",
"return",
"self",
... | 37 | 9 |
def _read_requirements(filename, extra_packages):
"""Returns a list of package requirements read from the file."""
requirements_file = open(filename).read()
hard_requirements = []
for line in requirements_file.splitlines():
if _is_requirement(line):
if line.find(';') > -1:
... | [
"def",
"_read_requirements",
"(",
"filename",
",",
"extra_packages",
")",
":",
"requirements_file",
"=",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
"hard_requirements",
"=",
"[",
"]",
"for",
"line",
"in",
"requirements_file",
".",
"splitlines",
"(",
... | 41.692308 | 13.230769 |
def get_password(vm_):
r'''
Return the password to use for a VM.
vm\_
The configuration to obtain the password from.
'''
return config.get_cloud_config_value(
'password', vm_, __opts__,
default=config.get_cloud_config_value(
'passwd', vm_, __opts__,
s... | [
"def",
"get_password",
"(",
"vm_",
")",
":",
"return",
"config",
".",
"get_cloud_config_value",
"(",
"'password'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'passwd'",
",",
"vm_",
",",
"__opts__",
",",
"... | 24.6 | 18.2 |
def _BuildStreamingResponse(self, binary_stream, method_name=None):
"""Builds HTTPResponse object for streaming."""
precondition.AssertType(method_name, Text)
# We get a first chunk of the output stream. This way the likelihood
# of catching an exception that may happen during response generation
#... | [
"def",
"_BuildStreamingResponse",
"(",
"self",
",",
"binary_stream",
",",
"method_name",
"=",
"None",
")",
":",
"precondition",
".",
"AssertType",
"(",
"method_name",
",",
"Text",
")",
"# We get a first chunk of the output stream. This way the likelihood",
"# of catching an... | 35.777778 | 19.962963 |
def get_chain_details_by_related_pdb_chains(self, pdb_id, chain_id, pfam_accs):
''' Returns a dict of SCOPe details using info
This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned.
If there are SCOPe entries for the assoc... | [
"def",
"get_chain_details_by_related_pdb_chains",
"(",
"self",
",",
"pdb_id",
",",
"chain_id",
",",
"pfam_accs",
")",
":",
"if",
"not",
"pfam_accs",
":",
"return",
"None",
"associated_pdb_chains",
"=",
"set",
"(",
")",
"pfam_api",
"=",
"self",
".",
"get_pfam_api... | 44.166667 | 25.166667 |
def set_scalar(self, indexer, value):
"""
Set scalar value into the array.
Parameters
----------
indexer : any
The indexer to set the value at.
value : str
The value to assign at the given locations.
Raises
------
ValueErr... | [
"def",
"set_scalar",
"(",
"self",
",",
"indexer",
",",
"value",
")",
":",
"try",
":",
"value_code",
"=",
"self",
".",
"reverse_categories",
"[",
"value",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"%r is not in LabelArray categories.\"",
"%",
... | 27.304348 | 20 |
def ssh_sa_ssh_client_cipher(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
client = ET.SubElement(ssh, "client")
... | [
"def",
"ssh_sa_ssh_client_cipher",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ssh_sa",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ssh-sa\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:... | 40.583333 | 12.5 |
def main(arguments=None):
"""Command-line entry point.
:param arguments: List of strings that contain the command-line arguments.
When ``None``, the command-line arguments are looked up in ``sys.argv``
(``sys.argv[0]`` is ignored).
:return: This function has no return value.
:raise System... | [
"def",
"main",
"(",
"arguments",
"=",
"None",
")",
":",
"# Parse command-line arguments.",
"if",
"arguments",
"is",
"None",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"arguments",
"=",
"cli",
".",
"parse_args",
"(",
"arguments",
")",
... | 31.658537 | 16.365854 |
def describe_unsupported(series, **kwargs):
"""Compute summary statistics of a unsupported (`S_TYPE_UNSUPPORTED`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with ind... | [
"def",
"describe_unsupported",
"(",
"series",
",",
"*",
"*",
"kwargs",
")",
":",
"leng",
"=",
"len",
"(",
"series",
")",
"# number of observations in the Series",
"count",
"=",
"series",
".",
"count",
"(",
")",
"# number of non-NaN observations in the Series",
"n_in... | 33.774194 | 21.935484 |
def generate_repr(*members):
"""
Decorator that binds an auto-generated ``__repr__()`` function to a class.
The generated ``__repr__()`` function prints in following format:
<ClassName object(field1=1, field2='A string', field3=[1, 2, 3]) at 0xAAAA>
Note that this decorator modifies the given clas... | [
"def",
"generate_repr",
"(",
"*",
"members",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"cls",
".",
"__repr__",
"=",
"__repr__",
"return",
"cls",
"if",
"members",
":",
"# Prepare members list.",
"members_to_print",
"=",
"list",
"(",
"members",
")",
... | 45.408451 | 24.478873 |
def emg_var(X):
''' variance (assuming a mean of zero) for each variable in the segmented time series
(equals abs_energy divided by (seg_size - 1)) '''
segment_width = X.shape[1]
return np.sum(X * X, axis=1) / (segment_width - 1) | [
"def",
"emg_var",
"(",
"X",
")",
":",
"segment_width",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"return",
"np",
".",
"sum",
"(",
"X",
"*",
"X",
",",
"axis",
"=",
"1",
")",
"/",
"(",
"segment_width",
"-",
"1",
")"
] | 48.2 | 22.2 |
def _set_af_ipv4_unicast(self, v, load=False):
"""
Setter method for af_ipv4_unicast, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_ipv4_uni... | [
"def",
"_set_af_ipv4_unicast",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 93.818182 | 45.409091 |
def name(self, src=None):
"""Return string representing the name of this type."""
res = [_get_type_name(tt, src) for tt in self._types]
if len(res) == 2 and "None" in res:
res.remove("None")
return "?" + res[0]
else:
return " | ".join(res) | [
"def",
"name",
"(",
"self",
",",
"src",
"=",
"None",
")",
":",
"res",
"=",
"[",
"_get_type_name",
"(",
"tt",
",",
"src",
")",
"for",
"tt",
"in",
"self",
".",
"_types",
"]",
"if",
"len",
"(",
"res",
")",
"==",
"2",
"and",
"\"None\"",
"in",
"res"... | 37.5 | 11.375 |
def huffman_compute_decode_tree(cls):
# type: () -> None
""" huffman_compute_decode_tree initializes/builds the static_huffman_tree
@return None
@raise InvalidEncodingException if there is an encoding problem
"""
cls.static_huffman_tree = HuffmanNode(None, None)
... | [
"def",
"huffman_compute_decode_tree",
"(",
"cls",
")",
":",
"# type: () -> None",
"cls",
".",
"static_huffman_tree",
"=",
"HuffmanNode",
"(",
"None",
",",
"None",
")",
"i",
"=",
"0",
"for",
"entry",
"in",
"cls",
".",
"static_huffman_code",
":",
"parent",
"=",
... | 42 | 15.190476 |
def decode_vlqs(s):
"""
Decode str `s` into a list of integers.
"""
ints = []
i = 0
shift = 0
for c in s:
raw = B64_INT[c]
cont = VLQ_CONT & raw
i = ((VLQ_BASE_MASK & raw) << shift) | i
shift += VLQ_SHIFT
if not cont:
sign = -1 if 1 & i e... | [
"def",
"decode_vlqs",
"(",
"s",
")",
":",
"ints",
"=",
"[",
"]",
"i",
"=",
"0",
"shift",
"=",
"0",
"for",
"c",
"in",
"s",
":",
"raw",
"=",
"B64_INT",
"[",
"c",
"]",
"cont",
"=",
"VLQ_CONT",
"&",
"raw",
"i",
"=",
"(",
"(",
"VLQ_BASE_MASK",
"&"... | 19.52381 | 18.380952 |
def _prepare_atoms(topology, compute_cycles=False):
"""Compute cycles and add white-/blacklists to atoms."""
atom1 = next(topology.atoms())
has_whitelists = hasattr(atom1, 'whitelist')
has_cycles = hasattr(atom1, 'cycles')
compute_cycles = compute_cycles and not has_cycles
if compute_cycles or ... | [
"def",
"_prepare_atoms",
"(",
"topology",
",",
"compute_cycles",
"=",
"False",
")",
":",
"atom1",
"=",
"next",
"(",
"topology",
".",
"atoms",
"(",
")",
")",
"has_whitelists",
"=",
"hasattr",
"(",
"atom1",
",",
"'whitelist'",
")",
"has_cycles",
"=",
"hasatt... | 40.217391 | 11.956522 |
def search_ap(self, mode, query):
"""搜索接入点
查看指定接入点的所有配置信息,包括所有监听端口的配置。
Args:
- mode: 搜索模式,可以是domain、ip、host
- query: 搜索文本
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回搜索结果,失败返回{"error": "<errMsg string... | [
"def",
"search_ap",
"(",
"self",
",",
"mode",
",",
"query",
")",
":",
"url",
"=",
"'{0}/v3/aps/search?{1}={2}'",
".",
"format",
"(",
"self",
".",
"host",
",",
"mode",
",",
"query",
")",
"return",
"self",
".",
"__get",
"(",
"url",
")"
] | 29.25 | 18.1875 |
def exportSite(self, location):
"""
This operation exports the portal site configuration to a location
you specify.
"""
params = {
"location" : location,
"f" : "json"
}
url = self._url + "/exportSite"
return self._post(url=url, para... | [
"def",
"exportSite",
"(",
"self",
",",
"location",
")",
":",
"params",
"=",
"{",
"\"location\"",
":",
"location",
",",
"\"f\"",
":",
"\"json\"",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/exportSite\"",
"return",
"self",
".",
"_post",
"(",
"url",
"... | 29.454545 | 13.818182 |
def update_endpoint(self, updated_ed):
"""
Update a previously advertised endpoint_description.
:param endpoint_description: an instance of EndpointDescription to
update. Must not be None.
:return: True if advertised, False if not
(e.g. it's already been advertised)
... | [
"def",
"update_endpoint",
"(",
"self",
",",
"updated_ed",
")",
":",
"endpoint_id",
"=",
"updated_ed",
".",
"get_id",
"(",
")",
"with",
"self",
".",
"_published_endpoints_lock",
":",
"if",
"self",
".",
"get_advertised_endpoint",
"(",
"endpoint_id",
")",
"is",
"... | 35.857143 | 15.571429 |
def _ignore_path(cls, path, ignore_list=None, white_list=None):
"""Returns a whether a path should be ignored or not."""
ignore_list = ignore_list or []
white_list = white_list or []
return (cls._matches_patterns(path, ignore_list) and
not cls._matches_patterns(path, whit... | [
"def",
"_ignore_path",
"(",
"cls",
",",
"path",
",",
"ignore_list",
"=",
"None",
",",
"white_list",
"=",
"None",
")",
":",
"ignore_list",
"=",
"ignore_list",
"or",
"[",
"]",
"white_list",
"=",
"white_list",
"or",
"[",
"]",
"return",
"(",
"cls",
".",
"_... | 53.833333 | 11.166667 |
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "... | [
"def",
"datetime_to_str",
"(",
"self",
",",
"format",
"=",
"\"%Y-%m-%dT%H:%M:%S%ZP\"",
")",
":",
"if",
"(",
"self",
".",
"dtype",
"!=",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"datetime_to_str expects SArray of datetime as input SArray\"",
... | 31.052632 | 25.263158 |
def xcoord(self):
"""The x coordinate :class:`xarray.Variable`"""
return self.decoder.get_x(self.data, coords=self.data.coords) | [
"def",
"xcoord",
"(",
"self",
")",
":",
"return",
"self",
".",
"decoder",
".",
"get_x",
"(",
"self",
".",
"data",
",",
"coords",
"=",
"self",
".",
"data",
".",
"coords",
")"
] | 47 | 17.333333 |
def getfile(self):
"""Gets the full file path of the entered/selected file
:returns: str -- the name of the data file to open/create
"""
current_file = str(self.selectedFiles()[0])
if os.path.isfile(current_file):
print 'current_file', current_file
if cur... | [
"def",
"getfile",
"(",
"self",
")",
":",
"current_file",
"=",
"str",
"(",
"self",
".",
"selectedFiles",
"(",
")",
"[",
"0",
"]",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"current_file",
")",
":",
"print",
"'current_file'",
",",
"current_file",... | 37.647059 | 16.941176 |
def add_signal_handler():
"""Adds a signal handler to handle KeyboardInterrupt."""
import signal
def handler(sig, frame):
if sig == signal.SIGINT:
librtmp.RTMP_UserInterrupt()
raise KeyboardInterrupt
signal.signal(signal.SIGINT, handler) | [
"def",
"add_signal_handler",
"(",
")",
":",
"import",
"signal",
"def",
"handler",
"(",
"sig",
",",
"frame",
")",
":",
"if",
"sig",
"==",
"signal",
".",
"SIGINT",
":",
"librtmp",
".",
"RTMP_UserInterrupt",
"(",
")",
"raise",
"KeyboardInterrupt",
"signal",
"... | 27.8 | 14.4 |
def assemble(self, module, *modules, **kwargs):
# type: (AbstractModule, *AbstractModule, **Any) -> SeqRecord
"""Assemble the provided modules into the vector.
Arguments:
module (`~moclo.base.modules.AbstractModule`): a module to insert
in the vector.
mod... | [
"def",
"assemble",
"(",
"self",
",",
"module",
",",
"*",
"modules",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (AbstractModule, *AbstractModule, **Any) -> SeqRecord",
"mgr",
"=",
"AssemblyManager",
"(",
"vector",
"=",
"self",
",",
"modules",
"=",
"[",
"module",... | 44.131579 | 24.447368 |
def Sample(self):
"""Takes a sample for profiling."""
self._profiling_sample += 1
if self._profiling_sample >= self._profiling_sample_rate:
if self._heapy:
heap = self._heapy.heap()
heap.dump(self._sample_file)
self._profiling_sample = 0 | [
"def",
"Sample",
"(",
"self",
")",
":",
"self",
".",
"_profiling_sample",
"+=",
"1",
"if",
"self",
".",
"_profiling_sample",
">=",
"self",
".",
"_profiling_sample_rate",
":",
"if",
"self",
".",
"_heapy",
":",
"heap",
"=",
"self",
".",
"_heapy",
".",
"hea... | 27 | 17.1 |
def dict_given_run_array(samples, thread_min_max):
"""
Converts an array of information about samples back into a nested sampling
run dictionary (see data_processing module docstring for more details).
N.B. the output dict only contains the following keys: 'logl',
'thread_label', 'nlive_array', 'th... | [
"def",
"dict_given_run_array",
"(",
"samples",
",",
"thread_min_max",
")",
":",
"ns_run",
"=",
"{",
"'logl'",
":",
"samples",
"[",
":",
",",
"0",
"]",
",",
"'thread_labels'",
":",
"samples",
"[",
":",
",",
"1",
"]",
",",
"'thread_min_max'",
":",
"thread_... | 47.857143 | 20.968254 |
def process(self, sched, coro):
"""Add the timeout in the scheduler, check for defaults."""
super(TimedOperation, self).process(sched, coro)
if sched.default_timeout and not self.timeout:
self.set_timeout(sched.default_timeout)
if self.timeout and self.timeout != -1:
... | [
"def",
"process",
"(",
"self",
",",
"sched",
",",
"coro",
")",
":",
"super",
"(",
"TimedOperation",
",",
"self",
")",
".",
"process",
"(",
"sched",
",",
"coro",
")",
"if",
"sched",
".",
"default_timeout",
"and",
"not",
"self",
".",
"timeout",
":",
"s... | 38.375 | 17.125 |
def remove_api_keys_from_group(self, group_id, body, **kwargs): # noqa: E501
"""Remove API keys from a group. # noqa: E501
An endpoint for removing API keys from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id}/api-keys -d '[0162056a9a1586f3... | [
"def",
"remove_api_keys_from_group",
"(",
"self",
",",
"group_id",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"retu... | 63.590909 | 37.818182 |
def send_token(self, token):
"""
Used by `Client.connect()`.
After connecting to an official server and sending the
handshake packets, the client has to send the token
acquired through `utils.find_server()`, otherwise the server will
drop the connection when receiving an... | [
"def",
"send_token",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"send_struct",
"(",
"'<B%iB'",
"%",
"len",
"(",
"token",
")",
",",
"80",
",",
"*",
"map",
"(",
"ord",
",",
"token",
")",
")",
"self",
".",
"server_token",
"=",
"token"
] | 40 | 16.909091 |
def _encode(values, salt, min_length, alphabet, separators, guards):
"""Helper function that does the hash building without argument checks."""
len_alphabet = len(alphabet)
len_separators = len(separators)
values_hash = sum(x % (i + 100) for i, x in enumerate(values))
encoded = lottery = alphabet[v... | [
"def",
"_encode",
"(",
"values",
",",
"salt",
",",
"min_length",
",",
"alphabet",
",",
"separators",
",",
"guards",
")",
":",
"len_alphabet",
"=",
"len",
"(",
"alphabet",
")",
"len_separators",
"=",
"len",
"(",
"separators",
")",
"values_hash",
"=",
"sum",... | 41.4 | 19.6 |
def _format_field_name(self, field_name) -> str:
"""Formats a field's name for usage in SQL.
Arguments:
field_name:
The field name to format.
Returns:
The specified field name formatted for
usage in SQL.
"""
field = self._get... | [
"def",
"_format_field_name",
"(",
"self",
",",
"field_name",
")",
"->",
"str",
":",
"field",
"=",
"self",
".",
"_get_model_field",
"(",
"field_name",
")",
"return",
"self",
".",
"qn",
"(",
"field",
".",
"column",
")"
] | 26.285714 | 16.428571 |
def verify_dataset(X, y):
"""Verifies if a dataset is valid for use i.e. scikit-learn format
Used to verify a dataset by returning shape and basic statistics of
returned data. This will also provide quick and dirty check on
capability of host machine to process the data.
Args:
X (array-lik... | [
"def",
"verify_dataset",
"(",
"X",
",",
"y",
")",
":",
"X_shape",
",",
"y_shape",
"=",
"np",
".",
"array",
"(",
"X",
")",
".",
"shape",
",",
"np",
".",
"array",
"(",
"y",
")",
".",
"shape",
"if",
"len",
"(",
"X_shape",
")",
"!=",
"2",
":",
"r... | 35.411765 | 23.029412 |
def XCHG(cpu, dest, src):
"""
Exchanges register/memory with register.
Exchanges the contents of the destination (first) and source (second)
operands. The operands can be two general-purpose registers or a register
and a memory location. If a memory operand is referenced, the pr... | [
"def",
"XCHG",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"temp",
"=",
"dest",
".",
"read",
"(",
")",
"dest",
".",
"write",
"(",
"src",
".",
"read",
"(",
")",
")",
"src",
".",
"write",
"(",
"temp",
")"
] | 39.807692 | 20.115385 |
def replace(self, pattern, replacement):
"""
Replace all instances of a pattern with a replacement.
Args:
pattern (str): Pattern to replace
replacement (str): Text to insert
"""
for i, line in enumerate(self):
if pattern in line:
... | [
"def",
"replace",
"(",
"self",
",",
"pattern",
",",
"replacement",
")",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"pattern",
"in",
"line",
":",
"self",
"[",
"i",
"]",
"=",
"line",
".",
"replace",
"(",
"pattern",
... | 32.454545 | 11.727273 |
def list_sets(self, project, **filters):
"""List the articlesets in a project"""
url = URL.articlesets.format(**locals())
return self.get_pages(url, **filters) | [
"def",
"list_sets",
"(",
"self",
",",
"project",
",",
"*",
"*",
"filters",
")",
":",
"url",
"=",
"URL",
".",
"articlesets",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"return",
"self",
".",
"get_pages",
"(",
"url",
",",
"*",
"*",
"fil... | 45 | 3.25 |
def _merge_user_attrs(self, attrs_backend, attrs_out, backend_name):
""" merge attributes from one backend search to the attributes dict
output
"""
for attr in attrs_backend:
if attr in self.attributes.backend_attributes[backend_name]:
attrid = self.attribute... | [
"def",
"_merge_user_attrs",
"(",
"self",
",",
"attrs_backend",
",",
"attrs_out",
",",
"backend_name",
")",
":",
"for",
"attr",
"in",
"attrs_backend",
":",
"if",
"attr",
"in",
"self",
".",
"attributes",
".",
"backend_attributes",
"[",
"backend_name",
"]",
":",
... | 45.5 | 19.3 |
def permissions(self, actor, inherited=None):
"""
Permissions for this model, plus permissions inherited from the parent.
"""
if inherited is not None:
return inherited | super(BaseScopedNameMixin, self).permissions(actor)
elif self.parent is not None and isinstance(s... | [
"def",
"permissions",
"(",
"self",
",",
"actor",
",",
"inherited",
"=",
"None",
")",
":",
"if",
"inherited",
"is",
"not",
"None",
":",
"return",
"inherited",
"|",
"super",
"(",
"BaseScopedNameMixin",
",",
"self",
")",
".",
"permissions",
"(",
"actor",
")... | 52.9 | 25.5 |
def write(self, data):
"""Write data to serial port."""
for chunk in chunks(data, 512):
self.wait_to_write()
self.comport.write(chunk)
self.comport.flush() | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"for",
"chunk",
"in",
"chunks",
"(",
"data",
",",
"512",
")",
":",
"self",
".",
"wait_to_write",
"(",
")",
"self",
".",
"comport",
".",
"write",
"(",
"chunk",
")",
"self",
".",
"comport",
".",
"... | 33 | 7 |
def respond_list_directory(self, dir_path, query=None):
"""
Respond to the client with an HTML page listing the contents of
the specified directory.
:param str dir_path: The path of the directory to list the contents of.
"""
del query
try:
dir_contents = os.listdir(dir_path)
except os.error:
self... | [
"def",
"respond_list_directory",
"(",
"self",
",",
"dir_path",
",",
"query",
"=",
"None",
")",
":",
"del",
"query",
"try",
":",
"dir_contents",
"=",
"os",
".",
"listdir",
"(",
"dir_path",
")",
"except",
"os",
".",
"error",
":",
"self",
".",
"respond_not_... | 36.478261 | 21.608696 |
def provider_parser(subparser):
"""Specify arguments for AWS Route 53 Lexicon Provider."""
subparser.add_argument("--auth-access-key",
help="specify ACCESS_KEY for authentication")
subparser.add_argument("--auth-access-secret",
help="specify ACCESS_SECRE... | [
"def",
"provider_parser",
"(",
"subparser",
")",
":",
"subparser",
".",
"add_argument",
"(",
"\"--auth-access-key\"",
",",
"help",
"=",
"\"specify ACCESS_KEY for authentication\"",
")",
"subparser",
".",
"add_argument",
"(",
"\"--auth-access-secret\"",
",",
"help",
"=",... | 53.833333 | 24.055556 |
def copy_submission_to_destination(self, src_filename, dst_subdir,
submission_id):
"""Copies submission to target directory.
Args:
src_filename: source filename of the submission
dst_subdir: subdirectory of the target directory where submission should
be... | [
"def",
"copy_submission_to_destination",
"(",
"self",
",",
"src_filename",
",",
"dst_subdir",
",",
"submission_id",
")",
":",
"extension",
"=",
"[",
"e",
"for",
"e",
"in",
"ALLOWED_EXTENSIONS",
"if",
"src_filename",
".",
"endswith",
"(",
"e",
")",
"]",
"if",
... | 41.73913 | 21.217391 |
def get_CV_prediction(self):
"""
Returns:
np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`).
"""
# TODO: get it from the test_prediction ...
# test_id, prediction
# sort by test_id
predict_vec = np.zeros((self._n_... | [
"def",
"get_CV_prediction",
"(",
"self",
")",
":",
"# TODO: get it from the test_prediction ...",
"# test_id, prediction",
"# sort by test_id",
"predict_vec",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"_n_rows",
",",
"self",
".",
"_concise_model",
".",
"_num_tas... | 40.769231 | 16.923077 |
def degrees_of_freedom(self):
"""
Returns the number of degrees of freedom.
"""
if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None
# Temporary hack: get the studentized residuals, which uses the massaged data
# This should later be changed to get_... | [
"def",
"degrees_of_freedom",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_set_xdata",
")",
"==",
"0",
"or",
"len",
"(",
"self",
".",
"_set_ydata",
")",
"==",
"0",
":",
"return",
"None",
"# Temporary hack: get the studentized residuals, which uses the ... | 33.555556 | 17 |
def _poll_slapd(self, timeout=DEFAULT_STARTUP_DELAY):
"""Poll slapd port until available."""
begin = time.time()
time.sleep(0.5)
while time.time() < begin + timeout:
if self._process.poll() is not None:
raise RuntimeError("LDAP server has exited before starti... | [
"def",
"_poll_slapd",
"(",
"self",
",",
"timeout",
"=",
"DEFAULT_STARTUP_DELAY",
")",
":",
"begin",
"=",
"time",
".",
"time",
"(",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"while",
"time",
".",
"time",
"(",
")",
"<",
"begin",
"+",
"timeout",
":",
... | 33 | 19.190476 |
def reset(self):
"""Remove all the information from previous dataset before loading a
new dataset.
"""
# store current dataset
max_dataset_history = self.value('max_dataset_history')
keep_recent_datasets(max_dataset_history, self.info)
# reset all the widgets
... | [
"def",
"reset",
"(",
"self",
")",
":",
"# store current dataset",
"max_dataset_history",
"=",
"self",
".",
"value",
"(",
"'max_dataset_history'",
")",
"keep_recent_datasets",
"(",
"max_dataset_history",
",",
"self",
".",
"info",
")",
"# reset all the widgets",
"self",... | 29.411765 | 16.058824 |
def video_pos(self):
"""
Returns:
(int, int, int, int): Video spatial position (x1, y1, x2, y2) where (x1, y1) is top left,
and (x2, y2) is bottom right. All values in px.
"""
position_string = self._player_interface.VideoPos(ObjectPath('/not... | [
"def",
"video_pos",
"(",
"self",
")",
":",
"position_string",
"=",
"self",
".",
"_player_interface",
".",
"VideoPos",
"(",
"ObjectPath",
"(",
"'/not/used'",
")",
")",
"return",
"list",
"(",
"map",
"(",
"int",
",",
"position_string",
".",
"split",
"(",
"\" ... | 47.375 | 25.625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.