text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_linestyle(self, increment=1):
"""
Returns the current marker, then increments the marker by what's specified
"""
i = self.linestyles_index
self.linestyles_index += increment
if self.linestyles_index >= len(self.linestyles):
self.linestyles_index = se... | [
"def",
"get_linestyle",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"i",
"=",
"self",
".",
"linestyles_index",
"self",
".",
"linestyles_index",
"+=",
"increment",
"if",
"self",
".",
"linestyles_index",
">=",
"len",
"(",
"self",
".",
"linestyles",
")... | 37.076923 | 22.615385 |
def create_attachment(self, upload_stream, scope_identifier, hub_name, plan_id, timeline_id, record_id, type, name, **kwargs):
"""CreateAttachment.
[Preview API]
:param object upload_stream: Stream to upload
:param str scope_identifier: The project GUID to scope the request
:para... | [
"def",
"create_attachment",
"(",
"self",
",",
"upload_stream",
",",
"scope_identifier",
",",
"hub_name",
",",
"plan_id",
",",
"timeline_id",
",",
"record_id",
",",
"type",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",... | 53.3 | 24.325 |
def hpd_credible_interval(mu_in, post, alpha=0.9, tolerance=1e-3):
'''
Returns the minimum and maximum rate values of the HPD
(Highest Posterior Density) credible interval for a posterior
post defined at the sample values mu_in. Samples need not be
uniformly spaced and posterior need not be normali... | [
"def",
"hpd_credible_interval",
"(",
"mu_in",
",",
"post",
",",
"alpha",
"=",
"0.9",
",",
"tolerance",
"=",
"1e-3",
")",
":",
"if",
"alpha",
"==",
"1",
":",
"nonzero_samples",
"=",
"mu_in",
"[",
"post",
">",
"0",
"]",
"mu_low",
"=",
"numpy",
".",
"mi... | 42.72 | 19.76 |
def SettingsAddConnection(self, connection_settings):
'''Add a connection.
connection_settings is a String String Variant Map Map. See
https://developer.gnome.org/NetworkManager/0.9/spec.html
#type-String_String_Variant_Map_Map
If you omit uuid, this method adds one for you.
'''
if 'u... | [
"def",
"SettingsAddConnection",
"(",
"self",
",",
"connection_settings",
")",
":",
"if",
"'uuid'",
"not",
"in",
"connection_settings",
"[",
"'connection'",
"]",
":",
"connection_settings",
"[",
"'connection'",
"]",
"[",
"'uuid'",
"]",
"=",
"str",
"(",
"uuid",
... | 36.397059 | 23.897059 |
def _notice_broker_or_pool(obj):
"""
Used by :mod:`mitogen.core` and :mod:`mitogen.service` to automatically
register every broker and pool on Python 2.4/2.5.
"""
if isinstance(obj, mitogen.core.Broker):
_brokers[obj] = True
else:
_pools[obj] = True | [
"def",
"_notice_broker_or_pool",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"mitogen",
".",
"core",
".",
"Broker",
")",
":",
"_brokers",
"[",
"obj",
"]",
"=",
"True",
"else",
":",
"_pools",
"[",
"obj",
"]",
"=",
"True"
] | 31.222222 | 13 |
def parse_networks_output(out):
"""
Parses the output of the Docker CLI 'docker network ls' and returns it in the format similar to the Docker API.
:param out: CLI output.
:type out: unicode | str
:return: Parsed result.
:rtype: list[dict]
"""
if not out:
return []
line_iter... | [
"def",
"parse_networks_output",
"(",
"out",
")",
":",
"if",
"not",
"out",
":",
"return",
"[",
"]",
"line_iter",
"=",
"islice",
"(",
"out",
".",
"splitlines",
"(",
")",
",",
"1",
",",
"None",
")",
"# Skip header",
"return",
"list",
"(",
"map",
"(",
"_... | 31.230769 | 19.846154 |
def get_calculation_dependencies_for(service):
"""Calculation dependencies of this service and the calculation of each
dependent service (recursively).
"""
def calc_dependencies_gen(service, collector=None):
"""Generator for recursive dependency resolution.
"""
# The UID of the... | [
"def",
"get_calculation_dependencies_for",
"(",
"service",
")",
":",
"def",
"calc_dependencies_gen",
"(",
"service",
",",
"collector",
"=",
"None",
")",
":",
"\"\"\"Generator for recursive dependency resolution.\n \"\"\"",
"# The UID of the service",
"service_uid",
"=",
... | 34.5 | 17.321429 |
def ModifyInstance(self, ModifiedInstance, IncludeQualifiers=None,
PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Modify the property values of an instance.
This method performs the ModifyInstance operation
(see :term:`DSP020... | [
"def",
"ModifyInstance",
"(",
"self",
",",
"ModifiedInstance",
",",
"IncludeQualifiers",
"=",
"None",
",",
"PropertyList",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"# pylint: disable=invalid-name,line-too-long",
"# noqa: E501",
"exc",
"=",
"None",
"method_name... | 45.25 | 26.114583 |
def errorstr(self, space, use_repr=False):
"The exception class and value, as a string."
w_value = self.get_w_value(space)
if space is None:
# this part NOT_RPYTHON
exc_typename = str(self.w_type)
exc_value = str(w_value)
else:
w = space.wr... | [
"def",
"errorstr",
"(",
"self",
",",
"space",
",",
"use_repr",
"=",
"False",
")",
":",
"w_value",
"=",
"self",
".",
"get_w_value",
"(",
"space",
")",
"if",
"space",
"is",
"None",
":",
"# this part NOT_RPYTHON",
"exc_typename",
"=",
"str",
"(",
"self",
".... | 40.344828 | 15.310345 |
def attribs_to_string(attrib_dict, keys):
"""
A more specific version of the subdict utility aimed at handling
node and edge attribute dictionaries for NetworkX file formats such as
gexf (which does not allow attributes to have a list type) by making
them writable in those formats
"""
for ke... | [
"def",
"attribs_to_string",
"(",
"attrib_dict",
",",
"keys",
")",
":",
"for",
"key",
",",
"value",
"in",
"attrib_dict",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"value",
",",
"list",
")",
"or",
"isinstance",
"(",
"value",
",",
"di... | 39.230769 | 15.076923 |
def get_submissions_multiple_assignments_by_sis_id(
self, is_section, sis_id, students=None, assignments=None,
**params):
"""
List submissions for multiple assignments by course/section sis id and
optionally student
https://canvas.instructure.com/doc/api/submissi... | [
"def",
"get_submissions_multiple_assignments_by_sis_id",
"(",
"self",
",",
"is_section",
",",
"sis_id",
",",
"students",
"=",
"None",
",",
"assignments",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"if",
"is_section",
":",
"return",
"self",
".",
"get_submi... | 43.529412 | 21.176471 |
def StoreResults(self, responses):
"""Stores the responses."""
client_id = responses.request.client_id
if responses.success:
logging.info("Client %s has a file %s.", client_id, self.args.filename)
else:
logging.info("Client %s has no file %s.", client_id, self.args.filename)
self.MarkC... | [
"def",
"StoreResults",
"(",
"self",
",",
"responses",
")",
":",
"client_id",
"=",
"responses",
".",
"request",
".",
"client_id",
"if",
"responses",
".",
"success",
":",
"logging",
".",
"info",
"(",
"\"Client %s has a file %s.\"",
",",
"client_id",
",",
"self",... | 33.1 | 21.6 |
def punct(self, text):
"""Push punctuation onto the token queue."""
cls = self.PUNCTUATION[text]
self.push_token(cls(text, self.lineno, self.offset)) | [
"def",
"punct",
"(",
"self",
",",
"text",
")",
":",
"cls",
"=",
"self",
".",
"PUNCTUATION",
"[",
"text",
"]",
"self",
".",
"push_token",
"(",
"cls",
"(",
"text",
",",
"self",
".",
"lineno",
",",
"self",
".",
"offset",
")",
")"
] | 42.5 | 10.5 |
def _get_dvportgroup_dict(pg_ref):
'''
Returns a dictionary with a distributed virutal portgroup data
pg_ref
Portgroup reference
'''
props = salt.utils.vmware.get_properties_of_managed_object(
pg_ref, ['name', 'config.description', 'config.numPorts',
'config.type',... | [
"def",
"_get_dvportgroup_dict",
"(",
"pg_ref",
")",
":",
"props",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_properties_of_managed_object",
"(",
"pg_ref",
",",
"[",
"'name'",
",",
"'config.description'",
",",
"'config.numPorts'",
",",
"'config.type'",
","... | 40.342857 | 17.028571 |
def mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean squared error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return F.mse_loss(pred, targ) | [
"def",
"mean_squared_error",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"F",
".",
"mse_loss",
"(",
"pred",
",",
"targ",
")"
... | 46.5 | 10 |
def variance(self):
"""Returns variance"""
if self.counter.value <= 1:
return 0.0
return self.var.value[1] / (self.counter.value - 1) | [
"def",
"variance",
"(",
"self",
")",
":",
"if",
"self",
".",
"counter",
".",
"value",
"<=",
"1",
":",
"return",
"0.0",
"return",
"self",
".",
"var",
".",
"value",
"[",
"1",
"]",
"/",
"(",
"self",
".",
"counter",
".",
"value",
"-",
"1",
")"
] | 33 | 12.6 |
def _session_key(self, key):
"""
Generates session key string.
:param str key:
e.g. ``"authomatic:facebook:key"``
"""
return '{0}:{1}:{2}'.format(self.settings.prefix, self.name, key) | [
"def",
"_session_key",
"(",
"self",
",",
"key",
")",
":",
"return",
"'{0}:{1}:{2}'",
".",
"format",
"(",
"self",
".",
"settings",
".",
"prefix",
",",
"self",
".",
"name",
",",
"key",
")"
] | 22.9 | 19.1 |
def check_download(obj, *args, **kwargs):
"""Verify a download"""
version = args[0]
workdir = args[1]
signame = args[2]
if version:
local_version = get_local_version(workdir, signame)
if not verify_sigfile(workdir, signame) or version != local_version:
error("[-] \033[91m... | [
"def",
"check_download",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"version",
"=",
"args",
"[",
"0",
"]",
"workdir",
"=",
"args",
"[",
"1",
"]",
"signame",
"=",
"args",
"[",
"2",
"]",
"if",
"version",
":",
"local_version",
... | 42.727273 | 19 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Parameter(key)
if key not in Parameter._member_map_:
extend_enum(Parameter, key, default)
return Parameter[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Parameter",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Parameter",
".",
"_member_map_",
":",
"extend_enum",
"(",
"P... | 37.428571 | 7.714286 |
def set_base_prompt(
self, pri_prompt_terminator=":", alt_prompt_terminator="#", delay_factor=2
):
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
super(AccedianSSH, self).set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
... | [
"def",
"set_base_prompt",
"(",
"self",
",",
"pri_prompt_terminator",
"=",
"\":\"",
",",
"alt_prompt_terminator",
"=",
"\"#\"",
",",
"delay_factor",
"=",
"2",
")",
":",
"super",
"(",
"AccedianSSH",
",",
"self",
")",
".",
"set_base_prompt",
"(",
"pri_prompt_termin... | 44.5 | 17.9 |
def _indexable_roles_and_users(self):
"""Return a string made for indexing roles having :any:`READ`
permission on this object."""
from abilian.services.indexing import indexable_role
from abilian.services.security import READ, Admin, Anonymous, Creator, Owner
from abilian.service... | [
"def",
"_indexable_roles_and_users",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"services",
".",
"indexing",
"import",
"indexable_role",
"from",
"abilian",
".",
"services",
".",
"security",
"import",
"READ",
",",
"Admin",
",",
"Anonymous",
",",
"Creator",
... | 36.25641 | 18.205128 |
def reset(self):
"""Reset emulator. All registers and memory are reset.
"""
self.__mem.reset()
self.__cpu.reset()
self.__tainter.reset()
# Instructions pre and post handlers.
self.__instr_handler_pre = None, None
self.__instr_handler_post = None, None
... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"__mem",
".",
"reset",
"(",
")",
"self",
".",
"__cpu",
".",
"reset",
"(",
")",
"self",
".",
"__tainter",
".",
"reset",
"(",
")",
"# Instructions pre and post handlers.",
"self",
".",
"__instr_handler_pre"... | 28.666667 | 13.416667 |
def rc2_cbc_pkcs5_decrypt(key, data, iv):
"""
Decrypts RC2 ciphertext using a 64 bit key
:param key:
The encryption key - a byte string 8 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector used for encryption - a byte string
:r... | [
"def",
"rc2_cbc_pkcs5_decrypt",
"(",
"key",
",",
"data",
",",
"iv",
")",
":",
"if",
"len",
"(",
"key",
")",
"<",
"5",
"or",
"len",
"(",
"key",
")",
">",
"16",
":",
"raise",
"ValueError",
"(",
"pretty_message",
"(",
"'''\n key must be 5 to 16 byt... | 26.641026 | 23.051282 |
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True):
"""
Get a logger for ResourceProvider and it's components, such as Allocators.
:param name: Name for logger
:param short_name: Shorthand name for the logger
:param log_to_file: Boolean, True if logger should log to a file... | [
"def",
"get_resourceprovider_logger",
"(",
"name",
"=",
"None",
",",
"short_name",
"=",
"\" \"",
",",
"log_to_file",
"=",
"True",
")",
":",
"global",
"LOGGERS",
"loggername",
"=",
"name",
"logger",
"=",
"_check_existing_logger",
"(",
"loggername",
",",
"short_na... | 34.935484 | 22.677419 |
def cublasSgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real general matrix.
"""
status = _libcublas.cublasSgemv_v2(handle,
_CUBLAS_OP[trans], m, n,
ctypes.byref(ctypes.c_fl... | [
"def",
"cublasSgemv",
"(",
"handle",
",",
"trans",
",",
"m",
",",
"n",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"x",
",",
"incx",
",",
"beta",
",",
"y",
",",
"incy",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasSgemv_v2",
"(",
"handle",
","... | 42.25 | 22.916667 |
def keyword_search(rows, **kwargs):
"""
Takes a list of dictionaries and finds all the dictionaries where the
keys and values match those found in the keyword arguments.
Keys in the row data have ' ' and '-' replaced with '_', so they can
match the keyword argument parsing. For example, the keywor... | [
"def",
"keyword_search",
"(",
"rows",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"[",
"]",
"if",
"not",
"kwargs",
":",
"return",
"results",
"# Allows us to transform the key and do lookups like __contains and",
"# __startswith",
"matchers",
"=",
"{",
"'defau... | 41.846154 | 25.358974 |
def update_launch_config(self, scaling_group, server_name=None, image=None,
flavor=None, disk_config=None, metadata=None, personality=None,
networks=None, load_balancers=None, key_name=None, config_drive=False,
user_data=None):
"""
Updates the server launch configurat... | [
"def",
"update_launch_config",
"(",
"self",
",",
"scaling_group",
",",
"server_name",
"=",
"None",
",",
"image",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"disk_config",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"personality",
"=",
"None",
",",
... | 56.777778 | 25.777778 |
def spit_config(self, conf_file, firstwordonly=False):
"""conf_file a file opened for writing."""
cfg = ConfigParser.RawConfigParser()
for sec in _CONFIG_SECS:
cfg.add_section(sec)
sec = 'channels'
for i in sorted(self.pack.D):
cfg.set(sec, str(i),
... | [
"def",
"spit_config",
"(",
"self",
",",
"conf_file",
",",
"firstwordonly",
"=",
"False",
")",
":",
"cfg",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
")",
"for",
"sec",
"in",
"_CONFIG_SECS",
":",
"cfg",
".",
"add_section",
"(",
"sec",
")",
"sec",
"... | 30.117647 | 16.588235 |
def _init_file(self):
"""Initialise the file header. This will erase any data previously in the file."""
header_length = 2*SECTOR_LENGTH
if self.size > header_length:
self.file.truncate(header_length)
self.file.seek(0)
self.file.write(header_length*b'\x00')
se... | [
"def",
"_init_file",
"(",
"self",
")",
":",
"header_length",
"=",
"2",
"*",
"SECTOR_LENGTH",
"if",
"self",
".",
"size",
">",
"header_length",
":",
"self",
".",
"file",
".",
"truncate",
"(",
"header_length",
")",
"self",
".",
"file",
".",
"seek",
"(",
"... | 42 | 7 |
def _assign_as_root(self, id_):
"""Assign an id_ a root object in the hierarchy"""
rfc = self._ras.get_relationship_form_for_create(self._phantom_root_id, id_, [])
rfc.set_display_name('Implicit Root to ' + str(id_) + ' Parent-Child Relationship')
rfc.set_description(self._relationship_t... | [
"def",
"_assign_as_root",
"(",
"self",
",",
"id_",
")",
":",
"rfc",
"=",
"self",
".",
"_ras",
".",
"get_relationship_form_for_create",
"(",
"self",
".",
"_phantom_root_id",
",",
"id_",
",",
"[",
"]",
")",
"rfc",
".",
"set_display_name",
"(",
"'Implicit Root ... | 71.714286 | 31.714286 |
def function(self, addr=None, name=None, create=False, syscall=False, plt=None):
"""
Get a function object from the function manager.
Pass either `addr` or `name` with the appropriate values.
:param int addr: Address of the function.
:param str name: Name of the function.
... | [
"def",
"function",
"(",
"self",
",",
"addr",
"=",
"None",
",",
"name",
"=",
"None",
",",
"create",
"=",
"False",
",",
"syscall",
"=",
"False",
",",
"plt",
"=",
"None",
")",
":",
"if",
"addr",
"is",
"not",
"None",
":",
"try",
":",
"f",
"=",
"sel... | 42 | 18.333333 |
def walk(self, cli):
""" Walk through children. """
yield self
for i in self.content.walk(cli):
yield i
for f in self.floats:
for i in f.content.walk(cli):
yield i | [
"def",
"walk",
"(",
"self",
",",
"cli",
")",
":",
"yield",
"self",
"for",
"i",
"in",
"self",
".",
"content",
".",
"walk",
"(",
"cli",
")",
":",
"yield",
"i",
"for",
"f",
"in",
"self",
".",
"floats",
":",
"for",
"i",
"in",
"f",
".",
"content",
... | 22.8 | 17.2 |
def parse_coordinate(string_rep):
"""
Parse a single coordinate
"""
# Any CRTF coordinate representation (sexagesimal or degrees)
if 'pix' in string_rep:
return u.Quantity(string_rep[:-3], u.dimensionless_unscaled)
if 'h' in string_rep or 'rad' in string_rep:... | [
"def",
"parse_coordinate",
"(",
"string_rep",
")",
":",
"# Any CRTF coordinate representation (sexagesimal or degrees)",
"if",
"'pix'",
"in",
"string_rep",
":",
"return",
"u",
".",
"Quantity",
"(",
"string_rep",
"[",
":",
"-",
"3",
"]",
",",
"u",
".",
"dimensionle... | 36.428571 | 15.285714 |
def _init_hex(self, hexval: str) -> None:
""" Initialize from a hex value string. """
self.hexval = hex2termhex(fix_hex(hexval))
self.code = hex2term(self.hexval)
self.rgb = hex2rgb(self.hexval) | [
"def",
"_init_hex",
"(",
"self",
",",
"hexval",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"hexval",
"=",
"hex2termhex",
"(",
"fix_hex",
"(",
"hexval",
")",
")",
"self",
".",
"code",
"=",
"hex2term",
"(",
"self",
".",
"hexval",
")",
"self",
"... | 44.4 | 2.6 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ECDSA_Curve(key)
if key not in ECDSA_Curve._member_map_:
extend_enum(ECDSA_Curve, key, default)
return ECDSA_Curve[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"ECDSA_Curve",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"ECDSA_Curve",
".",
"_member_map_",
":",
"extend_enum",
"(",
... | 38.571429 | 7.714286 |
def build_service(service_descriptor, did):
"""
Build a service.
:param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes
and the second item is a dict of parameters and values required by the service
:param did: DID, str
:return: Service... | [
"def",
"build_service",
"(",
"service_descriptor",
",",
"did",
")",
":",
"assert",
"isinstance",
"(",
"service_descriptor",
",",
"tuple",
")",
"and",
"len",
"(",
"service_descriptor",
")",
"==",
"2",
",",
"'Unknown service descriptor format.'",
"service_type",
",",
... | 39.263158 | 20.947368 |
def file_decrypt( blockchain_id, hostname, sender_blockchain_id, sender_key_id, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
"""
Decrypt a file from a sender's blockchain ID.
Try our current key, and then the old keys
(but warn if there are revoked keys)
Ret... | [
"def",
"file_decrypt",
"(",
"blockchain_id",
",",
"hostname",
",",
"sender_blockchain_id",
",",
"sender_key_id",
",",
"input_path",
",",
"output_path",
",",
"passphrase",
"=",
"None",
",",
"config_path",
"=",
"CONFIG_PATH",
",",
"wallet_keys",
"=",
"None",
")",
... | 39.913043 | 26.434783 |
def get_current_nodes(self, clusters):
"""
Returns two dictionaries, the current nodes and the enabled nodes.
The current_nodes dictionary is keyed off of the cluster name and
values are a list of nodes known to HAProxy.
The enabled_nodes dictionary is also keyed off of the clu... | [
"def",
"get_current_nodes",
"(",
"self",
",",
"clusters",
")",
":",
"current_nodes",
"=",
"self",
".",
"control",
".",
"get_active_nodes",
"(",
")",
"enabled_nodes",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"cluster",
"in",
"clusters",
... | 36.974359 | 19.589744 |
def check_X(X, n_feats=None, min_samples=1, edge_knots=None, dtypes=None,
features=None, verbose=True):
"""
tool to ensure that X:
- is 2 dimensional
- contains float-compatible data-types
- has at least min_samples
- has n_feats
- has categorical features in the right range
... | [
"def",
"check_X",
"(",
"X",
",",
"n_feats",
"=",
"None",
",",
"min_samples",
"=",
"1",
",",
"edge_knots",
"=",
"None",
",",
"dtypes",
"=",
"None",
",",
"features",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"# check all features are there",
"if"... | 32.662162 | 18.337838 |
def _hasReturnValue(self, node):
"""
Determine whether the given method or function has a return statement.
@param node: the node currently checks
"""
returnFound = False
for subnode in node.body:
if type(subnode) == node_classes.Return and subnode.value:
... | [
"def",
"_hasReturnValue",
"(",
"self",
",",
"node",
")",
":",
"returnFound",
"=",
"False",
"for",
"subnode",
"in",
"node",
".",
"body",
":",
"if",
"type",
"(",
"subnode",
")",
"==",
"node_classes",
".",
"Return",
"and",
"subnode",
".",
"value",
":",
"r... | 32.416667 | 15.083333 |
def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone):
"""
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_a... | [
"def",
"fast_group_adder",
"(",
"wires_to_add",
",",
"reducer",
"=",
"wallace_reducer",
",",
"final_adder",
"=",
"kogge_stone",
")",
":",
"import",
"math",
"longest_wire_len",
"=",
"max",
"(",
"len",
"(",
"w",
")",
"for",
"w",
"in",
"wires_to_add",
")",
"res... | 39.36 | 22.32 |
def _getAuth(self):
"""
Main step in authorizing with Reader.
Sends request to Google ClientAuthMethod URL which returns an Auth token.
Returns Auth token or raises IOError on error.
"""
parameters = {
'service' : 'reader',
'Email' : sel... | [
"def",
"_getAuth",
"(",
"self",
")",
":",
"parameters",
"=",
"{",
"'service'",
":",
"'reader'",
",",
"'Email'",
":",
"self",
".",
"username",
",",
"'Passwd'",
":",
"self",
".",
"password",
",",
"'accountType'",
":",
"'GOOGLE'",
"}",
"req",
"=",
"requests... | 40.25 | 14.65 |
def use_session(self, session_id):
"""
Use the specified lightning session.
Specify a lightning session by id number. Check the number of an existing
session in the attribute lightning.session.id.
"""
self.session = Session(lgn=self, id=session_id)
return self.se... | [
"def",
"use_session",
"(",
"self",
",",
"session_id",
")",
":",
"self",
".",
"session",
"=",
"Session",
"(",
"lgn",
"=",
"self",
",",
"id",
"=",
"session_id",
")",
"return",
"self",
".",
"session"
] | 35.222222 | 14.777778 |
def from_json(j):
"""
load an nparray object from a json-formatted string
@parameter str j: json-formatted string
"""
if isinstance(j, dict):
return from_dict(j)
if not (isinstance(j, str) or isinstance(j, unicode)):
raise TypeError("argument must be of type str")
return f... | [
"def",
"from_json",
"(",
"j",
")",
":",
"if",
"isinstance",
"(",
"j",
",",
"dict",
")",
":",
"return",
"from_dict",
"(",
"j",
")",
"if",
"not",
"(",
"isinstance",
"(",
"j",
",",
"str",
")",
"or",
"isinstance",
"(",
"j",
",",
"unicode",
")",
")",
... | 25.461538 | 17.307692 |
def _parse_type(self, element, types):
"""Parse a 'complexType' element.
@param element: The top-level complexType element
@param types: A map of the elements of all available complexType's.
@return: The schema for the complexType.
"""
name = element.attrib["name"]
... | [
"def",
"_parse_type",
"(",
"self",
",",
"element",
",",
"types",
")",
":",
"name",
"=",
"element",
".",
"attrib",
"[",
"\"name\"",
"]",
"type",
"=",
"element",
".",
"attrib",
"[",
"\"type\"",
"]",
"if",
"not",
"type",
".",
"startswith",
"(",
"\"tns:\""... | 44.036364 | 18.436364 |
def emit(self):
"""We are finished processing one element. Emit it"""
self.count += 1
# event_name = 'on_{0}'.format(self.context.subcategory.lower())
event_name = self.context.subcategory
if hasattr(self.handler, event_name):
getattr(self.handler, event_name)(self.... | [
"def",
"emit",
"(",
"self",
")",
":",
"self",
".",
"count",
"+=",
"1",
"# event_name = 'on_{0}'.format(self.context.subcategory.lower())",
"event_name",
"=",
"self",
".",
"context",
".",
"subcategory",
"if",
"hasattr",
"(",
"self",
".",
"handler",
",",
"event_name... | 37.454545 | 17.727273 |
def with_context(self, required_by):
"""
If required_by is non-empty, return a version of self that is a
ContextualVersionConflict.
"""
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args) | [
"def",
"with_context",
"(",
"self",
",",
"required_by",
")",
":",
"if",
"not",
"required_by",
":",
"return",
"self",
"args",
"=",
"self",
".",
"args",
"+",
"(",
"required_by",
",",
")",
"return",
"ContextualVersionConflict",
"(",
"*",
"args",
")"
] | 33.444444 | 8.777778 |
def get_value(self, field, quick):
# type: (Field, bool) -> Any
""" Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quic... | [
"def",
"get_value",
"(",
"self",
",",
"field",
",",
"quick",
")",
":",
"# type: (Field, bool) -> Any",
"if",
"callable",
"(",
"field",
".",
"default",
")",
":",
"default",
"=",
"field",
".",
"default",
"(",
"self",
")",
"else",
":",
"default",
"=",
"fiel... | 37.771429 | 20.571429 |
def validate_type(prop, value, expected):
""" Default validation for all types """
# Validate on expected type(s), but ignore None: defaults handled elsewhere
if value is not None and not isinstance(value, expected):
_validation_error(prop, type(value).__name__, None, expected) | [
"def",
"validate_type",
"(",
"prop",
",",
"value",
",",
"expected",
")",
":",
"# Validate on expected type(s), but ignore None: defaults handled elsewhere",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"expected",
")",
":",
"_va... | 49 | 21.666667 |
def list_projects(self, entity=None):
"""Lists projects in W&B scoped by entity.
Args:
entity (str, optional): The entity to scope this project to.
Returns:
[{"id","name","description"}]
"""
query = gql('''
query Models($entity: String!) {
... | [
"def",
"list_projects",
"(",
"self",
",",
"entity",
"=",
"None",
")",
":",
"query",
"=",
"gql",
"(",
"'''\n query Models($entity: String!) {\n models(first: 10, entityName: $entity) {\n edges {\n node {\n id\n ... | 29.375 | 18.583333 |
def dic(self):
r""" Returns the corrected Deviance Information Criterion (DIC) for all chains loaded into ChainConsumer.
If a chain does not have a posterior, this method will return `None` for that chain. **Note that
the DIC metric is only valid on posterior surfaces which closely resemble mul... | [
"def",
"dic",
"(",
"self",
")",
":",
"dics",
"=",
"[",
"]",
"dics_bool",
"=",
"[",
"]",
"for",
"i",
",",
"chain",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"chains",
")",
":",
"p",
"=",
"chain",
".",
"posterior",
"if",
"p",
"is",
"Non... | 39.792453 | 25.679245 |
def reparent(self, other, name):
"""
Remove :meth:`get_toplevel` from any current parent and add it to
*other[name]*.
"""
# http://developer.gnome.org/gtk-faq/stable/x635.html
# warns against reparent()
old = self.toplevel.get_parent()
if old:
... | [
"def",
"reparent",
"(",
"self",
",",
"other",
",",
"name",
")",
":",
"# http://developer.gnome.org/gtk-faq/stable/x635.html",
"# warns against reparent()",
"old",
"=",
"self",
".",
"toplevel",
".",
"get_parent",
"(",
")",
"if",
"old",
":",
"old",
".",
"remove",
... | 32.583333 | 11.583333 |
def polar(x, y, deg=0): # radian if deg=0; degree if deg=1
""" Convert from rectangular (x,y) to polar (r,w)
r = sqrt(x^2 + y^2)
w = arctan(y/x) = [-\pi,\pi] = [-180,180]
"""
if deg:
return hypot(x, y), 180.0 * atan2(y, x) / pi
else:
return hypot(x, y), atan2(y, ... | [
"def",
"polar",
"(",
"x",
",",
"y",
",",
"deg",
"=",
"0",
")",
":",
"# radian if deg=0; degree if deg=1",
"if",
"deg",
":",
"return",
"hypot",
"(",
"x",
",",
"y",
")",
",",
"180.0",
"*",
"atan2",
"(",
"y",
",",
"x",
")",
"/",
"pi",
"else",
":",
... | 28.363636 | 18.181818 |
def strip_db_antsignal(self, idx):
"""strip(1 byte) radiotap.db_antsignal
:return: int
idx
:return: int
"""
db_antsignal, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, db_antsignal | [
"def",
"strip_db_antsignal",
"(",
"self",
",",
"idx",
")",
":",
"db_antsignal",
",",
"=",
"struct",
".",
"unpack_from",
"(",
"'<B'",
",",
"self",
".",
"_rtap",
",",
"idx",
")",
"return",
"idx",
"+",
"1",
",",
"db_antsignal"
] | 30.875 | 12.5 |
def tempo_account_get_all_account_by_customer_id(self, customer_id):
"""
Get un-archived Accounts by customer. The Caller must have the Browse Account permission for the Account.
:param customer_id: the Customer id.
:return:
"""
url = 'rest/tempo-accounts/1/account/custom... | [
"def",
"tempo_account_get_all_account_by_customer_id",
"(",
"self",
",",
"customer_id",
")",
":",
"url",
"=",
"'rest/tempo-accounts/1/account/customer/{customerId}/'",
".",
"format",
"(",
"customerId",
"=",
"customer_id",
")",
"return",
"self",
".",
"get",
"(",
"url",
... | 48.75 | 25 |
def _add_timedeltalike_scalar(self, other):
"""
Parameters
----------
other : timedelta, Tick, np.timedelta64
Returns
-------
result : ndarray[int64]
"""
assert isinstance(self.freq, Tick) # checked by calling function
assert isinstance(o... | [
"def",
"_add_timedeltalike_scalar",
"(",
"self",
",",
"other",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
"# checked by calling function",
"assert",
"isinstance",
"(",
"other",
",",
"(",
"timedelta",
",",
"np",
".",
"timedelt... | 38.304348 | 23.086957 |
def crude_tokenizer(line):
"""This is a very crude tokenizer from pynlpl"""
tokens = []
buffer = ''
for c in line.strip():
if c == ' ' or c in string.punctuation:
if buffer:
tokens.append(buffer)
buffer = ''
else:
buffer += c
if... | [
"def",
"crude_tokenizer",
"(",
"line",
")",
":",
"tokens",
"=",
"[",
"]",
"buffer",
"=",
"''",
"for",
"c",
"in",
"line",
".",
"strip",
"(",
")",
":",
"if",
"c",
"==",
"' '",
"or",
"c",
"in",
"string",
".",
"punctuation",
":",
"if",
"buffer",
":",... | 27.384615 | 14.615385 |
def fit(self, X, y=None, sample_weight=None):
"""Compute k-means clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
y : Ignored
not used, present here for API consistency by convention.
sample_weight : array-li... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"sample_weight",
"=",
"None",
")",
":",
"if",
"self",
".",
"normalize",
":",
"X",
"=",
"normalize",
"(",
"X",
")",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_s... | 30.236842 | 20.947368 |
def get_fragment_language() -> ParserElement:
"""Build a protein fragment parser."""
_fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING)
_fragment_value = _fragment_value_inner | And([Suppress('"'), _fragment_value_inner, Suppress('"')])
parser_element = fragment_tag + nest(_frag... | [
"def",
"get_fragment_language",
"(",
")",
"->",
"ParserElement",
":",
"_fragment_value_inner",
"=",
"fragment_range",
"|",
"missing_fragment",
"(",
"FRAGMENT_MISSING",
")",
"_fragment_value",
"=",
"_fragment_value_inner",
"|",
"And",
"(",
"[",
"Suppress",
"(",
"'\"'",... | 66.333333 | 31 |
def __fetch_question(self, question):
"""Fetch an Askbot HTML question body.
The method fetchs the HTML question retrieving the
question body of the item question received
:param question: item with the question itself
:returns: a list of HTML page/s for the question
"... | [
"def",
"__fetch_question",
"(",
"self",
",",
"question",
")",
":",
"html_question_items",
"=",
"[",
"]",
"npages",
"=",
"1",
"next_request",
"=",
"True",
"while",
"next_request",
":",
"try",
":",
"html_question",
"=",
"self",
".",
"client",
".",
"get_html_qu... | 32.966667 | 21.866667 |
def get_relations(self, database, schema):
"""Case-insensitively yield all relations matching the given schema.
:param str schema: The case-insensitive schema name to list from.
:return List[BaseRelation]: The list of relations with the given
schema
"""
schema = _low... | [
"def",
"get_relations",
"(",
"self",
",",
"database",
",",
"schema",
")",
":",
"schema",
"=",
"_lower",
"(",
"schema",
")",
"with",
"self",
".",
"lock",
":",
"results",
"=",
"[",
"r",
".",
"inner",
"for",
"r",
"in",
"self",
".",
"relations",
".",
"... | 36.4 | 19.05 |
def setup(app):
"""Register the extension with Sphinx.
Args:
app: The Sphinx application.
"""
for name, (default, rebuild, _) in ref.CONFIG_VALUES.iteritems():
app.add_config_value(name, default, rebuild)
app.add_directive('javaimport', ref.JavarefImportDirective)
app.add_role... | [
"def",
"setup",
"(",
"app",
")",
":",
"for",
"name",
",",
"(",
"default",
",",
"rebuild",
",",
"_",
")",
"in",
"ref",
".",
"CONFIG_VALUES",
".",
"iteritems",
"(",
")",
":",
"app",
".",
"add_config_value",
"(",
"name",
",",
"default",
",",
"rebuild",
... | 31.764706 | 19.470588 |
def set_drop_target(obj, root, designer, inspector):
"Recursively create and set the drop target for obj and childs"
if obj._meta.container:
dt = ToolBoxDropTarget(obj, root, designer=designer,
inspector=inspector)
obj.drop_target = dt
for child in ... | [
"def",
"set_drop_target",
"(",
"obj",
",",
"root",
",",
"designer",
",",
"inspector",
")",
":",
"if",
"obj",
".",
"_meta",
".",
"container",
":",
"dt",
"=",
"ToolBoxDropTarget",
"(",
"obj",
",",
"root",
",",
"designer",
"=",
"designer",
",",
"inspector",... | 46.875 | 17.875 |
def load(self, **kwargs):
"""Override load to retrieve object based on exists above."""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if self._check_existence_by_collection(
self._meta_data['container'], kwargs['name']):
if LooseVersion(tmos_v) == Loose... | [
"def",
"load",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tmos_v",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'tmos_version'",
"]",
"if",
"self",
".",
"_check_existence_by_collection",
"(",
"self",
".",
"_meta_data"... | 48.833333 | 14.916667 |
def choose_font(self, font=None):
"""Choose a font for the label through a dialog"""
fmt_widget = self.parent()
if font is None:
if self.current_font:
font, ok = QFontDialog.getFont(
self.current_font, fmt_widget,
'Select %s fon... | [
"def",
"choose_font",
"(",
"self",
",",
"font",
"=",
"None",
")",
":",
"fmt_widget",
"=",
"self",
".",
"parent",
"(",
")",
"if",
"font",
"is",
"None",
":",
"if",
"self",
".",
"current_font",
":",
"font",
",",
"ok",
"=",
"QFontDialog",
".",
"getFont",... | 38.777778 | 11.444444 |
def _insert_common_sphinx_configs(c, *, project_name):
"""Add common core Sphinx configurations to the state.
"""
c['project'] = project_name
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
c['source_suffix'] = '.rst'
# The encoding of source fi... | [
"def",
"_insert_common_sphinx_configs",
"(",
"c",
",",
"*",
",",
"project_name",
")",
":",
"c",
"[",
"'project'",
"]",
"=",
"project_name",
"# The suffix(es) of source filenames.",
"# You can specify multiple suffix as a list of string:",
"c",
"[",
"'source_suffix'",
"]",
... | 33.615385 | 18.769231 |
def path_from_keywords(keywords,into='path'):
'''
turns keyword pairs into path or filename
if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy
'''
subdirs = []
def prepare_string(s):
s = str(s)
s = re.sub('[]... | [
"def",
"path_from_keywords",
"(",
"keywords",
",",
"into",
"=",
"'path'",
")",
":",
"subdirs",
"=",
"[",
"]",
"def",
"prepare_string",
"(",
"s",
")",
":",
"s",
"=",
"str",
"(",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"'[][{},*\"'",
"+",
"f\"'{os... | 42.444444 | 24.944444 |
async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if not isinstance(frame, FramePasswordEnterConfirmation):
return False
if frame.status == PasswordEnterConfirmationStatus.FAILED:
PYVLXLOG.warning('Failed to ... | [
"async",
"def",
"handle_frame",
"(",
"self",
",",
"frame",
")",
":",
"if",
"not",
"isinstance",
"(",
"frame",
",",
"FramePasswordEnterConfirmation",
")",
":",
"return",
"False",
"if",
"frame",
".",
"status",
"==",
"PasswordEnterConfirmationStatus",
".",
"FAILED"... | 52.3 | 19.5 |
def get_thumbnail(file_, name):
"""
get_thumbnail version that uses aliasses defined in THUMBNAIL_OPTIONS_DICT
"""
options = settings.OPTIONS_DICT[name]
opt = copy(options)
geometry = opt.pop('geometry')
return original_get_thumbnail(file_, geometry, **opt) | [
"def",
"get_thumbnail",
"(",
"file_",
",",
"name",
")",
":",
"options",
"=",
"settings",
".",
"OPTIONS_DICT",
"[",
"name",
"]",
"opt",
"=",
"copy",
"(",
"options",
")",
"geometry",
"=",
"opt",
".",
"pop",
"(",
"'geometry'",
")",
"return",
"original_get_t... | 30.888889 | 14.222222 |
def _float(text):
"""Fonction to convert the 'decimal point assumed' format of TLE to actual
float
>>> _float('0000+0')
0.0
>>> _float('+0000+0')
0.0
>>> _float('34473-3')
0.00034473
>>> _float('-60129-4')
-6.0129e-05
>>> _float('+45871-4')
4.5871e-05
"""
text ... | [
"def",
"_float",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"text",
"[",
"0",
"]",
"in",
"(",
"'-'",
",",
"'+'",
")",
":",
"text",
"=",
"\"%s.%s\"",
"%",
"(",
"text",
"[",
"0",
"]",
",",
"text",
"[",
"1",
":",... | 22.741935 | 25.032258 |
def _generate_dockerfile(base_image, layers):
"""
Generate the Dockerfile contents
A generated Dockerfile will look like the following:
```
FROM lambci/lambda:python3.6
ADD --chown=sbx_user1051:495 layer1 /opt
ADD --chown=sbx_user1051:495 layer2 /opt
```... | [
"def",
"_generate_dockerfile",
"(",
"base_image",
",",
"layers",
")",
":",
"dockerfile_content",
"=",
"\"FROM {}\\n\"",
".",
"format",
"(",
"base_image",
")",
"for",
"layer",
"in",
"layers",
":",
"dockerfile_content",
"=",
"dockerfile_content",
"+",
"\"ADD --chown=s... | 30.483871 | 22.16129 |
def getComic(number, silent=True):
""" Produces a :class:`Comic` object with index equal to the provided argument.
Prints an error in the event of a failure (i.e. the number is less than zero
or greater than the latest comic number) and returns an empty Comic object.
Arguments:
an integer or string that repr... | [
"def",
"getComic",
"(",
"number",
",",
"silent",
"=",
"True",
")",
":",
"numComics",
"=",
"getLatestComicNum",
"(",
")",
"if",
"type",
"(",
"number",
")",
"is",
"str",
"and",
"number",
".",
"isdigit",
"(",
")",
":",
"number",
"=",
"int",
"(",
"number... | 41.272727 | 24.954545 |
def max_lemma_count(ambiguous_word: str) -> "wn.Synset":
"""
Returns the sense with the highest lemma_name count.
The max_lemma_count() can be treated as a rough gauge for the
Most Frequent Sense (MFS), if no other sense annotated corpus is available.
NOTE: The lemma counts are from the Brown Corpus... | [
"def",
"max_lemma_count",
"(",
"ambiguous_word",
":",
"str",
")",
"->",
"\"wn.Synset\"",
":",
"sense2lemmacounts",
"=",
"{",
"}",
"for",
"i",
"in",
"wn",
".",
"synsets",
"(",
"ambiguous_word",
",",
"pos",
"=",
"None",
")",
":",
"sense2lemmacounts",
"[",
"i... | 44.142857 | 16.571429 |
def add(self, snapshot, distributions, component='main', storage=""):
""" Add mirror or repo to publish """
for dist in distributions:
self.publish(dist, storage=storage).add(snapshot, component) | [
"def",
"add",
"(",
"self",
",",
"snapshot",
",",
"distributions",
",",
"component",
"=",
"'main'",
",",
"storage",
"=",
"\"\"",
")",
":",
"for",
"dist",
"in",
"distributions",
":",
"self",
".",
"publish",
"(",
"dist",
",",
"storage",
"=",
"storage",
")... | 55 | 16.75 |
def to_string(self):
'''
API: to_string(self)
Description:
This method is based on pydot Graph class with the same name.
Returns a string representation of the graph in dot language.
It will return the graph and all its subelements in string form.
Return:
... | [
"def",
"to_string",
"(",
"self",
")",
":",
"graph",
"=",
"list",
"(",
")",
"processed_edges",
"=",
"{",
"}",
"graph",
".",
"append",
"(",
"'%s %s {\\n'",
"%",
"(",
"self",
".",
"graph_type",
",",
"self",
".",
"name",
")",
")",
"for",
"a",
"in",
"se... | 39.681818 | 13.984848 |
def load(self, data):
"""
Load an image that was previously saved using
:py:meth:`~docker.models.images.Image.save` (or ``docker save``).
Similar to ``docker load``.
Args:
data (binary): Image data to be loaded.
Returns:
(list of :py:class:`Image... | [
"def",
"load",
"(",
"self",
",",
"data",
")",
":",
"resp",
"=",
"self",
".",
"client",
".",
"api",
".",
"load_image",
"(",
"data",
")",
"images",
"=",
"[",
"]",
"for",
"chunk",
"in",
"resp",
":",
"if",
"'stream'",
"in",
"chunk",
":",
"match",
"="... | 31 | 16.032258 |
def view_sbo(self):
"""View slackbuild.org
"""
sbo_url = self.sbo_url.replace("/slackbuilds/", "/repository/")
br1, br2, fix_sp = "", "", " "
if self.meta.use_colors in ["off", "OFF"]:
br1 = "("
br2 = ")"
fix_sp = ""
print("") # new l... | [
"def",
"view_sbo",
"(",
"self",
")",
":",
"sbo_url",
"=",
"self",
".",
"sbo_url",
".",
"replace",
"(",
"\"/slackbuilds/\"",
",",
"\"/repository/\"",
")",
"br1",
",",
"br2",
",",
"fix_sp",
"=",
"\"\"",
",",
"\"\"",
",",
"\" \"",
"if",
"self",
".",
"meta... | 53.716981 | 21.962264 |
def yaml_to_dict(yaml_str=None, str_or_buffer=None, ordered=False):
"""
Load YAML from a string, file, or buffer (an object with a .read method).
Parameters are mutually exclusive.
Parameters
----------
yaml_str : str, optional
A string of YAML.
str_or_buffer : str or file like, opt... | [
"def",
"yaml_to_dict",
"(",
"yaml_str",
"=",
"None",
",",
"str_or_buffer",
"=",
"None",
",",
"ordered",
"=",
"False",
")",
":",
"if",
"not",
"yaml_str",
"and",
"not",
"str_or_buffer",
":",
"raise",
"ValueError",
"(",
"'One of yaml_str or str_or_buffer is required.... | 25.184211 | 19.552632 |
def handle(self):
"The actual service to which the user has connected."
if self.TELNET_ISSUE:
self.writeline(self.TELNET_ISSUE)
if not self.authentication_ok():
return
if self.DOECHO:
self.writeline(self.WELCOME)
self.session_start()
w... | [
"def",
"handle",
"(",
"self",
")",
":",
"if",
"self",
".",
"TELNET_ISSUE",
":",
"self",
".",
"writeline",
"(",
"self",
".",
"TELNET_ISSUE",
")",
"if",
"not",
"self",
".",
"authentication_ok",
"(",
")",
":",
"return",
"if",
"self",
".",
"DOECHO",
":",
... | 38.821429 | 13.535714 |
def _getPayload(self, record):
"""
The data that will be sent to loggly.
"""
payload = super(LogglyHandler, self)._getPayload(record)
payload['tags'] = self._implodeTags()
return payload | [
"def",
"_getPayload",
"(",
"self",
",",
"record",
")",
":",
"payload",
"=",
"super",
"(",
"LogglyHandler",
",",
"self",
")",
".",
"_getPayload",
"(",
"record",
")",
"payload",
"[",
"'tags'",
"]",
"=",
"self",
".",
"_implodeTags",
"(",
")",
"return",
"p... | 28.5 | 12.75 |
def check_status_code(response, codes=None):
"""
Checks response.status_code is in codes.
:param requests.request response: Requests response
:param list codes: List of accepted codes or callable
:raises: StatusCodeError if code invalid
"""
codes = codes or [200]
if response.status_code... | [
"def",
"check_status_code",
"(",
"response",
",",
"codes",
"=",
"None",
")",
":",
"codes",
"=",
"codes",
"or",
"[",
"200",
"]",
"if",
"response",
".",
"status_code",
"not",
"in",
"codes",
":",
"raise",
"StatusCodeError",
"(",
"response",
".",
"status_code"... | 34.181818 | 10 |
def from_json(cls, data):
"""Create an analysis period from a dictionary.
Args:
data: {
st_month: An integer between 1-12 for starting month (default = 1)
st_day: An integer between 1-31 for starting day (default = 1).
Note that some months are sho... | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"keys",
"=",
"(",
"'st_month'",
",",
"'st_day'",
",",
"'st_hour'",
",",
"'end_month'",
",",
"'end_day'",
",",
"'end_hour'",
",",
"'timestep'",
",",
"'is_leap_year'",
")",
"for",
"key",
"in",
"keys",
... | 48.92 | 24.76 |
def tbframes(tb):
'unwind traceback tb_next structure to array'
frames=[tb.tb_frame]
while tb.tb_next: tb=tb.tb_next; frames.append(tb.tb_frame)
return frames | [
"def",
"tbframes",
"(",
"tb",
")",
":",
"frames",
"=",
"[",
"tb",
".",
"tb_frame",
"]",
"while",
"tb",
".",
"tb_next",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"frames",
".",
"append",
"(",
"tb",
".",
"tb_frame",
")",
"return",
"frames"
] | 32.4 | 18.8 |
def set_default_property_values(self, dev_class, class_prop, dev_prop):
"""
set_default_property_values(self, dev_class, class_prop, dev_prop) -> None
Sets the default property values
Parameters :
- dev_class : (DeviceClass) device class object
... | [
"def",
"set_default_property_values",
"(",
"self",
",",
"dev_class",
",",
"class_prop",
",",
"dev_prop",
")",
":",
"for",
"name",
"in",
"class_prop",
":",
"type",
"=",
"self",
".",
"get_property_type",
"(",
"name",
",",
"class_prop",
")",
"val",
"=",
"self",... | 42 | 20.153846 |
def db_snapshot_append(cls, cur, block_id, consensus_hash, ops_hash, timestamp):
"""
Append hash info for the last block processed, and the time at which it was done.
Meant to be executed as part of a transaction.
Return True on success
Raise an exception on invalid block number... | [
"def",
"db_snapshot_append",
"(",
"cls",
",",
"cur",
",",
"block_id",
",",
"consensus_hash",
",",
"ops_hash",
",",
"timestamp",
")",
":",
"query",
"=",
"'INSERT INTO snapshots (block_id,consensus_hash,ops_hash,timestamp) VALUES (?,?,?,?);'",
"args",
"=",
"(",
"block_id",
... | 39.466667 | 23.333333 |
def _methodcall(self, methodname, objectname, Params=None, **params):
"""
Perform an extrinsic CIM-XML method call.
Parameters:
methodname (string): CIM method name.
objectname (string or CIMInstanceName or CIMClassName):
Target object. Strings are interpreted ... | [
"def",
"_methodcall",
"(",
"self",
",",
"methodname",
",",
"objectname",
",",
"Params",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"if",
"isinstance",
"(",
"objectname",
",",
"(",
"CIMInstanceName",
",",
"CIMClassName",
")",
")",
":",
"localobject",
... | 38.662745 | 18.521569 |
def convolve(image, pixel_filter, channels=3, name=None):
"""Perform a 2D pixel convolution on the given image.
Arguments:
image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,
where `channels` is the third argument to this function and the
first two dimensions are arbitrary.
pix... | [
"def",
"convolve",
"(",
"image",
",",
"pixel_filter",
",",
"channels",
"=",
"3",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'convolve'",
")",
":",
"tf",
".",
"compat",
".",
"v1",
".",
"assert_type",
"(",
... | 46.413793 | 19.034483 |
def filter_graph(g, cutoff=7.0, min_kihs=2):
""" Get subgraph formed from edges that have max_kh_distance < cutoff.
Parameters
----------
g : MultiDiGraph representing KIHs
g is the output from graph_from_protein
cutoff : float
Socket cutoff in Angstroms.... | [
"def",
"filter_graph",
"(",
"g",
",",
"cutoff",
"=",
"7.0",
",",
"min_kihs",
"=",
"2",
")",
":",
"edge_list",
"=",
"[",
"e",
"for",
"e",
"in",
"g",
".",
"edges",
"(",
"keys",
"=",
"True",
",",
"data",
"=",
"True",
")",
"if",
"e",
"[",
"3",
"]... | 44.56 | 24.28 |
def look(self):
"""Look at the next token."""
old_token = next(self)
result = self.current
self.push(result)
self.current = old_token
return result | [
"def",
"look",
"(",
"self",
")",
":",
"old_token",
"=",
"next",
"(",
"self",
")",
"result",
"=",
"self",
".",
"current",
"self",
".",
"push",
"(",
"result",
")",
"self",
".",
"current",
"=",
"old_token",
"return",
"result"
] | 27 | 12.571429 |
def cashdraw(self, pin):
""" Send pulse to kick the cash drawer """
if pin == 2:
self._raw(CD_KICK_2)
elif pin == 5:
self._raw(CD_KICK_5)
else:
raise CashDrawerError() | [
"def",
"cashdraw",
"(",
"self",
",",
"pin",
")",
":",
"if",
"pin",
"==",
"2",
":",
"self",
".",
"_raw",
"(",
"CD_KICK_2",
")",
"elif",
"pin",
"==",
"5",
":",
"self",
".",
"_raw",
"(",
"CD_KICK_5",
")",
"else",
":",
"raise",
"CashDrawerError",
"(",
... | 28.5 | 12.75 |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the enclave.
"""
if remo... | [
"def",
"to_dict",
"(",
"self",
",",
"remove_nones",
"=",
"False",
")",
":",
"if",
"remove_nones",
":",
"return",
"super",
"(",
")",
".",
"to_dict",
"(",
"remove_nones",
"=",
"True",
")",
"return",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'name'",
"... | 30.25 | 22.375 |
def covariance(x,
y=None,
sample_axis=0,
event_axis=-1,
keepdims=False,
name=None):
"""Sample covariance between observations indexed by `event_axis`.
Given `N` samples of scalar random variables `X` and `Y`, covariance may be
estimated a... | [
"def",
"covariance",
"(",
"x",
",",
"y",
"=",
"None",
",",
"sample_axis",
"=",
"0",
",",
"event_axis",
"=",
"-",
"1",
",",
"keepdims",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(... | 40.972067 | 22.944134 |
def write(self, data):
"""Sends some data to the client."""
# I don't want to add a separate 'Client disconnected' logic for sending.
# Therefore I just ignore any writes after the first error - the server
# won't send that much data anyway. Afterwards the read will detect the
# ... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"# I don't want to add a separate 'Client disconnected' logic for sending.",
"# Therefore I just ignore any writes after the first error - the server",
"# won't send that much data anyway. Afterwards the read will detect the",
"# broken conne... | 43.214286 | 17.5 |
def population_counts(
self,
population_size,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
):
"""Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values... | [
"def",
"population_counts",
"(",
"self",
",",
"population_size",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
")",
":",
"population_counts",
"=",
"[",
"sli... | 31.931818 | 18.727273 |
def _cleanJsbAllClassesSection(self, config):
"""
Fixes two issues with the sencha created JSB:
- All extjs urls are prefixed by ``../static`` instead of
``/static`` (no idea why).
- We assume static files are served at ``/static``, but collectstatic may
... | [
"def",
"_cleanJsbAllClassesSection",
"(",
"self",
",",
"config",
")",
":",
"allclasses",
"=",
"config",
"[",
"'builds'",
"]",
"[",
"0",
"]",
"for",
"fileinfo",
"in",
"allclasses",
"[",
"'files'",
"]",
":",
"path",
"=",
"fileinfo",
"[",
"'path'",
"]",
"if... | 43.529412 | 14.235294 |
def parse(name, content, releases, get_head_fn):
"""
Parses the given content for a valid changelog
:param name: str, package name
:param content: str, content
:param releases: list, releases
:param get_head_fn: function
:return: dict, changelog
"""
changelog = {}
releases = froz... | [
"def",
"parse",
"(",
"name",
",",
"content",
",",
"releases",
",",
"get_head_fn",
")",
":",
"changelog",
"=",
"{",
"}",
"releases",
"=",
"frozenset",
"(",
"releases",
")",
"head",
"=",
"False",
"for",
"line",
"in",
"content",
".",
"splitlines",
"(",
")... | 29.916667 | 11.416667 |
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1
"""
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h/60%2 - 1))
m = l - c/2
if h<60:
r, g, b = c, x, 0
elif h<120:
r, g,... | [
"def",
"hsla_to_rgba",
"(",
"h",
",",
"s",
",",
"l",
",",
"a",
")",
":",
"h",
"=",
"h",
"%",
"360",
"s",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"1",
",",
"s",
")",
")",
"l",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"1",
",",
"l",
")",
... | 20.074074 | 20.851852 |
def get_instance(self, payload):
"""
Build an instance of DomainInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.DomainInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.DomainInstance
"""
retu... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"DomainInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | 39.7 | 23.1 |
async def connection_exists(ssid: str) -> Optional[str]:
""" If there is already a connection for this ssid, return the name of
the connection; if there is not, return None.
"""
nmcli_conns = await connections()
for wifi in [c['name']
for c in nmcli_conns if c['type'] == 'wireless']... | [
"async",
"def",
"connection_exists",
"(",
"ssid",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"nmcli_conns",
"=",
"await",
"connections",
"(",
")",
"for",
"wifi",
"in",
"[",
"c",
"[",
"'name'",
"]",
"for",
"c",
"in",
"nmcli_conns",
"if",
... | 41.923077 | 13.538462 |
def cumulative_statistics(self):
"""
Access the cumulative_statistics
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStat... | [
"def",
"cumulative_statistics",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cumulative_statistics",
"is",
"None",
":",
"self",
".",
"_cumulative_statistics",
"=",
"WorkersCumulativeStatisticsList",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
"... | 46.461538 | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.