text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def MessageToJson(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitiv... | [
"def",
"MessageToJson",
"(",
"message",
",",
"including_default_value_fields",
"=",
"False",
",",
"preserving_proto_field_name",
"=",
"False",
")",
":",
"printer",
"=",
"_Printer",
"(",
"including_default_value_fields",
",",
"preserving_proto_field_name",
")",
"return",
... | 43.619048 | 20.904762 |
def tobytes(
self,
root=None,
encoding='UTF-8',
doctype=None,
canonicalized=True,
xml_declaration=True,
pretty_print=True,
with_comments=True,
):
"""return the content of the XML document as a byte string suitable for writing"""
... | [
"def",
"tobytes",
"(",
"self",
",",
"root",
"=",
"None",
",",
"encoding",
"=",
"'UTF-8'",
",",
"doctype",
"=",
"None",
",",
"canonicalized",
"=",
"True",
",",
"xml_declaration",
"=",
"True",
",",
"pretty_print",
"=",
"True",
",",
"with_comments",
"=",
"T... | 32.291667 | 14.666667 |
def summarize_crud_mutation(method, model, isAsync=False):
"""
This function provides the standard form for crud mutations.
"""
# create the approrpriate action type
action_type = get_crud_action(method=method, model=model)
# the name of the mutation
name = crud_mutation_name(model=mode... | [
"def",
"summarize_crud_mutation",
"(",
"method",
",",
"model",
",",
"isAsync",
"=",
"False",
")",
":",
"# create the approrpriate action type",
"action_type",
"=",
"get_crud_action",
"(",
"method",
"=",
"method",
",",
"model",
"=",
"model",
")",
"# the name of the m... | 30.676471 | 13.617647 |
def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already... | [
"def",
"merge_global_options",
"(",
"self",
",",
"needs_info",
")",
":",
"global_options",
"=",
"getattr",
"(",
"self",
".",
"env",
".",
"app",
".",
"config",
",",
"'needs_global_options'",
",",
"None",
")",
"if",
"global_options",
"is",
"None",
":",
"return... | 41.166667 | 21.166667 |
def build_authorization_endpoint(self, request, disable_sso=None):
"""
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server... | [
"def",
"build_authorization_endpoint",
"(",
"self",
",",
"request",
",",
"disable_sso",
"=",
"None",
")",
":",
"self",
".",
"load_config",
"(",
")",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"REDIRECT_FIELD_NAME",
",",
"None",
")",
"if",
... | 39.516129 | 21.258065 |
def prt_gos_flat(self, prt):
"""Print flat GO list."""
prtfmt = self.datobj.kws['fmtgo']
_go2nt = self.sortobj.grprobj.go2nt
go2nt = {go:_go2nt[go] for go in self.go2nt}
prt.write("\n{N} GO IDs:\n".format(N=len(go2nt)))
_sortby = self._get_sortgo()
for ntgo in sor... | [
"def",
"prt_gos_flat",
"(",
"self",
",",
"prt",
")",
":",
"prtfmt",
"=",
"self",
".",
"datobj",
".",
"kws",
"[",
"'fmtgo'",
"]",
"_go2nt",
"=",
"self",
".",
"sortobj",
".",
"grprobj",
".",
"go2nt",
"go2nt",
"=",
"{",
"go",
":",
"_go2nt",
"[",
"go",... | 44.444444 | 8.777778 |
def configure_discord_logger(
self,
discord_webhook=None,
discord_recipient=None,
log_level='ERROR',
log_format=ReportingFormats.PRETTY_PRINT.value,
custom_args=''
):
"""logger for sending messages to Discord. Easy way to alert humans ... | [
"def",
"configure_discord_logger",
"(",
"self",
",",
"discord_webhook",
"=",
"None",
",",
"discord_recipient",
"=",
"None",
",",
"log_level",
"=",
"'ERROR'",
",",
"log_format",
"=",
"ReportingFormats",
".",
"PRETTY_PRINT",
".",
"value",
",",
"custom_args",
"=",
... | 36.633333 | 19.683333 |
def writeXYCatalog(self,filename):
""" Write out the X,Y catalog to a file
"""
if self.xypos is None:
warnstr = textutil.textbox(
'WARNING: \n No X,Y source catalog to write to file. ')
for line in warnstr.split('\n'):
log.warning(line)
... | [
"def",
"writeXYCatalog",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"xypos",
"is",
"None",
":",
"warnstr",
"=",
"textutil",
".",
"textbox",
"(",
"'WARNING: \\n No X,Y source catalog to write to file. '",
")",
"for",
"line",
"in",
"warnstr",
".... | 36.115385 | 17.807692 |
def resolve_post(self, post):
"""Mark post as resolved
:type post: dict|str|int
:param post: Either the post dict returned by another API method, or
the `cid` field of that post.
:returns: True if it is successful. False otherwise
"""
try:
cid = ... | [
"def",
"resolve_post",
"(",
"self",
",",
"post",
")",
":",
"try",
":",
"cid",
"=",
"post",
"[",
"\"id\"",
"]",
"except",
"KeyError",
":",
"cid",
"=",
"post",
"params",
"=",
"{",
"\"cid\"",
":",
"cid",
",",
"\"resolved\"",
":",
"\"true\"",
"}",
"retur... | 26.368421 | 19.052632 |
def _get_uncolored_output(self, script, value):
"""
Creates an uncolored output.
:param bytes script: The output script.
:param int value: The satoshi value of the output.
:return: An object representing the uncolored output.
:rtype: TransactionOutput
"""
... | [
"def",
"_get_uncolored_output",
"(",
"self",
",",
"script",
",",
"value",
")",
":",
"if",
"value",
"<",
"self",
".",
"_dust_amount",
":",
"raise",
"DustOutputError",
"return",
"bitcoin",
".",
"core",
".",
"CTxOut",
"(",
"value",
",",
"bitcoin",
".",
"core"... | 34.230769 | 14.230769 |
def _check_auth_handler(self, request: Dict[str, Any]):
"""用于验证客户端是否有权限调服务.
如果服务端有验证信息,则会根据验证信息判断是否合法
+ 如果合法,那么返回一条信息用于响应验证请求
+ 如果不合法,那么返回验证错误
如果服务端没有验证信息
+ 如果验证信息都为空,直接返回响应
+ 如果信息不为空,那么返回验证错误
Parameters:
request (Dict[str, Any]): - python字典... | [
"def",
"_check_auth_handler",
"(",
"self",
",",
"request",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"a_username",
"=",
"request",
".",
"get",
"(",
"\"AUTH\"",
")",
".",
"get",
"(",
"\"USERNAME\"",
")",
"a_password",
"=",
"request",
".",
"get... | 35.188679 | 18.358491 |
def walk_regularity_symmetry(self, data_frame):
"""
This method extracts the step and stride regularity and also walk symmetry.
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame: pandas.DataFrame
:return step_regularity: Reg... | [
"def",
"walk_regularity_symmetry",
"(",
"self",
",",
"data_frame",
")",
":",
"def",
"_symmetry",
"(",
"v",
")",
":",
"maxtab",
",",
"_",
"=",
"peakdet",
"(",
"v",
",",
"self",
".",
"delta",
")",
"return",
"maxtab",
"[",
"1",
"]",
"[",
"1",
"]",
","... | 56.548387 | 34.322581 |
def spkltc(targ, et, ref, abcorr, stobs):
"""
Return the state (position and velocity) of a target body
relative to an observer, optionally corrected for light time,
expressed relative to an inertial reference frame.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkltc_c.html
:param ... | [
"def",
"spkltc",
"(",
"targ",
",",
"et",
",",
"ref",
",",
"abcorr",
",",
"stobs",
")",
":",
"assert",
"len",
"(",
"stobs",
")",
"==",
"6",
"targ",
"=",
"stypes",
".",
"c_int",
"(",
"targ",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
"... | 36.057143 | 15.371429 |
def Ping(self, request, context):
"""
Invoke the Server health endpoint
:param request: Empty
:param context: the request context
:return: Status message 'alive'
"""
status = processor_pb2.Status()
status.message='alive'
return status | [
"def",
"Ping",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"status",
"=",
"processor_pb2",
".",
"Status",
"(",
")",
"status",
".",
"message",
"=",
"'alive'",
"return",
"status"
] | 29.8 | 5.2 |
def under_variable_scope():
"""
Returns:
A decorator which makes the function happen under a variable scope,
which is named by the function itself.
Example:
.. code-block:: python
@under_variable_scope()
def mid_level(x):
with argscope(Conv2D, kernel_shape=... | [
"def",
"under_variable_scope",
"(",
")",
":",
"def",
"_impl",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"wit... | 25.814815 | 18.62963 |
def description(self):
""" Cursor description, see http://legacy.python.org/dev/peps/pep-0249/#description
"""
if self._session is None:
return None
res = self._session.res_info
if res:
return res.description
else:
return None | [
"def",
"description",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"return",
"None",
"res",
"=",
"self",
".",
"_session",
".",
"res_info",
"if",
"res",
":",
"return",
"res",
".",
"description",
"else",
":",
"return",
"None"
... | 30.1 | 12.1 |
def dispatch_on(*dispatch_args):
"""
Factory of decorators turning a function into a generic function
dispatching on the given arguments.
"""
assert dispatch_args, 'No dispatch args passed'
dispatch_str = '(%s,)' % ', '.join(dispatch_args)
def check(arguments, wrong=operator.ne, msg=''):
... | [
"def",
"dispatch_on",
"(",
"*",
"dispatch_args",
")",
":",
"assert",
"dispatch_args",
",",
"'No dispatch args passed'",
"dispatch_str",
"=",
"'(%s,)'",
"%",
"', '",
".",
"join",
"(",
"dispatch_args",
")",
"def",
"check",
"(",
"arguments",
",",
"wrong",
"=",
"o... | 35.563107 | 16.485437 |
def _get_instance_attributes(self):
"""Return a generator for instance attributes' name and value.
.. code-block:: python3
for _name, _value in self._get_instance_attributes():
print("attribute name: {}".format(_name))
print("attribute value: {}".format(_val... | [
"def",
"_get_instance_attributes",
"(",
"self",
")",
":",
"for",
"name",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"map",
"(",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
",",
"self",
".",... | 35.125 | 20.4375 |
def onlineTable(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_onlineTable(login, tableName)
self.recv_onlineTable() | [
"def",
"onlineTable",
"(",
"self",
",",
"login",
",",
"tableName",
")",
":",
"self",
".",
"send_onlineTable",
"(",
"login",
",",
"tableName",
")",
"self",
".",
"recv_onlineTable",
"(",
")"
] | 20.875 | 11.625 |
def oracle_grover(oracle: Program, qubits: List[int], num_iter: int = None) -> Program:
"""
Implementation of Grover's Algorithm for a given oracle.
:param oracle: An oracle defined as a Program. It should send :math:`\ket{x}`
to :math:`(-1)^{f(x)}\ket{x}`, where the range of f is {... | [
"def",
"oracle_grover",
"(",
"oracle",
":",
"Program",
",",
"qubits",
":",
"List",
"[",
"int",
"]",
",",
"num_iter",
":",
"int",
"=",
"None",
")",
"->",
"Program",
":",
"if",
"num_iter",
"is",
"None",
":",
"num_iter",
"=",
"int",
"(",
"round",
"(",
... | 59.235294 | 30.764706 |
def _build_app(args, extra_args):
"""Builds an app or applet and returns the resulting executable ID
(unless it was a dry-run, in which case None is returned).
TODO: remote app builds still return None, but we should fix this.
"""
if not args.remote:
# LOCAL BUILD
try:
... | [
"def",
"_build_app",
"(",
"args",
",",
"extra_args",
")",
":",
"if",
"not",
"args",
".",
"remote",
":",
"# LOCAL BUILD",
"try",
":",
"output",
"=",
"build_and_upload_locally",
"(",
"args",
".",
"src_dir",
",",
"args",
".",
"mode",
",",
"overwrite",
"=",
... | 41.126214 | 21.097087 |
def is_complete(self):
""":rtype: ``bool`` ``True`` if transfer is complete"""
if 'status' in self.transfer_info:
self._complete = self.transfer_info['status'] == 'STATUS_COMPLETE'
return self._complete | [
"def",
"is_complete",
"(",
"self",
")",
":",
"if",
"'status'",
"in",
"self",
".",
"transfer_info",
":",
"self",
".",
"_complete",
"=",
"self",
".",
"transfer_info",
"[",
"'status'",
"]",
"==",
"'STATUS_COMPLETE'",
"return",
"self",
".",
"_complete"
] | 33.428571 | 21.285714 |
def get_maximum_range(self, hmm):
'''
If no maximum range has been specified, and if using a hmm search, a
maximum range can be determined by using the length of the HMM
Parameters
----------
hmm : str
path to hmm profile
Returns
-------
... | [
"def",
"get_maximum_range",
"(",
"self",
",",
"hmm",
")",
":",
"length",
"=",
"int",
"(",
"[",
"x",
"for",
"x",
"in",
"open",
"(",
"hmm",
")",
"if",
"x",
".",
"startswith",
"(",
"\"LENG\"",
")",
"]",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
... | 29.055556 | 25.388889 |
def istriangular(am):
r"""
Returns ``True`` is the sparse adjacency matrix is either upper or lower
triangular
"""
if am.format != 'coo':
am = am.tocoo(copy=False)
return istril(am) or istriu(am) | [
"def",
"istriangular",
"(",
"am",
")",
":",
"if",
"am",
".",
"format",
"!=",
"'coo'",
":",
"am",
"=",
"am",
".",
"tocoo",
"(",
"copy",
"=",
"False",
")",
"return",
"istril",
"(",
"am",
")",
"or",
"istriu",
"(",
"am",
")"
] | 27.5 | 13.375 |
def normalize_slice(s, total):
"""
Return a "canonical" version of slice ``s``.
:param slice s: the original slice expression
:param total int: total number of elements in the collection sliced by ``s``
:return slice: a slice equivalent to ``s`` but not containing any negative indices or Nones.
... | [
"def",
"normalize_slice",
"(",
"s",
",",
"total",
")",
":",
"newstart",
"=",
"0",
"if",
"s",
".",
"start",
"is",
"None",
"else",
"max",
"(",
"0",
",",
"s",
".",
"start",
"+",
"total",
")",
"if",
"s",
".",
"start",
"<",
"0",
"else",
"min",
"(",
... | 51.083333 | 24.916667 |
def CallUDFUNS(f, x):
"""
We are given a UDF CFUNCTYPE and want to call it in python
:param f: SpiceUDFUNS
:type f: CFUNCTYPE
:param x: some scalar
:type x: float
:return: value
:rtype: float
"""
value = c_double()
f(x, byref(value))
return value.value | [
"def",
"CallUDFUNS",
"(",
"f",
",",
"x",
")",
":",
"value",
"=",
"c_double",
"(",
")",
"f",
"(",
"x",
",",
"byref",
"(",
"value",
")",
")",
"return",
"value",
".",
"value"
] | 20.571429 | 17.857143 |
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)... | [
"def",
"_load",
"(",
"pathtovector",
",",
"wordlist",
",",
"num_to_load",
"=",
"None",
",",
"truncate_embeddings",
"=",
"None",
",",
"sep",
"=",
"\" \"",
")",
":",
"vectors",
"=",
"[",
"]",
"addedwords",
"=",
"set",
"(",
")",
"words",
"=",
"[",
"]",
... | 33.9 | 21.642857 |
def do_ls(self, params):
"""
\x1b[1mNAME\x1b[0m
ls - Lists the znodes for the given <path>
\x1b[1mSYNOPSIS\x1b[0m
ls <path> [watch] [sep]
\x1b[1mOPTIONS\x1b[0m
* watch: set a (child) watch on the path (default: false)
* sep: separator to be used (default: '\\n')
\x1b[1mEXAMPLE... | [
"def",
"do_ls",
"(",
"self",
",",
"params",
")",
":",
"watcher",
"=",
"lambda",
"evt",
":",
"self",
".",
"show_output",
"(",
"str",
"(",
"evt",
")",
")",
"kwargs",
"=",
"{",
"\"watch\"",
":",
"watcher",
"}",
"if",
"params",
".",
"watch",
"else",
"{... | 24.088235 | 22.676471 |
def post(self, request):
"""
POST /consent/api/v1/data_sharing_consent
Requires a JSON object of the following format:
>>> {
>>> "username": "bob",
>>> "course_id": "course-v1:edX+DemoX+Demo_Course",
>>> "enterprise_customer_uuid": "enterprise-uuid-go... | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"consent_record",
"=",
"self",
".",
"get_consent_record",
"(",
"request",
")",
"if",
"consent_record",
"is",
"None",
":",
"return",
"self",
".",
"get_no_record_response",
"(",
"request",
")",
... | 43.684211 | 25.315789 |
def stop(self, timeout=None):
""" Initiates a graceful stop of the processes """
self.stopping = True
for process in list(self.processes):
self.stop_process(process, timeout=timeout) | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"stopping",
"=",
"True",
"for",
"process",
"in",
"list",
"(",
"self",
".",
"processes",
")",
":",
"self",
".",
"stop_process",
"(",
"process",
",",
"timeout",
"=",
"timeo... | 30.571429 | 17.428571 |
def mass_3d(self, r, rho0, gamma):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return:
"""
mass_3d = 4 * np.pi * rho0 /(-gamma + 3) * r ** (-gamma + 3)
return mass_3d | [
"def",
"mass_3d",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"gamma",
")",
":",
"mass_3d",
"=",
"4",
"*",
"np",
".",
"pi",
"*",
"rho0",
"/",
"(",
"-",
"gamma",
"+",
"3",
")",
"*",
"r",
"**",
"(",
"-",
"gamma",
"+",
"3",
")",
"return",
"mass_3... | 25.8 | 15 |
def word_groups_for_language(language_code):
"""
Return the math word groups for a language code.
The language_code should be an ISO 639-2 language code.
https://www.loc.gov/standards/iso639-2/php/code_list.php
"""
if language_code not in LANGUAGE_CODES:
message = '{} is not an availabl... | [
"def",
"word_groups_for_language",
"(",
"language_code",
")",
":",
"if",
"language_code",
"not",
"in",
"LANGUAGE_CODES",
":",
"message",
"=",
"'{} is not an available language code'",
".",
"format",
"(",
"language_code",
")",
"raise",
"InvalidLanguageCodeException",
"(",
... | 36.416667 | 15.916667 |
def entries_view(self, request, form_id):
"""
Displays the form entries in a HTML table with option to
export as CSV file.
"""
if request.POST.get("back"):
change_url = admin_url(Form, "change", form_id)
return HttpResponseRedirect(change_url)
form... | [
"def",
"entries_view",
"(",
"self",
",",
"request",
",",
"form_id",
")",
":",
"if",
"request",
".",
"POST",
".",
"get",
"(",
"\"back\"",
")",
":",
"change_url",
"=",
"admin_url",
"(",
"Form",
",",
"\"change\"",
",",
"form_id",
")",
"return",
"HttpRespons... | 49.981132 | 15.301887 |
def deep_del(data, fn):
"""Create dict copy with removed items.
Recursively remove items where fn(value) is True.
Returns:
dict: New dict with matching items removed.
"""
result = {}
for k, v in data.iteritems():
if not fn(v):
if isinstance(v, dict):
... | [
"def",
"deep_del",
"(",
"data",
",",
"fn",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"fn",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"... | 22.166667 | 19.166667 |
def _compute_rtfilter_map(self):
"""Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a particular neighbor is
... | [
"def",
"_compute_rtfilter_map",
"(",
"self",
")",
":",
"rtfilter_map",
"=",
"{",
"}",
"def",
"get_neigh_filter",
"(",
"neigh",
")",
":",
"neigh_filter",
"=",
"rtfilter_map",
".",
"get",
"(",
"neigh",
")",
"# Lazy creation of neighbor RT filter",
"if",
"neigh_filte... | 43.25 | 19 |
def _set_data(self):
"""
This method will be called to set Series data
"""
if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False):
_x = XVariable()
_y = YVariable()
_x.contribute_to_class(self, 'X', self.d... | [
"def",
"_set_data",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'data'",
",",
"False",
")",
"and",
"not",
"getattr",
"(",
"self",
",",
"'_x'",
",",
"False",
")",
"and",
"not",
"getattr",
"(",
"self",
",",
"'_y'",
",",
"False",
")",
... | 43.473684 | 19.263158 |
def unflatten(master):
"""
:param dict master: a multilevel dictionary
:return: a unflattened dictionary
:rtype: dict
Unflattens a single-level dictionary a multilevel into one so that::
{'foo.bar.a': 1,
'foo.bar.b': True,
'foo.bar.a': 1,
}
would become::
... | [
"def",
"unflatten",
"(",
"master",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"master",
".",
"items",
"(",
")",
":",
"*",
"first",
",",
"last",
"=",
"k",
".",
"split",
"(",
"'.'",
")",
"r",
"=",
"result",
"for",
"i",
"in",... | 19.485714 | 20.857143 |
def _operation_speak_as_spell_out(self, content, index, children):
"""
The operation method of _speak_as method for spell-out.
:param content: The text content of element.
:type content: str
:param index: The index of pattern in text content of element.
:type index: int
... | [
"def",
"_operation_speak_as_spell_out",
"(",
"self",
",",
"content",
",",
"index",
",",
"children",
")",
":",
"children",
".",
"append",
"(",
"self",
".",
"_create_content_element",
"(",
"content",
"[",
"0",
":",
"(",
"index",
"+",
"1",
")",
"]",
",",
"'... | 33.55 | 22.35 |
def set_background(self, color, loc='all'):
"""
Sets background color
Parameters
----------
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w... | [
"def",
"set_background",
"(",
"self",
",",
"color",
",",
"loc",
"=",
"'all'",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"rcParams",
"[",
"'background'",
"]",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"if",
"color",
".",
... | 34.794118 | 17.088235 |
def set_many(self, mapping, timeout=None):
"""Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
for key, ... | [
"def",
"set_many",
"(",
"self",
",",
"mapping",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"key",
",",
"value",
"in",
"_items",
"(",
"mapping",
")",
":",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"timeout",
")"
] | 42.111111 | 12.444444 |
def set_value(self, *args, **kwargs):
"""
Quickly set single value at (item, major, minor) location.
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
item : item label (panel item)
major : major axis label (panel item r... | [
"def",
"set_value",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"set_value is deprecated and will be removed \"",
"\"in a future release. Please use \"",
"\".at[] or .iat[] accessors instead\"",
",",
"FutureWarning",
"... | 33.740741 | 19.296296 |
def _all_number_groups_are_exactly_present(numobj, normalized_candidate, formatted_number_groups):
"""Returns True if the groups of digits found in our candidate phone number match our
expectations.
Arguments:
numobj -- the original number we found when parsing
normalized_candidate -- the candidate... | [
"def",
"_all_number_groups_are_exactly_present",
"(",
"numobj",
",",
"normalized_candidate",
",",
"formatted_number_groups",
")",
":",
"candidate_groups",
"=",
"re",
".",
"split",
"(",
"NON_DIGITS_PATTERN",
",",
"normalized_candidate",
")",
"# Set this to the last group, skip... | 56.5 | 25.710526 |
def delete_file(self, path):
"""Delete the file or directory at path.
"""
self.log.debug("S3contents.GenericManager: delete_file '%s'", path)
if self.file_exists(path) or self.dir_exists(path):
self.fs.rm(path)
else:
self.no_such_entity(path) | [
"def",
"delete_file",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"S3contents.GenericManager: delete_file '%s'\"",
",",
"path",
")",
"if",
"self",
".",
"file_exists",
"(",
"path",
")",
"or",
"self",
".",
"dir_exists",
"(",
... | 37.375 | 13.5 |
def open_resource(self, path: FilePath, mode: str='rb') -> IO[AnyStr]:
"""Open a file for reading.
Use as
.. code-block:: python
with app.open_resouce(path) as file_:
file_.read()
"""
if mode not in {'r', 'rb'}:
raise ValueError('Files c... | [
"def",
"open_resource",
"(",
"self",
",",
"path",
":",
"FilePath",
",",
"mode",
":",
"str",
"=",
"'rb'",
")",
"->",
"IO",
"[",
"AnyStr",
"]",
":",
"if",
"mode",
"not",
"in",
"{",
"'r'",
",",
"'rb'",
"}",
":",
"raise",
"ValueError",
"(",
"'Files can... | 31.307692 | 20.538462 |
def get_chaotic_pairs(graph: BELGraph) -> SetOfNodePairs:
"""Find pairs of nodes that have mutual causal edges that are increasing each other such that ``A -> B`` and
``B -> A``.
:return: A set of pairs of nodes with mutual causal edges
"""
cg = get_causal_subgraph(graph)
results = set()
... | [
"def",
"get_chaotic_pairs",
"(",
"graph",
":",
"BELGraph",
")",
"->",
"SetOfNodePairs",
":",
"cg",
"=",
"get_causal_subgraph",
"(",
"graph",
")",
"results",
"=",
"set",
"(",
")",
"for",
"u",
",",
"v",
",",
"d",
"in",
"cg",
".",
"edges",
"(",
"data",
... | 33.444444 | 23.944444 |
async def mod(self, iden, query):
'''
Change the query of an appointment
'''
appt = self.appts.get(iden)
if appt is None:
raise s_exc.NoSuchIden()
if not query:
raise ValueError('empty query')
if self.enabled:
self.core.getSto... | [
"async",
"def",
"mod",
"(",
"self",
",",
"iden",
",",
"query",
")",
":",
"appt",
"=",
"self",
".",
"appts",
".",
"get",
"(",
"iden",
")",
"if",
"appt",
"is",
"None",
":",
"raise",
"s_exc",
".",
"NoSuchIden",
"(",
")",
"if",
"not",
"query",
":",
... | 25.166667 | 18.944444 |
def _debug_line(linenum: int, line: str, extramsg: str = "") -> None:
"""
Writes a debugging report on a line.
"""
log.critical("{}Line {}: {!r}", extramsg, linenum, line) | [
"def",
"_debug_line",
"(",
"linenum",
":",
"int",
",",
"line",
":",
"str",
",",
"extramsg",
":",
"str",
"=",
"\"\"",
")",
"->",
"None",
":",
"log",
".",
"critical",
"(",
"\"{}Line {}: {!r}\"",
",",
"extramsg",
",",
"linenum",
",",
"line",
")"
] | 39.8 | 11.4 |
def format_system_message(errno):
"""
Call FormatMessage with a system error number to retrieve
the descriptive error message.
"""
# first some flags used by FormatMessageW
ALLOCATE_BUFFER = 0x100
FROM_SYSTEM = 0x1000
# Let FormatMessageW allocate the buffer (we'll free it below)
# ... | [
"def",
"format_system_message",
"(",
"errno",
")",
":",
"# first some flags used by FormatMessageW",
"ALLOCATE_BUFFER",
"=",
"0x100",
"FROM_SYSTEM",
"=",
"0x1000",
"# Let FormatMessageW allocate the buffer (we'll free it below)",
"# Also, let it know we want a system error message.",
"... | 30.588235 | 16.294118 |
def _init_parameters_random(self, X_bin):
"""Initialise parameters for unsupervised learning.
"""
_, n_features = X_bin.shape
# The parameter class_log_prior_ has shape (2,). The values represent
# 'match' and 'non-match'.
rand_vals = np.random.rand(2)
class_pr... | [
"def",
"_init_parameters_random",
"(",
"self",
",",
"X_bin",
")",
":",
"_",
",",
"n_features",
"=",
"X_bin",
".",
"shape",
"# The parameter class_log_prior_ has shape (2,). The values represent",
"# 'match' and 'non-match'.",
"rand_vals",
"=",
"np",
".",
"random",
".",
... | 29.606061 | 19.848485 |
def from_stub(cls, data, udas=None):
""" Create a Task from an already deserialized dict. """
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
... | [
"def",
"from_stub",
"(",
"cls",
",",
"data",
",",
"udas",
"=",
"None",
")",
":",
"udas",
"=",
"udas",
"or",
"{",
"}",
"fields",
"=",
"cls",
".",
"FIELDS",
".",
"copy",
"(",
")",
"fields",
".",
"update",
"(",
"udas",
")",
"processed",
"=",
"{",
... | 28.166667 | 16.333333 |
def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and permanent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmI... | [
"def",
"simBirth",
"(",
"self",
",",
"which_agents",
")",
":",
"# Get and store states for newly born agents",
"N",
"=",
"np",
".",
"sum",
"(",
"which_agents",
")",
"# Number of new consumers to make",
"self",
".",
"aNrmNow",
"[",
"which_agents",
"]",
"=",
"drawLogn... | 54.130435 | 39.521739 |
def affine_matrix_from_points(v0, v1, shear=True, scale=True, usesvd=True):
"""Return affine transform matrix to register two point sets.
v0 and v1 are shape (ndims, \*) arrays of at least ndims non-homogeneous
coordinates, where ndims is the dimensionality of the coordinate space.
If shear is False, ... | [
"def",
"affine_matrix_from_points",
"(",
"v0",
",",
"v1",
",",
"shear",
"=",
"True",
",",
"scale",
"=",
"True",
",",
"usesvd",
"=",
"True",
")",
":",
"v0",
"=",
"numpy",
".",
"array",
"(",
"v0",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"cop... | 39.738318 | 18.672897 |
def process_request(self, request):
"""Adds data necessary for Horizon to function to the request."""
# Activate timezone handling
tz = request.session.get('django_timezone')
if tz:
timezone.activate(tz)
# Check for session timeout
try:
timeout = ... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"# Activate timezone handling",
"tz",
"=",
"request",
".",
"session",
".",
"get",
"(",
"'django_timezone'",
")",
"if",
"tz",
":",
"timezone",
".",
"activate",
"(",
"tz",
")",
"# Check for session... | 45.253968 | 19.238095 |
def resolve_colors(n_colors=None, colormap=None, colors=None):
"""
Generates a list of colors based on common color arguments, for example
the name of a colormap or palette or another iterable of colors. The list
is then truncated (or multiplied) to the specific number of requested
colors.
Para... | [
"def",
"resolve_colors",
"(",
"n_colors",
"=",
"None",
",",
"colormap",
"=",
"None",
",",
"colors",
"=",
"None",
")",
":",
"# Work with the colormap if specified and colors is not",
"if",
"colormap",
"is",
"not",
"None",
"and",
"colors",
"is",
"None",
":",
"if",... | 31.969231 | 24.707692 |
def tree(path, depth=2, topdown=True, followlinks=False, showhidden=False):
"""A generator return a tuple with three elements (root, dirs, files)."""
rt = []
for root, dirs, files in os.walk(path, topdown=topdown, followlinks=followlinks):
if not showhidden and File.is_hidden(root):
cont... | [
"def",
"tree",
"(",
"path",
",",
"depth",
"=",
"2",
",",
"topdown",
"=",
"True",
",",
"followlinks",
"=",
"False",
",",
"showhidden",
"=",
"False",
")",
":",
"rt",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
... | 35.846154 | 26.038462 |
def _get_to_many_relationship_value(self, obj, column):
"""
Get the resulting datas for a One To many or a many to many relationship
:param obj obj: The instance we manage
:param dict column: The column description dictionnary
:returns: The associated value
"""
r... | [
"def",
"_get_to_many_relationship_value",
"(",
"self",
",",
"obj",
",",
"column",
")",
":",
"related_key",
"=",
"column",
".",
"get",
"(",
"'related_key'",
",",
"None",
")",
"related",
"=",
"getattr",
"(",
"obj",
",",
"column",
"[",
"'__col__'",
"]",
".",
... | 34.558824 | 17.441176 |
def load_texture(self, texture_version):
'''
Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/.
Currently there are versions [0, 1, 2, 3] availiable.
'''
import numpy as np
lowres_tex_templat... | [
"def",
"load_texture",
"(",
"self",
",",
"texture_version",
")",
":",
"import",
"numpy",
"as",
"np",
"lowres_tex_template",
"=",
"'s3://bodylabs-korper-assets/is/ps/shared/data/body/template/texture_coordinates/textured_template_low_v%d.obj'",
"%",
"texture_version",
"highres_tex_t... | 66.071429 | 38.214286 |
def _unicode(ctx, text):
"""
Returns a numeric code for the first character in a text string
"""
text = conversions.to_string(text, ctx)
if len(text) == 0:
raise ValueError("Text can't be empty")
return ord(text[0]) | [
"def",
"_unicode",
"(",
"ctx",
",",
"text",
")",
":",
"text",
"=",
"conversions",
".",
"to_string",
"(",
"text",
",",
"ctx",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Text can't be empty\"",
")",
"return",
"ord"... | 30 | 11 |
def QA_util_get_trade_gap(start, end):
'返回start_day到end_day中间有多少个交易天 算首尾'
start, end = QA_util_get_real_datelist(start, end)
if start is not None:
return trade_date_sse.index(end) + 1 - trade_date_sse.index(start)
else:
return 0 | [
"def",
"QA_util_get_trade_gap",
"(",
"start",
",",
"end",
")",
":",
"start",
",",
"end",
"=",
"QA_util_get_real_datelist",
"(",
"start",
",",
"end",
")",
"if",
"start",
"is",
"not",
"None",
":",
"return",
"trade_date_sse",
".",
"index",
"(",
"end",
")",
... | 36.285714 | 17.428571 |
def insert(self, name, value, timestamp=None, intervals=0, **kwargs):
'''
Insert a value for the timeseries "name". For each interval in the
configuration, will insert the value into a bucket for the interval
"timestamp". If time is not supplied, will default to time.time(), else it
should be a floa... | [
"def",
"insert",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
"=",
"None",
",",
"intervals",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"timestamp",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"if",
"isinstance... | 42.764706 | 26.352941 |
def makeArg(segID, N, CA, C, O, geo):
'''Creates an Arginie residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle= geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diang... | [
"def",
"makeArg",
"(",
"segID",
",",
"N",
",",
"CA",
",",
"C",
",",
"O",
",",
"geo",
")",
":",
"##R-Group",
"CA_CB_length",
"=",
"geo",
".",
"CA_CB_length",
"C_CA_CB_angle",
"=",
"geo",
".",
"C_CA_CB_angle",
"N_C_CA_CB_diangle",
"=",
"geo",
".",
"N_C_CA_... | 38.166667 | 21.9 |
def send(self, send_email=True):
"""Marks the invoice as sent in Holvi
If send_email is False then the invoice is *not* automatically emailed to the recipient
and your must take care of sending the invoice yourself.
"""
url = str(self.api.base_url + '{code}/status/').format(code... | [
"def",
"send",
"(",
"self",
",",
"send_email",
"=",
"True",
")",
":",
"url",
"=",
"str",
"(",
"self",
".",
"api",
".",
"base_url",
"+",
"'{code}/status/'",
")",
".",
"format",
"(",
"code",
"=",
"self",
".",
"code",
")",
"# six.u messes this up",
"paylo... | 42 | 22.333333 |
def normalized_distance(self, image):
"""Calculates the distance of a given image to the
original image.
Parameters
----------
image : `numpy.ndarray`
The image that should be compared to the original image.
Returns
-------
:class:`Distance`
... | [
"def",
"normalized_distance",
"(",
"self",
",",
"image",
")",
":",
"return",
"self",
".",
"__distance",
"(",
"self",
".",
"__original_image_for_distance",
",",
"image",
",",
"bounds",
"=",
"self",
".",
"bounds",
"(",
")",
")"
] | 27.368421 | 19.105263 |
def prt_summary_code(self, prt=sys.stdout):
"""Print summary of codes and groups that can be inputs to get_evcodes."""
prt.write('EVIDENCE GROUP AND CODES:\n')
for grp, c2nt in self.grp2code2nt.items():
prt.write(' {GRP:19}: {CODES}\n'.format(GRP=grp, CODES=' '.join(c2nt.keys()))) | [
"def",
"prt_summary_code",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"prt",
".",
"write",
"(",
"'EVIDENCE GROUP AND CODES:\\n'",
")",
"for",
"grp",
",",
"c2nt",
"in",
"self",
".",
"grp2code2nt",
".",
"items",
"(",
")",
":",
"prt",
"... | 63.2 | 14.8 |
def neighbor_add(self, address, remote_as,
remote_port=DEFAULT_BGP_PORT,
enable_ipv4=DEFAULT_CAP_MBGP_IPV4,
enable_ipv6=DEFAULT_CAP_MBGP_IPV6,
enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4,
enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6... | [
"def",
"neighbor_add",
"(",
"self",
",",
"address",
",",
"remote_as",
",",
"remote_port",
"=",
"DEFAULT_BGP_PORT",
",",
"enable_ipv4",
"=",
"DEFAULT_CAP_MBGP_IPV4",
",",
"enable_ipv6",
"=",
"DEFAULT_CAP_MBGP_IPV6",
",",
"enable_vpnv4",
"=",
"DEFAULT_CAP_MBGP_VPNV4",
"... | 39.013514 | 22.331081 |
def isel(self, indexers=None, drop=False, **indexers_kwargs):
"""Return a new DataArray whose dataset is given by integer indexing
along the specified dimension(s).
See Also
--------
Dataset.isel
DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers... | [
"def",
"isel",
"(",
"self",
",",
"indexers",
"=",
"None",
",",
"drop",
"=",
"False",
",",
"*",
"*",
"indexers_kwargs",
")",
":",
"indexers",
"=",
"either_dict_or_kwargs",
"(",
"indexers",
",",
"indexers_kwargs",
",",
"'isel'",
")",
"ds",
"=",
"self",
"."... | 37.5 | 18.083333 |
def router_fabric_virtual_gateway_address_family_ipv4_gratuitous_arp_timer(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
router = ET.SubElement(config, "router", xmlns="urn:brocade.com:mgmt:brocade-common-def")
fabric_virtual_gateway = ET.SubElement(ro... | [
"def",
"router_fabric_virtual_gateway_address_family_ipv4_gratuitous_arp_timer",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"router",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"router\"",
... | 55.428571 | 25.642857 |
def dict_diff(old, new):
"""
Return a dict representing the differences between the dicts `old` and
`new`. Deleted keys appear as a key with the value :data:`None`, added and
changed keys appear as a key with the new value.
"""
old_keys = viewkeys(old)
new_keys = viewkeys(dict(new))
out ... | [
"def",
"dict_diff",
"(",
"old",
",",
"new",
")",
":",
"old_keys",
"=",
"viewkeys",
"(",
"old",
")",
"new_keys",
"=",
"viewkeys",
"(",
"dict",
"(",
"new",
")",
")",
"out",
"=",
"{",
"}",
"for",
"key",
"in",
"new_keys",
"-",
"old_keys",
":",
"out",
... | 32.235294 | 13.764706 |
def add_mpl_colorscale(fig, heatmap_gs, ax_map, params, title=None):
"""Add colour scale to heatmap."""
# Set tick intervals
cbticks = [params.vmin + e * params.vdiff for e in (0, 0.25, 0.5, 0.75, 1)]
if params.vmax > 10:
exponent = int(floor(log10(params.vmax))) - 1
cbticks = [int(round... | [
"def",
"add_mpl_colorscale",
"(",
"fig",
",",
"heatmap_gs",
",",
"ax_map",
",",
"params",
",",
"title",
"=",
"None",
")",
":",
"# Set tick intervals",
"cbticks",
"=",
"[",
"params",
".",
"vmin",
"+",
"e",
"*",
"params",
".",
"vdiff",
"for",
"e",
"in",
... | 40.25 | 17.35 |
def _parse_lists(self, match):
'''Parse lists.'''
# Don't parse usernames here
if match.group(4) is None:
return match.group(0)
pre, at_char, user, list_name = match.groups()
list_name = list_name[1:]
if self._include_spans:
self._lists.append((u... | [
"def",
"_parse_lists",
"(",
"self",
",",
"match",
")",
":",
"# Don't parse usernames here",
"if",
"match",
".",
"group",
"(",
"4",
")",
"is",
"None",
":",
"return",
"match",
".",
"group",
"(",
"0",
")",
"pre",
",",
"at_char",
",",
"user",
",",
"list_na... | 31.375 | 19.125 |
def open(filename,
mode='r',
content_type=None,
options=None,
read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE,
retry_params=None,
_account_id=None,
offset=0):
"""Opens a Google Cloud Storage file and returns it as a File-like object.
Args:
... | [
"def",
"open",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"content_type",
"=",
"None",
",",
"options",
"=",
"None",
",",
"read_buffer_size",
"=",
"storage_api",
".",
"ReadBuffer",
".",
"DEFAULT_BUFFER_SIZE",
",",
"retry_params",
"=",
"None",
",",
"_accou... | 43.327869 | 21.704918 |
def unpack(packed, object_hook=decode,
list_hook=None, use_list=False, encoding='utf-8',
unicode_errors='strict', object_pairs_hook=None,
max_buffer_size=0, ext_hook=ExtType):
"""
Unpack a packed object, return an iterator
Note: packed lists will be returned as tuples
""... | [
"def",
"unpack",
"(",
"packed",
",",
"object_hook",
"=",
"decode",
",",
"list_hook",
"=",
"None",
",",
"use_list",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
",",
"unicode_errors",
"=",
"'strict'",
",",
"object_pairs_hook",
"=",
"None",
",",
"max_buffer_... | 41.1875 | 10.8125 |
def from_url(cls, url, **kwargs):
"""
Creates an instance of the KubeConfig class from a single URL (useful
for interacting with kubectl proxy).
"""
doc = {
"clusters": [
{
"name": "self",
"cluster": {
... | [
"def",
"from_url",
"(",
"cls",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"doc",
"=",
"{",
"\"clusters\"",
":",
"[",
"{",
"\"name\"",
":",
"\"self\"",
",",
"\"cluster\"",
":",
"{",
"\"server\"",
":",
"url",
",",
"}",
",",
"}",
",",
"]",
",",
... | 26.730769 | 14.346154 |
def labels(self, *labelvalues, **labelkwargs):
"""Return the child for the given labelset.
All metrics can have labels, allowing grouping of related time series.
Taking a counter as an example:
from prometheus_client import Counter
c = Counter('my_requests_total', 'HTT... | [
"def",
"labels",
"(",
"self",
",",
"*",
"labelvalues",
",",
"*",
"*",
"labelkwargs",
")",
":",
"if",
"not",
"self",
".",
"_labelnames",
":",
"raise",
"ValueError",
"(",
"'No label names were set when constructing %s'",
"%",
"self",
")",
"if",
"self",
".",
"_... | 41.166667 | 22.611111 |
def _get_lutfiles_version(self):
"""Check the version of the atm correction luts from the version file in the
specific aerosol correction directory
"""
basedir = RAYLEIGH_LUT_DIRS[self._aerosol_type]
lutfiles_version_path = os.path.join(basedir,
... | [
"def",
"_get_lutfiles_version",
"(",
"self",
")",
":",
"basedir",
"=",
"RAYLEIGH_LUT_DIRS",
"[",
"self",
".",
"_aerosol_type",
"]",
"lutfiles_version_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"ATM_CORRECTION_LUT_VERSION",
"[",
"self",
".",... | 40.266667 | 18.066667 |
def recompress_archive(archive, verbosity=0, interactive=True):
"""Recompress an archive to hopefully smaller size."""
util.check_existing_filename(archive)
util.check_writable_filename(archive)
if verbosity >= 0:
util.log_info("Recompressing %s ..." % (archive,))
res = _recompress_archive(a... | [
"def",
"recompress_archive",
"(",
"archive",
",",
"verbosity",
"=",
"0",
",",
"interactive",
"=",
"True",
")",
":",
"util",
".",
"check_existing_filename",
"(",
"archive",
")",
"util",
".",
"check_writable_filename",
"(",
"archive",
")",
"if",
"verbosity",
">=... | 43.5 | 15.7 |
def _ps(self, sys_output):
''' a helper method for parsing docker ps output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
container_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
... | [
"def",
"_ps",
"(",
"self",
",",
"sys_output",
")",
":",
"import",
"re",
"gap_pattern",
"=",
"re",
".",
"compile",
"(",
"'\\t|\\s{2,}'",
")",
"container_list",
"=",
"[",
"]",
"output_lines",
"=",
"sys_output",
".",
"split",
"(",
"'\\n'",
")",
"column_header... | 44.76 | 18.12 |
def parse_css (url_data):
"""
Parse a CSS file for url() patterns.
"""
lineno = 0
linkfinder = linkparse.css_url_re.finditer
strip_comments = linkparse.strip_c_comments
for line in strip_comments(url_data.get_content()).splitlines():
lineno += 1
for mo in linkfinder(line):
... | [
"def",
"parse_css",
"(",
"url_data",
")",
":",
"lineno",
"=",
"0",
"linkfinder",
"=",
"linkparse",
".",
"css_url_re",
".",
"finditer",
"strip_comments",
"=",
"linkparse",
".",
"strip_c_comments",
"for",
"line",
"in",
"strip_comments",
"(",
"url_data",
".",
"ge... | 35.769231 | 11.769231 |
def ccs_normalize(compIM, ccsnorm):
""" normalize the ccs representation
Parameters
----------
compIM: 2d array
The CCS image in CCS representation
ccsnorm: 2d array
The normalization matrix in ccs representation
Returns
-------
compIM: 2d array
The normalized C... | [
"def",
"ccs_normalize",
"(",
"compIM",
",",
"ccsnorm",
")",
":",
"compIM",
"=",
"np",
".",
"asarray",
"(",
"compIM",
")",
"ccsnorm",
"=",
"np",
".",
"asarray",
"(",
"ccsnorm",
")",
"ys",
"=",
"ccsnorm",
".",
"shape",
"[",
"0",
"]",
"xs",
"=",
"ccsn... | 26.416667 | 17.611111 |
def do_b0(self, line):
"""Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0"""
self.application.apply_update(opendnp3.Binary(False), index=6) | [
"def",
"do_b0",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"application",
".",
"apply_update",
"(",
"opendnp3",
".",
"Binary",
"(",
"False",
")",
",",
"index",
"=",
"6",
")"
] | 64.666667 | 16 |
def computePreRec(cm, class_names):
'''
This function computes the precision, recall and f1 measures,
given a confusion matrix
'''
n_classes = cm.shape[0]
if len(class_names) != n_classes:
print("Error in computePreRec! Confusion matrix and class_names "
"list must be of th... | [
"def",
"computePreRec",
"(",
"cm",
",",
"class_names",
")",
":",
"n_classes",
"=",
"cm",
".",
"shape",
"[",
"0",
"]",
"if",
"len",
"(",
"class_names",
")",
"!=",
"n_classes",
":",
"print",
"(",
"\"Error in computePreRec! Confusion matrix and class_names \"",
"\"... | 35.833333 | 18.722222 |
def k_closest(points, k, origin=(0, 0)):
# Time: O(k+(n-k)logk)
# Space: O(k)
"""Initialize max heap with first k points.
Python does not support a max heap; thus we can use the default min heap where the keys (distance) are negated.
"""
heap = [(-distance(p, origin), p) for p in points[:k]]
... | [
"def",
"k_closest",
"(",
"points",
",",
"k",
",",
"origin",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"# Time: O(k+(n-k)logk)",
"# Space: O(k)",
"heap",
"=",
"[",
"(",
"-",
"distance",
"(",
"p",
",",
"origin",
")",
",",
"p",
")",
"for",
"p",
"in",
... | 32.178571 | 17.178571 |
def create_entity(self):
"""Create a new entity.
The entity will have a higher UID than any previously associated
with this world.
:return: the new entity
:rtype: :class:`essence.Entity`"""
self._highest_id_seen += 1
entity = Entity(self._highest_id_seen, self)
... | [
"def",
"create_entity",
"(",
"self",
")",
":",
"self",
".",
"_highest_id_seen",
"+=",
"1",
"entity",
"=",
"Entity",
"(",
"self",
".",
"_highest_id_seen",
",",
"self",
")",
"self",
".",
"_entities",
".",
"append",
"(",
"entity",
")",
"return",
"entity"
] | 30.666667 | 16.083333 |
def set_itunes_closed_captioned(self):
"""Parses isClosedCaptioned from itunes tags and sets value"""
try:
self.itunes_closed_captioned = self.soup.find(
'itunes:isclosedcaptioned').string
self.itunes_closed_captioned = self.itunes_closed_captioned.lower()
... | [
"def",
"set_itunes_closed_captioned",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_closed_captioned",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:isclosedcaptioned'",
")",
".",
"string",
"self",
".",
"itunes_closed_captioned",
"=",
"self",
".... | 48 | 14.25 |
def verify(password, encoded):
"""
Verify a Password
:param password:
:param encoded:
:return: True or False
"""
algorithm, iterations, salt, h = split(encoded)
to_verify = encode(password, algorithm, salt, int(iterations))
return hmac.compare_digest(to_verify.encode(), encoded.enco... | [
"def",
"verify",
"(",
"password",
",",
"encoded",
")",
":",
"algorithm",
",",
"iterations",
",",
"salt",
",",
"h",
"=",
"split",
"(",
"encoded",
")",
"to_verify",
"=",
"encode",
"(",
"password",
",",
"algorithm",
",",
"salt",
",",
"int",
"(",
"iteratio... | 28.636364 | 17.181818 |
def update(cls):
"""
Update rows to include known network interfaces
"""
ifaddrs = getifaddrs()
# Create new interfaces
for ifname in ifaddrs.keys():
if filter(ifname.startswith, cls.NAME_FILTER):
cls.objects.get_or_create(name=ifname)
... | [
"def",
"update",
"(",
"cls",
")",
":",
"ifaddrs",
"=",
"getifaddrs",
"(",
")",
"# Create new interfaces",
"for",
"ifname",
"in",
"ifaddrs",
".",
"keys",
"(",
")",
":",
"if",
"filter",
"(",
"ifname",
".",
"startswith",
",",
"cls",
".",
"NAME_FILTER",
")",... | 33.666667 | 12.833333 |
def plot_sgls(mask_exp, depths, mask_tag_filt, sgls, mask_sgls_filt, Az_g_hf,
idx_start=None, idx_end=None, path_plot=None, linewidth=0.5,
leg_bbox=(1.23,1), clip_x=False):
'''Plot sub-glides over depth and high-pass filtered accelerometer signal
Args
----
mask_exp: ndarray
Bool... | [
"def",
"plot_sgls",
"(",
"mask_exp",
",",
"depths",
",",
"mask_tag_filt",
",",
"sgls",
",",
"mask_sgls_filt",
",",
"Az_g_hf",
",",
"idx_start",
"=",
"None",
",",
"idx_end",
"=",
"None",
",",
"path_plot",
"=",
"None",
",",
"linewidth",
"=",
"0.5",
",",
"l... | 32.966667 | 18.177778 |
def _infer_spaces(s):
"""
Uses dynamic programming to infer the location of spaces in a string
without spaces.
"""
s = s.lower()
# Find the best match for the i first characters, assuming cost has
# been built for the i-1 first characters.
# Returns a pair (match_cost, match_length).
... | [
"def",
"_infer_spaces",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"lower",
"(",
")",
"# Find the best match for the i first characters, assuming cost has",
"# been built for the i-1 first characters.",
"# Returns a pair (match_cost, match_length).",
"def",
"best_match",
"(",
"i",... | 27.612903 | 19.548387 |
def previousSibling(self) -> Optional[AbstractNode]:
"""Return the previous sibling of this node.
If there is no previous sibling, return ``None``.
"""
parent = self.parentNode
if parent is None:
return None
return parent.childNodes.item(parent.childNodes.ind... | [
"def",
"previousSibling",
"(",
"self",
")",
"->",
"Optional",
"[",
"AbstractNode",
"]",
":",
"parent",
"=",
"self",
".",
"parentNode",
"if",
"parent",
"is",
"None",
":",
"return",
"None",
"return",
"parent",
".",
"childNodes",
".",
"item",
"(",
"parent",
... | 36.111111 | 15.555556 |
def get_annotated_list_qs(cls, qs):
"""
Gets an annotated list from a queryset.
"""
result, info = [], {}
start_depth, prev_depth = (None, None)
for node in qs:
depth = node.get_depth()
if start_depth is None:
start_depth = depth
... | [
"def",
"get_annotated_list_qs",
"(",
"cls",
",",
"qs",
")",
":",
"result",
",",
"info",
"=",
"[",
"]",
",",
"{",
"}",
"start_depth",
",",
"prev_depth",
"=",
"(",
"None",
",",
"None",
")",
"for",
"node",
"in",
"qs",
":",
"depth",
"=",
"node",
".",
... | 41.578947 | 12.631579 |
def estimateBIsochrone(pot,R,z,phi=None):
"""
NAME:
estimateBIsochrone
PURPOSE:
Estimate a good value for the scale of the isochrone potential by matching the slope of the rotation curve
INPUT:
pot- Potential instance or list thereof
R,z - coordinates (if these are arra... | [
"def",
"estimateBIsochrone",
"(",
"pot",
",",
"R",
",",
"z",
",",
"phi",
"=",
"None",
")",
":",
"if",
"pot",
"is",
"None",
":",
"#pragma: no cover",
"raise",
"IOError",
"(",
"\"pot= needs to be set to a Potential instance or list thereof\"",
")",
"if",
"isinstance... | 32.037736 | 28.45283 |
def mkstemp(self, suffix, prefix, directory=None):
"""
Generate temp file name in artifacts base dir
and close temp file handle
"""
if not directory:
directory = self.artifacts_dir
fd, fname = tempfile.mkstemp(suffix, prefix, directory)
os.close(fd)
... | [
"def",
"mkstemp",
"(",
"self",
",",
"suffix",
",",
"prefix",
",",
"directory",
"=",
"None",
")",
":",
"if",
"not",
"directory",
":",
"directory",
"=",
"self",
".",
"artifacts_dir",
"fd",
",",
"fname",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
","... | 36.090909 | 12.454545 |
def _adjust_n_years(other, n, month, reference_day):
"""Adjust the number of times an annual offset is applied based on
another date, and the reference day provided"""
if n > 0:
if other.month < month or (other.month == month and
other.day < reference_day):
... | [
"def",
"_adjust_n_years",
"(",
"other",
",",
"n",
",",
"month",
",",
"reference_day",
")",
":",
"if",
"n",
">",
"0",
":",
"if",
"other",
".",
"month",
"<",
"month",
"or",
"(",
"other",
".",
"month",
"==",
"month",
"and",
"other",
".",
"day",
"<",
... | 40.416667 | 18.666667 |
def get_tools(whitelist, known_plugins):
"""
Filter all known plugins by a whitelist specified. If the whitelist is
empty, default to all plugins.
"""
def getpath(c):
return "%s:%s" % (c.__module__, c.__class__.__name__)
tools = [x for x in known_plugins if getpath(x) in whitelist]
... | [
"def",
"get_tools",
"(",
"whitelist",
",",
"known_plugins",
")",
":",
"def",
"getpath",
"(",
"c",
")",
":",
"return",
"\"%s:%s\"",
"%",
"(",
"c",
".",
"__module__",
",",
"c",
".",
"__class__",
".",
"__name__",
")",
"tools",
"=",
"[",
"x",
"for",
"x",... | 29.933333 | 18.866667 |
def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
"""Profile a Python statement like timeit."""
del _ignored
globals_ = {}
exec_(setup, globals_)
if number is None:
# determine number so ... | [
"def",
"timeit_profile",
"(",
"stmt",
",",
"number",
",",
"repeat",
",",
"setup",
",",
"profiler_factory",
",",
"pickle_protocol",
",",
"dump_filename",
",",
"mono",
",",
"*",
"*",
"_ignored",
")",
":",
"del",
"_ignored",
"globals_",
"=",
"{",
"}",
"exec_"... | 38.2 | 14 |
def trigger_installed(connection: connection, table: str, schema: str='public'):
"""Test whether or not a psycopg2-pgevents trigger is installed for a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table... | [
"def",
"trigger_installed",
"(",
"connection",
":",
"connection",
",",
"table",
":",
"str",
",",
"schema",
":",
"str",
"=",
"'public'",
")",
":",
"installed",
"=",
"False",
"log",
"(",
"'Checking if {}.{} trigger installed...'",
".",
"format",
"(",
"schema",
"... | 26.617647 | 25.705882 |
def read_proto_object(fobj, klass):
"""Read a block of data and parse using the given protobuf object."""
log.debug('%s chunk', klass.__name__)
obj = klass()
obj.ParseFromString(read_block(fobj))
log.debug('Header: %s', str(obj))
return obj | [
"def",
"read_proto_object",
"(",
"fobj",
",",
"klass",
")",
":",
"log",
".",
"debug",
"(",
"'%s chunk'",
",",
"klass",
".",
"__name__",
")",
"obj",
"=",
"klass",
"(",
")",
"obj",
".",
"ParseFromString",
"(",
"read_block",
"(",
"fobj",
")",
")",
"log",
... | 36.857143 | 8.428571 |
def exceptions(self):
"""
Returns a list of ParamDoc objects (with empty names) of the
exception tags for the function.
>>> comments = parse_comments_for_file('examples/module_closure.js')
>>> fn1 = FunctionDoc(comments[1])
>>> fn1.exceptions[0].doc
'Another exce... | [
"def",
"exceptions",
"(",
"self",
")",
":",
"def",
"make_param",
"(",
"text",
")",
":",
"if",
"'{'",
"in",
"text",
"and",
"'}'",
"in",
"text",
":",
"# Make sure param name is blank:",
"word_split",
"=",
"list",
"(",
"split_delimited",
"(",
"'{}'",
",",
"' ... | 38.071429 | 15.285714 |
def dir_is_glotk(path):
"""check that the current directory is a glotk project folder"""
test_set = set(["gloTK_info", "gloTK_assemblies",
"gloTK_configs", "gloTK_reads",
"gloTK_fastqc", "gloTK_kmer",
"gloTK_reports"])
#http://stackoverflow.com/que... | [
"def",
"dir_is_glotk",
"(",
"path",
")",
":",
"test_set",
"=",
"set",
"(",
"[",
"\"gloTK_info\"",
",",
"\"gloTK_assemblies\"",
",",
"\"gloTK_configs\"",
",",
"\"gloTK_reads\"",
",",
"\"gloTK_fastqc\"",
",",
"\"gloTK_kmer\"",
",",
"\"gloTK_reports\"",
"]",
")",
"#h... | 39.923077 | 13.615385 |
def LatLngsToGoogleLink(source, destination):
"""Return a string "<a ..." for a trip at a random time."""
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source), FormatLatLng(destination),
dt.ctime()) | [
"def",
"LatLngsToGoogleLink",
"(",
"source",
",",
"destination",
")",
":",
"dt",
"=",
"GetRandomDatetime",
"(",
")",
"return",
"\"<a href='%s'>from:%s to:%s on %s</a>\"",
"%",
"(",
"LatLngsToGoogleUrl",
"(",
"source",
",",
"destination",
",",
"dt",
")",
",",
"Form... | 43.428571 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.