text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def device_info(soapy_args=''):
"""Returns info about selected SoapySDR device"""
text = []
try:
device = simplesoapy.SoapyDevice(soapy_args)
text.append('Selected device: {}'.format(device.hardware))
text.append(' Available RX channels:')
text.append(' {}'.format(', '.jo... | [
"def",
"device_info",
"(",
"soapy_args",
"=",
"''",
")",
":",
"text",
"=",
"[",
"]",
"try",
":",
"device",
"=",
"simplesoapy",
".",
"SoapyDevice",
"(",
"soapy_args",
")",
"text",
".",
"append",
"(",
"'Selected device: {}'",
".",
"format",
"(",
"device",
... | 49.489362 | 20.574468 |
def output_sizes(self):
"""Returns a tuple of all output sizes of all the layers."""
return tuple([l() if callable(l) else l for l in self._output_sizes]) | [
"def",
"output_sizes",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"[",
"l",
"(",
")",
"if",
"callable",
"(",
"l",
")",
"else",
"l",
"for",
"l",
"in",
"self",
".",
"_output_sizes",
"]",
")"
] | 53.333333 | 16.666667 |
def prior(self, samples):
"""priori distribution
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
Retu... | [
"def",
"prior",
"(",
"self",
",",
"samples",
")",
":",
"ret",
"=",
"np",
".",
"ones",
"(",
"NUM_OF_INSTANCE",
")",
"for",
"i",
"in",
"range",
"(",
"NUM_OF_INSTANCE",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"effective_model_num",
")",
"... | 32.545455 | 20.045455 |
def iterable(item):
"""generate iterable from item, but leaves out strings
"""
if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
return item
else:
return [item] | [
"def",
"iterable",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"return",
"item",
"else",
":",
"return",
"[",
"item",
"]"
] | 27.875 | 21.5 |
def remove_info_file():
"""Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised.
"""
try:
os.unlink(_get_info_file_path())
except OSError as e:
if e.errno == errno.ENOENT:
# The user may have wiped their temporary... | [
"def",
"remove_info_file",
"(",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"_get_info_file_path",
"(",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"# The user may have wiped their temporary ... | 31.214286 | 21.928571 |
def display_start(self):
"""Set up status display if option selected. NB: this method
assumes that the first entry is the iteration count and the last
is the rho value.
"""
if self.opt['Verbose']:
# If AutoRho option enabled rho is included in iteration status
... | [
"def",
"display_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Verbose'",
"]",
":",
"# If AutoRho option enabled rho is included in iteration status",
"if",
"self",
".",
"opt",
"[",
"'AutoRho'",
",",
"'Enabled'",
"]",
":",
"hdrtxt",
"=",
"type",... | 38.782609 | 17 |
def _onActivateItem(self, index):
'''Handle activation of item in listing.'''
item = self._filesystemWidget.model().item(index)
if not isinstance(item, riffle.model.File):
self._acceptButton.setDisabled(True)
self.setLocation(item.path, interactive=True) | [
"def",
"_onActivateItem",
"(",
"self",
",",
"index",
")",
":",
"item",
"=",
"self",
".",
"_filesystemWidget",
".",
"model",
"(",
")",
".",
"item",
"(",
"index",
")",
"if",
"not",
"isinstance",
"(",
"item",
",",
"riffle",
".",
"model",
".",
"File",
")... | 49.5 | 11.833333 |
def get_search_regex(query, ignore_case=True):
"""Returns a compiled regex pattern to search for query letters in order.
Parameters
----------
query : str
String to search in another string (in order of character occurrence).
ignore_case : True
Optional value perform a case insensit... | [
"def",
"get_search_regex",
"(",
"query",
",",
"ignore_case",
"=",
"True",
")",
":",
"regex_text",
"=",
"[",
"char",
"for",
"char",
"in",
"query",
"if",
"char",
"!=",
"' '",
"]",
"regex_text",
"=",
"'.*'",
".",
"join",
"(",
"regex_text",
")",
"regex",
"... | 26.1 | 23.233333 |
def query(cls, volume=None, state=None, offset=None,
limit=None, api=None):
"""
Query (List) exports.
:param volume: Optional volume identifier.
:param state: Optional import sate.
:param api: Api instance.
:return: Collection object.
"""
ap... | [
"def",
"query",
"(",
"cls",
",",
"volume",
"=",
"None",
",",
"state",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"or",
"cls",
".",
"_API",
"if",
"volume",
":",
"volu... | 29.947368 | 15.210526 |
def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > sel... | [
"def",
"_does_require_deprecation",
"(",
"self",
")",
":",
"for",
"index",
",",
"version_number",
"in",
"enumerate",
"(",
"self",
".",
"current_version",
"[",
"0",
"]",
"[",
":",
"2",
"]",
")",
":",
"# We loop through the 2 last elements of the version.",
"if",
... | 35.235294 | 23.235294 |
def create_default_policies(self):
'''**Description**
Create a set of default policies using the current system falco rules file as a reference. For every falco rule in the system
falco rules file, one policy will be created. The policy will take the name and description from the name an... | [
"def",
"create_default_policies",
"(",
"self",
")",
":",
"res",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
"+",
"'/api/policies/createDefault'",
",",
"headers",
"=",
"self",
".",
"hdrs",
",",
"verify",
"=",
"self",
".",
"ssl_verify",
")",
"retu... | 51.052632 | 40.526316 |
def delete_event(self, calendar_id, event_id):
"""Delete an event from the specified calendar.
:param string calendar_id: ID of calendar to delete from.
:param string event_id: ID of event to delete.
"""
self.request_handler.delete(endpoint='calendars/%s/events' % calendar_id, d... | [
"def",
"delete_event",
"(",
"self",
",",
"calendar_id",
",",
"event_id",
")",
":",
"self",
".",
"request_handler",
".",
"delete",
"(",
"endpoint",
"=",
"'calendars/%s/events'",
"%",
"calendar_id",
",",
"data",
"=",
"{",
"'event_id'",
":",
"event_id",
"}",
")... | 48.714286 | 22.142857 |
def upload(ui, repo, name, **opts):
"""upload diffs to the code review server
Uploads the current modifications for a given change to the server.
"""
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
repo.ui.quiet = True
cl, err = LoadCL(ui, repo, name, web=True)
if err != "":
raise hg_util.... | [
"def",
"upload",
"(",
"ui",
",",
"repo",
",",
"name",
",",
"*",
"*",
"opts",
")",
":",
"if",
"codereview_disabled",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"codereview_disabled",
")",
"repo",
".",
"ui",
".",
"quiet",
"=",
"True",
"cl",
",",
"err"... | 27.294118 | 16.823529 |
def smart_open(filename_or_file, *args, **kwargs):
'''
This context manager allows you to open a filename, if you want to default
some already-existing file object, like sys.stdout, which shouldn't be
closed at the end of the context. If the filename argument is a str, bytes,
or int, the file object... | [
"def",
"smart_open",
"(",
"filename_or_file",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"filename_or_file",
",",
"(",
"str",
",",
"bytes",
",",
"int",
")",
")",
":",
"with",
"open",
"(",
"filename_or_file",
",",
"*",... | 49.227273 | 24.409091 |
def OpenEnumerateInstancePaths(self, ClassName, namespace=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
# pylint: disable=inval... | [
"def",
"OpenEnumerateInstancePaths",
"(",
"self",
",",
"ClassName",
",",
"namespace",
"=",
"None",
",",
"FilterQueryLanguage",
"=",
"None",
",",
"FilterQuery",
"=",
"None",
",",
"OperationTimeout",
"=",
"None",
",",
"ContinueOnError",
"=",
"None",
",",
"MaxObjec... | 45.0131 | 24.078603 |
def _pad_bytes_new(name, length):
"""
Takes a bytes instance and pads it with null bytes until it's length chars.
"""
if isinstance(name, str):
name = bytes(name, 'utf-8')
return name + b'\x00' * (length - len(name)) | [
"def",
"_pad_bytes_new",
"(",
"name",
",",
"length",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"name",
"=",
"bytes",
"(",
"name",
",",
"'utf-8'",
")",
"return",
"name",
"+",
"b'\\x00'",
"*",
"(",
"length",
"-",
"len",
"(",
"n... | 34 | 10 |
def _authenticate_https(org):
"""Try authenticating via HTTPS, if succesful yields User, otherwise raises Error."""
_CREDENTIAL_SOCKET.parent.mkdir(mode=0o700, exist_ok=True)
try:
Git.cache = f"-c credential.helper= -c credential.helper='cache --socket {_CREDENTIAL_SOCKET}'"
git = Git(Git.ca... | [
"def",
"_authenticate_https",
"(",
"org",
")",
":",
"_CREDENTIAL_SOCKET",
".",
"parent",
".",
"mkdir",
"(",
"mode",
"=",
"0o700",
",",
"exist_ok",
"=",
"True",
")",
"try",
":",
"Git",
".",
"cache",
"=",
"f\"-c credential.helper= -c credential.helper='cache --socke... | 46.266667 | 23.95 |
def auto_override_module(md, force_recursive = False):
"""Works like auto_override, but is only applicable to modules (by explicit call).
md must be a module or a module name contained in sys.modules.
"""
if not pytypes.checking_enabled:
return md
if isinstance(md, str):
if md in sys... | [
"def",
"auto_override_module",
"(",
"md",
",",
"force_recursive",
"=",
"False",
")",
":",
"if",
"not",
"pytypes",
".",
"checking_enabled",
":",
"return",
"md",
"if",
"isinstance",
"(",
"md",
",",
"str",
")",
":",
"if",
"md",
"in",
"sys",
".",
"modules",
... | 47.351351 | 18.567568 |
def contains_point(self, x, y):
"""
:param x: x coordinate of a point
:param y: y coordinate of a point
:returns: True if the point (x, y) is on the curve, False otherwise
"""
if x is None and y is None:
return True
return (y * y - (x * x * x + self._a... | [
"def",
"contains_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"x",
"is",
"None",
"and",
"y",
"is",
"None",
":",
"return",
"True",
"return",
"(",
"y",
"*",
"y",
"-",
"(",
"x",
"*",
"x",
"*",
"x",
"+",
"self",
".",
"_a",
"*",
"x",... | 38.111111 | 11.444444 |
def get(self, max_lines=None):
"""Returns a big list of all log lines since the last run
"""
rows = []
self.get_fn(lambda row: rows.append(row), max_lines=max_lines)
return rows | [
"def",
"get",
"(",
"self",
",",
"max_lines",
"=",
"None",
")",
":",
"rows",
"=",
"[",
"]",
"self",
".",
"get_fn",
"(",
"lambda",
"row",
":",
"rows",
".",
"append",
"(",
"row",
")",
",",
"max_lines",
"=",
"max_lines",
")",
"return",
"rows"
] | 26.5 | 20.5 |
def set_inode(self, ino):
# type: (inode.Inode) -> None
'''
A method to set the Inode associated with this El Torito Entry.
Parameters:
ino - The Inode object corresponding to this entry.
Returns:
Nothing.
'''
if not self._initialized:
... | [
"def",
"set_inode",
"(",
"self",
",",
"ino",
")",
":",
"# type: (inode.Inode) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'El Torito Entry not yet initialized'",
")",
"self",
".",
"inode",
... | 32.153846 | 24 |
def create_postgresql_psycopg2cffi(self, **kwargs):
"""
:rtype: Engine
"""
return self._ce(
self._ccs(self.DialectAndDriver.psql_psycopg2cffi), **kwargs
) | [
"def",
"create_postgresql_psycopg2cffi",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_ce",
"(",
"self",
".",
"_ccs",
"(",
"self",
".",
"DialectAndDriver",
".",
"psql_psycopg2cffi",
")",
",",
"*",
"*",
"kwargs",
")"
] | 28.571429 | 15.428571 |
def require_valid_type(value, *classes):
"""
Checks that the specified object reference is instance of classes and
throws a :py:class:`TypeError` if it is not.
:param value: The object.
:type value: object
:param classes: The classes.
:type classes: list(class)
"""
if value is not ... | [
"def",
"require_valid_type",
"(",
"value",
",",
"*",
"classes",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"valid",
"=",
"False",
"for",
"auxiliar_class",
"in",
"classes",
":",
"if",
"isinstance",
"(",
"value",
",",
"auxiliar_class",
")",
":",
"v... | 27.421053 | 14.368421 |
def multiply(multiplicand: list, multiplier: list) -> list:
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
multiplicand_row, multiplicand_col = len(
multiplicand), len(multiplicand[0])
multiplier_row, multiplier_col = len(multiplier), len(multiplier... | [
"def",
"multiply",
"(",
"multiplicand",
":",
"list",
",",
"multiplier",
":",
"list",
")",
"->",
"list",
":",
"multiplicand_row",
",",
"multiplicand_col",
"=",
"len",
"(",
"multiplicand",
")",
",",
"len",
"(",
"multiplicand",
"[",
"0",
"]",
")",
"multiplier... | 39.894737 | 13.052632 |
def _construct_output_to_match(output_block):
"""Transform a ConstructResult block into a MATCH query string."""
output_block.validate()
selections = (
u'%s AS `%s`' % (output_block.fields[key].to_match(), key)
for key in sorted(output_block.fields.keys()) # Sort keys for deterministic out... | [
"def",
"_construct_output_to_match",
"(",
"output_block",
")",
":",
"output_block",
".",
"validate",
"(",
")",
"selections",
"=",
"(",
"u'%s AS `%s`'",
"%",
"(",
"output_block",
".",
"fields",
"[",
"key",
"]",
".",
"to_match",
"(",
")",
",",
"key",
")",
"f... | 38.5 | 25.5 |
def deployments(namespace='default', **kwargs):
'''
Return a list of kubernetes deployments defined in the namespace
CLI Examples::
salt '*' kubernetes.deployments
salt '*' kubernetes.deployments namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kube... | [
"def",
"deployments",
"(",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"_setup_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"api_instance",
"=",
"kubernetes",
".",
"client",
".",
"ExtensionsV1beta1Api",
"(",
")",
"ap... | 33.576923 | 22.807692 |
def sanitize_line(txt: str) -> str:
"""
Fixes common mistakes with 'new line' signifiers so that they can be recognized
"""
for key in LINE_FIXES:
index = txt.find(key)
if index > -1:
txt = txt[:index] + LINE_FIXES[key] + txt[index + len(key):]
# Fix when space is missing... | [
"def",
"sanitize_line",
"(",
"txt",
":",
"str",
")",
"->",
"str",
":",
"for",
"key",
"in",
"LINE_FIXES",
":",
"index",
"=",
"txt",
".",
"find",
"(",
"key",
")",
"if",
"index",
">",
"-",
"1",
":",
"txt",
"=",
"txt",
"[",
":",
"index",
"]",
"+",
... | 38.214286 | 14.214286 |
def print_list(cls, l, output='table'):
"""
prints a list
:param l: the list
:param output: the output, default is a table
:return:
"""
def dict_from_list(l):
"""
returns a dict from a list for printing
:param l: the list
... | [
"def",
"print_list",
"(",
"cls",
",",
"l",
",",
"output",
"=",
"'table'",
")",
":",
"def",
"dict_from_list",
"(",
"l",
")",
":",
"\"\"\"\n returns a dict from a list for printing\n :param l: the list\n :return: \n \"\"\"",
"d",
"=",... | 29.282051 | 12.153846 |
def group(text, size):
"""Group ``text`` into blocks of ``size``.
Example:
>>> group("test", 2)
['te', 'st']
Args:
text (str): text to separate
size (int): size of groups to split the text into
Returns:
List of n-sized groups of text
Raises:
ValueE... | [
"def",
"group",
"(",
"text",
",",
"size",
")",
":",
"if",
"size",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"n must be a positive integer\"",
")",
"return",
"[",
"text",
"[",
"i",
":",
"i",
"+",
"size",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
... | 22.619048 | 21.52381 |
def convert_to_sympy_matrix(expr, full_space=None):
"""Convert a QNET expression to an explicit ``n x n`` instance of
`sympy.Matrix`, where ``n`` is the dimension of `full_space`. The entries
of the matrix may contain symbols.
Parameters:
expr: a QNET expression
full_space (qnet.algebra... | [
"def",
"convert_to_sympy_matrix",
"(",
"expr",
",",
"full_space",
"=",
"None",
")",
":",
"if",
"full_space",
"is",
"None",
":",
"full_space",
"=",
"expr",
".",
"space",
"if",
"not",
"expr",
".",
"space",
".",
"is_tensor_factor_of",
"(",
"full_space",
")",
... | 44.122807 | 15.192982 |
def get_smart_data():
"""
Get SMART attribute data
:return: list of multi leveled dictionaries
each dict has a key "DeviceName" with the identification of the device in smartctl
also has keys of the SMART attribute id, with value of another dict of the attributes
[
... | [
"def",
"get_smart_data",
"(",
")",
":",
"stats",
"=",
"[",
"]",
"# get all devices",
"devlist",
"=",
"DeviceList",
"(",
")",
"for",
"dev",
"in",
"devlist",
".",
"devices",
":",
"stats",
".",
"append",
"(",
"{",
"DEVKEY",
":",
"str",
"(",
"dev",
")",
... | 31.5 | 19.595238 |
def get_redshift(self, dist):
"""Returns the redshift for the given distance.
"""
dist, input_is_array = ensurearray(dist)
try:
zs = self.nearby_d2z(dist)
except TypeError:
# interpolant hasn't been setup yet
self.setup_interpolant()
... | [
"def",
"get_redshift",
"(",
"self",
",",
"dist",
")",
":",
"dist",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"dist",
")",
"try",
":",
"zs",
"=",
"self",
".",
"nearby_d2z",
"(",
"dist",
")",
"except",
"TypeError",
":",
"# interpolant hasn't been setup y... | 46.72 | 14.24 |
def get_supported_versions(self):
"""
Gets a list of supported U2F versions from the device.
"""
if not hasattr(self, '_versions'):
try:
self._versions = [self.send_apdu(INS_GET_VERSION).decode()]
except exc.APDUError as e:
# v0 did... | [
"def",
"get_supported_versions",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_versions'",
")",
":",
"try",
":",
"self",
".",
"_versions",
"=",
"[",
"self",
".",
"send_apdu",
"(",
"INS_GET_VERSION",
")",
".",
"decode",
"(",
")",
"... | 36.333333 | 15.166667 |
def _get_template_dict(template):
"""
Parse string template and or copy dictionary template.
:param template: Content of a packaged YAML or JSON SAM template
:type template: str_or_dict
:return: Template as a dictionary
:rtype: dict
:raises ValueError
"""
if isinstance(template, str... | [
"def",
"_get_template_dict",
"(",
"template",
")",
":",
"if",
"isinstance",
"(",
"template",
",",
"str",
")",
":",
"return",
"parse_template",
"(",
"template",
")",
"if",
"isinstance",
"(",
"template",
",",
"dict",
")",
":",
"return",
"copy",
".",
"deepcop... | 29.058824 | 16.117647 |
def copy_selection_access_string(self):
"""Copys access_string to selection to the clipboard
An access string is Python code to reference the selection
If there is no selection then a reference to the current cell is copied
"""
selection = self.get_selection()
if not s... | [
"def",
"copy_selection_access_string",
"(",
"self",
")",
":",
"selection",
"=",
"self",
".",
"get_selection",
"(",
")",
"if",
"not",
"selection",
":",
"cursor",
"=",
"self",
".",
"grid",
".",
"actions",
".",
"cursor",
"selection",
"=",
"Selection",
"(",
"[... | 38.461538 | 21.807692 |
def update_agent_state():
'''Update the current agent state in opencast.
'''
configure_service('capture.admin')
status = 'idle'
# Determine reported agent state with priority list
if get_service_status(db.Service.SCHEDULE) == db.ServiceStatus.STOPPED:
status = 'offline'
elif get_ser... | [
"def",
"update_agent_state",
"(",
")",
":",
"configure_service",
"(",
"'capture.admin'",
")",
"status",
"=",
"'idle'",
"# Determine reported agent state with priority list",
"if",
"get_service_status",
"(",
"db",
".",
"Service",
".",
"SCHEDULE",
")",
"==",
"db",
".",
... | 35.066667 | 21.6 |
def write(cls, filename, samples, write_params=None, static_args=None,
**metadata):
"""Writes the injection samples to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldAr... | [
"def",
"write",
"(",
"cls",
",",
"filename",
",",
"samples",
",",
"write_params",
"=",
"None",
",",
"static_args",
"=",
"None",
",",
"*",
"*",
"metadata",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"# ... | 40.757576 | 12.969697 |
def ris(self):
"""Bibliographic entry in RIS (Research Information System Format)
format.
Returns
-------
ris : str
The RIS string representing an item.
Raises
------
ValueError : If the item's aggregationType is not Journal.
"""
... | [
"def",
"ris",
"(",
"self",
")",
":",
"if",
"self",
".",
"aggregationType",
"!=",
"'Journal'",
":",
"raise",
"ValueError",
"(",
"'Only Journal articles supported.'",
")",
"template",
"=",
"u'''TY - JOUR\nTI - {title}\nJO - {journal}\nVL - {volume}\nDA - {date}\nSP - {pag... | 28.971429 | 20.657143 |
def getActiveAxes(self):
"""Return a list of the selected axes."""
active = []
for i in range(len(self._axisId)):
if self._menu.IsChecked(self._axisId[i]):
active.append(i)
return active | [
"def",
"getActiveAxes",
"(",
"self",
")",
":",
"active",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_axisId",
")",
")",
":",
"if",
"self",
".",
"_menu",
".",
"IsChecked",
"(",
"self",
".",
"_axisId",
"[",
"i",
"]",
... | 34.285714 | 11.285714 |
def _prepare_arguments(self, argv):
"""Prepares arguments by:
- removing placeholder and moving arguments after it to beginning,
we need this to distinguish arguments from `command` with ours;
- adding `--` before `command`, so our parse would ignore arguments
of `command`.... | [
"def",
"_prepare_arguments",
"(",
"self",
",",
"argv",
")",
":",
"if",
"ARGUMENT_PLACEHOLDER",
"in",
"argv",
":",
"index",
"=",
"argv",
".",
"index",
"(",
"ARGUMENT_PLACEHOLDER",
")",
"return",
"argv",
"[",
"index",
"+",
"1",
":",
"]",
"+",
"[",
"'--'",
... | 36.058824 | 21 |
def initialize(self, *args):
"""Initialize a recommender by resetting stored users and items.
"""
# number of observed users
self.n_user = 0
# store user data
self.users = {}
# number of observed items
self.n_item = 0
# store item data
s... | [
"def",
"initialize",
"(",
"self",
",",
"*",
"args",
")",
":",
"# number of observed users",
"self",
".",
"n_user",
"=",
"0",
"# store user data",
"self",
".",
"users",
"=",
"{",
"}",
"# number of observed items",
"self",
".",
"n_item",
"=",
"0",
"# store item ... | 22.928571 | 17.285714 |
def chi_eff(mass1, mass2, spin1z, spin2z):
"""Returns the effective spin from mass1, mass2, spin1z, and spin2z."""
return (spin1z * mass1 + spin2z * mass2) / (mass1 + mass2) | [
"def",
"chi_eff",
"(",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
")",
":",
"return",
"(",
"spin1z",
"*",
"mass1",
"+",
"spin2z",
"*",
"mass2",
")",
"/",
"(",
"mass1",
"+",
"mass2",
")"
] | 59.666667 | 8 |
def get_vnetwork_portgroups_input_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, "input")
... | [
"def",
"get_vnetwork_portgroups_input_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_portgroups",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_portgroups\"",
")",
"config",
"="... | 39.666667 | 11.916667 |
def buffer(self,
geometries,
inSR,
distances,
units,
outSR=None,
bufferSR=None,
unionResults=True,
geodesic=True
):
"""
The buffer operation is performed on a geometr... | [
"def",
"buffer",
"(",
"self",
",",
"geometries",
",",
"inSR",
",",
"distances",
",",
"units",
",",
"outSR",
"=",
"None",
",",
"bufferSR",
"=",
"None",
",",
"unionResults",
"=",
"True",
",",
"geodesic",
"=",
"True",
")",
":",
"url",
"=",
"self",
".",
... | 46.4 | 21.876923 |
def bucket_ops(bid, api=""):
"""Context manager for dealing with s3 errors in one place
bid: bucket_id in form of account_name:bucket_name
"""
try:
yield 42
except ClientError as e:
code = e.response['Error']['Code']
log.info(
"bucket error bucket:%s error:%s",
... | [
"def",
"bucket_ops",
"(",
"bid",
",",
"api",
"=",
"\"\"",
")",
":",
"try",
":",
"yield",
"42",
"except",
"ClientError",
"as",
"e",
":",
"code",
"=",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"log",
".",
"info",
"(",
"\"bucket e... | 29.413793 | 13.931034 |
def bind(self, __fun, *args, **kwargs):
"""
Bind a worker function to the future. This worker function will be
executed when the future is executed.
"""
with self._lock:
if self._running or self._completed or self._cancelled:
raise RuntimeError('Future object can not be reused')
... | [
"def",
"bind",
"(",
"self",
",",
"__fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_running",
"or",
"self",
".",
"_completed",
"or",
"self",
".",
"_cancelled",
":",
"raise",
"Runtim... | 35.769231 | 16.846154 |
def install_package(self, team, user, package, contents):
"""
Creates a new package in the default package store
and allocates a per-user directory if needed.
"""
self.check_name(team, user, package)
assert contents is not None
self.create_dirs()
path = s... | [
"def",
"install_package",
"(",
"self",
",",
"team",
",",
"user",
",",
"package",
",",
"contents",
")",
":",
"self",
".",
"check_name",
"(",
"team",
",",
"user",
",",
"package",
")",
"assert",
"contents",
"is",
"not",
"None",
"self",
".",
"create_dirs",
... | 28.8125 | 15.6875 |
def parallel_execute(self, cell, block=None, groupby='type', save_name=None):
"""implementation used by %px and %%parallel"""
# defaults:
block = self.view.block if block is None else block
base = "Parallel" if block else "Async parallel"
targets = self.view.ta... | [
"def",
"parallel_execute",
"(",
"self",
",",
"cell",
",",
"block",
"=",
"None",
",",
"groupby",
"=",
"'type'",
",",
"save_name",
"=",
"None",
")",
":",
"# defaults:",
"block",
"=",
"self",
".",
"view",
".",
"block",
"if",
"block",
"is",
"None",
"else",... | 35.107143 | 21.571429 |
def _infer_mutants_handler(self, request):
"""Returns JSON for the `vz-line-chart`s for a feature.
Args:
request: A request that should contain 'feature_name', 'example_index',
'inference_address', 'model_name', 'model_type', 'model_version', and
'model_signature'.
Returns:
A... | [
"def",
"_infer_mutants_handler",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"if",
"request",
".",
"method",
"!=",
"'GET'",
":",
"logger",
".",
"error",
"(",
"'%s requests are forbidden.'",
",",
"request",
".",
"method",
")",
"return",
"http_util",
".... | 43.510638 | 19.638298 |
def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data):
"""
this has to use the -o option, not redirect to stdout in order for
gzipping to be supported
"""
min_length = dd.get_min_read_length(data)
cmd = base_cmd + " --minimum-length={min_length} ".format(**locals())
fq1 = objectstore.... | [
"def",
"_cutadapt_se_cmd",
"(",
"fastq_files",
",",
"out_files",
",",
"base_cmd",
",",
"data",
")",
":",
"min_length",
"=",
"dd",
".",
"get_min_read_length",
"(",
"data",
")",
"cmd",
"=",
"base_cmd",
"+",
"\" --minimum-length={min_length} \"",
".",
"format",
"("... | 37.25 | 13.083333 |
def set(self, section, key, value):
"""
Creates the section value if it does not exists and sets the value.
Use write_config to actually set the value.
"""
if not section in self.config:
self.config.add_section(section)
self.config.set(section, key, va... | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"section",
"in",
"self",
".",
"config",
":",
"self",
".",
"config",
".",
"add_section",
"(",
"section",
")",
"self",
".",
"config",
".",
"set",
"(",
"sectio... | 39.625 | 8.625 |
def fetch(self):
"""
Fetch & return a new `Action` object representing the action's current
state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return api._action(api.request(self.url)["action"]) | [
"def",
"fetch",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"doapi_manager",
"return",
"api",
".",
"_action",
"(",
"api",
".",
"request",
"(",
"self",
".",
"url",
")",
"[",
"\"action\"",
"]",
")"
] | 31.1 | 20.3 |
def _parse_layer_info(list_of_layers, resources):
"""
Creates a list of Layer objects that are represented by the resources and the list of layers
Parameters
----------
list_of_layers List(str)
List of layers that are defined within the Layers Property on a function
... | [
"def",
"_parse_layer_info",
"(",
"list_of_layers",
",",
"resources",
")",
":",
"layers",
"=",
"[",
"]",
"for",
"layer",
"in",
"list_of_layers",
":",
"# If the layer is a string, assume it is the arn",
"if",
"isinstance",
"(",
"layer",
",",
"six",
".",
"string_types"... | 48.588235 | 31.294118 |
def rparents(self, level=-1, intermediate=True):
"""Create a recursive list of children.
Note that the :param:`intermediate` can be used to include every
parents to the returned list, not only the most nested ones.
Parameters:
level (int): The depth level to continue fetchi... | [
"def",
"rparents",
"(",
"self",
",",
"level",
"=",
"-",
"1",
",",
"intermediate",
"=",
"True",
")",
":",
"try",
":",
"return",
"self",
".",
"_rparents",
"[",
"(",
"level",
",",
"intermediate",
")",
"]",
"except",
"KeyError",
":",
"rparents",
"=",
"["... | 33.694444 | 23.805556 |
def singleton_init_by(init_fn=None):
"""
>>> from Redy.Magic.Classic import singleton
>>> @singleton
>>> class S:
>>> pass
>>> assert isinstance(S, S)
"""
if not init_fn:
def wrap_init(origin_init):
return origin_init
else:
def wrap_init(origin_init):... | [
"def",
"singleton_init_by",
"(",
"init_fn",
"=",
"None",
")",
":",
"if",
"not",
"init_fn",
":",
"def",
"wrap_init",
"(",
"origin_init",
")",
":",
"return",
"origin_init",
"else",
":",
"def",
"wrap_init",
"(",
"origin_init",
")",
":",
"def",
"__init__",
"("... | 27.441176 | 20.441176 |
def deserialize_dataframe(reader, data_type_id):
"""
Deserialize a dataframe.
Parameters
----------
reader : file
File-like object to read from. Must be opened in binary mode.
data_type_id : dict
Serialization format of the raw data.
See the azureml.DataTypeIds class for... | [
"def",
"deserialize_dataframe",
"(",
"reader",
",",
"data_type_id",
")",
":",
"_not_none",
"(",
"'reader'",
",",
"reader",
")",
"_not_none_or_empty",
"(",
"'data_type_id'",
",",
"data_type_id",
")",
"serializer",
"=",
"_SERIALIZERS",
".",
"get",
"(",
"data_type_id... | 26.875 | 18.041667 |
def close(self):
"""
Close the connection.
:param purge: If True (the default), the receive buffer will
be purged.
"""
# Close the underlying socket
if self._sock:
with utils.ignore_except():
self._sock.close()
... | [
"def",
"close",
"(",
"self",
")",
":",
"# Close the underlying socket",
"if",
"self",
".",
"_sock",
":",
"with",
"utils",
".",
"ignore_except",
"(",
")",
":",
"self",
".",
"_sock",
".",
"close",
"(",
")",
"self",
".",
"_sock",
"=",
"None",
"# Purge the m... | 24.882353 | 15 |
def delay_embedding(data, emb_dim, lag=1):
"""
Perform a time-delay embedding of a time series
Args:
data (array-like):
the data that should be embedded
emb_dim (int):
the embedding dimension
Kwargs:
lag (int):
the lag between elements in the embedded vectors
Returns:
emb_d... | [
"def",
"delay_embedding",
"(",
"data",
",",
"emb_dim",
",",
"lag",
"=",
"1",
")",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"min_len",
"=",
"(",
"emb_dim",
"-",
"1",
")",
"*",
"lag",
"+",
"1",
"if",
"len",
"(",
"data",
")",
"<",... | 31.862069 | 17.37931 |
def get_pres_features(self, features=None):
"""
Returns a df of features for presented items
"""
if features is None:
features = self.dist_funcs.keys()
elif not isinstance(features, list):
features = [features]
return self.pres.applymap(lambda x: {... | [
"def",
"get_pres_features",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"self",
".",
"dist_funcs",
".",
"keys",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"features",
",",
"list",
")",
":"... | 42.444444 | 13.111111 |
def add_tags(self, tags):
"""
Add tags to the comments
"""
if not isinstance(tags, list):
tags = [tags]
self._bugsy.request('bug/comment/%s/tags' % self._comment['id'],
method='PUT', json={"add": tags}) | [
"def",
"add_tags",
"(",
"self",
",",
"tags",
")",
":",
"if",
"not",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"self",
".",
"_bugsy",
".",
"request",
"(",
"'bug/comment/%s/tags'",
"%",
"self",
".",
"_comment",
"[... | 34.875 | 11.125 |
def p_declnamelist(self, p):
'declnamelist : declnamelist COMMA declname'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_declnamelist",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"3",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 36.25 | 9.75 |
def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
cert_path = os.environ.get('DOCKER_CERT_PATH', '')
if cert_path == '':
cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')... | [
"def",
"docker_client",
"(",
")",
":",
"cert_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DOCKER_CERT_PATH'",
",",
"''",
")",
"if",
"cert_path",
"==",
"''",
":",
"cert_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"."... | 33.03125 | 19.28125 |
def get_history(self, start, end):
"""返回历史成交
Arguments:
start {str} -- [description]
end {str]} -- [description]
"""
return self.history_table.set_index(
'datetime',
drop=False
).loc[slice(pd.Timestamp(start),
p... | [
"def",
"get_history",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"return",
"self",
".",
"history_table",
".",
"set_index",
"(",
"'datetime'",
",",
"drop",
"=",
"False",
")",
".",
"loc",
"[",
"slice",
"(",
"pd",
".",
"Timestamp",
"(",
"start",
"... | 27.25 | 9.083333 |
def apply_meta(self, arr, funcs):
"""
Apply metadata to help formatting the output:
- conv_funcs: convert data before column alignments
- deco_funcs: decorate data after column alignments
"""
if arr is None:
logging.error("unable to convert data: emtpy sectio... | [
"def",
"apply_meta",
"(",
"self",
",",
"arr",
",",
"funcs",
")",
":",
"if",
"arr",
"is",
"None",
":",
"logging",
".",
"error",
"(",
"\"unable to convert data: emtpy section\"",
")",
"return",
"None",
"tmp",
"=",
"np",
".",
"copy",
"(",
"arr",
")",
"for",... | 36.3 | 15.4 |
def render(self, **kwargs):
""" Plots the volume and the control points. """
# Calling parent function
super(VisVolume, self).render(**kwargs)
# Initialize variables
legend_proxy = []
legend_names = []
# Start plotting of the surface and the control points grid
... | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Calling parent function",
"super",
"(",
"VisVolume",
",",
"self",
")",
".",
"render",
"(",
"*",
"*",
"kwargs",
")",
"# Initialize variables",
"legend_proxy",
"=",
"[",
"]",
"legend_names",
... | 40.227848 | 23.594937 |
def salt_ssh_create_dirs(self):
"""
Creates the `salt-ssh` required directory structure
"""
logger.debug('Creating salt-ssh dirs into: %s', self.settings_dir)
utils.create_dir(os.path.join(self.settings_dir, 'salt'))
utils.create_dir(os.path.join(self.settings_dir, 'pilla... | [
"def",
"salt_ssh_create_dirs",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Creating salt-ssh dirs into: %s'",
",",
"self",
".",
"settings_dir",
")",
"utils",
".",
"create_dir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"settings_dir",
... | 55 | 22.6 |
def add_nodes(self, nodes): # noqa: D302
r"""
Add nodes to tree.
:param nodes: Node(s) to add with associated data. If there are
several list items in the argument with the same node
name the resulting node data is a list with items
... | [
"def",
"add_nodes",
"(",
"self",
",",
"nodes",
")",
":",
"# noqa: D302",
"self",
".",
"_validate_nodes_with_data",
"(",
"nodes",
")",
"nodes",
"=",
"nodes",
"if",
"isinstance",
"(",
"nodes",
",",
"list",
")",
"else",
"[",
"nodes",
"]",
"# Create root node (i... | 37.650602 | 21.204819 |
def read(self):
"""Read a Response, do some validation, and return it."""
if FLAGS.sc2_verbose_protocol:
self._log(" Reading response ".center(60, "-"))
start = time.time()
response = self._read()
if FLAGS.sc2_verbose_protocol:
self._log(" %0.1f msec\n" % (1000 * (time.time() - start))... | [
"def",
"read",
"(",
"self",
")",
":",
"if",
"FLAGS",
".",
"sc2_verbose_protocol",
":",
"self",
".",
"_log",
"(",
"\" Reading response \"",
".",
"center",
"(",
"60",
",",
"\"-\"",
")",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"response",
"=",
... | 43.15 | 16.2 |
def install(ctx, services, delete_after_install=False):
"""Install a honeypot service from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
... | [
"def",
"install",
"(",
"ctx",
",",
"services",
",",
"delete_after_install",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\... | 39.777778 | 20.222222 |
def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=... | [
"def",
"get_encodings_from_content",
"(",
"content",
")",
":",
"charset_re",
"=",
"re",
".",
"compile",
"(",
"r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]'",
",",
"flags",
"=",
"re",
".",
"I",
")",
"pragma_re",
"=",
"re",
".",
"compile",
"(",
"r'<meta.*?content=[\"\\']... | 38.384615 | 19.153846 |
def compute_key(cli, familly, discriminant=None):
"""This function is used to compute a unique key from all connection parametters."""
hash_key = hashlib.sha256()
hash_key.update(familly)
hash_key.update(cli.host)
hash_key.update(cli.user)
hash_key.update(cli.password)
if discriminant:
... | [
"def",
"compute_key",
"(",
"cli",
",",
"familly",
",",
"discriminant",
"=",
"None",
")",
":",
"hash_key",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"hash_key",
".",
"update",
"(",
"familly",
")",
"hash_key",
".",
"update",
"(",
"cli",
".",
"host",
")",
... | 38.190476 | 8.761905 |
def swo_supported_speeds(self, cpu_speed, num_speeds=3):
"""Retrives a list of SWO speeds supported by both the target and the
connected J-Link.
The supported speeds are returned in order from highest to lowest.
Args:
self (JLink): the ``JLink`` instance
cpu_speed (... | [
"def",
"swo_supported_speeds",
"(",
"self",
",",
"cpu_speed",
",",
"num_speeds",
"=",
"3",
")",
":",
"buf_size",
"=",
"num_speeds",
"buf",
"=",
"(",
"ctypes",
".",
"c_uint32",
"*",
"buf_size",
")",
"(",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINK... | 36.809524 | 21.952381 |
def display_name(self):
"""Readable name for the variant."""
if self.is_snv:
gene_ids = self.gene_symbols[:2]
return ', '.join(gene_ids)
else:
return "{this.cytoband_start} ({this.sv_len})".format(this=self) | [
"def",
"display_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_snv",
":",
"gene_ids",
"=",
"self",
".",
"gene_symbols",
"[",
":",
"2",
"]",
"return",
"', '",
".",
"join",
"(",
"gene_ids",
")",
"else",
":",
"return",
"\"{this.cytoband_start} ({this.sv... | 37.285714 | 14.714286 |
def add(self, constraint, check=False):
"""
Add a constraint to the set
:param constraint: The constraint to add to the set.
:param check: Currently unused.
:return:
"""
if isinstance(constraint, bool):
constraint = BoolConstant(constraint)
as... | [
"def",
"add",
"(",
"self",
",",
"constraint",
",",
"check",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"constraint",
",",
"bool",
")",
":",
"constraint",
"=",
"BoolConstant",
"(",
"constraint",
")",
"assert",
"isinstance",
"(",
"constraint",
",",
"... | 37.6875 | 16.125 |
def __headers(self):
"""
Get HTTP headers for a HTTP/HTTPS SOAP request.
@return: A dictionary of header/values.
@rtype: dict
"""
action = self.method.soap.action
if isinstance(action, unicode):
action = action.encode("utf-8")
result = {
... | [
"def",
"__headers",
"(",
"self",
")",
":",
"action",
"=",
"self",
".",
"method",
".",
"soap",
".",
"action",
"if",
"isinstance",
"(",
"action",
",",
"unicode",
")",
":",
"action",
"=",
"action",
".",
"encode",
"(",
"\"utf-8\"",
")",
"result",
"=",
"{... | 29.294118 | 12.588235 |
def check_levels(imls, imt, min_iml=1E-10):
"""
Raise a ValueError if the given levels are invalid.
:param imls: a list of intensity measure and levels
:param imt: the intensity measure type
:param min_iml: minimum intensity measure level (default 1E-10)
>>> check_levels([0.1, 0.2], 'PGA') # ... | [
"def",
"check_levels",
"(",
"imls",
",",
"imt",
",",
"min_iml",
"=",
"1E-10",
")",
":",
"if",
"len",
"(",
"imls",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'No imls for %s: %s'",
"%",
"(",
"imt",
",",
"imls",
")",
")",
"elif",
"imls",
"!=",
... | 39.969697 | 16.272727 |
def _do_connect(self):
""" Connect to the remote. """
self.load_system_host_keys()
if self.username is None or self.port is None:
self._configure()
try:
self.connect(hostname=self.hostname,
port=self.port,
username... | [
"def",
"_do_connect",
"(",
"self",
")",
":",
"self",
".",
"load_system_host_keys",
"(",
")",
"if",
"self",
".",
"username",
"is",
"None",
"or",
"self",
".",
"port",
"is",
"None",
":",
"self",
".",
"_configure",
"(",
")",
"try",
":",
"self",
".",
"con... | 40.7 | 15.6 |
def randomize_colors(im, keep_vals=[0]):
r'''
Takes a greyscale image and randomly shuffles the greyscale values, so that
all voxels labeled X will be labelled Y, and all voxels labeled Y will be
labeled Z, where X, Y, Z and so on are randomly selected from the values
in the input image.
This f... | [
"def",
"randomize_colors",
"(",
"im",
",",
"keep_vals",
"=",
"[",
"0",
"]",
")",
":",
"im_flat",
"=",
"im",
".",
"flatten",
"(",
")",
"keep_vals",
"=",
"sp",
".",
"array",
"(",
"keep_vals",
")",
"swap_vals",
"=",
"~",
"sp",
".",
"in1d",
"(",
"im_fl... | 31.787879 | 24.484848 |
def _emplace_transcript(transcripts, parent):
"""Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID')))
pt = transcripts.pop()
parent.children = [pt] | [
"def",
"_emplace_transcript",
"(",
"transcripts",
",",
"parent",
")",
":",
"transcripts",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"(",
"len",
"(",
"t",
")",
",",
"t",
".",
"get_attribute",
"(",
"'ID'",
")",
")",
")",
"pt",
"=",
"transcripts... | 45.8 | 12 |
def create(recipients, data, cipher, flags=0):
"""
Creates and encrypts message
@param recipients - list of X509 objects
@param data - contents of the message
@param cipher - CipherType object
@param flags - flag
"""
recp = StackOfX509(recipients)
... | [
"def",
"create",
"(",
"recipients",
",",
"data",
",",
"cipher",
",",
"flags",
"=",
"0",
")",
":",
"recp",
"=",
"StackOfX509",
"(",
"recipients",
")",
"bio",
"=",
"Membio",
"(",
"data",
")",
"cms_ptr",
"=",
"libcrypto",
".",
"CMS_encrypt",
"(",
"recp",
... | 37.533333 | 7.933333 |
def delete_location(self, location_name):
"""
Remove location with name location_name from self.locations.
If the location had any sites, change site.location to "".
"""
location = self.find_by_name(location_name, self.locations)
if not location:
return False
... | [
"def",
"delete_location",
"(",
"self",
",",
"location_name",
")",
":",
"location",
"=",
"self",
".",
"find_by_name",
"(",
"location_name",
",",
"self",
".",
"locations",
")",
"if",
"not",
"location",
":",
"return",
"False",
"sites",
"=",
"location",
".",
"... | 33.4 | 13.666667 |
def QueryUserDefinedFunctions(self, collection_link, query, options=None):
"""Queries user defined functions in a collection.
:param str collection_link:
The link to the collection.
:param (str or dict) query:
:param dict options:
The request options for the requ... | [
"def",
"QueryUserDefinedFunctions",
"(",
"self",
",",
"collection_link",
",",
"query",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"path",
"=",
"base",
".",
"GetPathFromLink",
"(",
"collection_link",
... | 37.862069 | 17.275862 |
def statement(self):
"""
statement: function_declaration
| variable_declaration
| expression_statement
| if_statement
| while_statement
| jump_statement
"""
if self.token.nature == Nature.DEF:
... | [
"def",
"statement",
"(",
"self",
")",
":",
"if",
"self",
".",
"token",
".",
"nature",
"==",
"Nature",
".",
"DEF",
":",
"node",
"=",
"self",
".",
"function_declaration",
"(",
")",
"elif",
"self",
".",
"token",
".",
"nature",
"==",
"Nature",
".",
"LET"... | 34.52 | 8.28 |
def index():
"""Show a list of available libraries, and resource files"""
kwdb = current_app.kwdb
libraries = get_collections(kwdb, libtype="library")
resource_files = get_collections(kwdb, libtype="resource")
return flask.render_template("libraryNames.html",
data=... | [
"def",
"index",
"(",
")",
":",
"kwdb",
"=",
"current_app",
".",
"kwdb",
"libraries",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"library\"",
")",
"resource_files",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"resource\"",
")"... | 42.166667 | 20.833333 |
def upload(self, **kwargs):
""" https://api.slack.com/methods/files.upload
"""
if kwargs:
self.params.update(kwargs)
return FromUrl('https://slack.com/api/files.upload', self._requests)(data=self.params).post() | [
"def",
"upload",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"self",
".",
"params",
".",
"update",
"(",
"kwargs",
")",
"return",
"FromUrl",
"(",
"'https://slack.com/api/files.upload'",
",",
"self",
".",
"_requests",
")",
"(",
"da... | 41.5 | 16.333333 |
def _transform(self, X, y):
'''
Transforms single series
'''
z, p, y_rle = self._rle(y)
p = np.append(p, len(y))
big_enough = p[1:] - p[:-1] >= self.min_length
Xt = []
for i in range(len(y_rle)):
if (big_enough[i]):
Xt.append(X... | [
"def",
"_transform",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"z",
",",
"p",
",",
"y_rle",
"=",
"self",
".",
"_rle",
"(",
"y",
")",
"p",
"=",
"np",
".",
"append",
"(",
"p",
",",
"len",
"(",
"y",
")",
")",
"big_enough",
"=",
"p",
"[",
"1... | 25.533333 | 16.466667 |
def get_readonly_fields(self, request, obj=None):
"""
Return readonly fields by user's permissions.
"""
readonly_fields = list(super(EntryAdmin, self).get_readonly_fields(
request, obj))
if not request.user.has_perm('zinnia.can_change_status'):
readonly_f... | [
"def",
"get_readonly_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"readonly_fields",
"=",
"list",
"(",
"super",
"(",
"EntryAdmin",
",",
"self",
")",
".",
"get_readonly_fields",
"(",
"request",
",",
"obj",
")",
")",
"if",
"not"... | 33.857143 | 18.571429 |
def parse_username_password_hostname(remote_url):
"""
Parse a command line string and return username, password, remote hostname and remote path.
:param remote_url: A command line string.
:return: A tuple, containing username, password, remote hostname and remote path.
"""
assert remote_url
... | [
"def",
"parse_username_password_hostname",
"(",
"remote_url",
")",
":",
"assert",
"remote_url",
"assert",
"':'",
"in",
"remote_url",
"if",
"'@'",
"in",
"remote_url",
":",
"username",
",",
"hostname",
"=",
"remote_url",
".",
"rsplit",
"(",
"'@'",
",",
"1",
")",... | 29.958333 | 21.125 |
def _wrap_callback_parse_parameter_data(subscription, on_data, message):
"""
Wraps an (optional) user callback to parse ParameterData
from a WebSocket data message
"""
if message.type == message.REPLY:
data = web_pb2.ParameterSubscriptionResponse()
data.ParseFromString(message.reply.... | [
"def",
"_wrap_callback_parse_parameter_data",
"(",
"subscription",
",",
"on_data",
",",
"message",
")",
":",
"if",
"message",
".",
"type",
"==",
"message",
".",
"REPLY",
":",
"data",
"=",
"web_pb2",
".",
"ParameterSubscriptionResponse",
"(",
")",
"data",
".",
... | 43 | 11.625 |
def get_updates(self, id, project=None, top=None, skip=None):
"""GetUpdates.
[Preview API] Returns a the deltas between work item revisions
:param int id:
:param str project: Project ID or project name
:param int top:
:param int skip:
:rtype: [WorkItemUpdate]
... | [
"def",
"get_updates",
"(",
"self",
",",
"id",
",",
"project",
"=",
"None",
",",
"top",
"=",
"None",
",",
"skip",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
... | 47.56 | 20.08 |
def register_model(cls: Type[Model]):
"""
Include the given model class into the registry.
:param cls: The class of the registered model.
:return: None
"""
if not issubclass(cls, Model):
raise TypeError("model bust be a subclass of Model")
if issubclass(cls, GenericModel):
r... | [
"def",
"register_model",
"(",
"cls",
":",
"Type",
"[",
"Model",
"]",
")",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"Model",
")",
":",
"raise",
"TypeError",
"(",
"\"model bust be a subclass of Model\"",
")",
"if",
"issubclass",
"(",
"cls",
",",
"Gen... | 31.461538 | 14.692308 |
def list_queue(self, embed_last_unused_offers=False):
"""List all the tasks queued up or waiting to be scheduled.
:returns: list of queue items
:rtype: list[:class:`marathon.models.queue.MarathonQueueItem`]
"""
if embed_last_unused_offers:
params = {'embed': 'lastUnu... | [
"def",
"list_queue",
"(",
"self",
",",
"embed_last_unused_offers",
"=",
"False",
")",
":",
"if",
"embed_last_unused_offers",
":",
"params",
"=",
"{",
"'embed'",
":",
"'lastUnusedOffers'",
"}",
"else",
":",
"params",
"=",
"{",
"}",
"response",
"=",
"self",
".... | 44.25 | 19.583333 |
async def run_checks(self):
"""
Run checks on itself and on the FSM
"""
async for check in self.fsm.health_check():
yield check
async for check in self.self_check():
yield check
for check in MiddlewareManager.health_check():
yield ch... | [
"async",
"def",
"run_checks",
"(",
"self",
")",
":",
"async",
"for",
"check",
"in",
"self",
".",
"fsm",
".",
"health_check",
"(",
")",
":",
"yield",
"check",
"async",
"for",
"check",
"in",
"self",
".",
"self_check",
"(",
")",
":",
"yield",
"check",
"... | 23.923077 | 16.692308 |
def __rename_directory(self, source, target):
"""
Renames a directory using given source and target names.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode
"""
for node in itertools.chain(self.__script_e... | [
"def",
"__rename_directory",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"for",
"node",
"in",
"itertools",
".",
"chain",
"(",
"self",
".",
"__script_editor",
".",
"model",
".",
"get_project_nodes",
"(",
"source",
")",
",",
"self",
".",
"__script_e... | 43.4 | 18.5 |
def mousePressEvent( self, event ):
"""
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
"""
self.setValue(self.valueAt(event.pos().x())) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"setValue",
"(",
"self",
".",
"valueAt",
"(",
"event",
".",
"pos",
"(",
")",
".",
"x",
"(",
")",
")",
")"
] | 32 | 10 |
def encode(
self, word, max_length=4, var='American', reverse=False, zero_pad=True
):
"""Return the Soundex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"max_length",
"=",
"4",
",",
"var",
"=",
"'American'",
",",
"reverse",
"=",
"False",
",",
"zero_pad",
"=",
"True",
")",
":",
"# Require a max_length of at least 4 and not more than 64",
"if",
"max_length",
"!=",
... | 33.072 | 23.096 |
def get_context_data(self, **kwargs):
""" TODO - possibly inherit this from DocumentEditFormView. This is same thing minus:
self.ident = self.kwargs.get('id')
self.document = self.document_type.objects.get(pk=self.ident)
"""
context = super(DocumentAddFormView, self).get_... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"DocumentAddFormView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"set_mongoadmin",
"(",
")",
"context",
"... | 51.625 | 24.125 |
def arcball_map_to_sphere(point, center, radius):
"""Return unit sphere coordinates from window coordinates."""
v = numpy.array(((point[0] - center[0]) / radius,
(center[1] - point[1]) / radius,
0.0), dtype=numpy.float64)
n = v[0]*v[0] + v[1]*v[1]
if n > 1.0:
... | [
"def",
"arcball_map_to_sphere",
"(",
"point",
",",
"center",
",",
"radius",
")",
":",
"v",
"=",
"numpy",
".",
"array",
"(",
"(",
"(",
"point",
"[",
"0",
"]",
"-",
"center",
"[",
"0",
"]",
")",
"/",
"radius",
",",
"(",
"center",
"[",
"1",
"]",
"... | 38.090909 | 14.363636 |
def add_binding(self, binding: Binding):
"""Stores binding"""
binding.add_error_info = lambda error: error.add_view_info(self._xml_node.view_info)
self._bindings.append(binding) | [
"def",
"add_binding",
"(",
"self",
",",
"binding",
":",
"Binding",
")",
":",
"binding",
".",
"add_error_info",
"=",
"lambda",
"error",
":",
"error",
".",
"add_view_info",
"(",
"self",
".",
"_xml_node",
".",
"view_info",
")",
"self",
".",
"_bindings",
".",
... | 49.5 | 13.5 |
def cluster_exists(self, name):
"""Check if a given cluster exists."""
clusters = self.data['clusters']
for cluster in clusters:
if cluster['name'] == name:
return True
return False | [
"def",
"cluster_exists",
"(",
"self",
",",
"name",
")",
":",
"clusters",
"=",
"self",
".",
"data",
"[",
"'clusters'",
"]",
"for",
"cluster",
"in",
"clusters",
":",
"if",
"cluster",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"True",
"return",
"Fal... | 33.571429 | 7.285714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.