text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def correct(tokens, term_freq):
"""
Correct a list of tokens, according to the term_freq
"""
log = []
output = []
for token in tokens:
corrected = _correct(token, term_freq)
if corrected != token:
log.append((token, corrected))
output.append(corrected)
ret... | [
"def",
"correct",
"(",
"tokens",
",",
"term_freq",
")",
":",
"log",
"=",
"[",
"]",
"output",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"corrected",
"=",
"_correct",
"(",
"token",
",",
"term_freq",
")",
"if",
"corrected",
"!=",
"token",
":",... | 27 | 11.5 |
def from_sqlite(cls, database_path, base_url, version='auto', client_id='ghost-admin'):
"""
Initialize a new Ghost API client,
reading the client ID and secret from the SQlite database.
:param database_path: The path to the database file.
:param base_url: The base url of the ser... | [
"def",
"from_sqlite",
"(",
"cls",
",",
"database_path",
",",
"base_url",
",",
"version",
"=",
"'auto'",
",",
"client_id",
"=",
"'ghost-admin'",
")",
":",
"import",
"os",
"import",
"sqlite3",
"fd",
"=",
"os",
".",
"open",
"(",
"database_path",
",",
"os",
... | 32.384615 | 21.307692 |
def strip_ip_port(ip_address):
"""
Strips the port from an IPv4 or IPv6 address, returns a unicode object.
"""
# IPv4 with or without port
if '.' in ip_address:
cleaned_ip = ip_address.split(':')[0]
# IPv6 with port
elif ']:' in ip_address:
# Remove the port following last ... | [
"def",
"strip_ip_port",
"(",
"ip_address",
")",
":",
"# IPv4 with or without port",
"if",
"'.'",
"in",
"ip_address",
":",
"cleaned_ip",
"=",
"ip_address",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"# IPv6 with port",
"elif",
"']:'",
"in",
"ip_address",
":"... | 26.157895 | 21.421053 |
def add_minute(self, minute):
"""Create a new DateTime after the minutes are added.
Args:
minute: An integer value for minutes.
"""
_moy = self.moy + int(minute)
return self.__class__.from_moy(_moy) | [
"def",
"add_minute",
"(",
"self",
",",
"minute",
")",
":",
"_moy",
"=",
"self",
".",
"moy",
"+",
"int",
"(",
"minute",
")",
"return",
"self",
".",
"__class__",
".",
"from_moy",
"(",
"_moy",
")"
] | 30.5 | 11.75 |
def do_gate_matrix(self, matrix: np.ndarray,
qubits: Sequence[int]) -> 'AbstractQuantumSimulator':
"""
Apply an arbitrary unitary; not necessarily a named gate.
:param matrix: The unitary matrix to apply. No checks are done
:param qubits: A list of qubits to apply... | [
"def",
"do_gate_matrix",
"(",
"self",
",",
"matrix",
":",
"np",
".",
"ndarray",
",",
"qubits",
":",
"Sequence",
"[",
"int",
"]",
")",
"->",
"'AbstractQuantumSimulator'",
":",
"# e.g. 2-qubit matrix is 4x4; turns into (2,2,2,2) tensor.",
"tensor",
"=",
"np",
".",
"... | 51.058824 | 26.352941 |
def timeseries(X, **kwargs):
"""Plot X. See timeseries_subplot."""
pl.figure(figsize=(2*rcParams['figure.figsize'][0], rcParams['figure.figsize'][1]),
subplotpars=sppars(left=0.12, right=0.98, bottom=0.13))
timeseries_subplot(X, **kwargs) | [
"def",
"timeseries",
"(",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"pl",
".",
"figure",
"(",
"figsize",
"=",
"(",
"2",
"*",
"rcParams",
"[",
"'figure.figsize'",
"]",
"[",
"0",
"]",
",",
"rcParams",
"[",
"'figure.figsize'",
"]",
"[",
"1",
"]",
")",
... | 52 | 18.6 |
def detect_metadata_url_scheme(url):
"""detect whether a url is a Service type that HHypermap supports"""
scheme = None
url_lower = url.lower()
if any(x in url_lower for x in ['wms', 'service=wms']):
scheme = 'OGC:WMS'
if any(x in url_lower for x in ['wmts', 'service=wmts']):
schem... | [
"def",
"detect_metadata_url_scheme",
"(",
"url",
")",
":",
"scheme",
"=",
"None",
"url_lower",
"=",
"url",
".",
"lower",
"(",
")",
"if",
"any",
"(",
"x",
"in",
"url_lower",
"for",
"x",
"in",
"[",
"'wms'",
",",
"'service=wms'",
"]",
")",
":",
"scheme",
... | 33.75 | 18 |
def add_pkg(pkgs, name, pkgver):
'''
Add a package to a dict of installed packages.
CLI Example:
.. code-block:: bash
salt '*' pkg_resource.add_pkg '{}' bind 9
'''
try:
pkgs.setdefault(name, []).append(pkgver)
except AttributeError as exc:
log.exception(exc) | [
"def",
"add_pkg",
"(",
"pkgs",
",",
"name",
",",
"pkgver",
")",
":",
"try",
":",
"pkgs",
".",
"setdefault",
"(",
"name",
",",
"[",
"]",
")",
".",
"append",
"(",
"pkgver",
")",
"except",
"AttributeError",
"as",
"exc",
":",
"log",
".",
"exception",
"... | 21.428571 | 22.428571 |
def reorder_translation_formset_by_language_code(inline_admin_form):
"""
Shuffle the forms in the formset of multilingual model in the
order of their language_ids.
"""
lang_to_form = dict([(form.form.initial['language_id'], form)
for form in inline_admin_form])
return [l... | [
"def",
"reorder_translation_formset_by_language_code",
"(",
"inline_admin_form",
")",
":",
"lang_to_form",
"=",
"dict",
"(",
"[",
"(",
"form",
".",
"form",
".",
"initial",
"[",
"'language_id'",
"]",
",",
"form",
")",
"for",
"form",
"in",
"inline_admin_form",
"]"... | 43.666667 | 14.333333 |
def pertibate(self, pertibate_columns=None, filter_func=None,
max_size=1000):
"""
:param pertibate_columns: list of str fo columns to pertibate see DOE
:param filter_func: func that takes a SeabornRow and return
True if this row should be exist
... | [
"def",
"pertibate",
"(",
"self",
",",
"pertibate_columns",
"=",
"None",
",",
"filter_func",
"=",
"None",
",",
"max_size",
"=",
"1000",
")",
":",
"pertibate_columns",
"=",
"pertibate_columns",
"or",
"self",
".",
"columns",
"for",
"c",
"in",
"pertibate_columns",... | 45.676471 | 21.382353 |
def hasDependency(self, name, target=None, test_dependencies=False):
''' Check if this module has any dependencies with the specified name
in its dependencies list, or in target dependencies for the
specified target
'''
if name in self.description.get('dependencies', {}).... | [
"def",
"hasDependency",
"(",
"self",
",",
"name",
",",
"target",
"=",
"None",
",",
"test_dependencies",
"=",
"False",
")",
":",
"if",
"name",
"in",
"self",
".",
"description",
".",
"get",
"(",
"'dependencies'",
",",
"{",
"}",
")",
".",
"keys",
"(",
"... | 48.692308 | 27.461538 |
def make_constants(builtin_only=False, stoplist=None, verbose=None):
"""Return a decorator for optimizing global references.
Replaces global references with their currently defined values.
If not defined, the dynamic (runtime) global lookup is left undisturbed.
If builtin_only is True, then only builti... | [
"def",
"make_constants",
"(",
"builtin_only",
"=",
"False",
",",
"stoplist",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"stoplist",
"is",
"None",
":",
"stoplist",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"builtin_only",
",",
"type",
"(",
... | 44.409091 | 26.409091 |
def create_resource(self, parent_id=""):
"""Create the specified resource.
Args:
parent_id (str): The resource ID of the parent resource in API Gateway
"""
resource_name = self.trigger_settings.get('resource', '')
resource_name = resource_name.replace('/', '')
... | [
"def",
"create_resource",
"(",
"self",
",",
"parent_id",
"=",
"\"\"",
")",
":",
"resource_name",
"=",
"self",
".",
"trigger_settings",
".",
"get",
"(",
"'resource'",
",",
"''",
")",
"resource_name",
"=",
"resource_name",
".",
"replace",
"(",
"'/'",
",",
"'... | 46.9375 | 21.4375 |
def token_is_valid(self,):
"""Check the validity of the token :3600s
"""
elapsed_time = time.time() - self.token_time
logger.debug("ELAPSED TIME : {0}".format(elapsed_time))
if elapsed_time > 3540: # 1 minute before it expires
logger.debug("TOKEN HAS EXPIRED")
... | [
"def",
"token_is_valid",
"(",
"self",
",",
")",
":",
"elapsed_time",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"token_time",
"logger",
".",
"debug",
"(",
"\"ELAPSED TIME : {0}\"",
".",
"format",
"(",
"elapsed_time",
")",
")",
"if",
"elapsed_tim... | 35.727273 | 14.090909 |
def create_properties(self): # pylint: disable=no-self-use
"""
Format the properties with which to instantiate the connection.
This acts like a user agent over HTTP.
:rtype: dict
"""
properties = {}
properties["product"] = "eventhub.python"
properties["v... | [
"def",
"create_properties",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"properties",
"=",
"{",
"}",
"properties",
"[",
"\"product\"",
"]",
"=",
"\"eventhub.python\"",
"properties",
"[",
"\"version\"",
"]",
"=",
"__version__",
"properties",
"[",
"\"frame... | 37.307692 | 15.923077 |
def main(command_line=True, **kwargs):
"""
NAME
jr6_txt_magic.py
DESCRIPTION
converts JR6 .txt format files to magic_measurements format files
SYNTAX
jr6_txt_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify i... | [
"def",
"main",
"(",
"command_line",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# initialize some stuff",
"noave",
"=",
"0",
"volume",
"=",
"2.5",
"*",
"1e-6",
"# default volume is 2.5 cm^3 (2.5 * 1e-6 meters^3)",
"inst",
"=",
"\"\"",
"samp_con",
",",
"Z",
... | 36.196013 | 18.096346 |
def apply_config_file(
command_function: Union[click.Command, click.Group],
cli_params: Dict[str, Any],
ctx,
config_file_option_name='config_file',
):
""" Applies all options set in the config file to `cli_params` """
paramname_to_param = {param.name: param for param in command_f... | [
"def",
"apply_config_file",
"(",
"command_function",
":",
"Union",
"[",
"click",
".",
"Command",
",",
"click",
".",
"Group",
"]",
",",
"cli_params",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"ctx",
",",
"config_file_option_name",
"=",
"'config_file'",
... | 41.380282 | 23.521127 |
def set_pre_handler(self, handler):
'''set pre handler'''
with self._lock:
if self._handler_ctx is not None:
return self._handler_ctx.set_pre_handler(handler)
return RET_ERROR | [
"def",
"set_pre_handler",
"(",
"self",
",",
"handler",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_handler_ctx",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_handler_ctx",
".",
"set_pre_handler",
"(",
"handler",
")",
"return",
... | 37 | 13 |
def _parse_phone_and_hash(self, phone, phone_hash):
"""
Helper method to both parse and validate phone and its hash.
"""
phone = utils.parse_phone(phone) or self._phone
if not phone:
raise ValueError(
'Please make sure to call send_code_request first.'... | [
"def",
"_parse_phone_and_hash",
"(",
"self",
",",
"phone",
",",
"phone_hash",
")",
":",
"phone",
"=",
"utils",
".",
"parse_phone",
"(",
"phone",
")",
"or",
"self",
".",
"_phone",
"if",
"not",
"phone",
":",
"raise",
"ValueError",
"(",
"'Please make sure to ca... | 35.466667 | 20.533333 |
def get_activity_search_session(self):
"""Gets the OsidSession associated with the activity search
service.
return: (osid.learning.ActivitySearchSession) - a
ActivitySearchSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - suppor... | [
"def",
"get_activity_search_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_activity_search",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"raise",
"Operati... | 36.304348 | 16.304348 |
def _generate_serializable_funcs(self, data_type_name):
"""Emits the two struct/union functions that implement the Serializable protocol."""
with self.block_func(
func='serialize',
args=fmt_func_args_declaration([('instance', 'id')]),
return_type='nullable... | [
"def",
"_generate_serializable_funcs",
"(",
"self",
",",
"data_type_name",
")",
":",
"with",
"self",
".",
"block_func",
"(",
"func",
"=",
"'serialize'",
",",
"args",
"=",
"fmt_func_args_declaration",
"(",
"[",
"(",
"'instance'",
",",
"'id'",
")",
"]",
")",
"... | 44.92 | 15.16 |
def get_site_dos(self, site):
"""
Get the total Dos for a site (all orbitals).
Args:
site: Site in Structure associated with CompleteDos.
Returns:
Dos containing summed orbital densities for site.
"""
site_dos = functools.reduce(add_densities, se... | [
"def",
"get_site_dos",
"(",
"self",
",",
"site",
")",
":",
"site_dos",
"=",
"functools",
".",
"reduce",
"(",
"add_densities",
",",
"self",
".",
"pdos",
"[",
"site",
"]",
".",
"values",
"(",
")",
")",
"return",
"Dos",
"(",
"self",
".",
"efermi",
",",
... | 32.416667 | 20.916667 |
def add_choice(self, text, name='', identifier=None):
"""stub"""
if not utilities.is_string(text):
raise InvalidArgument('text is not a string')
choice_display_text = self._choice_text_metadata['default_string_values'][0]
choice_display_text['text'] = text
if identifi... | [
"def",
"add_choice",
"(",
"self",
",",
"text",
",",
"name",
"=",
"''",
",",
"identifier",
"=",
"None",
")",
":",
"if",
"not",
"utilities",
".",
"is_string",
"(",
"text",
")",
":",
"raise",
"InvalidArgument",
"(",
"'text is not a string'",
")",
"choice_disp... | 37.133333 | 15.133333 |
def poll(self, authzr):
"""
Update an authorization from the server (usually to check its status).
"""
action = LOG_ACME_POLL_AUTHORIZATION(authorization=authzr)
with action.context():
return (
DeferredContext(self._client.get(authzr.uri))
... | [
"def",
"poll",
"(",
"self",
",",
"authzr",
")",
":",
"action",
"=",
"LOG_ACME_POLL_AUTHORIZATION",
"(",
"authorization",
"=",
"authzr",
")",
"with",
"action",
".",
"context",
"(",
")",
":",
"return",
"(",
"DeferredContext",
"(",
"self",
".",
"_client",
"."... | 44.96 | 17.36 |
def get_colors(n):
"""get colors for freqpoly graph"""
cb_palette = ["#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00",
"#CC79A7","#001F3F", "#0074D9", "#7FDBFF", "#39CCCC", "#3D9970", "#2ECC40",
"#01FF70", "#FFDC00", "#FF851B", "#FF4136", "#F0... | [
"def",
"get_colors",
"(",
"n",
")",
":",
"cb_palette",
"=",
"[",
"\"#E69F00\"",
",",
"\"#56B4E9\"",
",",
"\"#009E73\"",
",",
"\"#F0E442\"",
",",
"\"#0072B2\"",
",",
"\"#D55E00\"",
",",
"\"#CC79A7\"",
",",
"\"#001F3F\"",
",",
"\"#0074D9\"",
",",
"\"#7FDBFF\"",
... | 42.692308 | 23.846154 |
def show_pages(parser, token):
"""Show page links.
Usage:
.. code-block:: html+django
{% show_pages %}
It is just a shortcut for:
.. code-block:: html+django
{% get_pages %}
{{ pages.get_rendered }}
You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *set... | [
"def",
"show_pages",
"(",
"parser",
",",
"token",
")",
":",
"# Validate args.",
"if",
"len",
"(",
"token",
".",
"contents",
".",
"split",
"(",
")",
")",
"!=",
"1",
":",
"msg",
"=",
"'%r tag takes no arguments'",
"%",
"token",
".",
"contents",
".",
"split... | 27.258065 | 22.612903 |
def delete_hc(kwargs=None, call=None):
'''
Permanently delete a health check.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_hc gce name=hc
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_hc function must be called with -f or --function.'
... | [
"def",
"delete_hc",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The delete_hc function must be called with -f or --function.'",
")",
"if",
"not",
"kwargs",
"or",
"'na... | 23.719298 | 20.350877 |
def print_debug(self, msg):
"""Log some debugging information to the console"""
assert isinstance(msg, bytes)
state = STATE_NAMES[self.state].encode()
console_output(b'[dbg] ' + self.display_name.encode() + b'[' + state +
b']: ' + msg + b'\n') | [
"def",
"print_debug",
"(",
"self",
",",
"msg",
")",
":",
"assert",
"isinstance",
"(",
"msg",
",",
"bytes",
")",
"state",
"=",
"STATE_NAMES",
"[",
"self",
".",
"state",
"]",
".",
"encode",
"(",
")",
"console_output",
"(",
"b'[dbg] '",
"+",
"self",
".",
... | 48.833333 | 11 |
def recent(self):
"""
Retrieve a selection of conversations with the most recent activity, and store them in the cache.
Each conversation is only retrieved once, so subsequent calls will retrieve older conversations.
Returns:
:class:`SkypeChat` list: collection of recent co... | [
"def",
"recent",
"(",
"self",
")",
":",
"url",
"=",
"\"{0}/users/ME/conversations\"",
".",
"format",
"(",
"self",
".",
"skype",
".",
"conn",
".",
"msgsHost",
")",
"params",
"=",
"{",
"\"startTime\"",
":",
"0",
",",
"\"view\"",
":",
"\"msnp24Equivalent\"",
... | 49.36 | 27.2 |
def _average(self):
"""
Returns one average color for the colors in the list.
"""
r, g, b, a = 0, 0, 0, 0
for clr in self:
r += clr.r
g += clr.g
b += clr.b
a += clr.alpha
r /= len(self)
g /= len(self)
b /= l... | [
"def",
"_average",
"(",
"self",
")",
":",
"r",
",",
"g",
",",
"b",
",",
"a",
"=",
"0",
",",
"0",
",",
"0",
",",
"0",
"for",
"clr",
"in",
"self",
":",
"r",
"+=",
"clr",
".",
"r",
"g",
"+=",
"clr",
".",
"g",
"b",
"+=",
"clr",
".",
"b",
... | 22.411765 | 17.117647 |
def _check_graphviz_available(output_format):
"""check if we need graphviz for different output format"""
try:
subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
print(
"The output format '%s' is currently not available.\n"
... | [
"def",
"_check_graphviz_available",
"(",
"output_format",
")",
":",
"try",
":",
"subprocess",
".",
"call",
"(",
"[",
"\"dot\"",
",",
"\"-V\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"except",... | 40.818182 | 22.363636 |
def apply_transforms(self, data, rot_deg):
"""Apply transformations to the given data.
These include flip/swap X/Y, invert Y, and rotation.
Parameters
----------
data : ndarray
Data to be transformed.
rot_deg : float
Rotate the data by the given ... | [
"def",
"apply_transforms",
"(",
"self",
",",
"data",
",",
"rot_deg",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"wd",
",",
"ht",
"=",
"self",
".",
"get_dims",
"(",
"data",
")",
"xoff",
",",
"yoff",
"=",
"self",
".",
"_org_xoff",
",... | 31.780822 | 19.890411 |
def load_sites(*basin_ids):
"""
Load metadata for all sites in given basin codes.
"""
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import ge... | [
"def",
"load_sites",
"(",
"*",
"basin_ids",
")",
":",
"# Resolve basin ids to HUC8s if needed",
"basins",
"=",
"[",
"]",
"for",
"basin",
"in",
"basin_ids",
":",
"if",
"basin",
".",
"isdigit",
"(",
")",
"and",
"len",
"(",
"basin",
")",
"==",
"8",
":",
"ba... | 30.747573 | 16.184466 |
def connect(remote_host):
""" Connect to remote host and show our status """
if remote_host in ('master', 'server'):
remote_host = nago.settings.get_option('server')
node = nago.core.get_node(remote_host)
if not node:
try:
address = socket.gethostbyname(remote_host)
... | [
"def",
"connect",
"(",
"remote_host",
")",
":",
"if",
"remote_host",
"in",
"(",
"'master'",
",",
"'server'",
")",
":",
"remote_host",
"=",
"nago",
".",
"settings",
".",
"get_option",
"(",
"'server'",
")",
"node",
"=",
"nago",
".",
"core",
".",
"get_node"... | 43.318182 | 15.681818 |
def make_simulation(tax_benefit_system, nb_persons, nb_groups, **kwargs):
"""
Generate a simulation containing nb_persons persons spread in nb_groups groups.
Example:
>>> from openfisca_core.scripts.simulation_generator import make_simulation
>>> from openfisca_france import Countr... | [
"def",
"make_simulation",
"(",
"tax_benefit_system",
",",
"nb_persons",
",",
"nb_groups",
",",
"*",
"*",
"kwargs",
")",
":",
"simulation",
"=",
"Simulation",
"(",
"tax_benefit_system",
"=",
"tax_benefit_system",
",",
"*",
"*",
"kwargs",
")",
"simulation",
".",
... | 45.736842 | 27.631579 |
def status(self):
"""Development status."""
return {self._acronym_status(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_status)} | [
"def",
"status",
"(",
"self",
")",
":",
"return",
"{",
"self",
".",
"_acronym_status",
"(",
"l",
")",
":",
"l",
"for",
"l",
"in",
"self",
".",
"resp_text",
".",
"split",
"(",
"'\\n'",
")",
"if",
"l",
".",
"startswith",
"(",
"self",
".",
"prefix_sta... | 45 | 18.25 |
def _prune_beam(states: List[State],
beam_size: int,
sort_states: bool = False) -> List[State]:
"""
This method can be used to prune the set of unfinished states on a beam or finished states
at the end of search. In the former case, the states need not be ... | [
"def",
"_prune_beam",
"(",
"states",
":",
"List",
"[",
"State",
"]",
",",
"beam_size",
":",
"int",
",",
"sort_states",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"State",
"]",
":",
"states_by_batch_index",
":",
"Dict",
"[",
"int",
",",
"List",
... | 55.56 | 22.84 |
def p_service(self, p):
'''service : SERVICE IDENTIFIER '{' function_seq '}' annotations
| SERVICE IDENTIFIER EXTENDS IDENTIFIER \
'{' function_seq '}' annotations
'''
if len(p) == 7:
p[0] = ast.Service(
name=p[2],
... | [
"def",
"p_service",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"7",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Service",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"functions",
"=",
"p",
"[",
"4",
"]",
",",
"parent... | 31.090909 | 16.909091 |
def visit_With(self, node):
"""Deal with the special with insert_grad_of(x) statement."""
if ast_.is_insert_grad_of_statement(node):
primal = []
adjoint = node.body
if isinstance(adjoint[0], gast.With):
_, adjoint = self.visit(adjoint[0])
node.body[0] = comments.add_comment(node.... | [
"def",
"visit_With",
"(",
"self",
",",
"node",
")",
":",
"if",
"ast_",
".",
"is_insert_grad_of_statement",
"(",
"node",
")",
":",
"primal",
"=",
"[",
"]",
"adjoint",
"=",
"node",
".",
"body",
"if",
"isinstance",
"(",
"adjoint",
"[",
"0",
"]",
",",
"g... | 40.1 | 15.55 |
def _Close(self):
"""Closes the file-like object."""
if self._zip_ext_file:
self._zip_ext_file.close()
self._zip_ext_file = None
self._zip_file = None
self._zip_info = None
self._file_system.Close()
self._file_system = None | [
"def",
"_Close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_zip_ext_file",
":",
"self",
".",
"_zip_ext_file",
".",
"close",
"(",
")",
"self",
".",
"_zip_ext_file",
"=",
"None",
"self",
".",
"_zip_file",
"=",
"None",
"self",
".",
"_zip_info",
"=",
"Non... | 22.818182 | 17 |
def delay(self, secondsLater):
"""Reschedule this call for a later time
@type secondsLater: C{float}
@param secondsLater: The number of seconds after the originally
scheduled time for which to reschedule this call.
@raise AlreadyCancelled: Raised if this call has been cancelled... | [
"def",
"delay",
"(",
"self",
",",
"secondsLater",
")",
":",
"if",
"self",
".",
"cancelled",
":",
"raise",
"error",
".",
"AlreadyCancelled",
"elif",
"self",
".",
"called",
":",
"raise",
"error",
".",
"AlreadyCalled",
"else",
":",
"self",
".",
"delayed_time"... | 36.421053 | 14.789474 |
def get_sql(self, debug=False, use_cache=True):
"""
Generates the sql for this query and returns the sql as a string.
:type debug: bool
:param debug: If True, the sql will be returned in a format that is easier to read and debug.
Defaults to False
:type use_cache: b... | [
"def",
"get_sql",
"(",
"self",
",",
"debug",
"=",
"False",
",",
"use_cache",
"=",
"True",
")",
":",
"# TODO: enable caching",
"# if self.sql and use_cache and not debug:",
"# return self.sql",
"# auto alias any naming collisions",
"self",
".",
"check_name_collisions",
"... | 32.707317 | 19.634146 |
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# ... | [
"def",
"_run_prospector",
"(",
"filename",
",",
"stamp_file_name",
",",
"disabled_linters",
",",
"show_lint_files",
")",
":",
"linter_tools",
"=",
"[",
"\"pep257\"",
",",
"\"pep8\"",
",",
"\"pyflakes\"",
"]",
"if",
"can_run_pylint",
"(",
")",
":",
"linter_tools",
... | 32.348837 | 17.581395 |
def get_path_name(self):
"""Gets path and name of song
:return: Name of path, name of file (or folder)
"""
path = fix_raw_path(os.path.dirname(os.path.abspath(self.path)))
name = os.path.basename(self.path)
return path, name | [
"def",
"get_path_name",
"(",
"self",
")",
":",
"path",
"=",
"fix_raw_path",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"path",
")",
")",
")",
"name",
"=",
"os",
".",
"path",
".",
"basename",
... | 33.25 | 15 |
def firstElementChild(self) -> Optional[AbstractNode]:
"""First Element child node.
If this node has no element child, return None.
"""
for child in self.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
return child
return None | [
"def",
"firstElementChild",
"(",
"self",
")",
"->",
"Optional",
"[",
"AbstractNode",
"]",
":",
"for",
"child",
"in",
"self",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"==",
"Node",
".",
"ELEMENT_NODE",
":",
"return",
"child",
"return",
"None"... | 32.333333 | 12.888889 |
def data_class(self):
"""
creates a Data() instance of lenstronomy based on knowledge of the observation
:return: instance of Data() class
"""
x_grid, y_grid, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix = util.make_grid_with_coordtransform(
... | [
"def",
"data_class",
"(",
"self",
")",
":",
"x_grid",
",",
"y_grid",
",",
"ra_at_xy_0",
",",
"dec_at_xy_0",
",",
"x_at_radec_0",
",",
"y_at_radec_0",
",",
"Mpix2coord",
",",
"Mcoord2pix",
"=",
"util",
".",
"make_grid_with_coordtransform",
"(",
"numPix",
"=",
"... | 54 | 29 |
def mount(name, device, mkmnt=False, fstype='', opts='defaults', user=None, util='mount'):
'''
Mount a device
CLI Example:
.. code-block:: bash
salt '*' mount.mount /mnt/foo /dev/sdz1 True
'''
if util != 'mount':
# This functionality used to live in img.mount_image
if ... | [
"def",
"mount",
"(",
"name",
",",
"device",
",",
"mkmnt",
"=",
"False",
",",
"fstype",
"=",
"''",
",",
"opts",
"=",
"'defaults'",
",",
"user",
"=",
"None",
",",
"util",
"=",
"'mount'",
")",
":",
"if",
"util",
"!=",
"'mount'",
":",
"# This functionali... | 31.833333 | 21.12963 |
def _get_emacs_vars(self, text):
"""Return a dictionary of emacs-style local variables.
Parsing is done loosely according to this spec (and according to
some in-practice deviations from this):
http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specif... | [
"def",
"_get_emacs_vars",
"(",
"self",
",",
"text",
")",
":",
"emacs_vars",
"=",
"{",
"}",
"SIZE",
"=",
"pow",
"(",
"2",
",",
"13",
")",
"# 8kB",
"# Search near the start for a '-*-'-style one-liner of variables.",
"head",
"=",
"text",
"[",
":",
"SIZE",
"]",
... | 48.83 | 20.06 |
def joint_distances(self):
'''Get the current joint separations for the skeleton.
Returns
-------
distances : list of float
A list expressing the distance between the two joint anchor points,
for each joint in the skeleton. These quantities describe how
... | [
"def",
"joint_distances",
"(",
"self",
")",
":",
"return",
"[",
"(",
"(",
"np",
".",
"array",
"(",
"j",
".",
"anchor",
")",
"-",
"j",
".",
"anchor2",
")",
"**",
"2",
")",
".",
"sum",
"(",
")",
"for",
"j",
"in",
"self",
".",
"joints",
"]"
] | 45.5 | 28.833333 |
def add_plugin(plugin, directory=None):
"""Adds the specified plugin. This returns False if it was already added."""
repo = require_repo(directory)
plugins = get_value(repo, 'plugins', expect_type=dict)
if plugin in plugins:
return False
plugins[plugin] = {}
set_value(repo, 'plugins', p... | [
"def",
"add_plugin",
"(",
"plugin",
",",
"directory",
"=",
"None",
")",
":",
"repo",
"=",
"require_repo",
"(",
"directory",
")",
"plugins",
"=",
"get_value",
"(",
"repo",
",",
"'plugins'",
",",
"expect_type",
"=",
"dict",
")",
"if",
"plugin",
"in",
"plug... | 33.4 | 14.2 |
async def put(self, request, resource=None, **kwargs):
"""Update a resource.
---
parameters:
- name: resource
in: path
type: string
"""
if resource is None:
raise RESTNotFound(reason='Resource not found')
return await ... | [
"async",
"def",
"put",
"(",
"self",
",",
"request",
",",
"resource",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"resource",
"is",
"None",
":",
"raise",
"RESTNotFound",
"(",
"reason",
"=",
"'Resource not found'",
")",
"return",
"await",
"self",... | 27.307692 | 19 |
def _mark_target(type, item):
"""
Wrap given item as input or output target that should be added to task.
Wrapper object will be handled specially in \
:paramref:`create_cmd_task.parts`.
:param type: Target type.
Allowed values:
- 'input'
- 'output'
:param ite... | [
"def",
"_mark_target",
"(",
"type",
",",
"item",
")",
":",
"# If given type is not valid",
"if",
"type",
"not",
"in",
"(",
"'input'",
",",
"'output'",
")",
":",
"# Get error message",
"msg",
"=",
"'Error (7D74X): Type is not valid: {0}'",
".",
"format",
"(",
"type... | 24.716667 | 19.716667 |
def _setup_dmtf_schema(self):
"""
Install the DMTF CIM schema from the DMTF web site if it is not already
installed. This includes downloading the DMTF CIM schema zip file from
the DMTF web site and expanding that file into a subdirectory defined
by `schema_mof_dir`.
Onc... | [
"def",
"_setup_dmtf_schema",
"(",
"self",
")",
":",
"def",
"print_verbose",
"(",
"msg",
")",
":",
"\"\"\"\n Inner method prints msg if self.verbose is `True`.\n \"\"\"",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"msg",
")",
"if",
"not",
"o... | 40.55814 | 20.651163 |
def deck_issue_mode(proto: DeckSpawnProto) -> Iterable[str]:
'''interpret issue mode bitfeg'''
if proto.issue_mode == 0:
yield "NONE"
return
for mode, value in proto.MODE.items():
if value > proto.issue_mode:
continue
if value & proto.issue_mode:
yie... | [
"def",
"deck_issue_mode",
"(",
"proto",
":",
"DeckSpawnProto",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"if",
"proto",
".",
"issue_mode",
"==",
"0",
":",
"yield",
"\"NONE\"",
"return",
"for",
"mode",
",",
"value",
"in",
"proto",
".",
"MODE",
".",
"... | 26.333333 | 17.333333 |
def _get_page_with_optional_heading(self, page_file_path: str) -> str or Dict:
'''Get the content of first heading of source Markdown file, if the file
contains any headings. Return a data element of ``pages`` section
of ``mkdocs.yml`` file.
:param page_file_path: path to source Markdow... | [
"def",
"_get_page_with_optional_heading",
"(",
"self",
",",
"page_file_path",
":",
"str",
")",
"->",
"str",
"or",
"Dict",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"f'Looking for the first heading in {page_file_path}'",
")",
"if",
"page_file_path",
".",
"endswi... | 41.466667 | 28.866667 |
def to_basestring(value):
"""Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user su... | [
"def",
"to_basestring",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_BASESTRING_TYPES",
")",
":",
"return",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bytes_type",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected bytes, unicode... | 42.625 | 19.5625 |
def _as_reference_point(self) -> np.ndarray:
""" Return classification information as reference point
"""
ref_val = []
for fn, f in self._classification.items():
if f[0] == "<":
ref_val.append(self._method.problem.ideal[fn])
elif f[0] == "<>":
... | [
"def",
"_as_reference_point",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"ref_val",
"=",
"[",
"]",
"for",
"fn",
",",
"f",
"in",
"self",
".",
"_classification",
".",
"items",
"(",
")",
":",
"if",
"f",
"[",
"0",
"]",
"==",
"\"<\"",
":",
"re... | 35 | 13.538462 |
def generate_help_text(self):
""" generates the help text based on commands typed """
param_descrip = example = ""
self.description_docs = u''
rows, _ = get_window_dim()
rows = int(rows)
param_args = self.completer.leftover_args
last_word = self.completer.unfini... | [
"def",
"generate_help_text",
"(",
"self",
")",
":",
"param_descrip",
"=",
"example",
"=",
"\"\"",
"self",
".",
"description_docs",
"=",
"u''",
"rows",
",",
"_",
"=",
"get_window_dim",
"(",
")",
"rows",
"=",
"int",
"(",
"rows",
")",
"param_args",
"=",
"se... | 44.025 | 22.75 |
def verify_jwt(jwt,
pub_key=None,
allowed_algs=None,
iat_skew=timedelta(),
checks_optional=False,
ignore_not_implemented=False):
"""
Verify a JSON Web Token.
:param jwt: The JSON Web Token to verify.
:type jwt: str or unicode
... | [
"def",
"verify_jwt",
"(",
"jwt",
",",
"pub_key",
"=",
"None",
",",
"allowed_algs",
"=",
"None",
",",
"iat_skew",
"=",
"timedelta",
"(",
")",
",",
"checks_optional",
"=",
"False",
",",
"ignore_not_implemented",
"=",
"False",
")",
":",
"if",
"allowed_algs",
... | 39.396226 | 25.981132 |
def container_search(self, query, across_collections=False):
'''search for a specific container. If across collections is False,
the query is parsed as a full container name and a specific container
is returned. If across_collections is True, the container is searched
for across collections. If across c... | [
"def",
"container_search",
"(",
"self",
",",
"query",
",",
"across_collections",
"=",
"False",
")",
":",
"results",
"=",
"self",
".",
"_search_all",
"(",
"quiet",
"=",
"True",
")",
"matches",
"=",
"[",
"]",
"for",
"result",
"in",
"results",
":",
"# This ... | 29.791667 | 23.541667 |
def _base_type(self):
"""Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears where a subtype is present.
"""
... | [
"def",
"_base_type",
"(",
"self",
")",
":",
"type_class",
"=",
"self",
".",
"_dimension_dict",
"[",
"\"type\"",
"]",
"[",
"\"class\"",
"]",
"if",
"type_class",
"==",
"\"categorical\"",
":",
"return",
"\"categorical\"",
"if",
"type_class",
"==",
"\"enum\"",
":"... | 47.857143 | 18.785714 |
def reverse_iter(self, start=None, stop=None, count=2000):
""" -> yields items of the list in reverse """
cursor = '0'
count = 1000
start = start if start is not None else (-1 * count)
stop = stop if stop is not None else -1
_loads = self._loads
while cursor:
... | [
"def",
"reverse_iter",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"count",
"=",
"2000",
")",
":",
"cursor",
"=",
"'0'",
"count",
"=",
"1000",
"start",
"=",
"start",
"if",
"start",
"is",
"not",
"None",
"else",
"(",
"-",
... | 38.769231 | 14.461538 |
def read(self, size):
"""
Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection.
"""
data = self.serial_h.read(size)
self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binasci... | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"data",
"=",
"self",
".",
"serial_h",
".",
"read",
"(",
"size",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'read data, length: '",
"+",
"str",
"(",
"len",
"(",
"data",
")",
")",
"+",
"' data: ... | 33.692308 | 20.923077 |
def contrast_rms(data, *kwargs):
""" Compute RMS contrast norm of an image
"""
av = np.average(data, *kwargs)
mal = 1 / (data.shape[0] * data.shape[1])
return np.sqrt(mal * np.sum(np.square(data - av))) | [
"def",
"contrast_rms",
"(",
"data",
",",
"*",
"kwargs",
")",
":",
"av",
"=",
"np",
".",
"average",
"(",
"data",
",",
"*",
"kwargs",
")",
"mal",
"=",
"1",
"/",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"*",
"data",
".",
"shape",
"[",
"1",
"]",... | 36.166667 | 5.5 |
def exist(self, table: str, libref: str ="") -> bool:
"""
table - the name of the SAS Data Set
libref - the libref for the Data Set, defaults to WORK, or USER if assigned
Returns True it the Data Set exists and False if it does not
"""
code = "data _null_; e = exist('"
if le... | [
"def",
"exist",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"\"\"",
")",
"->",
"bool",
":",
"code",
"=",
"\"data _null_; e = exist('\"",
"if",
"len",
"(",
"libref",
")",
":",
"code",
"+=",
"libref",
"+",
"\".\"",
"code",
"+... | 30.25 | 17.166667 |
def load_graph_xml(xml, filename, load_all=False):
'''load a graph from one xml string'''
ret = []
try:
root = objectify.fromstring(xml)
except Exception:
return []
if root.tag != 'graphs':
return []
if not hasattr(root, 'graph'):
return []
for g in root.graph... | [
"def",
"load_graph_xml",
"(",
"xml",
",",
"filename",
",",
"load_all",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"try",
":",
"root",
"=",
"objectify",
".",
"fromstring",
"(",
"xml",
")",
"except",
"Exception",
":",
"return",
"[",
"]",
"if",
"root... | 31.791667 | 19.041667 |
def etherscan_verify_contract(
chain_id: int,
apikey: str,
source_module: DeploymentModule,
contract_name: str,
):
""" Calls Etherscan API for verifying the Solidity source of a contract.
Args:
chain_id: EIP-155 chain id of the Ethereum chain
apikey: key for call... | [
"def",
"etherscan_verify_contract",
"(",
"chain_id",
":",
"int",
",",
"apikey",
":",
"str",
",",
"source_module",
":",
"DeploymentModule",
",",
"contract_name",
":",
"str",
",",
")",
":",
"etherscan_api",
"=",
"api_of_chain_id",
"[",
"chain_id",
"]",
"deployment... | 37.513889 | 19.236111 |
def get_signing_key(self):
"""
Download a local copy of repo signing key for installation
"""
"""
Download a local copy of repo signing key key metadata.
Fixes #17 Scan Keys no available in all GPG versions.
"""
tmp_key_path = "/tmp/{0}".format(self.repo_... | [
"def",
"get_signing_key",
"(",
"self",
")",
":",
"\"\"\"\n Download a local copy of repo signing key key metadata.\n Fixes #17 Scan Keys no available in all GPG versions.\n \"\"\"",
"tmp_key_path",
"=",
"\"/tmp/{0}\"",
".",
"format",
"(",
"self",
".",
"repo_signing... | 36.692308 | 18.333333 |
def _file_list(self, folder):
'''returns a list of file names in an sosreport directory'''
rtn = []
walk = self._walk_report(folder)
for key,val in walk.items():
for v in val:
x=os.path.join(key,v)
rtn.append(x)
self.file_count = len(r... | [
"def",
"_file_list",
"(",
"self",
",",
"folder",
")",
":",
"rtn",
"=",
"[",
"]",
"walk",
"=",
"self",
".",
"_walk_report",
"(",
"folder",
")",
"for",
"key",
",",
"val",
"in",
"walk",
".",
"items",
"(",
")",
":",
"for",
"v",
"in",
"val",
":",
"x... | 37.454545 | 21.090909 |
def Input_synthesizePinchGesture(self, x, y, scaleFactor, **kwargs):
"""
Function path: Input.synthesizePinchGesture
Domain: Input
Method name: synthesizePinchGesture
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'x' (type: number) -> X coordinate of the... | [
"def",
"Input_synthesizePinchGesture",
"(",
"self",
",",
"x",
",",
"y",
",",
"scaleFactor",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"x",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"Argument 'x' must be of type '['float', 'int']'. R... | 49.4 | 29.1 |
def create_post_execute(task_params, parameter_map):
"""
Builds the code block for the GPTool Execute method after the job is
submitted based on the input task_params.
:param task_params: A list of task parameters from the task info structure.
:return: A string representing the code block to the GP... | [
"def",
"create_post_execute",
"(",
"task_params",
",",
"parameter_map",
")",
":",
"gp_params",
"=",
"[",
"]",
"for",
"task_param",
"in",
"task_params",
":",
"if",
"task_param",
"[",
"'direction'",
"]",
".",
"upper",
"(",
")",
"==",
"'INPUT'",
":",
"continue"... | 33.391304 | 21.043478 |
def dispatch(self, inp):
"""Send the inputs to the experts.
Args:
inp: a `Tensor` of shape "[batch, length, depth]`
Returns:
a tensor with shape [batch, num_experts, expert_capacity, depth]
"""
inp = tf.reshape(inp, [self._batch * self._length, -1])
# [batch, num_experts, expert_cap... | [
"def",
"dispatch",
"(",
"self",
",",
"inp",
")",
":",
"inp",
"=",
"tf",
".",
"reshape",
"(",
"inp",
",",
"[",
"self",
".",
"_batch",
"*",
"self",
".",
"_length",
",",
"-",
"1",
"]",
")",
"# [batch, num_experts, expert_capacity, depth]",
"ret",
"=",
"tf... | 31.833333 | 18.25 |
def evalop(op,left,right):
"this takes evaluated left and right (i.e. values not expressions)"
if op in ('=','!=','>','<'): return threevl.ThreeVL.compare(op,left,right)
elif op in ('+','-','*','/'): # todo: does arithmetic require threevl?
if op=='/': raise NotImplementedError('todo: spec about int/float div... | [
"def",
"evalop",
"(",
"op",
",",
"left",
",",
"right",
")",
":",
"if",
"op",
"in",
"(",
"'='",
",",
"'!='",
",",
"'>'",
",",
"'<'",
")",
":",
"return",
"threevl",
".",
"ThreeVL",
".",
"compare",
"(",
"op",
",",
"left",
",",
"right",
")",
"elif"... | 64.545455 | 37 |
def dataCollector( self ):
"""
Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |fro... | [
"def",
"dataCollector",
"(",
"self",
")",
":",
"func",
"=",
"None",
"if",
"(",
"self",
".",
"_dataCollectorRef",
")",
":",
"func",
"=",
"self",
".",
"_dataCollectorRef",
"(",
")",
"if",
"(",
"not",
"func",
")",
":",
"self",
".",
"_dataCollectorRef",
"=... | 39.181818 | 19.121212 |
def get_atom_sequence_to_rosetta_map(self):
'''Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mapping[c].map.get(... | [
"def",
"get_atom_sequence_to_rosetta_map",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"rosetta_to_atom_sequence_maps",
"and",
"self",
".",
"rosetta_sequences",
":",
"raise",
"Exception",
"(",
"'The PDB to Rosetta mapping has not been determined. Please call construct_pdb_... | 60.956522 | 36.26087 |
def mask(key, original):
"""
Mask an octet string using the given masking key.
The following masking algorithm is used, as defined in RFC 6455:
for each octet:
j = i MOD 4
transformed-octet-i = original-octet-i XOR masking-key-octet-j
"""
if len(key) != 4:
raise ValueErr... | [
"def",
"mask",
"(",
"key",
",",
"original",
")",
":",
"if",
"len",
"(",
"key",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"'invalid masking key \"%s\"'",
"%",
"key",
")",
"key",
"=",
"map",
"(",
"ord",
",",
"key",
")",
"masked",
"=",
"bytearray... | 25.368421 | 20.526316 |
def init():
"""
Creates the project infrastructure assuming the current directory is the project root.
Typically used as a command-line entry point called by `pygoose init`.
"""
project = Project(os.path.abspath(os.getcwd()))
paths_to_create = [
project.data_... | [
"def",
"init",
"(",
")",
":",
"project",
"=",
"Project",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"paths_to_create",
"=",
"[",
"project",
".",
"data_dir",
",",
"project",
".",
"notebooks_dir",
",",
"projec... | 32.25 | 16.15 |
def subsample_X(X, labels, num_samples=1000):
"""
Stratified subsampling if labels are given.
This means due to rounding errors you might get a little differences between the
num_samples and the returned subsampled X.
"""
if X.shape[0] > num_samples:
print("Warning: subsampling X, as it ... | [
"def",
"subsample_X",
"(",
"X",
",",
"labels",
",",
"num_samples",
"=",
"1000",
")",
":",
"if",
"X",
".",
"shape",
"[",
"0",
"]",
">",
"num_samples",
":",
"print",
"(",
"\"Warning: subsampling X, as it has more samples then {}. X.shape={!s}\"",
".",
"format",
"(... | 54.984127 | 27.492063 |
def get_remaining_time(program):
'''
Get the remaining time in seconds of a program that is currently on.
'''
now = datetime.datetime.now()
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could no... | [
"def",
"get_remaining_time",
"(",
"program",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"program_start",
"=",
"program",
".",
"get",
"(",
"'start_time'",
")",
"program_end",
"=",
"program",
".",
"get",
"(",
"'end_time'",
")",
... | 37.470588 | 16.882353 |
def effective_max_ar_order(self):
"""The maximum number of AR coefficients that shall or can be
determined.
It is the minimum of |ARMA.max_ar_order| and the number of
coefficients of the pure |MA| after their turning point.
"""
return min(self.max_ar_order, self.ma.order... | [
"def",
"effective_max_ar_order",
"(",
"self",
")",
":",
"return",
"min",
"(",
"self",
".",
"max_ar_order",
",",
"self",
".",
"ma",
".",
"order",
"-",
"self",
".",
"ma",
".",
"turningpoint",
"[",
"0",
"]",
"-",
"1",
")"
] | 42.5 | 19.5 |
async def async_execute(self, command: Command, password: str = '',
timeout: int = EXECUTE_TIMEOUT_SECS) -> Response:
"""
Execute a command and return response.
command: the command instance to be executed
password: if specified, will be used to execute ... | [
"async",
"def",
"async_execute",
"(",
"self",
",",
"command",
":",
"Command",
",",
"password",
":",
"str",
"=",
"''",
",",
"timeout",
":",
"int",
"=",
"EXECUTE_TIMEOUT_SECS",
")",
"->",
"Response",
":",
"if",
"not",
"self",
".",
"_is_connected",
":",
"ra... | 43.652174 | 18.521739 |
def get_results(self, stream, time_interval):
"""
Calculates/receives the documents in the stream interval determined by the stream
:param stream: The stream reference
:param time_interval: The time interval
:return: The sorted data items
"""
return [StreamInstanc... | [
"def",
"get_results",
"(",
"self",
",",
"stream",
",",
"time_interval",
")",
":",
"return",
"[",
"StreamInstance",
"(",
"t",
",",
"self",
".",
"data",
"[",
"stream",
".",
"stream_id",
"]",
"[",
"t",
"]",
")",
"for",
"t",
"in",
"sorted",
"(",
"self",
... | 48 | 14.888889 |
def make_ready(self):
"""Make a task ready for execution"""
SCons.Taskmaster.OutOfDateTask.make_ready(self)
if self.out_of_date and self.options.debug_explain:
explanation = self.out_of_date[0].explain()
if explanation:
sys.stdout.write("scons: " + explana... | [
"def",
"make_ready",
"(",
"self",
")",
":",
"SCons",
".",
"Taskmaster",
".",
"OutOfDateTask",
".",
"make_ready",
"(",
"self",
")",
"if",
"self",
".",
"out_of_date",
"and",
"self",
".",
"options",
".",
"debug_explain",
":",
"explanation",
"=",
"self",
".",
... | 45.571429 | 14 |
def serialize_dictionary(dictionary):
"""Function to stringify a dictionary recursively.
:param dictionary: The dictionary.
:type dictionary: dict
:return: The string.
:rtype: basestring
"""
string_value = {}
for k, v in list(dictionary.items()):
if isinstance(v, QUrl):
... | [
"def",
"serialize_dictionary",
"(",
"dictionary",
")",
":",
"string_value",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"dictionary",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"QUrl",
")",
":",
"string_value",
"... | 31.16 | 11.36 |
def remove_behavior_from_work_item_type(self, process_id, wit_ref_name_for_behaviors, behavior_ref_name):
"""RemoveBehaviorFromWorkItemType.
[Preview API] Removes a behavior for the work item type of the process.
:param str process_id: The ID of the process
:param str wit_ref_name_for_be... | [
"def",
"remove_behavior_from_work_item_type",
"(",
"self",
",",
"process_id",
",",
"wit_ref_name_for_behaviors",
",",
"behavior_ref_name",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"process_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'processId'",
"]",... | 63.5 | 27.333333 |
def get_port_channel_detail_output_lacp_aggregator_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_detai... | [
"def",
"get_port_channel_detail_output_lacp_aggregator_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_channel_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_channel_detail\"",
")",
... | 44.769231 | 15.769231 |
def load(self, steps_dir=None, step_file=None, step_list=None):
"""Load CWL steps into the WorkflowGenerator's steps library.
Adds steps (command line tools and workflows) to the
``WorkflowGenerator``'s steps library. These steps can be used to
create workflows.
Args:
... | [
"def",
"load",
"(",
"self",
",",
"steps_dir",
"=",
"None",
",",
"step_file",
"=",
"None",
",",
"step_list",
"=",
"None",
")",
":",
"self",
".",
"_closed",
"(",
")",
"self",
".",
"steps_library",
".",
"load",
"(",
"steps_dir",
"=",
"steps_dir",
",",
"... | 41.294118 | 22.470588 |
def output(self):
"""!
@brief Returns output dynamic of the network.
"""
if (self.__ccore_legion_dynamic_pointer is not None):
return wrapper.legion_dynamic_get_output(self.__ccore_legion_dynamic_pointer);
return self.__output; | [
"def",
"output",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"__ccore_legion_dynamic_pointer",
"is",
"not",
"None",
")",
":",
"return",
"wrapper",
".",
"legion_dynamic_get_output",
"(",
"self",
".",
"__ccore_legion_dynamic_pointer",
")",
"return",
"self",
"."... | 33.444444 | 19.777778 |
def save(self, to_save, manipulate=True, check_keys=True, **kwargs):
"""Save a document in this collection.
**DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
... | [
"def",
"save",
"(",
"self",
",",
"to_save",
",",
"manipulate",
"=",
"True",
",",
"check_keys",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"save is deprecated. Use insert_one or replace_one \"",
"\"instead\"",
",",
"Deprecatio... | 45.666667 | 24.592593 |
def visit_module(self, node):
"""
A interface will be called when visiting a module.
@param node: node of current module
"""
modulename = node.name.split(".")[-1]
if isTestModule(node.name) and self.moduleContainsTestCase(node):
self._checkTestModuleName(modu... | [
"def",
"visit_module",
"(",
"self",
",",
"node",
")",
":",
"modulename",
"=",
"node",
".",
"name",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"if",
"isTestModule",
"(",
"node",
".",
"name",
")",
"and",
"self",
".",
"moduleContainsTestCase",
... | 36.111111 | 13.888889 |
def maximum(attrs, inputs, proto_obj):
"""
Elementwise maximum of arrays.
MXNet maximum compares only two symbols at a time.
ONNX can send more than two to compare.
Breaking into multiple mxnet ops to compare two symbols at a time
"""
if len(inputs) > 1:
mxnet_op = symbol.maximum(inp... | [
"def",
"maximum",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"if",
"len",
"(",
"inputs",
")",
">",
"1",
":",
"mxnet_op",
"=",
"symbol",
".",
"maximum",
"(",
"inputs",
"[",
"0",
"]",
",",
"inputs",
"[",
"1",
"]",
")",
"for",
"op_inpu... | 37.142857 | 11.428571 |
def get_record(self, xml_file):
""" Reads a xml file in JATS format and returns
a xml string in marc format """
self.document = parse(xml_file)
if get_value_in_tag(self.document, "meta"):
raise ApsPackageXMLError("The XML format of %s is not correct"
... | [
"def",
"get_record",
"(",
"self",
",",
"xml_file",
")",
":",
"self",
".",
"document",
"=",
"parse",
"(",
"xml_file",
")",
"if",
"get_value_in_tag",
"(",
"self",
".",
"document",
",",
"\"meta\"",
")",
":",
"raise",
"ApsPackageXMLError",
"(",
"\"The XML format... | 48.605263 | 19.026316 |
def is_inf(self):
"""Asserts that val is real number and Inf (infinity)."""
self._validate_number()
self._validate_real()
if not math.isinf(self.val):
self._err('Expected <%s> to be <Inf>, but was not.' % self.val)
return self | [
"def",
"is_inf",
"(",
"self",
")",
":",
"self",
".",
"_validate_number",
"(",
")",
"self",
".",
"_validate_real",
"(",
")",
"if",
"not",
"math",
".",
"isinf",
"(",
"self",
".",
"val",
")",
":",
"self",
".",
"_err",
"(",
"'Expected <%s> to be <Inf>, but w... | 38.857143 | 14.714286 |
def parse(cls: Type[MessageT], uid: int, data: bytes,
permanent_flags: Iterable[Flag], internal_date: datetime,
expunged: bool = False, **kwargs: Any) -> MessageT:
"""Parse the given file object containing a MIME-encoded email message
into a :class:`BaseLoadedMessage` object.... | [
"def",
"parse",
"(",
"cls",
":",
"Type",
"[",
"MessageT",
"]",
",",
"uid",
":",
"int",
",",
"data",
":",
"bytes",
",",
"permanent_flags",
":",
"Iterable",
"[",
"Flag",
"]",
",",
"internal_date",
":",
"datetime",
",",
"expunged",
":",
"bool",
"=",
"Fa... | 45.588235 | 18 |
def process_debug_request(self, req):
"""
Debgging helper used for testing, processes the given request and dumps
the internal state of cached user to group mappings. Note that this is
only callable if TRAC_GITHUB_ENABLE_DEBUGGING is set in the
environment.
"""
re... | [
"def",
"process_debug_request",
"(",
"self",
",",
"req",
")",
":",
"req",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"_fetch_groups",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"'application/json'",
",",
"200",
")"
] | 49.25 | 22.25 |
def evaluate_postfix(tokens):
"""
Given a list of evaluatable tokens in postfix format,
calculate a solution.
"""
stack = []
for token in tokens:
total = None
if is_int(token) or is_float(token) or is_constant(token):
stack.append(token)
elif is_unary(token)... | [
"def",
"evaluate_postfix",
"(",
"tokens",
")",
":",
"stack",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"total",
"=",
"None",
"if",
"is_int",
"(",
"token",
")",
"or",
"is_float",
"(",
"token",
")",
"or",
"is_constant",
"(",
"token",
")",
":"... | 28.543478 | 16.76087 |
def add_routes(meteor_app, url_path='/importv2'):
"""
Add two routes to the specified instance of :class:`meteorpi_server.MeteorApp` to implement the import API and allow
for replication of data to this server.
:param meteorpi_server.MeteorApp meteor_app:
The :class:`meteorpi_server.MeteorApp` ... | [
"def",
"add_routes",
"(",
"meteor_app",
",",
"url_path",
"=",
"'/importv2'",
")",
":",
"app",
"=",
"meteor_app",
".",
"app",
"@",
"app",
".",
"route",
"(",
"url_path",
",",
"methods",
"=",
"[",
"'POST'",
"]",
")",
"@",
"meteor_app",
".",
"requires_auth",... | 47.506329 | 24.012658 |
def list_namespaced_pod(self, namespace, **kwargs):
"""
list or watch objects of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod(namespace, async_req=True)
... | [
"def",
"list_namespaced_pod",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_namespaced_pod... | 165.285714 | 136 |
def distance_matrix(client, origins, destinations,
mode=None, language=None, avoid=None, units=None,
departure_time=None, arrival_time=None, transit_mode=None,
transit_routing_preference=None, traffic_model=None, region=None):
""" Gets travel distance and ... | [
"def",
"distance_matrix",
"(",
"client",
",",
"origins",
",",
"destinations",
",",
"mode",
"=",
"None",
",",
"language",
"=",
"None",
",",
"avoid",
"=",
"None",
",",
"units",
"=",
"None",
",",
"departure_time",
"=",
"None",
",",
"arrival_time",
"=",
"Non... | 40.321739 | 26.391304 |
def get_expiration_seconds_v2(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid ... | [
"def",
"get_expiration_seconds_v2",
"(",
"expiration",
")",
":",
"# If it's a timedelta, add it to `now` in UTC.",
"if",
"isinstance",
"(",
"expiration",
",",
"datetime",
".",
"timedelta",
")",
":",
"now",
"=",
"NOW",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
... | 37.518519 | 19.740741 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.