text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def install_logger(logger=None, module=None):
"""
Installs given logger in given module or default logger in caller introspected module.
:param logger: Logger to install.
:type logger: Logger
:param module: Module.
:type module: ModuleType
:return: Logger.
:rtype: Logger
"""
lo... | [
"def",
"install_logger",
"(",
"logger",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"Constants",
".",
"logger",
")",
"if",
"logger",
"is",
"None",
"else",
"logger",
"if",
"module",
"is",
"None",
"... | 33.571429 | 24.428571 |
def parallaxMinError(G, vmini, extension=0.0):
"""
Calculate the minimum parallax error from G and (V-I). This correspond to the sky regions with the
smallest astrometric errors. At the bright end the parallax error is at least 14 muas due to the
gating scheme.
Parameters
----------
G - Value(s) of... | [
"def",
"parallaxMinError",
"(",
"G",
",",
"vmini",
",",
"extension",
"=",
"0.0",
")",
":",
"return",
"_astrometricErrorFactors",
"[",
"\"parallax\"",
"]",
".",
"min",
"(",
")",
"*",
"parallaxErrorSkyAvg",
"(",
"G",
",",
"vmini",
",",
"extension",
"=",
"ext... | 28.434783 | 30.434783 |
def _setup_subnet_parameters(self, params, data, is_create=True):
"""Setup subnet parameters
This methods setups subnet parameters which are available
in both create and update.
"""
is_update = not is_create
params['enable_dhcp'] = data['enable_dhcp']
if int(data... | [
"def",
"_setup_subnet_parameters",
"(",
"self",
",",
"params",
",",
"data",
",",
"is_create",
"=",
"True",
")",
":",
"is_update",
"=",
"not",
"is_create",
"params",
"[",
"'enable_dhcp'",
"]",
"=",
"data",
"[",
"'enable_dhcp'",
"]",
"if",
"int",
"(",
"data"... | 46.709677 | 12.290323 |
def _get_query(self, cursor):
'''
Query tempalte for source Solr, sorts by id by default.
'''
query = {'q':'*:*',
'sort':'id desc',
'rows':self._rows,
'cursorMark':cursor}
if self._date_field:
query['sort'] = "{... | [
"def",
"_get_query",
"(",
"self",
",",
"cursor",
")",
":",
"query",
"=",
"{",
"'q'",
":",
"'*:*'",
",",
"'sort'",
":",
"'id desc'",
",",
"'rows'",
":",
"self",
".",
"_rows",
",",
"'cursorMark'",
":",
"cursor",
"}",
"if",
"self",
".",
"_date_field",
"... | 33.769231 | 14.692308 |
def filter_record(self, record):
"""
Filter record, truncating any over some maximum length
"""
if len(record) >= self.max_length:
return record[:self.max_length]
else:
return record | [
"def",
"filter_record",
"(",
"self",
",",
"record",
")",
":",
"if",
"len",
"(",
"record",
")",
">=",
"self",
".",
"max_length",
":",
"return",
"record",
"[",
":",
"self",
".",
"max_length",
"]",
"else",
":",
"return",
"record"
] | 29.875 | 9.625 |
def list_firewall_rules(self, server_name):
'''
Retrieves the set of firewall rules for an Azure SQL Database Server.
server_name:
Name of the server.
'''
_validate_not_none('server_name', server_name)
response = self._perform_get(self._get_firewall_rules_pat... | [
"def",
"list_firewall_rules",
"(",
"self",
",",
"server_name",
")",
":",
"_validate_not_none",
"(",
"'server_name'",
",",
"server_name",
")",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_firewall_rules_path",
"(",
"server_name",
")",
",",
... | 39.333333 | 21.333333 |
def get_form(self, request, obj=None, **kwargs):
"""
Build the form used for changing the model.
"""
widgets = kwargs.pop('widgets', {})
labels = kwargs.pop('labels', {})
glossary_fields = kwargs.pop('glossary_fields', self.glossary_fields)
widgets.update(glossary... | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"widgets",
"=",
"kwargs",
".",
"pop",
"(",
"'widgets'",
",",
"{",
"}",
")",
"labels",
"=",
"kwargs",
".",
"pop",
"(",
"'labels'",
",",
"{"... | 54.4 | 19.8 |
def del_depth(d, depth):
"""Delete all the nodes on specific depth in this dict
"""
for node in DictTree.v_depth(d, depth-1):
for key in [key for key in DictTree.k(node)]:
del node[key] | [
"def",
"del_depth",
"(",
"d",
",",
"depth",
")",
":",
"for",
"node",
"in",
"DictTree",
".",
"v_depth",
"(",
"d",
",",
"depth",
"-",
"1",
")",
":",
"for",
"key",
"in",
"[",
"key",
"for",
"key",
"in",
"DictTree",
".",
"k",
"(",
"node",
")",
"]",
... | 38.666667 | 8.833333 |
def isContained(bbox1, bbox2, tol=TOLERANCE):
"""
:param bbox1: bounding box of the first rectangle
:param bbox2: bounding box of the second rectangle
:return: True if bbox1 is contaned in bbox2
"""
if bbox1[0] > bbox2[0] - tol and bbox1[1] > bbox2[1] - tol:
if bbox1[2] < bbox2[2] + tol ... | [
"def",
"isContained",
"(",
"bbox1",
",",
"bbox2",
",",
"tol",
"=",
"TOLERANCE",
")",
":",
"if",
"bbox1",
"[",
"0",
"]",
">",
"bbox2",
"[",
"0",
"]",
"-",
"tol",
"and",
"bbox1",
"[",
"1",
"]",
">",
"bbox2",
"[",
"1",
"]",
"-",
"tol",
":",
"if"... | 38.2 | 13 |
def border_pixels(
self,
grad_sigma=0.5,
grad_lower_thresh=0.1,
grad_upper_thresh=1.0):
"""
Returns the pixels on the boundary between all segments, excluding the zero segment.
Parameters
----------
grad_sigma : float
s... | [
"def",
"border_pixels",
"(",
"self",
",",
"grad_sigma",
"=",
"0.5",
",",
"grad_lower_thresh",
"=",
"0.1",
",",
"grad_upper_thresh",
"=",
"1.0",
")",
":",
"# boundary pixels",
"boundary_im",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"shape",
")",
"for",
"i"... | 35.769231 | 18.076923 |
def get_total_size_of_queued_replicas():
"""Return the total number of bytes of requested, unprocessed replicas."""
return (
d1_gmn.app.models.ReplicationQueue.objects.filter(
local_replica__info__status__status='queued'
).aggregate(Sum('size'))['size__sum']
or 0
) | [
"def",
"get_total_size_of_queued_replicas",
"(",
")",
":",
"return",
"(",
"d1_gmn",
".",
"app",
".",
"models",
".",
"ReplicationQueue",
".",
"objects",
".",
"filter",
"(",
"local_replica__info__status__status",
"=",
"'queued'",
")",
".",
"aggregate",
"(",
"Sum",
... | 38.25 | 16.25 |
def msg_curse(self, args=None, max_width=None):
"""Return the list to display in the curse interface."""
# Init the return message
ret = []
# Build the string message
# Header
ret.append(self.curse_add_line(self.view_data['version'], 'TITLE'))
ret.append(self.cur... | [
"def",
"msg_curse",
"(",
"self",
",",
"args",
"=",
"None",
",",
"max_width",
"=",
"None",
")",
":",
"# Init the return message",
"ret",
"=",
"[",
"]",
"# Build the string message",
"# Header",
"ret",
".",
"append",
"(",
"self",
".",
"curse_add_line",
"(",
"s... | 53.925926 | 23.407407 |
async def create_email_identity(self,
client_id, identity, passwd, *,
user_id=None # 如果设置用户ID,则创建该用户的新登录身份
) -> SessionIdentity :
""" 创建使用电子邮件地址和密码登录的用户身份 """
assert passwd
value, _ = await self._client.get(f"/users/identity/{identity}")
if val... | [
"async",
"def",
"create_email_identity",
"(",
"self",
",",
"client_id",
",",
"identity",
",",
"passwd",
",",
"*",
",",
"user_id",
"=",
"None",
"# 如果设置用户ID,则创建该用户的新登录身份",
")",
"->",
"SessionIdentity",
":",
"assert",
"passwd",
"value",
",",
"_",
"=",
"await",
... | 30.1 | 22.033333 |
def Tb(counts):
r'''Estimates the normal boiling temperature of an organic compound
using the Joback method as a function of chemical structure only.
.. math::
T_b = 198.2 + \sum_i {T_{b,i}}
For 438 compounds tested by Joback, the absolute average error... | [
"def",
"Tb",
"(",
"counts",
")",
":",
"tot",
"=",
"0.0",
"for",
"group",
",",
"count",
"in",
"counts",
".",
"items",
"(",
")",
":",
"tot",
"+=",
"joback_groups_id_dict",
"[",
"group",
"]",
".",
"Tb",
"*",
"count",
"Tb",
"=",
"198.2",
"+",
"tot",
... | 29.875 | 23.5625 |
def update_ports(self):
"""
Sets the `ports` attribute to the set of valid port values set in
the configuration.
"""
ports = set()
for port in self.configured_ports:
try:
ports.add(int(port))
except ValueError:
logg... | [
"def",
"update_ports",
"(",
"self",
")",
":",
"ports",
"=",
"set",
"(",
")",
"for",
"port",
"in",
"self",
".",
"configured_ports",
":",
"try",
":",
"ports",
".",
"add",
"(",
"int",
"(",
"port",
")",
")",
"except",
"ValueError",
":",
"logger",
".",
... | 26.6 | 16.866667 |
def replicate(ctx, args):
"""Make node to be the slave of a master.
"""
slave = ClusterNode.from_uri(args.node)
master = ClusterNode.from_uri(args.master)
if not master.is_master():
ctx.abort("Node {!r} is not a master.".format(args.master))
try:
slave.replicate(master.name)
... | [
"def",
"replicate",
"(",
"ctx",
",",
"args",
")",
":",
"slave",
"=",
"ClusterNode",
".",
"from_uri",
"(",
"args",
".",
"node",
")",
"master",
"=",
"ClusterNode",
".",
"from_uri",
"(",
"args",
".",
"master",
")",
"if",
"not",
"master",
".",
"is_master",... | 28.857143 | 14.285714 |
def readlines(self, encoding=None):
"""Reads from the file and returns result as a list of lines."""
try:
encoding = encoding or ENCODING
with codecs.open(self.path, encoding=None) as fi:
return fi.readlines()
except:
return [] | [
"def",
"readlines",
"(",
"self",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"encoding",
"=",
"encoding",
"or",
"ENCODING",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"path",
",",
"encoding",
"=",
"None",
")",
"as",
"fi",
":",
"return",... | 37 | 13 |
def _logger_stream(self):
"""Add stream logging handler."""
sh = logging.StreamHandler()
sh.set_name('sh')
sh.setLevel(logging.INFO)
sh.setFormatter(self._logger_formatter)
self.log.addHandler(sh) | [
"def",
"_logger_stream",
"(",
"self",
")",
":",
"sh",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"sh",
".",
"set_name",
"(",
"'sh'",
")",
"sh",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"sh",
".",
"setFormatter",
"(",
"self",
".",
"_log... | 34 | 8.142857 |
def _high_dim_sim(self, v, w, normalize=False, X=None, idx=0):
"""Similarity measurement based on Gaussian Distribution"""
sim = np.exp((-np.linalg.norm(v - w) ** 2) / (2*self._sigma[idx] ** 2))
if normalize:
return sim / sum(map(lambda x: x[1], self._knn(idx, X, high_dim=True)))
... | [
"def",
"_high_dim_sim",
"(",
"self",
",",
"v",
",",
"w",
",",
"normalize",
"=",
"False",
",",
"X",
"=",
"None",
",",
"idx",
"=",
"0",
")",
":",
"sim",
"=",
"np",
".",
"exp",
"(",
"(",
"-",
"np",
".",
"linalg",
".",
"norm",
"(",
"v",
"-",
"w... | 38.555556 | 27.555556 |
def enable(self, enable_password):
"""Change to the privilege mode."""
if self.device.prompt[-1] == '#':
self.log("Device is already in privileged mode")
return
events = [self.password_re, self.device.prompt_re, pexpect.TIMEOUT, pexpect.EOF]
transitions = [
... | [
"def",
"enable",
"(",
"self",
",",
"enable_password",
")",
":",
"if",
"self",
".",
"device",
".",
"prompt",
"[",
"-",
"1",
"]",
"==",
"'#'",
":",
"self",
".",
"log",
"(",
"\"Device is already in privileged mode\"",
")",
"return",
"events",
"=",
"[",
"sel... | 60.333333 | 33.428571 |
def pWMRead(fileHandle, alphabetSize=4):
"""reads in standard position weight matrix format,
rows are different types of base, columns are individual residues
"""
lines = fileHandle.readlines()
assert len(lines) == alphabetSize
l = [ [ float(i) ] for i in lines[0].split() ]
for line in lines... | [
"def",
"pWMRead",
"(",
"fileHandle",
",",
"alphabetSize",
"=",
"4",
")",
":",
"lines",
"=",
"fileHandle",
".",
"readlines",
"(",
")",
"assert",
"len",
"(",
"lines",
")",
"==",
"alphabetSize",
"l",
"=",
"[",
"[",
"float",
"(",
"i",
")",
"]",
"for",
... | 35.5 | 9.125 |
def vpn_status(self):
"""Returns response dict"""
# Start signal handler thread if it should be running
if not self.check_pid and not self.thread_started:
self._start_handler_thread()
# Set color_bad as default output. Replaced if VPN active.
name = None
col... | [
"def",
"vpn_status",
"(",
"self",
")",
":",
"# Start signal handler thread if it should be running",
"if",
"not",
"self",
".",
"check_pid",
"and",
"not",
"self",
".",
"thread_started",
":",
"self",
".",
"_start_handler_thread",
"(",
")",
"# Set color_bad as default outp... | 32.166667 | 18.416667 |
def make_factor(var, e, bn):
"""Return the factor for var in bn's joint distribution given e.
That is, bn's full joint distribution, projected to accord with e,
is the pointwise product of these factors for bn's variables."""
node = bn.variable_node(var)
vars = [X for X in [var] + node.parents if X ... | [
"def",
"make_factor",
"(",
"var",
",",
"e",
",",
"bn",
")",
":",
"node",
"=",
"bn",
".",
"variable_node",
"(",
"var",
")",
"vars",
"=",
"[",
"X",
"for",
"X",
"in",
"[",
"var",
"]",
"+",
"node",
".",
"parents",
"if",
"X",
"not",
"in",
"e",
"]"... | 51.222222 | 12.111111 |
def check_user_can_review(recID, client_ip_address, uid=-1):
""" Check if a user hasn't already reviewed within the last seconds
time limit: CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_REVIEWS_IN_SECONDS
:param recID: record ID
:param client_ip_address: IP => use: str(req.remote_ip)
:param uid: user id, as ... | [
"def",
"check_user_can_review",
"(",
"recID",
",",
"client_ip_address",
",",
"uid",
"=",
"-",
"1",
")",
":",
"action_code",
"=",
"CFG_WEBCOMMENT_ACTION_CODE",
"[",
"'ADD_REVIEW'",
"]",
"query",
"=",
"\"\"\"SELECT id_bibrec\n FROM \"cmtACTIONHISTORY\"\n ... | 38.045455 | 11.863636 |
def resource(self, resource_type):
"""Get instance of Resource Class with dynamic type.
Args:
resource_type: The resource type name (e.g Adversary, User Agent, etc).
Returns:
(object): Instance of Resource Object child class.
"""
try:
resourc... | [
"def",
"resource",
"(",
"self",
",",
"resource_type",
")",
":",
"try",
":",
"resource",
"=",
"getattr",
"(",
"self",
".",
"resources",
",",
"self",
".",
"safe_rt",
"(",
"resource_type",
")",
")",
"(",
"self",
")",
"except",
"AttributeError",
":",
"self",... | 35.933333 | 23.066667 |
def term_with_coeff(term, coeff):
"""
Change the coefficient of a PauliTerm.
:param PauliTerm term: A PauliTerm object
:param Number coeff: The coefficient to set on the PauliTerm
:returns: A new PauliTerm that duplicates term but sets coeff
:rtype: PauliTerm
"""
if not isinstance(coeff... | [
"def",
"term_with_coeff",
"(",
"term",
",",
"coeff",
")",
":",
"if",
"not",
"isinstance",
"(",
"coeff",
",",
"Number",
")",
":",
"raise",
"ValueError",
"(",
"\"coeff must be a Number\"",
")",
"new_pauli",
"=",
"term",
".",
"copy",
"(",
")",
"# We cast to a c... | 37 | 15 |
def num_feats(self):
""" The number of features per time step in the corpus. """
if not self._num_feats:
filename = self.get_train_fns()[0][0]
feats = np.load(filename)
# pylint: disable=maybe-no-member
if len(feats.shape) == 3:
# Then ther... | [
"def",
"num_feats",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_num_feats",
":",
"filename",
"=",
"self",
".",
"get_train_fns",
"(",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"feats",
"=",
"np",
".",
"load",
"(",
"filename",
")",
"# pylint: disable=m... | 45.3125 | 13.125 |
def namedtuple_asdict(obj):
"""
Serializing a nested namedtuple into a Python dict
"""
if obj is None:
return obj
if hasattr(obj, "_asdict"): # detect namedtuple
return OrderedDict(zip(obj._fields, (namedtuple_asdict(item)
for item in obj... | [
"def",
"namedtuple_asdict",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"obj",
"if",
"hasattr",
"(",
"obj",
",",
"\"_asdict\"",
")",
":",
"# detect namedtuple",
"return",
"OrderedDict",
"(",
"zip",
"(",
"obj",
".",
"_fields",
",",
"("... | 41.944444 | 17.166667 |
def analysis_title_header_element(feature, parent):
"""Retrieve analysis title header string from definitions."""
_ = feature, parent # NOQA
header = analysis_title_header['string_format']
return header.capitalize() | [
"def",
"analysis_title_header_element",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"header",
"=",
"analysis_title_header",
"[",
"'string_format'",
"]",
"return",
"header",
".",
"capitalize",
"(",
")"
] | 45.6 | 8.2 |
def gradient(self, wrt):
"""Gets the autodiff of current symbol.
This function can only be used if current symbol is a loss function.
.. note:: This function is currently not implemented.
Parameters
----------
wrt : Array of String
keyword arguments of the ... | [
"def",
"gradient",
"(",
"self",
",",
"wrt",
")",
":",
"handle",
"=",
"SymbolHandle",
"(",
")",
"c_wrt",
"=",
"c_str_array",
"(",
"wrt",
")",
"check_call",
"(",
"_LIB",
".",
"MXSymbolGrad",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
... | 32.625 | 20.875 |
def remove(self):
"""Remove this file from the remote storage."""
response = self._delete(self._delete_url)
if response.status_code != 204:
raise RuntimeError('Could not delete {}.'.format(self.path)) | [
"def",
"remove",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_delete",
"(",
"self",
".",
"_delete_url",
")",
"if",
"response",
".",
"status_code",
"!=",
"204",
":",
"raise",
"RuntimeError",
"(",
"'Could not delete {}.'",
".",
"format",
"(",
"self... | 46.4 | 13 |
def Crop(px=None, percent=None, keep_size=True, sample_independently=True,
name=None, deterministic=False, random_state=None):
"""
Augmenter that crops/cuts away pixels at the sides of the image.
That allows to cut out subimages from given (full) input images.
The number of pixels to cut off m... | [
"def",
"Crop",
"(",
"px",
"=",
"None",
",",
"percent",
"=",
"None",
",",
"keep_size",
"=",
"True",
",",
"sample_independently",
"=",
"True",
",",
"name",
"=",
"None",
",",
"deterministic",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
"def"... | 43.489796 | 27.489796 |
def _cast(cls, base_info, take_ownership=True):
"""Casts a GIBaseInfo instance to the right sub type.
The original GIBaseInfo can't have ownership.
Will take ownership.
"""
type_value = base_info.type.value
try:
new_obj = cast(base_info, cls.__types[type_val... | [
"def",
"_cast",
"(",
"cls",
",",
"base_info",
",",
"take_ownership",
"=",
"True",
")",
":",
"type_value",
"=",
"base_info",
".",
"type",
".",
"value",
"try",
":",
"new_obj",
"=",
"cast",
"(",
"base_info",
",",
"cls",
".",
"__types",
"[",
"type_value",
... | 27.444444 | 16.888889 |
def matching_line(lines, keyword):
""" Returns the first matching line in a list of lines.
@see match()
"""
for line in lines:
matching = match(line,keyword)
if matching != None:
return matching
return None | [
"def",
"matching_line",
"(",
"lines",
",",
"keyword",
")",
":",
"for",
"line",
"in",
"lines",
":",
"matching",
"=",
"match",
"(",
"line",
",",
"keyword",
")",
"if",
"matching",
"!=",
"None",
":",
"return",
"matching",
"return",
"None"
] | 27.333333 | 11.111111 |
def get_children(self):
"""
Get tile children (intersecting tiles in next zoom level).
Returns
-------
children : list
a list of ``BufferedTiles``
"""
return [BufferedTile(t, self.pixelbuffer) for t in self._tile.get_children()] | [
"def",
"get_children",
"(",
"self",
")",
":",
"return",
"[",
"BufferedTile",
"(",
"t",
",",
"self",
".",
"pixelbuffer",
")",
"for",
"t",
"in",
"self",
".",
"_tile",
".",
"get_children",
"(",
")",
"]"
] | 28.8 | 19.6 |
def expect_keyword(parser, value):
# type: (Parser, str) -> Token
"""If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False."""
token = parser.token
if token.kind == TokenKind.NAME and token.va... | [
"def",
"expect_keyword",
"(",
"parser",
",",
"value",
")",
":",
"# type: (Parser, str) -> Token",
"token",
"=",
"parser",
".",
"token",
"if",
"token",
".",
"kind",
"==",
"TokenKind",
".",
"NAME",
"and",
"token",
".",
"value",
"==",
"value",
":",
"advance",
... | 34.533333 | 18.333333 |
def fetch_from_sdr(folder=data_folder, data='test'):
"""
Download MRS data from SDR
Parameters
----------
folder : str
Full path to a location in which to place the data. Per default this
will be a directory under the user's home `.mrs_data`.
data : str
Which data to downloa... | [
"def",
"fetch_from_sdr",
"(",
"folder",
"=",
"data_folder",
",",
"data",
"=",
"'test'",
")",
":",
"url",
"=",
"\"https://stacks.stanford.edu/file/druid:fn662rv4961/\"",
"if",
"data",
"==",
"'test'",
":",
"md5_dict",
"=",
"{",
"'5182_1_1.nii.gz'",
":",
"'0656e5981853... | 36.681818 | 22.545455 |
def listener(self, acceptor, wrapper):
"""
Listens for new connections to the manager's endpoint. Once a
new connection is received, a UDPTendril object is generated
for it and it is passed to the acceptor, which must initialize
the state of the connection. If no acceptor is gi... | [
"def",
"listener",
"(",
"self",
",",
"acceptor",
",",
"wrapper",
")",
":",
"# OK, set up the socket",
"sock",
"=",
"socket",
".",
"socket",
"(",
"self",
".",
"addr_family",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"with",
"utils",
".",
"SocketCloser",
"(",
"... | 38.635135 | 19.256757 |
def space_acl(args):
''' Retrieve access control list for a workspace'''
r = fapi.get_workspace_acl(args.project, args.workspace)
fapi._check_response_code(r, 200)
result = dict()
for user, info in sorted(r.json()['acl'].items()):
result[user] = info['accessLevel']
return result | [
"def",
"space_acl",
"(",
"args",
")",
":",
"r",
"=",
"fapi",
".",
"get_workspace_acl",
"(",
"args",
".",
"project",
",",
"args",
".",
"workspace",
")",
"fapi",
".",
"_check_response_code",
"(",
"r",
",",
"200",
")",
"result",
"=",
"dict",
"(",
")",
"... | 38 | 14.75 |
def defined_namespace_keywords(self) -> Set[str]: # noqa: D401
"""The set of all keywords defined as namespaces in this graph."""
return set(self.namespace_pattern) | set(self.namespace_url) | [
"def",
"defined_namespace_keywords",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"# noqa: D401",
"return",
"set",
"(",
"self",
".",
"namespace_pattern",
")",
"|",
"set",
"(",
"self",
".",
"namespace_url",
")"
] | 68.333333 | 17 |
def sort(self, cmp=None, key=None, reverse=False):
"""Overrides sort func to use the KeyValue for the key."""
if not key and self._keys:
key = self.KeyValue
super(CliTable, self).sort(cmp=cmp, key=key, reverse=reverse) | [
"def",
"sort",
"(",
"self",
",",
"cmp",
"=",
"None",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"not",
"key",
"and",
"self",
".",
"_keys",
":",
"key",
"=",
"self",
".",
"KeyValue",
"super",
"(",
"CliTable",
",",
"self"... | 50 | 10.8 |
def _set_index(self, key, index):
"""Set a new index array for this series
"""
axis = key[0]
origin = "{}0".format(axis)
delta = "d{}".format(axis)
if index is None:
return delattr(self, key)
if not isinstance(index, Index):
try:
... | [
"def",
"_set_index",
"(",
"self",
",",
"key",
",",
"index",
")",
":",
"axis",
"=",
"key",
"[",
"0",
"]",
"origin",
"=",
"\"{}0\"",
".",
"format",
"(",
"axis",
")",
"delta",
"=",
"\"d{}\"",
".",
"format",
"(",
"axis",
")",
"if",
"index",
"is",
"No... | 34.95 | 10.3 |
def position_to_value(self, y):
"""Convert position in pixels to value"""
vsb = self.editor.verticalScrollBar()
return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()]) | [
"def",
"position_to_value",
"(",
"self",
",",
"y",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"return",
"vsb",
".",
"minimum",
"(",
")",
"+",
"max",
"(",
"[",
"0",
",",
"(",
"y",
"-",
"self",
".",
"offset",
"... | 50.75 | 13 |
def wcs_coord_transform(ct, x, y):
"""Computes tha WCS corrected pixel coordinates (RA and Dec
in degrees) given a coordinate transformation and the screen
coordinates (x and y, in pixels).
Input:
ct coordinate transformation. instance of coord_tran.
x x coordinate in pixels.
y ... | [
"def",
"wcs_coord_transform",
"(",
"ct",
",",
"x",
",",
"y",
")",
":",
"x",
"=",
"float",
"(",
"x",
")",
"y",
"=",
"float",
"(",
"y",
")",
"if",
"(",
"ct",
".",
"valid",
")",
":",
"# The imtool WCS assumes that the center of the first display",
"# pixel is... | 28.206897 | 18.62069 |
def maskAt(self, index):
""" Returns the mask at the index.
It the mask is a boolean it is returned since this boolean representes the mask for
all array elements.
"""
if isinstance(self.mask, bool):
return self.mask
else:
return self.mask... | [
"def",
"maskAt",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"mask",
",",
"bool",
")",
":",
"return",
"self",
".",
"mask",
"else",
":",
"return",
"self",
".",
"mask",
"[",
"index",
"]"
] | 31.8 | 16.5 |
def jsondump(model, fp):
'''
Dump Versa model into JSON form
'''
fp.write('[')
links_ser = []
for link in model:
links_ser.append(json.dumps(link))
fp.write(',\n'.join(links_ser))
fp.write(']') | [
"def",
"jsondump",
"(",
"model",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"'['",
")",
"links_ser",
"=",
"[",
"]",
"for",
"link",
"in",
"model",
":",
"links_ser",
".",
"append",
"(",
"json",
".",
"dumps",
"(",
"link",
")",
")",
"fp",
".",
"... | 22.4 | 18 |
def readline(self, timeout=None): # timeout is not in use
"""
Read data from port and strip escape characters
:param timeout:
:return: Stripped line.
"""
fil = self.port.makefile()
line = fil.readline()
return strip_escape(line.strip()) | [
"def",
"readline",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# timeout is not in use",
"fil",
"=",
"self",
".",
"port",
".",
"makefile",
"(",
")",
"line",
"=",
"fil",
".",
"readline",
"(",
")",
"return",
"strip_escape",
"(",
"line",
".",
"st... | 32.555556 | 8.555556 |
def collect_consequences(self):
"""Recursively collect a set of _ReferenceKeys that would
consequentially get dropped if this were dropped via
"drop ... cascade".
:return Set[_ReferenceKey]: All the relations that would be dropped
"""
consequences = {self.key()}
... | [
"def",
"collect_consequences",
"(",
"self",
")",
":",
"consequences",
"=",
"{",
"self",
".",
"key",
"(",
")",
"}",
"for",
"relation",
"in",
"self",
".",
"referenced_by",
".",
"values",
"(",
")",
":",
"consequences",
".",
"update",
"(",
"relation",
".",
... | 40.636364 | 15.545455 |
def generate_sbi(index: int = None):
"""Generate a SBI config JSON string."""
date = datetime.datetime.utcnow().strftime('%Y%m%d')
if index is None:
index = randint(0, 999)
sbi_id = 'SBI-{}-sip-demo-{:03d}'.format(date, index)
sb_id = 'SBI-{}-sip-demo-{:03d}'.format(date, index)
pb_id = ... | [
"def",
"generate_sbi",
"(",
"index",
":",
"int",
"=",
"None",
")",
":",
"date",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"randint",
"(",
"0",
"... | 31.368421 | 14.421053 |
def disable_script(zap_helper, script_name):
"""Disable a script."""
with zap_error_handler():
console.debug('Disabling script "{0}"'.format(script_name))
result = zap_helper.zap.script.disable(script_name)
if result != 'OK':
raise ZAPError('Error disabling script: {0}'.form... | [
"def",
"disable_script",
"(",
"zap_helper",
",",
"script_name",
")",
":",
"with",
"zap_error_handler",
"(",
")",
":",
"console",
".",
"debug",
"(",
"'Disabling script \"{0}\"'",
".",
"format",
"(",
"script_name",
")",
")",
"result",
"=",
"zap_helper",
".",
"za... | 38.5 | 20.8 |
def SqueezeNet(include_top=True, weights='imagenet',
input_tensor=None, input_shape=None,
pooling=None,
classes=1000):
"""Instantiates the SqueezeNet architecture.
"""
if weights not in {'imagenet', None}:
raise ValueError('The `weights` argument... | [
"def",
"SqueezeNet",
"(",
"include_top",
"=",
"True",
",",
"weights",
"=",
"'imagenet'",
",",
"input_tensor",
"=",
"None",
",",
"input_shape",
"=",
"None",
",",
"pooling",
"=",
"None",
",",
"classes",
"=",
"1000",
")",
":",
"if",
"weights",
"not",
"in",
... | 39.942857 | 21.704762 |
def unified_job_template_options(method):
"""
Adds the decorators for all types of unified job templates,
and if the non-unified type is specified, converts it into the
unified_job_template kwarg.
"""
jt_dec = click.option(
'--job-template', type=types.Related('job_template'),
he... | [
"def",
"unified_job_template_options",
"(",
"method",
")",
":",
"jt_dec",
"=",
"click",
".",
"option",
"(",
"'--job-template'",
",",
"type",
"=",
"types",
".",
"Related",
"(",
"'job_template'",
")",
",",
"help",
"=",
"'Use this job template as unified_job_template f... | 36.818182 | 18.939394 |
def QueryValueEx(key, value_name):
"""This calls the Windows QueryValueEx function in a Unicode safe way."""
regqueryvalueex = advapi32["RegQueryValueExW"]
regqueryvalueex.restype = ctypes.c_long
regqueryvalueex.argtypes = [
ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPBYTE, LPDWORD
]
size ... | [
"def",
"QueryValueEx",
"(",
"key",
",",
"value_name",
")",
":",
"regqueryvalueex",
"=",
"advapi32",
"[",
"\"RegQueryValueExW\"",
"]",
"regqueryvalueex",
".",
"restype",
"=",
"ctypes",
".",
"c_long",
"regqueryvalueex",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
... | 33.517241 | 20.862069 |
def series2cat(df:DataFrame, *col_names):
"Categorifies the columns `col_names` in `df`."
for c in listify(col_names): df[c] = df[c].astype('category').cat.as_ordered() | [
"def",
"series2cat",
"(",
"df",
":",
"DataFrame",
",",
"*",
"col_names",
")",
":",
"for",
"c",
"in",
"listify",
"(",
"col_names",
")",
":",
"df",
"[",
"c",
"]",
"=",
"df",
"[",
"c",
"]",
".",
"astype",
"(",
"'category'",
")",
".",
"cat",
".",
"... | 58 | 18 |
def column_constructor(text, name=None, type="text", delim=None):
"""
Converts raw content to a list of strutured tuple where each tuple contains
(type, name, content).
:param text: content to be converted ()
:type path: str
:param type: content name (default: None)
:type path: str
... | [
"def",
"column_constructor",
"(",
"text",
",",
"name",
"=",
"None",
",",
"type",
"=",
"\"text\"",
",",
"delim",
"=",
"None",
")",
":",
"if",
"delim",
"is",
"None",
":",
"return",
"[",
"(",
"type",
",",
"name",
",",
"text",
")",
"]",
"return",
"[",
... | 35.105263 | 15.210526 |
def emulate_wheel(self, data, direction, timeval):
"""Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
... | [
"def",
"emulate_wheel",
"(",
"self",
",",
"data",
",",
"direction",
",",
"timeval",
")",
":",
"if",
"direction",
"==",
"'x'",
":",
"code",
"=",
"0x06",
"elif",
"direction",
"==",
"'z'",
":",
"# Not enitely sure if this exists",
"code",
"=",
"0x07",
"else",
... | 35.28125 | 22 |
def inactive(self):
"""
Return inactive staff members
"""
qset = super(StaffMemberManager, self).get_queryset()
return qset.filter(is_active=False) | [
"def",
"inactive",
"(",
"self",
")",
":",
"qset",
"=",
"super",
"(",
"StaffMemberManager",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"return",
"qset",
".",
"filter",
"(",
"is_active",
"=",
"False",
")"
] | 30.333333 | 8 |
def close_position(self, repay_only):
""" Close position.
Args:
repay_only (bool): Undocumented by cbpro.
Returns:
Undocumented
"""
params = {'repay_only': repay_only}
return self._send_message('post', '/position/close',
... | [
"def",
"close_position",
"(",
"self",
",",
"repay_only",
")",
":",
"params",
"=",
"{",
"'repay_only'",
":",
"repay_only",
"}",
"return",
"self",
".",
"_send_message",
"(",
"'post'",
",",
"'/position/close'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"pa... | 26.307692 | 18.769231 |
def to_array(self):
"""
Serializes this PhotoSize to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(PhotoSize, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array[... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"PhotoSize",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'file_id'",
"]",
"=",
"u",
"(",
"self",
".",
"file_id",
")",
"# py2: type unicode, py3: type str",
"array",
"["... | 34.933333 | 17.866667 |
def get_config(self, view = None):
"""
Retrieve the service's configuration.
Retrieves both the service configuration and role type configuration
for each of the service's supported role types. The role type
configurations are returned as a dictionary, whose keys are the
role type name, and val... | [
"def",
"get_config",
"(",
"self",
",",
"view",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"_path",
"(",
")",
"+",
"'/config'",
"resp",
"=",
"self",
".",
"_get_resource_root",
"(",
")",
".",
"get",
"(",
"path",
",",
"params",
"=",
"view",
"and... | 42.315789 | 19.578947 |
def serve(self, port=None, address=None):
"""Serves the SMTP server on the given port and address."""
port = port or self.port
address = address or self.address
log.info('Starting SMTP server at {0}:{1}'.format(address, port))
server = InboxServer(self.collator, (address, port)... | [
"def",
"serve",
"(",
"self",
",",
"port",
"=",
"None",
",",
"address",
"=",
"None",
")",
":",
"port",
"=",
"port",
"or",
"self",
".",
"port",
"address",
"=",
"address",
"or",
"self",
".",
"address",
"log",
".",
"info",
"(",
"'Starting SMTP server at {0... | 32.846154 | 18.615385 |
def mask(args):
"""
%prog mask fastafile
This script pipelines the windowmasker in NCBI BLAST+. Masked fasta file
will have an appended suffix of .mask with all the low-complexity bases masked
(default to lower case, set --hard for hardmasking).
"""
p = OptionParser(mask.__doc__)
p.add... | [
"def",
"mask",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mask",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--hard\"",
",",
"dest",
"=",
"\"hard\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
... | 32.37037 | 23.111111 |
async def getItemCmdr(prox, outp=None, locs=None):
'''Get a Cmdr instance with prepopulated locs'''
cmdr = await s_cmdr.getItemCmdr(prox, outp=outp)
cmdr.echoline = True
if locs:
cmdr.locs.update(locs)
return cmdr | [
"async",
"def",
"getItemCmdr",
"(",
"prox",
",",
"outp",
"=",
"None",
",",
"locs",
"=",
"None",
")",
":",
"cmdr",
"=",
"await",
"s_cmdr",
".",
"getItemCmdr",
"(",
"prox",
",",
"outp",
"=",
"outp",
")",
"cmdr",
".",
"echoline",
"=",
"True",
"if",
"l... | 33.571429 | 16.142857 |
def makedirs(self, path, mode=511, exist_ok=False):
"""Create a directory on the remote side.
If intermediate directories do not exist, they will be created.
Parameters
----------
path : str
Path of directory on the remote side to create.
mode : int
... | [
"def",
"makedirs",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"511",
",",
"exist_ok",
"=",
"False",
")",
":",
"if",
"exist_ok",
"is",
"False",
"and",
"self",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"OSError",
"(",
"'Target directory {} already exi... | 37.105263 | 21.842105 |
def _get_segments(self):
"""
Subclasses may override this method.
"""
points = list(self.points)
segments = [[]]
lastWasOffCurve = False
firstIsMove = points[0].type == "move"
for point in points:
segments[-1].append(point)
if point... | [
"def",
"_get_segments",
"(",
"self",
")",
":",
"points",
"=",
"list",
"(",
"self",
".",
"points",
")",
"segments",
"=",
"[",
"[",
"]",
"]",
"lastWasOffCurve",
"=",
"False",
"firstIsMove",
"=",
"points",
"[",
"0",
"]",
".",
"type",
"==",
"\"move\"",
"... | 33.529412 | 7.411765 |
def _printTriples(self, entity):
""" display triples """
self._print("----------------", "TIP")
self._print(unicode(entity.uri), "IMPORTANT")
for x in entity.triples:
self._print("=> " + unicode(x[1]), "MAGENTA")
self._print(".... " + unicode(x[2]), "GREEN")
... | [
"def",
"_printTriples",
"(",
"self",
",",
"entity",
")",
":",
"self",
".",
"_print",
"(",
"\"----------------\"",
",",
"\"TIP\"",
")",
"self",
".",
"_print",
"(",
"unicode",
"(",
"entity",
".",
"uri",
")",
",",
"\"IMPORTANT\"",
")",
"for",
"x",
"in",
"... | 44.25 | 9.375 |
def header(self, title, level, key, width=80):
"""Example::
.. _header_2:
Header 2
-------------------------------------------------------------------
**中文文档**
"""
linestyle_code = {1: "=", 2: "-", 3: "~"}
if level not in linestyle_code:
... | [
"def",
"header",
"(",
"self",
",",
"title",
",",
"level",
",",
"key",
",",
"width",
"=",
"80",
")",
":",
"linestyle_code",
"=",
"{",
"1",
":",
"\"=\"",
",",
"2",
":",
"\"-\"",
",",
"3",
":",
"\"~\"",
"}",
"if",
"level",
"not",
"in",
"linestyle_co... | 29.2 | 21.55 |
def rquad(a, b, c):
"""
Find the roots of a quadratic equation.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rquad_c.html
:param a: Coefficient of quadratic term.
:type a: float
:param b: Coefficient of linear term.
:type b: float
:param c: Constant.
:type c: float
:... | [
"def",
"rquad",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"a",
"=",
"ctypes",
".",
"c_double",
"(",
"a",
")",
"b",
"=",
"ctypes",
".",
"c_double",
"(",
"b",
")",
"c",
"=",
"ctypes",
".",
"c_double",
"(",
"c",
")",
"root1",
"=",
"stypes",
".",
... | 30.272727 | 16.090909 |
def reset(self):
"""Resets the cache of compiled templates."""
with self.lock:
if self.cache:
if self.use_tmp:
shutil.rmtree(self.tmp_dir, ignore_errors=True)
else:
self.templates = {} | [
"def",
"reset",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"cache",
":",
"if",
"self",
".",
"use_tmp",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"tmp_dir",
",",
"ignore_errors",
"=",
"True",
")",
"else",
":",
... | 35.5 | 13.25 |
def _verify_support(identity, ecdh):
"""Make sure the device supports given configuration."""
protocol = identity.identity_dict['proto']
if protocol not in {'ssh'}:
raise NotImplementedError(
'Unsupported protocol: {}'.format(protocol))
if ecdh:
raise NotImplementedError('No ... | [
"def",
"_verify_support",
"(",
"identity",
",",
"ecdh",
")",
":",
"protocol",
"=",
"identity",
".",
"identity_dict",
"[",
"'proto'",
"]",
"if",
"protocol",
"not",
"in",
"{",
"'ssh'",
"}",
":",
"raise",
"NotImplementedError",
"(",
"'Unsupported protocol: {}'",
... | 45.090909 | 12.909091 |
def send_login():
"""View function that sends login instructions for passwordless login"""
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login... | [
"def",
"send_login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"passwordless_login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",... | 32.666667 | 21.809524 |
def _generate_grid(self):
"""Get the all possible values for each of the tunables."""
grid_axes = []
for _, param in self.tunables:
grid_axes.append(param.get_grid_axis(self.grid_width))
return grid_axes | [
"def",
"_generate_grid",
"(",
"self",
")",
":",
"grid_axes",
"=",
"[",
"]",
"for",
"_",
",",
"param",
"in",
"self",
".",
"tunables",
":",
"grid_axes",
".",
"append",
"(",
"param",
".",
"get_grid_axis",
"(",
"self",
".",
"grid_width",
")",
")",
"return"... | 34.571429 | 16.714286 |
def flush(self, timeout=None):
"""
Invoking this method makes all buffered records immediately available
to send (even if linger_ms is greater than 0) and blocks on the
completion of the requests associated with these records. The
post-condition of :meth:`~kafka.KafkaProducer.flu... | [
"def",
"flush",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\"Flushing accumulated records in producer.\"",
")",
"# trace",
"self",
".",
"_accumulator",
".",
"begin_flush",
"(",
")",
"self",
".",
"_sender",
".",
"wakeup",
"... | 48.423077 | 25.807692 |
def delete(self, path, data=None, headers=None, params=None):
"""
Deletes resources at given paths.
:rtype: dict
:return: Empty dictionary to have consistent interface.
Some of Atlassian REST resources don't return any content.
"""
self.request('DELETE', path=path... | [
"def",
"delete",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"self",
".",
"request",
"(",
"'DELETE'",
",",
"path",
"=",
"path",
",",
"data",
"=",
"data",
",",
"headers",
"... | 44.625 | 16.875 |
def set_attributes(self, obj, **attributes):
""" Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set
"""
attributes_url = '{}/{}/attributes'.format(self.session_url, obj.ref)
attributes_list = [{u'name': str(name), u'... | [
"def",
"set_attributes",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"attributes",
")",
":",
"attributes_url",
"=",
"'{}/{}/attributes'",
".",
"format",
"(",
"self",
".",
"session_url",
",",
"obj",
".",
"ref",
")",
"attributes_list",
"=",
"[",
"{",
"u'name'",
... | 47.818182 | 26.727273 |
def places_radar(client, location, radius, keyword=None, min_price=None,
max_price=None, name=None, open_now=False, type=None):
"""
Performs radar search for places.
:param location: The latitude/longitude value for which you wish to obtain the
closest, human-readable ... | [
"def",
"places_radar",
"(",
"client",
",",
"location",
",",
"radius",
",",
"keyword",
"=",
"None",
",",
"min_price",
"=",
"None",
",",
"max_price",
"=",
"None",
",",
"name",
"=",
"None",
",",
"open_now",
"=",
"False",
",",
"type",
"=",
"None",
")",
"... | 40.759259 | 25.055556 |
def _map_filtered_clusters_to_full_clusters(self,
clusters,
filter_map):
"""
Input: clusters, a list of cluster lists
filter_map, the seq_id in each clusters
... | [
"def",
"_map_filtered_clusters_to_full_clusters",
"(",
"self",
",",
"clusters",
",",
"filter_map",
")",
":",
"results",
"=",
"[",
"]",
"for",
"cluster",
"in",
"clusters",
":",
"full_cluster",
"=",
"[",
"]",
"for",
"seq_id",
"in",
"cluster",
":",
"full_cluster"... | 42 | 12.222222 |
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,
dest_coord=None):
"""Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Option... | [
"def",
"_queueMouseButton",
"(",
"self",
",",
"coord",
",",
"mouseButton",
",",
"modFlags",
",",
"clickCount",
"=",
"1",
",",
"dest_coord",
"=",
"None",
")",
":",
"# For now allow only left and right mouse buttons:",
"mouseButtons",
"=",
"{",
"Quartz",
".",
"kCGMo... | 47.520548 | 19.808219 |
def airing_today(self, **kwargs):
"""
Get the list of TV shows that air today. Without a specified timezone,
this query defaults to EST (Eastern Time UTC-05:00).
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639 code.
timezo... | [
"def",
"airing_today",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'airing_today'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"... | 34.166667 | 19.055556 |
def main():
"""
Upload a vcl file to a fastly service, cloning the current version if
necessary. The uploaded vcl is set as main unless --include is given.
All existing vcl files will be deleted first if --delete is given.
"""
parser = OptionParser(description=
"Upload ... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"description",
"=",
"\"Upload a vcl file (set as main) to a given fastly service. All arguments are required.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-k\"",
",",
"\"--key\"",
",",
"dest",
"=",
"\"ap... | 40.884615 | 20.705128 |
def update_instance(InstanceId=None, LayerIds=None, InstanceType=None, AutoScalingType=None, Hostname=None, Os=None, AmiId=None, SshKeyName=None, Architecture=None, InstallUpdatesOnBoot=None, EbsOptimized=None, AgentVersion=None):
"""
Updates a specified instance.
See also: AWS API Documentation
... | [
"def",
"update_instance",
"(",
"InstanceId",
"=",
"None",
",",
"LayerIds",
"=",
"None",
",",
"InstanceType",
"=",
"None",
",",
"AutoScalingType",
"=",
"None",
",",
"Hostname",
"=",
"None",
",",
"Os",
"=",
"None",
",",
"AmiId",
"=",
"None",
",",
"SshKeyNa... | 62.380952 | 53.166667 |
def cubic_acquaintance_strategy(
qubits: Iterable[ops.Qid],
swap_gate: ops.Gate=ops.SWAP
) -> circuits.Circuit:
"""Acquaints every triple of qubits.
Exploits the fact that in a simple linear swap network every pair of
logical qubits that starts at distance two remains so (except tem... | [
"def",
"cubic_acquaintance_strategy",
"(",
"qubits",
":",
"Iterable",
"[",
"ops",
".",
"Qid",
"]",
",",
"swap_gate",
":",
"ops",
".",
"Gate",
"=",
"ops",
".",
"SWAP",
")",
"->",
"circuits",
".",
"Circuit",
":",
"qubits",
"=",
"tuple",
"(",
"qubits",
")... | 44.068182 | 17.909091 |
def safe_record(ctx, item):
"""Make sure we get a record instance even if we pass an xmlid."""
if isinstance(item, basestring):
return ctx.env.ref(item)
return item | [
"def",
"safe_record",
"(",
"ctx",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"return",
"ctx",
".",
"env",
".",
"ref",
"(",
"item",
")",
"return",
"item"
] | 36 | 10 |
def _create_app(self):
"""
Create `Application` instance for this .
"""
pymux = self.pymux
def on_focus_changed():
""" When the focus changes to a read/write buffer, make sure to go
to insert mode. This happens when the ViState was set to NAVIGATION
... | [
"def",
"_create_app",
"(",
"self",
")",
":",
"pymux",
"=",
"self",
".",
"pymux",
"def",
"on_focus_changed",
"(",
")",
":",
"\"\"\" When the focus changes to a read/write buffer, make sure to go\n to insert mode. This happens when the ViState was set to NAVIGATION\n ... | 39.422535 | 21.183099 |
def _idForObject(self, defaultObject):
"""
Generate an opaque identifier which can be used to talk about
C{defaultObject}.
@rtype: C{int}
"""
identifier = self._allocateID()
self._idsToObjects[identifier] = defaultObject
return identifier | [
"def",
"_idForObject",
"(",
"self",
",",
"defaultObject",
")",
":",
"identifier",
"=",
"self",
".",
"_allocateID",
"(",
")",
"self",
".",
"_idsToObjects",
"[",
"identifier",
"]",
"=",
"defaultObject",
"return",
"identifier"
] | 29.4 | 13.4 |
def _bnd(self, xloc, dist, cache):
"""Distribution bounds."""
return numpy.log(evaluation.evaluate_bound(
dist, numpy.e**xloc, cache=cache)) | [
"def",
"_bnd",
"(",
"self",
",",
"xloc",
",",
"dist",
",",
"cache",
")",
":",
"return",
"numpy",
".",
"log",
"(",
"evaluation",
".",
"evaluate_bound",
"(",
"dist",
",",
"numpy",
".",
"e",
"**",
"xloc",
",",
"cache",
"=",
"cache",
")",
")"
] | 41.25 | 5.75 |
def save(self, file):
"""
Save the image to *file*.
If *file* looks like an open file
descriptor then it is used, otherwise it is treated as a
filename and a fresh file is opened.
In general, you can only call this method once; after it has
been called the first... | [
"def",
"save",
"(",
"self",
",",
"file",
")",
":",
"w",
"=",
"Writer",
"(",
"*",
"*",
"self",
".",
"info",
")",
"try",
":",
"file",
".",
"write",
"def",
"close",
"(",
")",
":",
"pass",
"except",
"AttributeError",
":",
"file",
"=",
"open",
"(",
... | 25.166667 | 20.633333 |
def load():
""" Check available plugins and attempt to import them """
# Code is based on beaker-client's command.py script
plugins = []
for filename in os.listdir(PLUGINS_PATH):
if not filename.endswith(".py") or filename.startswith("_"):
continue
if not os.path.isfile(os.pa... | [
"def",
"load",
"(",
")",
":",
"# Code is based on beaker-client's command.py script",
"plugins",
"=",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"PLUGINS_PATH",
")",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"\".py\"",
")",
"or",
... | 41.192308 | 17.192308 |
def is_sub_to_any_kind(self, *super_entity_kinds):
"""
Find all entities that have super_entities of any of the specified kinds
"""
if super_entity_kinds:
# get the pks of the desired subs from the relationships table
if len(super_entity_kinds) == 1:
... | [
"def",
"is_sub_to_any_kind",
"(",
"self",
",",
"*",
"super_entity_kinds",
")",
":",
"if",
"super_entity_kinds",
":",
"# get the pks of the desired subs from the relationships table",
"if",
"len",
"(",
"super_entity_kinds",
")",
"==",
"1",
":",
"entity_pks",
"=",
"Entity... | 50.888889 | 22.666667 |
def read_value(self):
"""Grabs a lux reading either with autoranging (gain=0) or with a specified gain (1, 16)"""
if self.gain == 1 or self.gain == 16:
self.set_gain(self.gain)
ambient = self.read_full()
ir_reading = self.read_ir()
elif self.gain == 0:
... | [
"def",
"read_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"gain",
"==",
"1",
"or",
"self",
".",
"gain",
"==",
"16",
":",
"self",
".",
"set_gain",
"(",
"self",
".",
"gain",
")",
"ambient",
"=",
"self",
".",
"read_full",
"(",
")",
"ir_reading",
... | 33.540541 | 15.135135 |
def refresh(self, index=None, params=None):
"""
Explicitly refresh one or more index, making all operations performed
since the last refresh available for search.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html>`_
:arg index: A comma-separat... | [
"def",
"refresh",
"(",
"self",
",",
"index",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"POST\"",
",",
"_make_path",
"(",
"index",
",",
"\"_refresh\"",
")",
",",
"params",
"=",
... | 54.7 | 24.7 |
def parse_library(lib_files):
"""
Analizuje pliki podane w liście lib_files
Zwraca instancję MusicLibrary
"""
tracks, playlists = lib_files
lib = MusicLibrary()
lib_length = len(tracks)
i = 0
writer = lib.ix.writer()
previous_procent_done_str = ""
for f in tracks:
tr... | [
"def",
"parse_library",
"(",
"lib_files",
")",
":",
"tracks",
",",
"playlists",
"=",
"lib_files",
"lib",
"=",
"MusicLibrary",
"(",
")",
"lib_length",
"=",
"len",
"(",
"tracks",
")",
"i",
"=",
"0",
"writer",
"=",
"lib",
".",
"ix",
".",
"writer",
"(",
... | 35.3 | 16.566667 |
def construct_result_generator_middleware(result_generators):
"""
Constructs a middleware which intercepts requests for any method found in
the provided mapping of endpoints to generator functions, returning
whatever response the generator function returns. Callbacks must be
functions with the sign... | [
"def",
"construct_result_generator_middleware",
"(",
"result_generators",
")",
":",
"def",
"result_generator_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"if",
"method",
"in",
"result_generator... | 45.3125 | 14.5625 |
def native(self):
"""
The native Python datatype representation of this value
:return:
A list or None. If a list, all child values are recursively
converted to native representation also.
"""
if self.contents is None:
return None
if ... | [
"def",
"native",
"(",
"self",
")",
":",
"if",
"self",
".",
"contents",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"_native",
"is",
"None",
":",
"if",
"self",
".",
"children",
"is",
"None",
":",
"self",
".",
"_parse_children",
"(",
"recur... | 32.5 | 19.045455 |
def listening_ports():
""" Reads listening ports from /proc/net/tcp """
ports = []
if not os.path.exists(PROC_TCP):
return ports
with open(PROC_TCP) as fh:
for line in fh:
if '00000000:0000' not in line:
continue
parts = line.lstrip(' ').split(' ... | [
"def",
"listening_ports",
"(",
")",
":",
"ports",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"PROC_TCP",
")",
":",
"return",
"ports",
"with",
"open",
"(",
"PROC_TCP",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"... | 26.65 | 17.55 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._type_ is not None:
return False
if self._value is not None:
return False
if self._name is not None:
return False
return True | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_type_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_value",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_name",
"is",
"not",
"None",
":... | 17.666667 | 18.466667 |
def send(self, message):
"""
Sends a message (synchronous)
:param message: Message to send
:return: Message response(s)
"""
future = self.post(message)
future.join()
return future.result | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"future",
"=",
"self",
".",
"post",
"(",
"message",
")",
"future",
".",
"join",
"(",
")",
"return",
"future",
".",
"result"
] | 24.2 | 10 |
def H11(self):
"Difference entropy."
return -(self.p_xminusy * np.log(self.p_xminusy + self.eps)).sum(1) | [
"def",
"H11",
"(",
"self",
")",
":",
"return",
"-",
"(",
"self",
".",
"p_xminusy",
"*",
"np",
".",
"log",
"(",
"self",
".",
"p_xminusy",
"+",
"self",
".",
"eps",
")",
")",
".",
"sum",
"(",
"1",
")"
] | 39.333333 | 24 |
def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""2D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevali... | [
"def",
"convolved_2d",
"(",
"iterable",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"default_value",
"=",
"None",
")",
":",
"kernel_size",
"=",
"dimensionize",
"(",
"kernel_size",
",",
"nd",
"=",
"2",
")",
"str... | 45.090909 | 20.590909 |
def run_func(self, func_path, *func_args, **kwargs):
"""Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.... | [
"def",
"run_func",
"(",
"self",
",",
"func_path",
",",
"*",
"func_args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"ValueError",
"(",
"'Session not started, use start()'",
")",
"nargout",
"=",
"kwargs",
".",
"pop... | 40.5 | 16.861111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.