text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def vcs_rbridge_context_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcs_rbridge_context = ET.Element("vcs_rbridge_context")
config = vcs_rbridge_context
input = ET.SubElement(vcs_rbridge_context, "input")
rbridge_id =... | [
"def",
"vcs_rbridge_context_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"vcs_rbridge_context",
"=",
"ET",
".",
"Element",
"(",
"\"vcs_rbridge_context\"",
")",
"config",
"=",
"v... | 40.5 | 13.083333 |
def only_owner(func):
"""
Only owner decorator
Restricts access to view ony to profile owner
"""
def decorated(*_, **kwargs):
id = kwargs['id']
if not current_user.is_authenticated:
abort(401)
elif current_user.id != id:
abort(403)
return func(... | [
"def",
"only_owner",
"(",
"func",
")",
":",
"def",
"decorated",
"(",
"*",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"id",
"=",
"kwargs",
"[",
"'id'",
"]",
"if",
"not",
"current_user",
".",
"is_authenticated",
":",
"abort",
"(",
"401",
")",
"elif",
"c... | 24.142857 | 13.142857 |
def run_samblaster(job, sam):
"""
Marks reads as PCR duplicates using SAMBLASTER
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str sam: FileStoreID for SAM file
:return: FileStoreID for deduped SAM file
:rtype: str
"""
work_dir = job.fileStore.getLocalTempDir()
... | [
"def",
"run_samblaster",
"(",
"job",
",",
"sam",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"job",
".",
"fileStore",
".",
"readGlobalFile",
"(",
"sam",
",",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
","... | 37.73913 | 14.173913 |
def _init_multicast_socket(self):
"""
Init multicast socket
:rtype: None
"""
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
... | [
"def",
"_init_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"# Create a UDP socket",
"self",
".",
"_multicast_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"... | 29 | 16.636364 |
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
for _, value in ast.iter_fields(node):
if isinstance(value, list):
self._handle_ast_list(value)
for item in value:
if isinstance(item, ast.AST):
... | [
"def",
"generic_visit",
"(",
"self",
",",
"node",
")",
":",
"for",
"_",
",",
"value",
"in",
"ast",
".",
"iter_fields",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"self",
".",
"_handle_ast_list",
"(",
"value",
")",... | 43 | 4.7 |
def parse_theme(self, xml):
""" Parses a theme from XML returned by Kuler.
Gets the theme's id, label and swatches.
All of the swatches are converted to RGB.
If we have a full description for a theme id in cache,
parse that to get tags associated with the theme.... | [
"def",
"parse_theme",
"(",
"self",
",",
"xml",
")",
":",
"kt",
"=",
"KulerTheme",
"(",
")",
"kt",
".",
"author",
"=",
"xml",
".",
"getElementsByTagName",
"(",
"\"author\"",
")",
"[",
"0",
"]",
"kt",
".",
"author",
"=",
"kt",
".",
"author",
".",
"ch... | 37 | 14.765957 |
def _expand(self):
"""
Expand the free pool, if possible.
If out of capacity w.r.t. the defined ID value range, ValueError is
raised.
"""
assert not self._free # free pool is empty
expand_end = self._expand_start + self._expand_len
if expand_end > self._... | [
"def",
"_expand",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_free",
"# free pool is empty",
"expand_end",
"=",
"self",
".",
"_expand_start",
"+",
"self",
".",
"_expand_len",
"if",
"expand_end",
">",
"self",
".",
"_range_end",
":",
"# This happens i... | 40.117647 | 13.882353 |
def item(self, infohash, prefetch=None, cache=False):
""" Fetch a single item by its info hash.
"""
return next(self.items(infohash, prefetch, cache)) | [
"def",
"item",
"(",
"self",
",",
"infohash",
",",
"prefetch",
"=",
"None",
",",
"cache",
"=",
"False",
")",
":",
"return",
"next",
"(",
"self",
".",
"items",
"(",
"infohash",
",",
"prefetch",
",",
"cache",
")",
")"
] | 42.75 | 7.75 |
def html_serialize(self, attributes, max_length=None):
"""Returns concatenated HTML code with SPAN tag.
Args:
attributes (dict): A map of name-value pairs for attributes of output
SPAN tags.
max_length (:obj:`int`, optional): Maximum length of span enclosed chunk.
Returns:
The ... | [
"def",
"html_serialize",
"(",
"self",
",",
"attributes",
",",
"max_length",
"=",
"None",
")",
":",
"doc",
"=",
"ET",
".",
"Element",
"(",
"'span'",
")",
"for",
"chunk",
"in",
"self",
":",
"if",
"(",
"chunk",
".",
"has_cjk",
"(",
")",
"and",
"not",
... | 33.921053 | 16.842105 |
def SingleModeCombine(pupils,modeDiameter=None):
"""
Return the instantaneous coherent fluxes and photometric fluxes for a
multiway single-mode fibre combiner
"""
if modeDiameter is None:
modeDiameter=0.9*pupils.shape[-1]
amplitudes=FibreCouple(pupils,modeDiameter)
cc=np.conj(amplitu... | [
"def",
"SingleModeCombine",
"(",
"pupils",
",",
"modeDiameter",
"=",
"None",
")",
":",
"if",
"modeDiameter",
"is",
"None",
":",
"modeDiameter",
"=",
"0.9",
"*",
"pupils",
".",
"shape",
"[",
"-",
"1",
"]",
"amplitudes",
"=",
"FibreCouple",
"(",
"pupils",
... | 36.357143 | 7.785714 |
def dot(self, vec):
"""Dot product with another vector"""
if not isinstance(vec, self.__class__):
raise TypeError('Dot product operand must be a VectorArray')
if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV:
raise ValueError('Dot product operands must have the same ... | [
"def",
"dot",
"(",
"self",
",",
"vec",
")",
":",
"if",
"not",
"isinstance",
"(",
"vec",
",",
"self",
".",
"__class__",
")",
":",
"raise",
"TypeError",
"(",
"'Dot product operand must be a VectorArray'",
")",
"if",
"self",
".",
"nV",
"!=",
"1",
"and",
"ve... | 55.75 | 20.375 |
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar, dctPrm=None,
lgcPrint=True):
"""Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *... | [
"def",
"crt_prf_ftr_tc",
"(",
"aryMdlRsp",
",",
"aryTmpExpInf",
",",
"varNumVol",
",",
"varTr",
",",
"varTmpOvsmpl",
",",
"switchHrfSet",
",",
"tplPngSize",
",",
"varPar",
",",
"dctPrm",
"=",
"None",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# Identify number o... | 40.130435 | 19.956522 |
def _get_format_name_loader_mapping(self):
"""
:return: Mappings of format-name and loader class.
:rtype: dict
"""
loader_table = self._get_common_loader_mapping()
loader_table.update(
{
"excel": ExcelTableFileLoader,
"json_lin... | [
"def",
"_get_format_name_loader_mapping",
"(",
"self",
")",
":",
"loader_table",
"=",
"self",
".",
"_get_common_loader_mapping",
"(",
")",
"loader_table",
".",
"update",
"(",
"{",
"\"excel\"",
":",
"ExcelTableFileLoader",
",",
"\"json_lines\"",
":",
"JsonLinesTableTex... | 29.833333 | 16.388889 |
async def jsk_vc_resume(self, ctx: commands.Context):
"""
Resumes a running audio source, if there is one.
"""
voice = ctx.guild.voice_client
if not voice.is_paused():
return await ctx.send("Audio is not paused.")
voice.resume()
await ctx.send(f"Res... | [
"async",
"def",
"jsk_vc_resume",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
")",
":",
"voice",
"=",
"ctx",
".",
"guild",
".",
"voice_client",
"if",
"not",
"voice",
".",
"is_paused",
"(",
")",
":",
"return",
"await",
"ctx",
".",
"send",
... | 28.833333 | 18.166667 |
def _create_decoding_layers(self):
"""Create the decoding layers for reconstruction finetuning.
:return: output of the final encoding layer.
"""
next_decode = self.encode
for l, layer in reversed(list(enumerate(self.layers))):
with tf.name_scope("decode-{}".format(... | [
"def",
"_create_decoding_layers",
"(",
"self",
")",
":",
"next_decode",
"=",
"self",
".",
"encode",
"for",
"l",
",",
"layer",
"in",
"reversed",
"(",
"list",
"(",
"enumerate",
"(",
"self",
".",
"layers",
")",
")",
")",
":",
"with",
"tf",
".",
"name_scop... | 33.35 | 20.725 |
def get_port_from_port_server(portserver_address, pid=None):
"""Request a free a port from a system-wide portserver.
This follows a very simple portserver protocol:
The request consists of our pid (in ASCII) followed by a newline.
The response is a port number and a newline, 0 on failure.
This fun... | [
"def",
"get_port_from_port_server",
"(",
"portserver_address",
",",
"pid",
"=",
"None",
")",
":",
"if",
"not",
"portserver_address",
":",
"return",
"None",
"# An AF_UNIX address may start with a zero byte, in which case it is in the",
"# \"abstract namespace\", and doesn't have any... | 35.9375 | 22.03125 |
def format_currency(number, currency, format=None,
locale=LC_NUMERIC, currency_digits=True,
format_type='standard', decimal_quantization=True):
"""Return formatted currency value.
>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_curren... | [
"def",
"format_currency",
"(",
"number",
",",
"currency",
",",
"format",
"=",
"None",
",",
"locale",
"=",
"LC_NUMERIC",
",",
"currency_digits",
"=",
"True",
",",
"format_type",
"=",
"'standard'",
",",
"decimal_quantization",
"=",
"True",
")",
":",
"locale",
... | 38.923077 | 24.10989 |
def data_url_scheme(self):
"""Get svg in Data URL Scheme format.
"""
# TODO: move to web.app or make it function
# remove #svg from dataframe
encoded = base64.b64encode(self.contents().encode())
return "data:image/svg+xml;base64," + encoded.decode() | [
"def",
"data_url_scheme",
"(",
"self",
")",
":",
"# TODO: move to web.app or make it function",
"# remove #svg from dataframe",
"encoded",
"=",
"base64",
".",
"b64encode",
"(",
"self",
".",
"contents",
"(",
")",
".",
"encode",
"(",
")",
")",
"return",
"\"data:image/... | 41.571429 | 10.142857 |
def name(self, name):
"""Set the member name.
Note that a member name cannot appear in other enums, or generally
anywhere else in the IDB.
"""
success = idaapi.set_enum_member_name(self.cid, name)
if not success:
raise exceptions.CantRenameEnumMember(
... | [
"def",
"name",
"(",
"self",
",",
"name",
")",
":",
"success",
"=",
"idaapi",
".",
"set_enum_member_name",
"(",
"self",
".",
"cid",
",",
"name",
")",
"if",
"not",
"success",
":",
"raise",
"exceptions",
".",
"CantRenameEnumMember",
"(",
"\"Failed renaming {!r}... | 41.2 | 21.6 |
def boll(self, n, dev, array=False):
"""布林通道"""
mid = self.sma(n, array)
std = self.std(n, array)
up = mid + std * dev
down = mid - std * dev
return up, down | [
"def",
"boll",
"(",
"self",
",",
"n",
",",
"dev",
",",
"array",
"=",
"False",
")",
":",
"mid",
"=",
"self",
".",
"sma",
"(",
"n",
",",
"array",
")",
"std",
"=",
"self",
".",
"std",
"(",
"n",
",",
"array",
")",
"up",
"=",
"mid",
"+",
"std",
... | 22.111111 | 15.444444 |
def create_proforma_invoice(sender, instance, created, **kwargs):
"""
For every Order if there are defined billing_data creates invoice proforma,
which is an order confirmation document
"""
if created:
Invoice.create(instance, Invoice.INVOICE_TYPES['PROFORMA']) | [
"def",
"create_proforma_invoice",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"Invoice",
".",
"create",
"(",
"instance",
",",
"Invoice",
".",
"INVOICE_TYPES",
"[",
"'PROFORMA'",
"]",
")"
] | 40.428571 | 17 |
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == ... | [
"def",
"_check_cron_env",
"(",
"user",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"\"\"",
"# Matching value set in salt.modules.cron._render_tab",
"lst",
"=",
"__salt__",
"[",
"'cron.list_tab'",
"]",
"(",
... | 29.133333 | 15.4 |
def p_literal_list(self, p):
"""literal_list : literal_list LITERAL
| LITERAL"""
if len(p) == 3:
p[0] = p[1] + [p[2][1:-1]]
else:
p[0] = [p[1][1:-1]] | [
"def",
"p_literal_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"[",
"1",
":",
"-",
"1",
"]",
"]",
"else",
":",
"p",
"[",... | 26.875 | 13.375 |
def get(self, agentml, user=None, key=None):
"""
Evaluate and return the current active topic
:param user: The active user object
:type user: agentml.User or None
:param agentml: The active AgentML instance
:type agentml: AgentML
:param key: The user id (defau... | [
"def",
"get",
"(",
"self",
",",
"agentml",
",",
"user",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"user",
"=",
"agentml",
".",
"get_user",
"(",
"key",
")",
"if",
"key",
"else",
"user",
"if",
"not",
"user",
":",
"return",
"return",
"user",
"... | 27.95 | 16.65 |
def wrap_io_os_err(e):
'''Formats IO and OS error messages for wrapping in FSQExceptions'''
msg = ''
if e.strerror:
msg = e.strerror
if e.message:
msg = ' '.join([e.message, msg])
if e.filename:
msg = ': '.join([msg, e.filename])
return msg | [
"def",
"wrap_io_os_err",
"(",
"e",
")",
":",
"msg",
"=",
"''",
"if",
"e",
".",
"strerror",
":",
"msg",
"=",
"e",
".",
"strerror",
"if",
"e",
".",
"message",
":",
"msg",
"=",
"' '",
".",
"join",
"(",
"[",
"e",
".",
"message",
",",
"msg",
"]",
... | 27.9 | 18.9 |
def list_cameras():
""" List all attached USB cameras that are supported by libgphoto2.
:return: All recognized cameras
:rtype: list of :py:class:`Camera`
"""
ctx = lib.gp_context_new()
camlist_p = new_gp_object("CameraList")
port_list_p = new_gp_object("GPPortInfoList")
lib.gp_p... | [
"def",
"list_cameras",
"(",
")",
":",
"ctx",
"=",
"lib",
".",
"gp_context_new",
"(",
")",
"camlist_p",
"=",
"new_gp_object",
"(",
"\"CameraList\"",
")",
"port_list_p",
"=",
"new_gp_object",
"(",
"\"GPPortInfoList\"",
")",
"lib",
".",
"gp_port_info_list_load",
"(... | 41.567568 | 15.405405 |
def hairball_files(self, paths, extensions):
"""Yield filepath to files with the proper extension within paths."""
def add_file(filename):
return os.path.splitext(filename)[1] in extensions
while paths:
arg_path = paths.pop(0)
if os.path.isdir(arg_path):
... | [
"def",
"hairball_files",
"(",
"self",
",",
"paths",
",",
"extensions",
")",
":",
"def",
"add_file",
"(",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"in",
"extensions",
"while",
"paths",
":",... | 44.695652 | 12.73913 |
def build(self, search, raw_query):
"""Build query.
:param search: Search query instance
:param raw_query: Raw query arguments dictionary
"""
unmatched_items = {}
for expression, value in raw_query.items():
# Parse query expression into tokens.
to... | [
"def",
"build",
"(",
"self",
",",
"search",
",",
"raw_query",
")",
":",
"unmatched_items",
"=",
"{",
"}",
"for",
"expression",
",",
"value",
"in",
"raw_query",
".",
"items",
"(",
")",
":",
"# Parse query expression into tokens.",
"tokens",
"=",
"expression",
... | 41.214286 | 21.880952 |
def subscribe(self, topic, callback, ordered=True):
"""Subscribe to future messages in the given topic
The contents of topic should be in the format created by self.publish with a
sequence number of message type encoded as a json string.
Wildcard topics containing + and # are allowed a... | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"callback",
",",
"ordered",
"=",
"True",
")",
":",
"if",
"'+'",
"in",
"topic",
"or",
"'#'",
"in",
"topic",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"topic",
".",
"replace",
"(",
"'+'",
",",
... | 47.076923 | 29.423077 |
def _setup_resources():
"""Attempt to increase resource limits up to hard limits.
This allows us to avoid out of file handle limits where we can
move beyond the soft limit up to the hard limit.
"""
target_procs = 10240
cur_proc, max_proc = resource.getrlimit(resource.RLIMIT_NPROC)
target_pr... | [
"def",
"_setup_resources",
"(",
")",
":",
"target_procs",
"=",
"10240",
"cur_proc",
",",
"max_proc",
"=",
"resource",
".",
"getrlimit",
"(",
"resource",
".",
"RLIMIT_NPROC",
")",
"target_proc",
"=",
"min",
"(",
"max_proc",
",",
"target_procs",
")",
"if",
"ma... | 53.461538 | 25.615385 |
def matches(self, desc):
"""Determines if a given label descriptor matches this enum instance
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the instance to test
Return:
`True` if desc is supported, otherwise `F... | [
"def",
"matches",
"(",
"self",
",",
"desc",
")",
":",
"desc_value_type",
"=",
"desc",
".",
"valueType",
"or",
"ValueType",
".",
"STRING",
"# default not parsed",
"return",
"(",
"self",
".",
"label_name",
"==",
"desc",
".",
"key",
"and",
"self",
".",
"value... | 36.285714 | 23.5 |
def regenerate_models(self, propnames=None, exclude=[], deep=False):
r"""
Re-runs the specified model or models.
Parameters
----------
propnames : string or list of strings
The list of property names to be regenerated. If None are given
then ALL models a... | [
"def",
"regenerate_models",
"(",
"self",
",",
"propnames",
"=",
"None",
",",
"exclude",
"=",
"[",
"]",
",",
"deep",
"=",
"False",
")",
":",
"# If empty list of propnames was given, do nothing and return",
"if",
"type",
"(",
"propnames",
")",
"is",
"list",
"and",... | 47.610169 | 23.627119 |
def _solve(self, x0, A, l, u, xmin, xmax):
""" Solves using Python Interior Point Solver (PIPS).
"""
s = pips(self._costfcn, x0, A, l, u, xmin, xmax,
self._consfcn, self._hessfcn, self.opt)
return s | [
"def",
"_solve",
"(",
"self",
",",
"x0",
",",
"A",
",",
"l",
",",
"u",
",",
"xmin",
",",
"xmax",
")",
":",
"s",
"=",
"pips",
"(",
"self",
".",
"_costfcn",
",",
"x0",
",",
"A",
",",
"l",
",",
"u",
",",
"xmin",
",",
"xmax",
",",
"self",
"."... | 40.333333 | 9.666667 |
def write_config_file(self, f, comments):
"""This method write a sample file, with attributes, descriptions,
sample values, required flags, using the configuration object
properties.
"""
if comments:
f.write("#####################################\n")
f.wri... | [
"def",
"write_config_file",
"(",
"self",
",",
"f",
",",
"comments",
")",
":",
"if",
"comments",
":",
"f",
".",
"write",
"(",
"\"#####################################\\n\"",
")",
"f",
".",
"write",
"(",
"\"# Section : \"",
")",
"f",
".",
"write",
"(",
"\"#\""... | 40.222222 | 11.388889 |
def monitor_experiment(args):
'''monitor the experiment'''
if args.time <= 0:
print_error('please input a positive integer as time interval, the unit is second.')
exit(1)
while True:
try:
os.system('clear')
update_experiment()
show_experiment_info(... | [
"def",
"monitor_experiment",
"(",
"args",
")",
":",
"if",
"args",
".",
"time",
"<=",
"0",
":",
"print_error",
"(",
"'please input a positive integer as time interval, the unit is second.'",
")",
"exit",
"(",
"1",
")",
"while",
"True",
":",
"try",
":",
"os",
".",... | 30.5 | 16 |
def _muck_w_date(record):
"""muck with the date because EPW starts counting from 1 and goes to 24."""
# minute 60 is actually minute 0?
temp_d = datetime.datetime(int(record['Year']), int(record['Month']),
int(record['Day']), int(record['Hour']) % 24,
... | [
"def",
"_muck_w_date",
"(",
"record",
")",
":",
"# minute 60 is actually minute 0?",
"temp_d",
"=",
"datetime",
".",
"datetime",
"(",
"int",
"(",
"record",
"[",
"'Year'",
"]",
")",
",",
"int",
"(",
"record",
"[",
"'Month'",
"]",
")",
",",
"int",
"(",
"re... | 49.6 | 18.5 |
def _unpack_body(self):
"""Unpack `body` replace it by the result."""
obj = self._get_body_instance()
obj.unpack(self.body.value)
self.body = obj | [
"def",
"_unpack_body",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"_get_body_instance",
"(",
")",
"obj",
".",
"unpack",
"(",
"self",
".",
"body",
".",
"value",
")",
"self",
".",
"body",
"=",
"obj"
] | 34.6 | 8 |
def console_print_rect_ex(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
flag: int,
alignment: int,
fmt: str,
) -> int:
"""Print a string constrained to a rectangle with blend and alignment.
Returns:
int: The number of lines of text once word-wrapped.
.... | [
"def",
"console_print_rect_ex",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"flag",
":",
"int",
",",
"alignment",
":",
"int",
",",
"fmt",
... | 22.173913 | 22.217391 |
def setupTable_VORG(self):
"""
Make the VORG table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "VORG" not in self.tables:
return
... | [
"def",
"setupTable_VORG",
"(",
"self",
")",
":",
"if",
"\"VORG\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"self",
".",
"otf",
"[",
"\"VORG\"",
"]",
"=",
"vorg",
"=",
"newTable",
"(",
"\"VORG\"",
")",
"vorg",
".",
"majorVersion",
"=",
"1",
... | 39.208333 | 16.125 |
def validate_rmq_cluster_running_nodes(self, sentry_units):
"""Check that all rmq unit hostnames are represented in the
cluster_status output of all units.
:param host_names: dict of juju unit names to host names
:param units: list of sentry unit pointers (all rmq units)
:return... | [
"def",
"validate_rmq_cluster_running_nodes",
"(",
"self",
",",
"sentry_units",
")",
":",
"host_names",
"=",
"self",
".",
"get_unit_hostnames",
"(",
"sentry_units",
")",
"errors",
"=",
"[",
"]",
"# Query every unit for cluster_status running nodes",
"for",
"query_unit",
... | 47.482759 | 22.034483 |
def teardown(self):
'''
cleanup the monitor data and
'''
self.monitor_thread.stop()
self.monitor_thread = None
super(BaseMonitor, self).teardown() | [
"def",
"teardown",
"(",
"self",
")",
":",
"self",
".",
"monitor_thread",
".",
"stop",
"(",
")",
"self",
".",
"monitor_thread",
"=",
"None",
"super",
"(",
"BaseMonitor",
",",
"self",
")",
".",
"teardown",
"(",
")"
] | 26.857143 | 14 |
def main():
"""Entrypoint for ``lander`` executable."""
args = parse_args()
config_logger(args)
logger = structlog.get_logger(__name__)
if args.show_version:
# only print the version
print_version()
sys.exit(0)
version = pkg_resources.get_distribution('lander').version
... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"config_logger",
"(",
"args",
")",
"logger",
"=",
"structlog",
".",
"get_logger",
"(",
"__name__",
")",
"if",
"args",
".",
"show_version",
":",
"# only print the version",
"print_version",
"(... | 25.533333 | 18.7 |
def link_marked_atoms(self, atoms):
"""
Take a list of marked "interesting" atoms (heteroatoms, special carbons)
and attempt to connect them, returning a list of disjoint groups of
special atoms (and their connected hydrogens).
:param atoms: set of marked "interesting" atoms, pr... | [
"def",
"link_marked_atoms",
"(",
"self",
",",
"atoms",
")",
":",
"# We will add hydrogens to functional groups",
"hydrogens",
"=",
"{",
"n",
"for",
"n",
"in",
"self",
".",
"molgraph",
".",
"graph",
".",
"nodes",
"if",
"str",
"(",
"self",
".",
"species",
"[",... | 38.882353 | 20.764706 |
def get(url, **kwargs):
"""
Wrapper for `request.get` function to set params.
"""
headers = kwargs.get('headers', {})
headers['User-Agent'] = config.USER_AGENT # overwrite
kwargs['headers'] = headers
timeout = kwargs.get('timeout', config.TIMEOUT)
kwargs['timeout'] = timeout
kwargs... | [
"def",
"get",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
"[",
"'User-Agent'",
"]",
"=",
"config",
".",
"USER_AGENT",
"# overwrite",
"kwargs",
"[",
"'headers'",
... | 27.666667 | 13.666667 |
def insert(self, index: int, obj: Any) -> None:
""" Inserts an item to the list as long as it is not None """
if obj is not None:
super().insert(index, obj) | [
"def",
"insert",
"(",
"self",
",",
"index",
":",
"int",
",",
"obj",
":",
"Any",
")",
"->",
"None",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"super",
"(",
")",
".",
"insert",
"(",
"index",
",",
"obj",
")"
] | 45.25 | 5.5 |
def perform_initialization(self):
'''Initialize the harvesting for a given job'''
log.debug('Initializing backend')
factory = HarvestJob if self.dryrun else HarvestJob.objects.create
self.job = factory(status='initializing',
started=datetime.now(),
... | [
"def",
"perform_initialization",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Initializing backend'",
")",
"factory",
"=",
"HarvestJob",
"if",
"self",
".",
"dryrun",
"else",
"HarvestJob",
".",
"objects",
".",
"create",
"self",
".",
"job",
"=",
"factory... | 36.282051 | 16.538462 |
def simplify(self, options=None):
"""
returns a dict describing a simple snapshot of this change, and
its children if any.
"""
simple = {
"class": type(self).__name__,
"is_change": self.is_change(),
"description": self.get_description(),
... | [
"def",
"simplify",
"(",
"self",
",",
"options",
"=",
"None",
")",
":",
"simple",
"=",
"{",
"\"class\"",
":",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"\"is_change\"",
":",
"self",
".",
"is_change",
"(",
")",
",",
"\"description\"",
":",
"self",
... | 25.423077 | 17.192308 |
def index_complement(index_list, len_=None):
"""
Returns the other indicies in a list of length ``len_``
"""
mask1 = index_to_boolmask(index_list, len_)
mask2 = not_list(mask1)
index_list_bar = list_where(mask2)
return index_list_bar | [
"def",
"index_complement",
"(",
"index_list",
",",
"len_",
"=",
"None",
")",
":",
"mask1",
"=",
"index_to_boolmask",
"(",
"index_list",
",",
"len_",
")",
"mask2",
"=",
"not_list",
"(",
"mask1",
")",
"index_list_bar",
"=",
"list_where",
"(",
"mask2",
")",
"... | 31.75 | 7.5 |
def list_connections(self, limit=500, offset=0):
"""List Points to which this Things is subscribed.
I.e. list all the Points this Thing is following and controls it's attached to
Returns subscription list e.g.
#!python
{
"<Subscription GUID 1>": {
... | [
"def",
"list_connections",
"(",
"self",
",",
"limit",
"=",
"500",
",",
"offset",
"=",
"0",
")",
":",
"evt",
"=",
"self",
".",
"_client",
".",
"_request_sub_list",
"(",
"self",
".",
"__lid",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")... | 42.125 | 23.96875 |
def is_python_script(filename):
'''Checks a file to see if it's a python script of some sort.
'''
if filename.lower().endswith('.py'):
return True
if not os.path.isfile(filename):
return False
try:
with open(filename, 'rb') as fp:
if fp.read(2) != b'#!':
... | [
"def",
"is_python_script",
"(",
"filename",
")",
":",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.py'",
")",
":",
"return",
"True",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"False",
"t... | 24.277778 | 20.833333 |
def calcMzFromMass(mass, charge):
"""Calculate the mz value of a peptide from its mass and charge.
:param mass: float, exact non protonated mass
:param charge: int, charge state
:returns: mass to charge ratio of the specified charge state
"""
mz = (mass + (maspy.constants.atomicMassProton * ch... | [
"def",
"calcMzFromMass",
"(",
"mass",
",",
"charge",
")",
":",
"mz",
"=",
"(",
"mass",
"+",
"(",
"maspy",
".",
"constants",
".",
"atomicMassProton",
"*",
"charge",
")",
")",
"/",
"charge",
"return",
"mz"
] | 34 | 18.1 |
def is_extension_type(arr):
"""
Check whether an array-like is of a pandas extension class instance.
Extension classes include categoricals, pandas sparse objects (i.e.
classes represented within the pandas library and not ones external
to it like scipy sparse matrices), and datetime-like arrays.
... | [
"def",
"is_extension_type",
"(",
"arr",
")",
":",
"if",
"is_categorical",
"(",
"arr",
")",
":",
"return",
"True",
"elif",
"is_sparse",
"(",
"arr",
")",
":",
"return",
"True",
"elif",
"is_datetime64tz_dtype",
"(",
"arr",
")",
":",
"return",
"True",
"return"... | 25.245614 | 22.649123 |
def delete_session(sid_s):
"""Delete entries in the data- and kvsessionstore with the given sid_s.
On a successful deletion, the flask-kvsession store returns 1 while the
sqlalchemy datastore returns None.
:param sid_s: The session ID.
:returns: ``1`` if deletion was successful.
"""
# Remo... | [
"def",
"delete_session",
"(",
"sid_s",
")",
":",
"# Remove entries from sessionstore",
"_sessionstore",
".",
"delete",
"(",
"sid_s",
")",
"# Find and remove the corresponding SessionActivity entry",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"Sess... | 35.933333 | 15.4 |
def get_fieldset_index(fieldsets, index_or_name):
"""
Return the index of a fieldset in the ``fieldsets`` list.
Args:
fieldsets (list): The original ``fieldsets`` list.
index_or_name (int or str): The value of the reference element, or directly its numeric index.
Returns:
(int)... | [
"def",
"get_fieldset_index",
"(",
"fieldsets",
",",
"index_or_name",
")",
":",
"if",
"isinstance",
"(",
"index_or_name",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"index_or_name",
"for",
"key",
",",
"value",
"in",
"enumerate",
"(",
"fieldsets",
")"... | 32.473684 | 22.473684 |
def _ProcessImage(self, tag, wall_time, step, image):
"""Processes an image by adding it to accumulated state."""
event = ImageEvent(wall_time=wall_time,
step=step,
encoded_image_string=image.encoded_image_string,
width=image.width,
... | [
"def",
"_ProcessImage",
"(",
"self",
",",
"tag",
",",
"wall_time",
",",
"step",
",",
"image",
")",
":",
"event",
"=",
"ImageEvent",
"(",
"wall_time",
"=",
"wall_time",
",",
"step",
"=",
"step",
",",
"encoded_image_string",
"=",
"image",
".",
"encoded_image... | 47.75 | 7.875 |
def _read_para_echo_request_unsigned(self, code, cbit, clen, *, desc, length, version):
"""Read HIP ECHO_REQUEST_UNSIGNED parameter.
Structure of HIP ECHO_REQUEST_UNSIGNED parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0... | [
"def",
"_read_para_echo_request_unsigned",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"_data",
"=",
"self",
".",
"_read_fileng",
"(",
"clen",
")",
"echo_request_unsigned",
"=",
"dict"... | 43.666667 | 27.333333 |
def get_best_electronegativity_anonymous_mapping(self, struct1, struct2):
"""
Performs an anonymous fitting, which allows distinct species in one
structure to map to another. E.g., to compare if the Li2O and Na2O
structures are similar. If multiple substitutions are within tolerance
... | [
"def",
"get_best_electronegativity_anonymous_mapping",
"(",
"self",
",",
"struct1",
",",
"struct2",
")",
":",
"struct1",
",",
"struct2",
"=",
"self",
".",
"_process_species",
"(",
"[",
"struct1",
",",
"struct2",
"]",
")",
"struct1",
",",
"struct2",
",",
"fu",
... | 41.451613 | 22.290323 |
def imbalance_metrics(data):
""" Computes imbalance metric for a given dataset.
Imbalance metric is equal to 0 when a dataset is perfectly balanced (i.e. number of in each class is exact).
:param data : pandas.DataFrame
A dataset in a panda's data frame
:returns int
A value of imbalan... | [
"def",
"imbalance_metrics",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"0",
"#imb - shows measure of inbalance within a dataset",
"imb",
"=",
"0",
"num_classes",
"=",
"float",
"(",
"len",
"(",
"Counter",
"(",
"data",
")",
")",
")",
"for",
"x"... | 46.95 | 22.85 |
def address_from_digest(digest):
# type: (Digest) -> Address
"""
Generates an address from a private key digest.
"""
address_trits = [0] * (Address.LEN * TRITS_PER_TRYTE) # type: List[int]
sponge = Kerl()
sponge.absorb(digest.as_trits())
sponge.squeeze(a... | [
"def",
"address_from_digest",
"(",
"digest",
")",
":",
"# type: (Digest) -> Address",
"address_trits",
"=",
"[",
"0",
"]",
"*",
"(",
"Address",
".",
"LEN",
"*",
"TRITS_PER_TRYTE",
")",
"# type: List[int]",
"sponge",
"=",
"Kerl",
"(",
")",
"sponge",
".",
"absor... | 28.647059 | 15.470588 |
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
'''
Waits wrapper that'll wait for the condition to become true, but will
not error if the condition isn't met.
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
time... | [
"def",
"wait_and_ignore",
"(",
"condition",
",",
"timeout",
"=",
"WTF_TIMEOUT_MANAGER",
".",
"NORMAL",
",",
"sleep",
"=",
"0.5",
")",
":",
"try",
":",
"return",
"wait_until",
"(",
"condition",
",",
"timeout",
",",
"sleep",
")",
"except",
":",
"pass"
] | 29.575758 | 26.242424 |
def random_draw(self, size=None):
"""Draw random samples of the hyperparameters.
Parameters
----------
size : None, int or array-like, optional
The number/shape of samples to draw. If None, only one sample is
returned. Default is None.
"""
... | [
"def",
"random_draw",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"return",
"scipy",
".",
"asarray",
"(",
"[",
"scipy",
".",
"stats",
".",
"norm",
".",
"rvs",
"(",
"loc",
"=",
"m",
",",
"scale",
"=",
"s",
",",
"size",
"=",
"size",
")",
"fo... | 42 | 20.5 |
def get_output_jsonpath_with_name(self, sub_output=None):
"""If ExtractorProcessor has a name defined, return
a JSONPath that has a filter on that name"""
if self.name is None:
return None
output_jsonpath_field = self.get_output_jsonpath_field(sub_output)
extractor_f... | [
"def",
"get_output_jsonpath_with_name",
"(",
"self",
",",
"sub_output",
"=",
"None",
")",
":",
"if",
"self",
".",
"name",
"is",
"None",
":",
"return",
"None",
"output_jsonpath_field",
"=",
"self",
".",
"get_output_jsonpath_field",
"(",
"sub_output",
")",
"extrac... | 41.166667 | 18.25 |
def parse_argv(self, argv=None, location='Command line.'):
"""Parse command line arguments.
args <list str> or None:
The argument list to parse. None means use a copy of sys.argv. argv[0] is
ignored.
location = '' <str>:
A user friendly string describ... | [
"def",
"parse_argv",
"(",
"self",
",",
"argv",
"=",
"None",
",",
"location",
"=",
"'Command line.'",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"list",
"(",
"sys",
".",
"argv",
")",
"argv",
".",
"pop",
"(",
"0",
")",
"self",
".",
"_p... | 37.823529 | 16.470588 |
def orthographic_u_umlaut(sound: str) -> str:
"""
>>> OldNorsePhonology.orthographic_u_umlaut("a")
'ö'
>>> OldNorsePhonology.orthographic_u_umlaut("e")
'e'
:param sound:
:return:
"""
if sound in OldNorsePhonology.U_UMLAUT:
return OldNo... | [
"def",
"orthographic_u_umlaut",
"(",
"sound",
":",
"str",
")",
"->",
"str",
":",
"if",
"sound",
"in",
"OldNorsePhonology",
".",
"U_UMLAUT",
":",
"return",
"OldNorsePhonology",
".",
"U_UMLAUT",
"[",
"sound",
"]",
"else",
":",
"return",
"sound"
] | 26.714286 | 17.142857 |
def change_first_point_by_coords(self, x, y, max_distance=1e-4,
raise_if_too_far_away=True):
"""
Set the first point of the exterior to the given point based on its coordinates.
If multiple points are found, the closest one will be picked.
If no matc... | [
"def",
"change_first_point_by_coords",
"(",
"self",
",",
"x",
",",
"y",
",",
"max_distance",
"=",
"1e-4",
",",
"raise_if_too_far_away",
"=",
"True",
")",
":",
"if",
"len",
"(",
"self",
".",
"exterior",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"C... | 37.659574 | 25.06383 |
def getSelectedTab(tabs, forURL):
"""
Returns the tab that should be selected when the current
resource lives at C{forURL}. Call me after L{setTabURLs}
@param tabs: sequence of L{Tab} instances
@param forURL: L{nevow.url.URL}
@return: L{Tab} instance
"""
flatTabs = []
def flatte... | [
"def",
"getSelectedTab",
"(",
"tabs",
",",
"forURL",
")",
":",
"flatTabs",
"=",
"[",
"]",
"def",
"flatten",
"(",
"tabs",
")",
":",
"for",
"t",
"in",
"tabs",
":",
"flatTabs",
".",
"append",
"(",
"t",
")",
"flatten",
"(",
"t",
".",
"children",
")",
... | 22.257143 | 19.685714 |
def __calculate_links(self, cluster1, cluster2):
"""!
@brief Returns number of link between two clusters.
@details Link between objects (points) exists only if distance between them less than connectivity radius.
@param[in] cluster1 (list): The first cluster.
@par... | [
"def",
"__calculate_links",
"(",
"self",
",",
"cluster1",
",",
"cluster2",
")",
":",
"number_links",
"=",
"0",
"for",
"index1",
"in",
"cluster1",
":",
"for",
"index2",
"in",
"cluster2",
":",
"number_links",
"+=",
"self",
".",
"__adjacency_matrix",
"[",
"inde... | 35.736842 | 21.368421 |
def partition_dict(items, key):
"""
Given an ordered dictionary of items and a key in that dict,
return an ordered dict of items before, the keyed item, and
an ordered dict of items after.
>>> od = collections.OrderedDict(zip(range(5), 'abcde'))
>>> before, item, after = partition_dict(od, 3)
>>> before
Ordere... | [
"def",
"partition_dict",
"(",
"items",
",",
"key",
")",
":",
"def",
"unmatched",
"(",
"pair",
")",
":",
"test_key",
",",
"item",
",",
"=",
"pair",
"return",
"test_key",
"!=",
"key",
"items_iter",
"=",
"iter",
"(",
"items",
".",
"items",
"(",
")",
")"... | 27.028571 | 19.885714 |
def _convert_nest_to_flat(self, params, _result=None, _prefix=None):
"""
Convert a data structure that looks like::
{"foo": {"bar": "baz", "shimmy": "sham"}}
to::
{"foo.bar": "baz",
"foo.shimmy": "sham"}
This is the inverse of L{_convert_flat_to_n... | [
"def",
"_convert_nest_to_flat",
"(",
"self",
",",
"params",
",",
"_result",
"=",
"None",
",",
"_prefix",
"=",
"None",
")",
":",
"if",
"_result",
"is",
"None",
":",
"_result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"params",
".",
"iteritems",
"(",... | 28.4 | 17.52 |
def set_value(self, treeiter, column, value):
"""
{{ all }}
`value` can also be a Python value and will be converted to a
:obj:`GObject.Value` using the corresponding column type (See
:obj:`Gtk.ListStore.set_column_types`\\()).
"""
value = self._convert_value(co... | [
"def",
"set_value",
"(",
"self",
",",
"treeiter",
",",
"column",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"_convert_value",
"(",
"column",
",",
"value",
")",
"Gtk",
".",
"ListStore",
".",
"set_value",
"(",
"self",
",",
"treeiter",
",",
"colum... | 35 | 19 |
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
This method... | [
"def",
"new_cells_from_excel",
"(",
"self",
",",
"book",
",",
"range_",
",",
"sheet",
"=",
"None",
",",
"names_row",
"=",
"None",
",",
"param_cols",
"=",
"None",
",",
"param_order",
"=",
"None",
",",
"transpose",
"=",
"False",
",",
"names_col",
"=",
"Non... | 43.520408 | 21.540816 |
def get_targets(conn=None):
"""
get_brain_targets function from Brain.Targets table.
:return: <generator> yields dict objects
"""
targets = RBT
results = targets.run(conn)
for item in results:
yield item | [
"def",
"get_targets",
"(",
"conn",
"=",
"None",
")",
":",
"targets",
"=",
"RBT",
"results",
"=",
"targets",
".",
"run",
"(",
"conn",
")",
"for",
"item",
"in",
"results",
":",
"yield",
"item"
] | 23.1 | 14.3 |
def create_project_connection(self, create_connection_inputs, project):
"""CreateProjectConnection.
[Preview API] Creates a new Pipeline connection between the provider installation and the specified project. Returns the PipelineConnection object created.
:param :class:`<CreatePipelineConnection... | [
"def",
"create_project_connection",
"(",
"self",
",",
"create_connection_inputs",
",",
"project",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
... | 67.764706 | 33.647059 |
def main():
"""The main function.
These are the steps performed for the data clean up:
1. Prints the version number.
2. Reads the configuration file (:py:func:`read_config_file`).
3. Creates a new directory with ``data_clean_up`` as prefix and the date
and time as suffix.
4. Check the i... | [
"def",
"main",
"(",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parse_args",
"(",
")",
"check_args",
"(",
"args",
")",
"# The directory name",
"dirname",
"=",
"\"data_clean_up.\"",
"dirname",
"+=",
"datetime",
".",
"datetime",
".",
"today",
"(",
... | 36.80203 | 19.106599 |
def calc_n_coarse_chan(self, chan_bw=None):
""" This makes an attempt to calculate the number of coarse channels in a given file.
Note:
This is unlikely to work on non-Breakthrough Listen data, as a-priori knowledge of
the digitizer system is required.
"""
... | [
"def",
"calc_n_coarse_chan",
"(",
"self",
",",
"chan_bw",
"=",
"None",
")",
":",
"nchans",
"=",
"int",
"(",
"self",
".",
"header",
"[",
"b'nchans'",
"]",
")",
"# Do we have a file with enough channels that it has coarse channelization?",
"if",
"chan_bw",
"is",
"not"... | 47.611111 | 18.555556 |
def do_alarm_definition_patch(mc, args):
'''Patch the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
if args.name:
fields['name'] = args.name
if args.description:
fields['description'] = args.description
if args.expression:
fields['expression'] = args.expre... | [
"def",
"do_alarm_definition_patch",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"if",
"args",
".",
"name",
":",
"fields",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"... | 41.764706 | 18.764706 |
def _pid_to_id(self, pid):
"""Converts a pid to a URI that can be used as an OAI-ORE identifier."""
return d1_common.url.joinPathElements(
self._base_url,
self._version_tag,
"resolve",
d1_common.url.encodePathElement(pid),
) | [
"def",
"_pid_to_id",
"(",
"self",
",",
"pid",
")",
":",
"return",
"d1_common",
".",
"url",
".",
"joinPathElements",
"(",
"self",
".",
"_base_url",
",",
"self",
".",
"_version_tag",
",",
"\"resolve\"",
",",
"d1_common",
".",
"url",
".",
"encodePathElement",
... | 36.125 | 12.625 |
async def import_aggregated(self, async_client, pid):
"""Import the SciObj at {pid}.
If the SciObj is a Resource Map, also recursively import the aggregated objects.
"""
self._logger.info('Importing: {}'.format(pid))
task_set = set()
object_info_pyxb = d1_common.types... | [
"async",
"def",
"import_aggregated",
"(",
"self",
",",
"async_client",
",",
"pid",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Importing: {}'",
".",
"format",
"(",
"pid",
")",
")",
"task_set",
"=",
"set",
"(",
")",
"object_info_pyxb",
"=",
"d1_... | 34.294118 | 25.970588 |
def generate_pseudo(strain_states, order=3):
"""
Generates the pseudoinverse for a given set of strains.
Args:
strain_states (6xN array like): a list of voigt-notation
"strain-states", i. e. perturbed indices of the strain
as a function of the smallest strain e. g. (0, 1, 0,... | [
"def",
"generate_pseudo",
"(",
"strain_states",
",",
"order",
"=",
"3",
")",
":",
"s",
"=",
"sp",
".",
"Symbol",
"(",
"'s'",
")",
"nstates",
"=",
"len",
"(",
"strain_states",
")",
"ni",
"=",
"np",
".",
"array",
"(",
"strain_states",
")",
"*",
"s",
... | 39.512821 | 14.538462 |
def _pirls(self, X, Y, weights):
"""
Performs stable PIRLS iterations to estimate GAM coefficients
Parameters
---------
X : array-like of shape (n_samples, m_features)
containing input data
Y : array-like of shape (n,)
containing target data
... | [
"def",
"_pirls",
"(",
"self",
",",
"X",
",",
"Y",
",",
"weights",
")",
":",
"modelmat",
"=",
"self",
".",
"_modelmat",
"(",
"X",
")",
"# build a basis matrix for the GLM",
"n",
",",
"m",
"=",
"modelmat",
".",
"shape",
"# initialize GLM coefficients if model is... | 34.831776 | 21.224299 |
def create_key_ring(
self,
parent,
key_ring_id,
key_ring,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Create a new ``KeyRing`` in a given Project and Location.
E... | [
"def",
"create_key_ring",
"(",
"self",
",",
"parent",
",",
"key_ring_id",
",",
"key_ring",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
... | 41.105882 | 24.517647 |
def _extract_functions(resources):
"""
Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This
method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function
:param dict resources: Dictionary of SAM/CloudForma... | [
"def",
"_extract_functions",
"(",
"resources",
")",
":",
"result",
"=",
"{",
"}",
"for",
"name",
",",
"resource",
"in",
"resources",
".",
"items",
"(",
")",
":",
"resource_type",
"=",
"resource",
".",
"get",
"(",
"\"Type\"",
")",
"resource_properties",
"="... | 48.964286 | 37.178571 |
def check_overlap(current, hit, overlap = 200):
"""
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
"""
for prev in current:
p_coords = prev[2:4]
coords = hit[2:4]
if get_overlap(coords, p_coords) >= over... | [
"def",
"check_overlap",
"(",
"current",
",",
"hit",
",",
"overlap",
"=",
"200",
")",
":",
"for",
"prev",
"in",
"current",
":",
"p_coords",
"=",
"prev",
"[",
"2",
":",
"4",
"]",
"coords",
"=",
"hit",
"[",
"2",
":",
"4",
"]",
"if",
"get_overlap",
"... | 32.272727 | 13.545455 |
def _get_repo_file(self, repo_path):
"""
Lazy load RepoFile objects on demand.
:param repo_path:
:return:
"""
if repo_path not in self._repo_files:
self._repo_files[repo_path] = RepoFile(repo_path)
return self._repo_files[repo_path] | [
"def",
"_get_repo_file",
"(",
"self",
",",
"repo_path",
")",
":",
"if",
"repo_path",
"not",
"in",
"self",
".",
"_repo_files",
":",
"self",
".",
"_repo_files",
"[",
"repo_path",
"]",
"=",
"RepoFile",
"(",
"repo_path",
")",
"return",
"self",
".",
"_repo_file... | 32.444444 | 8.444444 |
def write_languages(f, l):
"""Write language information."""
f.write("Languages = {%s" % os.linesep)
for lang in sorted(l):
f.write(" %r: %r,%s" % (lang, l[lang], os.linesep))
f.write("}%s" % os.linesep) | [
"def",
"write_languages",
"(",
"f",
",",
"l",
")",
":",
"f",
".",
"write",
"(",
"\"Languages = {%s\"",
"%",
"os",
".",
"linesep",
")",
"for",
"lang",
"in",
"sorted",
"(",
"l",
")",
":",
"f",
".",
"write",
"(",
"\" %r: %r,%s\"",
"%",
"(",
"lang",
... | 37.5 | 10.333333 |
def get_icohp_dict_of_site(self, site, minsummedicohp=None, maxsummedicohp=None, minbondlength=0.0,
maxbondlength=8.0, only_bonds_to=None):
"""
get a dict of IcohpValue for a certain site (indicated by integer)
Args:
site: integer describing the site of... | [
"def",
"get_icohp_dict_of_site",
"(",
"self",
",",
"site",
",",
"minsummedicohp",
"=",
"None",
",",
"maxsummedicohp",
"=",
"None",
",",
"minbondlength",
"=",
"0.0",
",",
"maxbondlength",
"=",
"8.0",
",",
"only_bonds_to",
"=",
"None",
")",
":",
"newicohp_dict",... | 57.304348 | 29.608696 |
def RSA_encrypt(public_key, message):
'''用RSA加密字符串.
public_key - 公钥
message - 要加密的信息, 使用UTF-8编码的字符串
@return - 使用base64编码的字符串
'''
# 如果没能成功导入RSA模块, 就直接返回空白字符串.
if not globals().get('RSA'):
return ''
rsakey = RSA.importKey(public_key)
rsakey = PKCS1_v1_5.new(rsakey)
e... | [
"def",
"RSA_encrypt",
"(",
"public_key",
",",
"message",
")",
":",
"# 如果没能成功导入RSA模块, 就直接返回空白字符串.",
"if",
"not",
"globals",
"(",
")",
".",
"get",
"(",
"'RSA'",
")",
":",
"return",
"''",
"rsakey",
"=",
"RSA",
".",
"importKey",
"(",
"public_key",
")",
"rsakey... | 29.928571 | 15.214286 |
def admin_tools_render_dashboard(context, location='index', dashboard=None):
"""
Template tag that renders the dashboard, it takes two optional arguments:
``location``
The location of the dashboard, it can be 'index' (for the admin index
dashboard) or 'app_index' (for the app index dashboar... | [
"def",
"admin_tools_render_dashboard",
"(",
"context",
",",
"location",
"=",
"'index'",
",",
"dashboard",
"=",
"None",
")",
":",
"if",
"dashboard",
"is",
"None",
":",
"dashboard",
"=",
"get_dashboard",
"(",
"context",
",",
"location",
")",
"dashboard",
".",
... | 34.42 | 20.1 |
def _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s)), ) | [
"def",
"_write_to_error",
"(",
"self",
",",
"s",
",",
"truncate",
"=",
"False",
")",
":",
"# if truncate is True, set write mode to truncate",
"with",
"open",
"(",
"self",
".",
"_errorfile",
",",
"'w'",
"if",
"truncate",
"else",
"'a'",
")",
"as",
"fp",
":",
... | 60.6 | 10 |
def working_yesterday(self, date_from=None, date_format=None):
"""
Retourne la date d'hier depuis maintenant ou depuis une date fournie
seulement sur les jours ouvrableq.
Ainsi lundi devient samedi et samedi devient vendredi
:param: :date_from date de référence
:return datetime
"""
# date d'hier que su... | [
"def",
"working_yesterday",
"(",
"self",
",",
"date_from",
"=",
"None",
",",
"date_format",
"=",
"None",
")",
":",
"# date d'hier que sur les jours de week-end",
"return",
"self",
".",
"delta",
"(",
"days",
"=",
"-",
"1",
",",
"date_from",
"=",
"date_from",
",... | 39.909091 | 18.636364 |
def from_ros_pose_msg(pose_msg,
from_frame='unassigned',
to_frame='world'):
"""Creates a RigidTransform from a ROS pose msg.
Parameters
----------
pose_msg : :obj:`geometry_msgs.msg.Pose`
ROS pose message
"... | [
"def",
"from_ros_pose_msg",
"(",
"pose_msg",
",",
"from_frame",
"=",
"'unassigned'",
",",
"to_frame",
"=",
"'world'",
")",
":",
"quaternion",
"=",
"np",
".",
"array",
"(",
"[",
"pose_msg",
".",
"orientation",
".",
"w",
",",
"pose_msg",
".",
"orientation",
... | 40.818182 | 12.090909 |
def get_rtr_name(self, router_id):
"""Retrieve the router name. Incomplete. """
try:
body = {}
router = self.neutronclient.show_router(router_id, body=body)
return router.get('router').get('name')
except Exception as exc:
LOG.error("Failed to show ... | [
"def",
"get_rtr_name",
"(",
"self",
",",
"router_id",
")",
":",
"try",
":",
"body",
"=",
"{",
"}",
"router",
"=",
"self",
".",
"neutronclient",
".",
"show_router",
"(",
"router_id",
",",
"body",
"=",
"body",
")",
"return",
"router",
".",
"get",
"(",
... | 45.555556 | 17.777778 |
def isLoopback (self, ifname):
"""Check whether interface is a loopback device.
@param ifname: interface name
@type ifname: string
"""
# since not all systems have IFF_LOOPBACK as a flag defined,
# the ifname is tested first
if ifname.startswith('lo'):
... | [
"def",
"isLoopback",
"(",
"self",
",",
"ifname",
")",
":",
"# since not all systems have IFF_LOOPBACK as a flag defined,",
"# the ifname is tested first",
"if",
"ifname",
".",
"startswith",
"(",
"'lo'",
")",
":",
"return",
"True",
"return",
"(",
"self",
".",
"getFlags... | 38.7 | 10.2 |
def inject(self, request, response):
"""
Inject the debug toolbar iframe into an HTML response.
"""
# called in host app
if not isinstance(response, Response):
return
settings = request.app[APP_KEY]['settings']
response_html = response.body
rou... | [
"def",
"inject",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# called in host app",
"if",
"not",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"return",
"settings",
"=",
"request",
".",
"app",
"[",
"APP_KEY",
"]",
"[",
"'settings'"... | 39.1 | 15.233333 |
def parse_oxide(self):
"""
Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.
Returns:
oxide_type (str): Type of oxide
ozonide/peroxide/superoxide/hydroxide/None.
nbonds (int): Number of peroxide/superoxide/hydroxide bonds in
st... | [
"def",
"parse_oxide",
"(",
"self",
")",
":",
"structure",
"=",
"self",
".",
"structure",
"relative_cutoff",
"=",
"self",
".",
"relative_cutoff",
"o_sites_frac_coords",
"=",
"[",
"]",
"h_sites_frac_coords",
"=",
"[",
"]",
"lattice",
"=",
"structure",
".",
"latt... | 39 | 15.873239 |
def get_extensions_assigned_to_user(self, user_id):
"""GetExtensionsAssignedToUser.
[Preview API] Returns extensions that are currently assigned to the user in the account
:param str user_id: The user's identity id.
:rtype: {LicensingSource}
"""
route_values = {}
... | [
"def",
"get_extensions_assigned_to_user",
"(",
"self",
",",
"user_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"user_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'userId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'user_id'",
"... | 53.285714 | 19.857143 |
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the tok... | [
"def",
"get_unverified_claims",
"(",
"token",
")",
":",
"try",
":",
"claims",
"=",
"jws",
".",
"get_unverified_claims",
"(",
"token",
")",
"except",
":",
"raise",
"JWTError",
"(",
"'Error decoding token claims.'",
")",
"try",
":",
"claims",
"=",
"json",
".",
... | 27.269231 | 23.269231 |
def _chooseBestSegmentPerCell(cls,
connections,
cells,
allMatchingSegments,
potentialOverlaps):
"""
For each specified cell, choose its matching segment with largest number
of acti... | [
"def",
"_chooseBestSegmentPerCell",
"(",
"cls",
",",
"connections",
",",
"cells",
",",
"allMatchingSegments",
",",
"potentialOverlaps",
")",
":",
"candidateSegments",
"=",
"connections",
".",
"filterSegmentsByCell",
"(",
"allMatchingSegments",
",",
"cells",
")",
"# Na... | 38.285714 | 19.357143 |
def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the fir... | [
"def",
"render_template",
"(",
"template_name_or_list",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
... | 46.642857 | 19.214286 |
def set_title(self,table=None,title=None,verbose=None):
"""
Changes the visible identifier of a single table.
:param table (string, optional): Specifies a table by table name. If the pr
efix SUID: is used, the table corresponding the SUID will be returne
d.
:para... | [
"def",
"set_title",
"(",
"self",
",",
"table",
"=",
"None",
",",
"title",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"'table'",
",",
"'title'",
"]",
",",
"[",
"table",
",",
"title",
"]",
")",
"response... | 45.230769 | 25.692308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.