text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def add_head(self, path: str, handler: _WebHandler,
**kwargs: Any) -> AbstractRoute:
"""
Shortcut for add_route with method HEAD
"""
return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs) | [
"def",
"add_head",
"(",
"self",
",",
"path",
":",
"str",
",",
"handler",
":",
"_WebHandler",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"AbstractRoute",
":",
"return",
"self",
".",
"add_route",
"(",
"hdrs",
".",
"METH_HEAD",
",",
"path",
",",
"h... | 39.833333 | 0.012295 |
def transactional_tasklet(func, args, kwds, **options):
"""The async version of @ndb.transaction.
Will return the result of the wrapped function as a Future.
"""
from . import tasklets
func = tasklets.tasklet(func)
return transactional_async.wrapped_decorator(func, args, kwds, **options) | [
"def",
"transactional_tasklet",
"(",
"func",
",",
"args",
",",
"kwds",
",",
"*",
"*",
"options",
")",
":",
"from",
".",
"import",
"tasklets",
"func",
"=",
"tasklets",
".",
"tasklet",
"(",
"func",
")",
"return",
"transactional_async",
".",
"wrapped_decorator"... | 36.75 | 0.016611 |
def wait_new_conf(self):
"""Send a HTTP request to the satellite (GET /wait_new_conf)
:return: True if wait new conf, otherwise False
:rtype: bool
"""
logger.debug("Wait new configuration for %s, %s %s", self.name, self.alive, self.reachable)
return self.con.get('_wait_n... | [
"def",
"wait_new_conf",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Wait new configuration for %s, %s %s\"",
",",
"self",
".",
"name",
",",
"self",
".",
"alive",
",",
"self",
".",
"reachable",
")",
"return",
"self",
".",
"con",
".",
"get",
"(",
... | 40.25 | 0.009119 |
def give_str(self):
"""
Give string representation of the callable.
"""
args = self._args[:]
kwargs = self._kwargs
return self._give_str(args, kwargs) | [
"def",
"give_str",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"_args",
"[",
":",
"]",
"kwargs",
"=",
"self",
".",
"_kwargs",
"return",
"self",
".",
"_give_str",
"(",
"args",
",",
"kwargs",
")"
] | 28 | 0.009901 |
def frames_to_tc(self, frames):
"""Converts frames back to timecode
:returns str: the string representation of the current time code
"""
if frames == 0:
return 0, 0, 0, 0
ffps = float(self._framerate)
if self.drop_frame:
# Number of frames to d... | [
"def",
"frames_to_tc",
"(",
"self",
",",
"frames",
")",
":",
"if",
"frames",
"==",
"0",
":",
"return",
"0",
",",
"0",
",",
"0",
",",
"0",
"ffps",
"=",
"float",
"(",
"self",
".",
"_framerate",
")",
"if",
"self",
".",
"drop_frame",
":",
"# Number of ... | 34.518519 | 0.001043 |
def _rem_id_from_keys(self, pk, conn=None):
'''
_rem_id_from_keys - Remove primary key from table
internal
'''
if conn is None:
conn = self._get_connection()
conn.srem(self._get_ids_key(), pk) | [
"def",
"_rem_id_from_keys",
"(",
"self",
",",
"pk",
",",
"conn",
"=",
"None",
")",
":",
"if",
"conn",
"is",
"None",
":",
"conn",
"=",
"self",
".",
"_get_connection",
"(",
")",
"conn",
".",
"srem",
"(",
"self",
".",
"_get_ids_key",
"(",
")",
",",
"p... | 25.25 | 0.043062 |
def _handle_request_error(self, orig_request, error, start_response):
"""Handle a request error, converting it to a WSGI response.
Args:
orig_request: An ApiRequest, the original request from the user.
error: A RequestError containing information about the error.
start_response: A function wi... | [
"def",
"_handle_request_error",
"(",
"self",
",",
"orig_request",
",",
"error",
",",
"start_response",
")",
":",
"headers",
"=",
"[",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"]",
"status_code",
"=",
"error",
".",
"status_code",
"(",
")",
"body",... | 43.428571 | 0.001073 |
def prepare(args):
"""
%prog prepare countfolder families
Parse list of count files and group per family into families folder.
"""
p = OptionParser(prepare.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
counts, families = args
coun... | [
"def",
"prepare",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"prepare",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | 31.111111 | 0.001154 |
def initSchd_5_to_6(self):
""" Initialize second(and last) tariff schedule :class:`~ekmmeters.SerialBlock`. """
self.m_schd_5_to_6["reserved_30"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_schd_5_to_6["Schedule_5_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False... | [
"def",
"initSchd_5_to_6",
"(",
"self",
")",
":",
"self",
".",
"m_schd_5_to_6",
"[",
"\"reserved_30\"",
"]",
"=",
"[",
"6",
",",
"FieldType",
".",
"Hex",
",",
"ScaleType",
".",
"No",
",",
"\"\"",
",",
"0",
",",
"False",
",",
"False",
"]",
"self",
".",... | 100.685714 | 0.009837 |
def update(self, fname):
"""
Adds a handler to save to a file. Includes debug stuff.
"""
ltfh = FileHandler(fname)
self._log.addHandler(ltfh) | [
"def",
"update",
"(",
"self",
",",
"fname",
")",
":",
"ltfh",
"=",
"FileHandler",
"(",
"fname",
")",
"self",
".",
"_log",
".",
"addHandler",
"(",
"ltfh",
")"
] | 29.333333 | 0.01105 |
def SaveData(self, raw_data):
"""Store the raw data as our configuration."""
if self.filename is None:
raise IOError("Unknown filename")
logging.info("Writing back configuration to file %s", self.filename)
# Ensure intermediate directories exist
try:
os.makedirs(os.path.dirname(self.fil... | [
"def",
"SaveData",
"(",
"self",
",",
"raw_data",
")",
":",
"if",
"self",
".",
"filename",
"is",
"None",
":",
"raise",
"IOError",
"(",
"\"Unknown filename\"",
")",
"logging",
".",
"info",
"(",
"\"Writing back configuration to file %s\"",
",",
"self",
".",
"file... | 35.909091 | 0.01233 |
def prepare(data):
'''
Try to get current process ready to unpickle process object
'''
if 'name' in data:
process.current_process().name = data['name']
if 'authkey' in data:
process.current_process().authkey = data['authkey']
if 'log_to_stderr' in data and data['log_to_stderr']... | [
"def",
"prepare",
"(",
"data",
")",
":",
"if",
"'name'",
"in",
"data",
":",
"process",
".",
"current_process",
"(",
")",
".",
"name",
"=",
"data",
"[",
"'name'",
"]",
"if",
"'authkey'",
"in",
"data",
":",
"process",
".",
"current_process",
"(",
")",
... | 27.333333 | 0.000841 |
def subscribe(self, py3_module, trigger_action, subsystem):
"""
Subscribe the given module to the given udev subsystem.
Here we will lazy load the monitor if necessary and return success or
failure based on the availability of pyudev.
"""
if self.pyudev_available:
... | [
"def",
"subscribe",
"(",
"self",
",",
"py3_module",
",",
"trigger_action",
",",
"subsystem",
")",
":",
"if",
"self",
".",
"pyudev_available",
":",
"# lazy load the udev monitor",
"if",
"self",
".",
"udev_observer",
"is",
"None",
":",
"self",
".",
"_setup_pyudev_... | 41.758621 | 0.002421 |
def convert_item_to_command_line_arg(self, action, key, value):
"""Converts a config file or env var key + value to a list of
commandline args to append to the commandline.
Args:
action: The argparse Action object for this setting, or None if this
config file setting... | [
"def",
"convert_item_to_command_line_arg",
"(",
"self",
",",
"action",
",",
"key",
",",
"value",
")",
":",
"args",
"=",
"[",
"]",
"if",
"action",
"is",
"None",
":",
"command_line_key",
"=",
"self",
".",
"get_command_line_key_for_unknown_config_file_setting",
"(",
... | 45.2 | 0.009528 |
def _make_default_header(self):
"""
Return a generic placeholder header based on the tables column count
"""
td_max = 0
for idx, tr in enumerate(self._tr_nodes):
td_count = len(tr.contents.filter_tags(matches=ftag('td')))
if td_count > td_max:
... | [
"def",
"_make_default_header",
"(",
"self",
")",
":",
"td_max",
"=",
"0",
"for",
"idx",
",",
"tr",
"in",
"enumerate",
"(",
"self",
".",
"_tr_nodes",
")",
":",
"td_count",
"=",
"len",
"(",
"tr",
".",
"contents",
".",
"filter_tags",
"(",
"matches",
"=",
... | 35.153846 | 0.010661 |
def add_number_widget(self, ref, x=1, value=1):
""" Add Number Widget """
if ref not in self.widgets:
widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value)
self.widgets[ref] = widget
return self.widgets[ref] | [
"def",
"add_number_widget",
"(",
"self",
",",
"ref",
",",
"x",
"=",
"1",
",",
"value",
"=",
"1",
")",
":",
"if",
"ref",
"not",
"in",
"self",
".",
"widgets",
":",
"widget",
"=",
"widgets",
".",
"NumberWidget",
"(",
"screen",
"=",
"self",
",",
"ref",... | 38.571429 | 0.01087 |
def top_in(self, leaderboard_name, number, **options):
'''
Retrieve members from the named leaderboard within a range from 1 to the number given.
@param leaderboard_name [String] Name of the leaderboard.
@param starting_rank [int] Starting rank (inclusive).
@param ending_rank [i... | [
"def",
"top_in",
"(",
"self",
",",
"leaderboard_name",
",",
"number",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"members_from_rank_range_in",
"(",
"leaderboard_name",
",",
"1",
",",
"number",
",",
"*",
"*",
"options",
")"
] | 51.416667 | 0.009554 |
def sendRequest(self, name, args):
"""sends a request to the peer"""
(respEvt, id) = self.newResponseEvent()
self.sendMessage({"id":id, "method":name, "params": args})
return respEvt | [
"def",
"sendRequest",
"(",
"self",
",",
"name",
",",
"args",
")",
":",
"(",
"respEvt",
",",
"id",
")",
"=",
"self",
".",
"newResponseEvent",
"(",
")",
"self",
".",
"sendMessage",
"(",
"{",
"\"id\"",
":",
"id",
",",
"\"method\"",
":",
"name",
",",
"... | 42 | 0.018692 |
def currencies(self):
"""Get all currencies with non-zero values"""
return [m.currency.code for m in self.monies() if m.amount] | [
"def",
"currencies",
"(",
"self",
")",
":",
"return",
"[",
"m",
".",
"currency",
".",
"code",
"for",
"m",
"in",
"self",
".",
"monies",
"(",
")",
"if",
"m",
".",
"amount",
"]"
] | 47 | 0.013986 |
def get_device(self, id=None):
"""Returns details of either the first or specified device
:param int id: Identifier of desired device. If not given, first device
found will be returned
:returns tuple: Device ID, Device Address, Firmware Version
"""
if id is None:
... | [
"def",
"get_device",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"if",
"id",
"is",
"None",
":",
"if",
"not",
"self",
".",
"devices",
":",
"raise",
"ValueError",
"(",
"'No default device for %s'",
"%",
"self",
".",
"hardware_id",
")",
"id",
",",
"(",... | 35 | 0.002317 |
def server_bind(self):
"""Override of TCPServer.server_bind() that tracks bind-time assigned random ports."""
TCPServer.server_bind(self)
_, self.server_port = self.socket.getsockname()[:2] | [
"def",
"server_bind",
"(",
"self",
")",
":",
"TCPServer",
".",
"server_bind",
"(",
"self",
")",
"_",
",",
"self",
".",
"server_port",
"=",
"self",
".",
"socket",
".",
"getsockname",
"(",
")",
"[",
":",
"2",
"]"
] | 49.5 | 0.00995 |
def node_to_xml(node, output=sys.stdout, nsmap=None):
"""
Convert a Node object into a pretty .xml file without keeping
everything in memory. If you just want the string representation
use tostring(node).
:param node: a Node-compatible object (ElementTree nodes are fine)
:param nsmap: if given,... | [
"def",
"node_to_xml",
"(",
"node",
",",
"output",
"=",
"sys",
".",
"stdout",
",",
"nsmap",
"=",
"None",
")",
":",
"if",
"nsmap",
":",
"for",
"ns",
",",
"prefix",
"in",
"nsmap",
".",
"items",
"(",
")",
":",
"if",
"prefix",
":",
"node",
"[",
"'xmln... | 33.555556 | 0.00161 |
def set_condition(self, condition, condition_instr=None):
"""
Defines the condition which decides how the basic block exits
:param condition:
:type condition:
:param condition_instr: If the 'condition' argument is a Variable, then\
condition_instr is None, else,... | [
"def",
"set_condition",
"(",
"self",
",",
"condition",
",",
"condition_instr",
"=",
"None",
")",
":",
"assert",
"(",
"isinstance",
"(",
"condition",
",",
"Numeric",
")",
")",
"if",
"condition_instr",
"is",
"not",
"None",
":",
"assert",
"(",
"isinstance",
"... | 47.703704 | 0.002283 |
def next(self):
"""Advances to and returns the next token or returns EndOfFile"""
self.index += 1
t = self.peek()
if not self.depth:
self._cut()
return t | [
"def",
"next",
"(",
"self",
")",
":",
"self",
".",
"index",
"+=",
"1",
"t",
"=",
"self",
".",
"peek",
"(",
")",
"if",
"not",
"self",
".",
"depth",
":",
"self",
".",
"_cut",
"(",
")",
"return",
"t"
] | 28.428571 | 0.009756 |
def get_workflow_status_of(brain_or_object, state_var="review_state"):
"""Get the current workflow status of the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param state_var: The name of ... | [
"def",
"get_workflow_status_of",
"(",
"brain_or_object",
",",
"state_var",
"=",
"\"review_state\"",
")",
":",
"# Try to get the state from the catalog brain first",
"if",
"is_brain",
"(",
"brain_or_object",
")",
":",
"if",
"state_var",
"in",
"brain_or_object",
".",
"schem... | 40.421053 | 0.001272 |
def create(self):
"""Create this cluster.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_create_cluster]
:end-before: [END bigtable_create_cluster]
.. note::
Uses the ``project``, ``instance`` and ``cluster_id`` on the
... | [
"def",
"create",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_instance",
".",
"_client",
"cluster_pb",
"=",
"self",
".",
"_to_pb",
"(",
")",
"return",
"client",
".",
"instance_admin_client",
".",
"create_cluster",
"(",
"self",
".",
"_instance",
"."... | 30.65625 | 0.001976 |
def execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False, locked = False, do_commit = True):
"""Execute SQL query. This uses DictCursor by default."""
i = 0
errcode = 0
caughte = None
cursor = None
if sql.find(";") != -1 or sql.find("\\G") != -1:
# Catches some injections
rais... | [
"def",
"execute",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"cursorClass",
"=",
"DictCursor",
",",
"quiet",
"=",
"False",
",",
"locked",
"=",
"False",
",",
"do_commit",
"=",
"True",
")",
":",
"i",
"=",
"0",
"errcode",
"=",
"0",
... | 30.440678 | 0.040453 |
def _validate_units(self, has_units, key, value):
"""Validate fields with `units` key in schema set to True.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if has_units:
if isinstance(self.test.units, dict):
required_u... | [
"def",
"_validate_units",
"(",
"self",
",",
"has_units",
",",
"key",
",",
"value",
")",
":",
"if",
"has_units",
":",
"if",
"isinstance",
"(",
"self",
".",
"test",
".",
"units",
",",
"dict",
")",
":",
"required_units",
"=",
"self",
".",
"test",
".",
"... | 46.857143 | 0.001992 |
def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if msg.startswith(b"#< CLIXML\r\n"):
# for proper xml, we need t... | [
"def",
"_clean_error_msg",
"(",
"self",
",",
"msg",
")",
":",
"# TODO prepare unit test, beautify code",
"# if the msg does not start with this, return it as is",
"if",
"msg",
".",
"startswith",
"(",
"b\"#< CLIXML\\r\\n\"",
")",
":",
"# for proper xml, we need to remove the CLIXM... | 49.388889 | 0.001103 |
def replace(self):
"""Replace index with a new one
zero_downtime_index for safety and rollback
"""
with zero_downtime_index(self.alias_name, self.index_config()) as target_index:
self.index_all(target_index) | [
"def",
"replace",
"(",
"self",
")",
":",
"with",
"zero_downtime_index",
"(",
"self",
".",
"alias_name",
",",
"self",
".",
"index_config",
"(",
")",
")",
"as",
"target_index",
":",
"self",
".",
"index_all",
"(",
"target_index",
")"
] | 41 | 0.011952 |
def build_disagg_matrix(bdata, bin_edges, sid, mon=Monitor):
"""
:param bdata: a dictionary of probabilities of no exceedence
:param bin_edges: bin edges
:param sid: site index
:param mon: a Monitor instance
:returns: a dictionary key -> matrix|pmf for each key in bdata
"""
with mon('bui... | [
"def",
"build_disagg_matrix",
"(",
"bdata",
",",
"bin_edges",
",",
"sid",
",",
"mon",
"=",
"Monitor",
")",
":",
"with",
"mon",
"(",
"'build_disagg_matrix'",
")",
":",
"mag_bins",
",",
"dist_bins",
",",
"lon_bins",
",",
"lat_bins",
",",
"eps_bins",
"=",
"bi... | 43.8 | 0.000372 |
def import_and_wrap_deprecated(module_name, module_dict, warn_import=True):
"""
Usage:
import_and_wrap_deprecated('conda.common.connection', locals())
# looks for conda.common.connection.__all__
"""
if warn_import:
deprecated_import(module_name)
from importlib import import_... | [
"def",
"import_and_wrap_deprecated",
"(",
"module_name",
",",
"module_dict",
",",
"warn_import",
"=",
"True",
")",
":",
"if",
"warn_import",
":",
"deprecated_import",
"(",
"module_name",
")",
"from",
"importlib",
"import",
"import_module",
"module",
"=",
"import_mod... | 34.461538 | 0.002174 |
def copy_all_a(input_a, *other_inputs, **kwargs):
"""Copy all readings in input a into the output.
All other inputs are skipped so that after this function runs there are no
readings left in any of the input walkers when the function finishes, even
if it generated no output readings.
Returns:
... | [
"def",
"copy_all_a",
"(",
"input_a",
",",
"*",
"other_inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"[",
"]",
"while",
"input_a",
".",
"count",
"(",
")",
">",
"0",
":",
"output",
".",
"append",
"(",
"input_a",
".",
"pop",
"(",
")",
"... | 26.210526 | 0.001938 |
def charge(self, cart, request):
"""
Use the Stripe token from the request and charge immediately.
This view is invoked by the Javascript function `scope.charge()` delivered
by `get_payment_request`.
"""
token_id = cart.extra['payment_extra_data']['token_id']
if L... | [
"def",
"charge",
"(",
"self",
",",
"cart",
",",
"request",
")",
":",
"token_id",
"=",
"cart",
".",
"extra",
"[",
"'payment_extra_data'",
"]",
"[",
"'token_id'",
"]",
"if",
"LooseVersion",
"(",
"SHOP_VERSION",
")",
"<",
"LooseVersion",
"(",
"'0.11'",
")",
... | 44.4 | 0.001889 |
def upload(self, fileobj, bucket, key, extra_args=None, subscribers=None):
"""Uploads a file to S3
:type fileobj: str or seekable file-like object
:param fileobj: The name of a file to upload or a seekable file-like
object to upload. It is recommended to use a filename because
... | [
"def",
"upload",
"(",
"self",
",",
"fileobj",
",",
"bucket",
",",
"key",
",",
"extra_args",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"{",
"}",
"if",
"subscribers",
"is",
"None",
... | 40 | 0.00122 |
def _assign_ascii_character(self, y_prev, y, y_next): # noqa for complexity
'''Assign the character to be placed into the graph'''
char = '?'
if y_next > y and y_prev > y:
char = '-'
elif y_next < y and y_prev < y:
char = '-'
e... | [
"def",
"_assign_ascii_character",
"(",
"self",
",",
"y_prev",
",",
"y",
",",
"y_next",
")",
":",
"# noqa for complexity",
"char",
"=",
"'?'",
"if",
"y_next",
">",
"y",
"and",
"y_prev",
">",
"y",
":",
"char",
"=",
"'-'",
"elif",
"y_next",
"<",
"y",
"and... | 32.958333 | 0.002457 |
def parallaxErrorSkyAvg(G, vmini, extension=0.0):
"""
Calculate the sky averaged parallax error from G and (V-I).
Parameters
----------
G - Value(s) of G-band magnitude.
vmini - Value(s) of (V-I) colour.
Keywords
--------
extension - Add this amount of years to the mission lifetime and scale t... | [
"def",
"parallaxErrorSkyAvg",
"(",
"G",
",",
"vmini",
",",
"extension",
"=",
"0.0",
")",
":",
"factor",
"=",
"errorScalingMissionLength",
"(",
"extension",
",",
"-",
"0.5",
")",
"z",
"=",
"calcZ",
"(",
"G",
")",
"return",
"sqrt",
"(",
"-",
"1.631",
"+"... | 23.521739 | 0.01421 |
def add_cluster(
self,
name,
server=None,
certificate_authority_data=None,
**attrs):
"""Add a cluster to config."""
if self.cluster_exists(name):
raise KubeConfError("Cluster with the given name already exists.")
clusters = self.get_clusters... | [
"def",
"add_cluster",
"(",
"self",
",",
"name",
",",
"server",
"=",
"None",
",",
"certificate_authority_data",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"self",
".",
"cluster_exists",
"(",
"name",
")",
":",
"raise",
"KubeConfError",
"(",
"\"Cl... | 31.454545 | 0.008415 |
def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
if sectors is None:
wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs
else:
try:
wc_keys = [k for s in sectors for k in wcxf.Basis['WET', 'JMS'].sectors[s]]
... | [
"def",
"JMS_to_array",
"(",
"C",
",",
"sectors",
"=",
"None",
")",
":",
"if",
"sectors",
"is",
"None",
":",
"wc_keys",
"=",
"wcxf",
".",
"Basis",
"[",
"'WET'",
",",
"'JMS'",
"]",
".",
"all_wcs",
"else",
":",
"try",
":",
"wc_keys",
"=",
"[",
"k",
... | 35 | 0.002418 |
def preserve(method=None, result=True, fields=None):
"""Preserve fields in deposit.
:param method: Function to execute. (Default: ``None``)
:param result: If `True` returns the result of method execution,
otherwise `self`. (Default: ``True``)
:param fields: List of fields to preserve (default: ... | [
"def",
"preserve",
"(",
"method",
"=",
"None",
",",
"result",
"=",
"True",
",",
"fields",
"=",
"None",
")",
":",
"if",
"method",
"is",
"None",
":",
"return",
"partial",
"(",
"preserve",
",",
"result",
"=",
"result",
",",
"fields",
"=",
"fields",
")",... | 36.130435 | 0.001172 |
def add(lhs, rhs):
"""Returns element-wise sum of the input arrays with broadcasting.
Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and
``mx.nd.broadcast_plus(lhs, rhs)`` when shapes of lhs and rhs do not
match. If lhs.shape == rhs.shape, this is equivalent to
``mx.nd.elemwise_add(... | [
"def",
"add",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"if",
"isinstance",
"(",
"lhs",
",",
"NDArray",
")",
"and",
"isinstance",
"(",
"rhs",
",",
"NDArray",
")",
"and",
"lhs",
".",
"shape",
"==",
"rhs",
".",
"shap... | 29.927536 | 0.001406 |
def get_playcount(self):
"""Returns the number of plays on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "playcount"
)
) | [
"def",
"get_playcount",
"(",
"self",
")",
":",
"return",
"_number",
"(",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
",",
"\"playcount\"",
")",
")"
] | 29.125 | 0.0125 |
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal:
"""
Get conversion rate to use in exchange
"""
reverse_rate = False
if to_currency == BASE_CURRENCY:
# Fetch exchange rate for base currency and use 1 / rate for conversion
rate_currency = from_currency
... | [
"def",
"get_conversion_rate",
"(",
"from_currency",
":",
"str",
",",
"to_currency",
":",
"str",
")",
"->",
"Decimal",
":",
"reverse_rate",
"=",
"False",
"if",
"to_currency",
"==",
"BASE_CURRENCY",
":",
"# Fetch exchange rate for base currency and use 1 / rate for conversi... | 30.333333 | 0.001776 |
def _weight_generator(self, reviewers):
"""Compute a weight function for the given reviewers.
Args:
reviewers: a set of reviewers to compute weight function.
Returns:
a function computing a weight for a reviewer.
"""
scores = [r.anomalous_score for r in revi... | [
"def",
"_weight_generator",
"(",
"self",
",",
"reviewers",
")",
":",
"scores",
"=",
"[",
"r",
".",
"anomalous_score",
"for",
"r",
"in",
"reviewers",
"]",
"mu",
"=",
"np",
".",
"average",
"(",
"scores",
")",
"sigma",
"=",
"np",
".",
"std",
"(",
"score... | 30.470588 | 0.001871 |
def _fit_orbit_mlogl(new_vxvv,vxvv,vxvv_err,pot,radec,lb,
customsky,lb_to_customsky,pmllpmbb_to_customsky,
tmockAA,
ro,vo,obs):
"""The log likelihood for fitting an orbit"""
#Use this _parse_args routine, which does forward and backward integration
... | [
"def",
"_fit_orbit_mlogl",
"(",
"new_vxvv",
",",
"vxvv",
",",
"vxvv_err",
",",
"pot",
",",
"radec",
",",
"lb",
",",
"customsky",
",",
"lb_to_customsky",
",",
"pmllpmbb_to_customsky",
",",
"tmockAA",
",",
"ro",
",",
"vo",
",",
"obs",
")",
":",
"#Use this _p... | 53.846154 | 0.023615 |
def get_actor(self, username, email):
"""
Get actor for the statement.
"""
return Agent(
name=username,
mbox='mailto:{email}'.format(email=email),
) | [
"def",
"get_actor",
"(",
"self",
",",
"username",
",",
"email",
")",
":",
"return",
"Agent",
"(",
"name",
"=",
"username",
",",
"mbox",
"=",
"'mailto:{email}'",
".",
"format",
"(",
"email",
"=",
"email",
")",
",",
")"
] | 25.625 | 0.009434 |
def get_group_index_sorter(group_index, ngroups):
"""
algos.groupsort_indexer implements `counting sort` and it is at least
O(ngroups), where
ngroups = prod(shape)
shape = map(len, keys)
that is, linear in the number of combinations (cartesian product) of unique
values of groupby key... | [
"def",
"get_group_index_sorter",
"(",
"group_index",
",",
"ngroups",
")",
":",
"count",
"=",
"len",
"(",
"group_index",
")",
"alpha",
"=",
"0.0",
"# taking complexities literally; there may be",
"beta",
"=",
"1.0",
"# some room for fine-tuning these parameters",
"do_group... | 46.12 | 0.00085 |
def _bashcomplete(cmd, prog_name, complete_var=None):
"""Internal handler for the bash completion support."""
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
fr... | [
"def",
"_bashcomplete",
"(",
"cmd",
",",
"prog_name",
",",
"complete_var",
"=",
"None",
")",
":",
"if",
"complete_var",
"is",
"None",
":",
"complete_var",
"=",
"'_%s_COMPLETE'",
"%",
"(",
"prog_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
"."... | 39.454545 | 0.002252 |
def unit_clause_assign(clause, model):
"""Return a single variable/value pair that makes clause true in
the model, if possible.
>>> unit_clause_assign(A|B|C, {A:True})
(None, None)
>>> unit_clause_assign(B|~C, {A:True})
(None, None)
>>> unit_clause_assign(~A|~B, {A:True})
(B, False)
... | [
"def",
"unit_clause_assign",
"(",
"clause",
",",
"model",
")",
":",
"P",
",",
"value",
"=",
"None",
",",
"None",
"for",
"literal",
"in",
"disjuncts",
"(",
"clause",
")",
":",
"sym",
",",
"positive",
"=",
"inspect_literal",
"(",
"literal",
")",
"if",
"s... | 32.857143 | 0.001408 |
def at(*args, **kwargs): # pylint: disable=C0103
'''
Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' ... | [
"def",
"at",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"# check args",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"return",
"{",
"'jobs'",
":",
"[",
"]",
"}",
"# build job",
"if",
"'tag'",
"in",
"kwargs",
":",... | 28.428571 | 0.00081 |
def add_warning (self, s, tag=None):
"""
Add a warning string.
"""
item = (tag, s)
if item not in self.warnings and \
tag not in self.aggregate.config["ignorewarnings"]:
self.warnings.append(item) | [
"def",
"add_warning",
"(",
"self",
",",
"s",
",",
"tag",
"=",
"None",
")",
":",
"item",
"=",
"(",
"tag",
",",
"s",
")",
"if",
"item",
"not",
"in",
"self",
".",
"warnings",
"and",
"tag",
"not",
"in",
"self",
".",
"aggregate",
".",
"config",
"[",
... | 31.5 | 0.011583 |
def login(method):
"""Require user to login."""
def wrapper(*args, **kwargs):
crawler = args[0].crawler # args[0] is a NetEase object
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
... | [
"def",
"login",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"crawler",
"=",
"args",
"[",
"0",
"]",
".",
"crawler",
"# args[0] is a NetEase object",
"try",
":",
"if",
"os",
".",
"path",
".",
"isfile"... | 34.2 | 0.001138 |
def valid_starter_settings(self):
'''check starter settings'''
if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8:
print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan)
return False
if self.gasheli_settings.starter_... | [
"def",
"valid_starter_settings",
"(",
"self",
")",
":",
"if",
"self",
".",
"gasheli_settings",
".",
"ignition_chan",
"<=",
"0",
"or",
"self",
".",
"gasheli_settings",
".",
"ignition_chan",
">",
"8",
":",
"print",
"(",
"\"Invalid ignition channel %d\"",
"%",
"sel... | 55 | 0.011928 |
def get_indented_block(prefix_lines):
"""Returns an integer.
The return value is the number of lines that belong to block begun
on the first line.
Parameters
----------
prefix_lines : list of basestring pairs
Each pair corresponds to a line of SHPAML source code. The
first e... | [
"def",
"get_indented_block",
"(",
"prefix_lines",
")",
":",
"prefix",
",",
"line",
"=",
"prefix_lines",
"[",
"0",
"]",
"len_prefix",
"=",
"len",
"(",
"prefix",
")",
"# Find the first nonempty line with len(prefix) <= len(prefix)",
"i",
"=",
"1",
"while",
"i",
"<",... | 27.966667 | 0.001152 |
def get_interface_detail_output_interface_actual_line_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "outp... | [
"def",
"get_interface_detail_output_interface_actual_line_speed",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",
... | 50.764706 | 0.002275 |
def cmd2list(cmd):
''' Executes a command through the operating system and returns the output
as a list, or on error a string with the standard error.
EXAMPLE:
>>> from subprocess import Popen, PIPE
>>> CMDout2array('ls -l')
'''
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
stdout, ... | [
"def",
"cmd2list",
"(",
"cmd",
")",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"shell",
"=",
"True",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"re... | 34.692308 | 0.019438 |
def calcRapRperi(self,*args,**kwargs):
"""
NAME:
calcRapRperi
PURPOSE:
calculate the apocenter and pericenter radii
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
... | [
"def",
"calcRapRperi",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#Set up the actionAngleAxi object",
"if",
"isinstance",
"(",
"self",
".",
"_pot",
",",
"list",
")",
":",
"thispot",
"=",
"[",
"p",
".",
"toPlanar",
"(",
")",
"for... | 36.444444 | 0.016832 |
def entries(self):
"""Returns a list of all entries"""
def add(x, y):
return x + y
try:
return reduce(add, list(self.cache.values()))
except:
return [] | [
"def",
"entries",
"(",
"self",
")",
":",
"def",
"add",
"(",
"x",
",",
"y",
")",
":",
"return",
"x",
"+",
"y",
"try",
":",
"return",
"reduce",
"(",
"add",
",",
"list",
"(",
"self",
".",
"cache",
".",
"values",
"(",
")",
")",
")",
"except",
":"... | 26.5 | 0.013699 |
def transcribe(self, text, punctuation=True):
"""
Parameters:
:param text: str: The text to be transcribed
:param punctuation: bool: Retain punctuation
This module attempts to reconstruct the approximate phonology
of Old English.
The algorithm first trie... | [
"def",
"transcribe",
"(",
"self",
",",
"text",
",",
"punctuation",
"=",
"True",
")",
":",
"if",
"not",
"punctuation",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"[\\.\\\";\\,\\:\\[\\]\\(\\)!&?‘]\", ",
"\"",
", ",
"t",
"xt)",
"",
"text",
"=",
"text",
"."... | 38.381818 | 0.002309 |
def renamenodes(idf, fieldtype):
"""rename all the changed nodes"""
renameds = []
for key in idf.model.dtls:
for idfobject in idf.idfobjects[key]:
for fieldvalue in idfobject.obj:
if type(fieldvalue) is list:
if fieldvalue not in renameds:
... | [
"def",
"renamenodes",
"(",
"idf",
",",
"fieldtype",
")",
":",
"renameds",
"=",
"[",
"]",
"for",
"key",
"in",
"idf",
".",
"model",
".",
"dtls",
":",
"for",
"idfobject",
"in",
"idf",
".",
"idfobjects",
"[",
"key",
"]",
":",
"for",
"fieldvalue",
"in",
... | 42.692308 | 0.000881 |
def _get_config_type(cla55: type) -> Optional[str]:
"""
Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it.
"""
# Special handling for pytorch RNN types:
if cla55 == torch.nn.RNN:
return "rnn"
elif cla... | [
"def",
"_get_config_type",
"(",
"cla55",
":",
"type",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"# Special handling for pytorch RNN types:",
"if",
"cla55",
"==",
"torch",
".",
"nn",
".",
"RNN",
":",
"return",
"\"rnn\"",
"elif",
"cla55",
"==",
"torch",
"."... | 31.730769 | 0.001176 |
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
"[Fig. 4.8]"
for i in range(ngen):
new_population = []
for i in len(population):
fitnesses = map(fitness_fn, population)
p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
chi... | [
"def",
"genetic_algorithm",
"(",
"population",
",",
"fitness_fn",
",",
"ngen",
"=",
"1000",
",",
"pmut",
"=",
"0.1",
")",
":",
"for",
"i",
"in",
"range",
"(",
"ngen",
")",
":",
"new_population",
"=",
"[",
"]",
"for",
"i",
"in",
"len",
"(",
"populatio... | 39.846154 | 0.001887 |
def run_experiment(self, qasm, backend='simulator', shots=1, name=None,
seed=None, timeout=60, access_token=None, user_id=None):
"""
Execute an experiment
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
s... | [
"def",
"run_experiment",
"(",
"self",
",",
"qasm",
",",
"backend",
"=",
"'simulator'",
",",
"shots",
"=",
"1",
",",
"name",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"timeout",
"=",
"60",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None... | 44.650602 | 0.000792 |
def _get_block_result(chars_a, chars_b):
"""Get the first block from two character lists and compare
If character list ``a`` begins with a digit, the :any:`_pop_digit`
function is called on both lists to get blocks of all consecutive
digits at the start of each list. If the length of the block
retu... | [
"def",
"_get_block_result",
"(",
"chars_a",
",",
"chars_b",
")",
":",
"logger",
".",
"debug",
"(",
"'_get_block_result(%s, %s)'",
",",
"chars_a",
",",
"chars_b",
")",
"first_is_digit",
"=",
"chars_a",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"pop_func",
"=",... | 45.885714 | 0.00061 |
def _execute(self, line):
"""
Evaluate the line and print the result.
"""
output = self.app.output
# WORKAROUND: Due to a bug in Jedi, the current directory is removed
# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
if '' not in sys.path:
... | [
"def",
"_execute",
"(",
"self",
",",
"line",
")",
":",
"output",
"=",
"self",
".",
"app",
".",
"output",
"# WORKAROUND: Due to a bug in Jedi, the current directory is removed",
"# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148",
"if",
"''",
"not",
"in",
... | 41.457143 | 0.001346 |
def _process_sample (self, ap1, ap2, ap3, triple, tflags):
"""We have computed one independent phase closure triple in one timeslot.
"""
# Frequency-resolved:
np.divide (triple, np.abs (triple), triple)
phase = np.angle (triple)
self.ap_spec_stats_by_ddid[self.cur_ddid]... | [
"def",
"_process_sample",
"(",
"self",
",",
"ap1",
",",
"ap2",
",",
"ap3",
",",
"triple",
",",
"tflags",
")",
":",
"# Frequency-resolved:",
"np",
".",
"divide",
"(",
"triple",
",",
"np",
".",
"abs",
"(",
"triple",
")",
",",
"triple",
")",
"phase",
"=... | 47.642857 | 0.021308 |
def patched(module_name):
"""import and return a named module with patches applied locally only
this function returns a module after importing it in such as way that it
will operate cooperatively, but not overriding the module globally.
>>> green_httplib = patched("httplib")
>>> # using green_http... | [
"def",
"patched",
"(",
"module_name",
")",
":",
"if",
"module_name",
"in",
"_patchers",
":",
"return",
"_patched_copy",
"(",
"module_name",
",",
"_patchers",
"[",
"module_name",
"]",
")",
"# grab the unpatched version of the module for posterity",
"old_module",
"=",
"... | 36.553191 | 0.000567 |
def convert(from_currency, to_currency, from_currency_price=1):
""" convert from from_currency to to_currency using cached info """
get_cache()
from_currency, to_currency = validate_currency(from_currency, to_currency)
update_cache(from_currency, to_currency)
return ccache[from_currency][to_currency]['value'] * fr... | [
"def",
"convert",
"(",
"from_currency",
",",
"to_currency",
",",
"from_currency_price",
"=",
"1",
")",
":",
"get_cache",
"(",
")",
"from_currency",
",",
"to_currency",
"=",
"validate_currency",
"(",
"from_currency",
",",
"to_currency",
")",
"update_cache",
"(",
... | 55.333333 | 0.017804 |
def extract_docs():
"""
Parses the nano.rpc.Client for methods that have a __doc_meta__ attribute
and saves generated docs
"""
methods = []
def _key(entry):
return
sorted_entries = sorted(Client.__dict__.items(), key=lambda x: x[0])
tree = {}
meta_key = '__doc_meta__'
... | [
"def",
"extract_docs",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"def",
"_key",
"(",
"entry",
")",
":",
"return",
"sorted_entries",
"=",
"sorted",
"(",
"Client",
".",
"__dict__",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",... | 28.369048 | 0.000811 |
def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
"""
Find the indices of a set of angles into a set of pixels
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels
... | [
"def",
"index_lonlat_in_pixels",
"(",
"lon",
",",
"lat",
",",
"pixels",
",",
"nside",
",",
"sort",
"=",
"False",
",",
"outside",
"=",
"-",
"1",
")",
":",
"pix",
"=",
"ang2pix",
"(",
"nside",
",",
"lon",
",",
"lat",
")",
"return",
"index_pix_in_pixels",... | 25 | 0.028916 |
def _sendPostDict(post_dict):
"""
Send `post_dict` to the :attr:`.ALEPH_EXPORT_URL`.
Args:
post_dict (dict): dictionary from :class:`PostData.get_POST_data()`
Returns:
str: Reponse from webform.
"""
downer = Downloader()
downer.headers["Referer"] = settings.EDEPOSIT_EXPORT_... | [
"def",
"_sendPostDict",
"(",
"post_dict",
")",
":",
"downer",
"=",
"Downloader",
"(",
")",
"downer",
".",
"headers",
"[",
"\"Referer\"",
"]",
"=",
"settings",
".",
"EDEPOSIT_EXPORT_REFERER",
"data",
"=",
"downer",
".",
"download",
"(",
"settings",
".",
"ALEP... | 30.956522 | 0.001362 |
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid... | [
"def",
"_gather_buffer_space",
"(",
")",
":",
"if",
"HAS_PSUTIL",
"and",
"psutil",
".",
"version_info",
">=",
"(",
"0",
",",
"6",
",",
"0",
")",
":",
"# Oh good, we have psutil. This will be quick.",
"total_mem",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
... | 37.8 | 0.00129 |
def identify(self):
"""Update client metadata on the server and negotiate features.
:returns: nsqd response data if there was feature negotiation,
otherwise ``None``
"""
self.send(nsq.identify({
# nsqd 0.2.28+
'client_id': self.client_id,
... | [
"def",
"identify",
"(",
"self",
")",
":",
"self",
".",
"send",
"(",
"nsq",
".",
"identify",
"(",
"{",
"# nsqd 0.2.28+",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'hostname'",
":",
"self",
".",
"hostname",
",",
"# nsqd 0.2.19+",
"'feature_negotiatio... | 28.553846 | 0.001042 |
def json2pattern(s):
"""
Convert JSON format to a query pattern.
Includes even mongo shell notation without quoted key names.
"""
# make valid JSON by wrapping field names in quotes
s, _ = re.subn(r'([{,])\s*([^,{\s\'"]+)\s*:', ' \\1 "\\2" : ', s)
# handle shell values that are not valid JS... | [
"def",
"json2pattern",
"(",
"s",
")",
":",
"# make valid JSON by wrapping field names in quotes",
"s",
",",
"_",
"=",
"re",
".",
"subn",
"(",
"r'([{,])\\s*([^,{\\s\\'\"]+)\\s*:'",
",",
"' \\\\1 \"\\\\2\" : '",
",",
"s",
")",
"# handle shell values that are not valid JSON",
... | 40.611111 | 0.001337 |
def normalize_path(path, filetype=None, has_filetype=True):
""" Convert dot-separated paths to directory paths
Allows non-python files to be placed in the PYTHONPATH and be referenced
using dot-notation instead of absolute or relative file-system paths.
If a text file, named test.txt was placed in a p... | [
"def",
"normalize_path",
"(",
"path",
",",
"filetype",
"=",
"None",
",",
"has_filetype",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"if",
"'.'",
"in",
"path",
"and",
"os",
".",
"path",
".",
... | 40.102041 | 0.000497 |
def uniqify(seq):
"""`Uniqify` a sequence, preserving order.
A plain-vanilla version of itertools' `unique_everseen`.
Example
-------
>>> s = list('zyxabccabxyz')
>>> uniqify(s)
['z', 'y', 'x', 'a', 'b', 'c'
Returns
-------
list
"""
if PY37:
#... | [
"def",
"uniqify",
"(",
"seq",
")",
":",
"if",
"PY37",
":",
"# Credit: Raymond Hettinger\r",
"return",
"list",
"(",
"dict",
".",
"fromkeys",
"(",
"seq",
")",
")",
"else",
":",
"# Credit: Dave Kirby\r",
"# https://www.peterbe.com/plog/uniqifiers-benchmark\r",
"seen",
... | 25.730769 | 0.001441 |
def mysql_aes_encrypt(val, key):
"""Mysql AES encrypt value with secret key.
:param val: Plain text value.
:param key: The AES key.
:returns: The encrypted AES value.
"""
assert isinstance(val, binary_type) or isinstance(val, text_type)
assert isinstance(key, binary_type) or isinstance(key,... | [
"def",
"mysql_aes_encrypt",
"(",
"val",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"binary_type",
")",
"or",
"isinstance",
"(",
"val",
",",
"text_type",
")",
"assert",
"isinstance",
"(",
"key",
",",
"binary_type",
")",
"or",
"isinstance... | 34.142857 | 0.002037 |
def count_annotations(self) -> int:
"""Count the number of annotations in the database."""
return self.session.query(Namespace).filter(Namespace.is_annotation).count() | [
"def",
"count_annotations",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Namespace",
")",
".",
"filter",
"(",
"Namespace",
".",
"is_annotation",
")",
".",
"count",
"(",
")"
] | 60.333333 | 0.016393 |
def restore_backup(path, backup_id):
'''
.. versionadded:: 0.17.0
Restore a previous version of a file that was backed up using Salt's
:ref:`file state backup <file-state-backups>` system.
path
The path on the minion to check for backups
backup_id
The numeric id for the backup ... | [
"def",
"restore_backup",
"(",
"path",
",",
"backup_id",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"# Note: This only supports minion backups, so this function will need to be",
"# modified if/when master backups are implemented.",
"ret",
... | 31.55 | 0.000512 |
def clear(self):
"""
Removes all pending Jobs from the queue and return them in a list. This
method does **no**t call #Job.cancel() on any of the jobs. If you want
that, use #cancel_all() or call it manually.
"""
with synchronized(self.__queue):
jobs = self.__queue.snapshot()
self._... | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"synchronized",
"(",
"self",
".",
"__queue",
")",
":",
"jobs",
"=",
"self",
".",
"__queue",
".",
"snapshot",
"(",
")",
"self",
".",
"__queue",
".",
"clear",
"(",
")",
"return",
"jobs"
] | 30.909091 | 0.008571 |
def add_piper(self, piper, xtra=None, create=True, branch=None):
"""
Adds a ``Piper`` instance to this ``Dagger``, but only if the ``Piper``
is not already there. Optionally creates a new ``Piper`` if the "piper"
argument is valid for the ``Piper`` constructor. Returns a ``tuple``
... | [
"def",
"add_piper",
"(",
"self",
",",
"piper",
",",
"xtra",
"=",
"None",
",",
"create",
"=",
"True",
",",
"branch",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'%s trying to add piper %s'",
"%",
"(",
"repr",
"(",
"self",
")",
",",
... | 51.6 | 0.008559 |
def dannots2dalignbed2dannotsagg(cfg):
"""
Aggregate annotations per query
step#8
:param cfg: configuration dict
"""
datatmpd=cfg['datatmpd']
daannotp=f'{datatmpd}/08_dannot.tsv'
cfg['daannotp']=daannotp
dannotsaggp=cfg['dannotsaggp']
logging.info(basename(daannotp))
if... | [
"def",
"dannots2dalignbed2dannotsagg",
"(",
"cfg",
")",
":",
"datatmpd",
"=",
"cfg",
"[",
"'datatmpd'",
"]",
"daannotp",
"=",
"f'{datatmpd}/08_dannot.tsv'",
"cfg",
"[",
"'daannotp'",
"]",
"=",
"daannotp",
"dannotsaggp",
"=",
"cfg",
"[",
"'dannotsaggp'",
"]",
"lo... | 41.901639 | 0.023318 |
def json_2_location(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Location object
"""
LOGGER.debug("Location.json_2_location")
return Location(locid=json_obj['loca... | [
"def",
"json_2_location",
"(",
"json_obj",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Location.json_2_location\"",
")",
"return",
"Location",
"(",
"locid",
"=",
"json_obj",
"[",
"'locationID'",
"]",
",",
"name",
"=",
"json_obj",
"[",
"'locationName'",
"]",
",",... | 52.947368 | 0.001953 |
def _is_colorbar_heuristic(obj):
"""Find out if the object is in fact a color bar.
"""
# TODO come up with something more accurate here
# Might help:
# TODO Are the colorbars exactly the l.collections.PolyCollection's?
try:
aspect = float(obj.get_aspect())
except ValueError:
... | [
"def",
"_is_colorbar_heuristic",
"(",
"obj",
")",
":",
"# TODO come up with something more accurate here",
"# Might help:",
"# TODO Are the colorbars exactly the l.collections.PolyCollection's?",
"try",
":",
"aspect",
"=",
"float",
"(",
"obj",
".",
"get_aspect",
"(",
")",
")"... | 33.833333 | 0.001198 |
def phrase_replace(self, replace_dict):
"""
Replace phrases with single token, mapping defined in replace_dict
"""
def r(tokens):
text = ' ' + ' '.join(tokens)
for k, v in replace_dict.items():
text = text.replace(... | [
"def",
"phrase_replace",
"(",
"self",
",",
"replace_dict",
")",
":",
"def",
"r",
"(",
"tokens",
")",
":",
"text",
"=",
"' '",
"+",
"' '",
".",
"join",
"(",
"tokens",
")",
"for",
"k",
",",
"v",
"in",
"replace_dict",
".",
"items",
"(",
")",
":",
"t... | 35 | 0.009281 |
def raster_to_shape(raster):
"""Take a raster and return a polygon representing the outer edge."""
left = raster.bounds.left
right = raster.bounds.right
top = raster.bounds.top
bottom = raster.bounds.bottom
top_left = (left, top)
top_right = (right, top)
bottom_left = (left, bottom)
... | [
"def",
"raster_to_shape",
"(",
"raster",
")",
":",
"left",
"=",
"raster",
".",
"bounds",
".",
"left",
"right",
"=",
"raster",
".",
"bounds",
".",
"right",
"top",
"=",
"raster",
".",
"bounds",
".",
"top",
"bottom",
"=",
"raster",
".",
"bounds",
".",
"... | 28.8 | 0.002242 |
def build_comparators(*values_or_types):
'''
All of the comparators that can be used for arguments.
'''
comparators = []
for item in values_or_types:
if isinstance(item, Comparator):
comparators.append(item)
elif isinstance(item, type):
# If you are passing ar... | [
"def",
"build_comparators",
"(",
"*",
"values_or_types",
")",
":",
"comparators",
"=",
"[",
"]",
"for",
"item",
"in",
"values_or_types",
":",
"if",
"isinstance",
"(",
"item",
",",
"Comparator",
")",
":",
"comparators",
".",
"append",
"(",
"item",
")",
"eli... | 34.2 | 0.001898 |
def visit(root: Node, visitor: Visitor, visitor_keys=None) -> Any:
"""Visit each node in an AST.
`visit()` will walk through an AST using a depth first traversal, calling the
visitor's enter methods at each node in the traversal, and calling the leave methods
after visiting that node and all of its chi... | [
"def",
"visit",
"(",
"root",
":",
"Node",
",",
"visitor",
":",
"Visitor",
",",
"visitor_keys",
"=",
"None",
")",
"->",
"Any",
":",
"if",
"not",
"isinstance",
"(",
"root",
",",
"Node",
")",
":",
"raise",
"TypeError",
"(",
"f\"Not an AST Node: {inspect(root)... | 33.175182 | 0.001923 |
def freeze(plugins_directory):
'''
Parameters
----------
plugins_directory : str
Path to MicroDrop user plugins directory.
Returns
-------
list
List of package strings corresponding to installed plugin versions.
'''
# Check existing version (if any).
package_vers... | [
"def",
"freeze",
"(",
"plugins_directory",
")",
":",
"# Check existing version (if any).",
"package_versions",
"=",
"[",
"]",
"for",
"plugin_path_i",
"in",
"plugins_directory",
".",
"dirs",
"(",
")",
":",
"try",
":",
"plugin_metadata",
"=",
"yaml",
".",
"load",
... | 32.8 | 0.00237 |
def recursive_input(input_label, type_class):
'''Recursive user input prompter with type checker
Args
----
type_class: type
name of python type (e.g. float, no parentheses)
Returns
-------
output: str
value entered by user converted to type `type_class`
Note
----
... | [
"def",
"recursive_input",
"(",
"input_label",
",",
"type_class",
")",
":",
"import",
"sys",
"type_str",
"=",
"str",
"(",
"type_class",
")",
".",
"split",
"(",
"\"'\"",
")",
"[",
"1",
"]",
"msg",
"=",
"'Enter {} (type `{}`): '",
".",
"format",
"(",
"input_l... | 24.842105 | 0.002039 |
def cross_lists(*sets):
"""Return the cross product of the arguments"""
wheels = [iter(_) for _ in sets]
digits = [next(it) for it in wheels]
while True:
yield digits[:]
for i in range(len(digits)-1, -1, -1):
try:
digits[i] = next(wheels[i])
br... | [
"def",
"cross_lists",
"(",
"*",
"sets",
")",
":",
"wheels",
"=",
"[",
"iter",
"(",
"_",
")",
"for",
"_",
"in",
"sets",
"]",
"digits",
"=",
"[",
"next",
"(",
"it",
")",
"for",
"it",
"in",
"wheels",
"]",
"while",
"True",
":",
"yield",
"digits",
"... | 30.733333 | 0.002105 |
def register(linter):
'''
Required method to auto register this checker
'''
linter.register_checker(ResourceLeakageChecker(linter))
linter.register_checker(BlacklistedImportsChecker(linter))
linter.register_checker(MovedTestCaseClassChecker(linter))
linter.register_checker(BlacklistedLoaderM... | [
"def",
"register",
"(",
"linter",
")",
":",
"linter",
".",
"register_checker",
"(",
"ResourceLeakageChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
"(",
"BlacklistedImportsChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
... | 44.888889 | 0.002427 |
def convert_old_commands(commands, annotate=True):
"""Converts old-style package commands into equivalent Rex code."""
from rez.config import config
from rez.utils.logging_ import print_debug
def _repl(s):
return s.replace('\\"', '"')
def _encode(s):
# this replaces all occurrances... | [
"def",
"convert_old_commands",
"(",
"commands",
",",
"annotate",
"=",
"True",
")",
":",
"from",
"rez",
".",
"config",
"import",
"config",
"from",
"rez",
".",
"utils",
".",
"logging_",
"import",
"print_debug",
"def",
"_repl",
"(",
"s",
")",
":",
"return",
... | 38.513274 | 0.000672 |
def generate_validator_constructor(ns, data_type):
"""
Given a Stone data type, returns a string that can be used to construct
the appropriate validation object in Python.
"""
dt, nullable_dt = unwrap_nullable(data_type)
if is_list_type(dt):
v = generate_func_call(
'bv.List',... | [
"def",
"generate_validator_constructor",
"(",
"ns",
",",
"data_type",
")",
":",
"dt",
",",
"nullable_dt",
"=",
"unwrap_nullable",
"(",
"data_type",
")",
"if",
"is_list_type",
"(",
"dt",
")",
":",
"v",
"=",
"generate_func_call",
"(",
"'bv.List'",
",",
"args",
... | 33.923077 | 0.000441 |
def cli(env, package_keyname, keyword):
"""List package presets.
.. Note::
Presets are set CPU / RAM / Disk allotments. You still need to specify required items.
Some packages do not have presets.
::
# List the presets for Bare Metal servers
slcli order preset-list BARE_ME... | [
"def",
"cli",
"(",
"env",
",",
"package_keyname",
",",
"keyword",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"_filter",
"=",
"{",
"}",
"if... | 28.548387 | 0.002186 |
def sysctl(
state, host, name, value,
persist=False, persist_file='/etc/sysctl.conf',
):
'''
Edit sysctl configuration.
+ name: name of the sysctl setting to ensure
+ value: the value or list of values the sysctl should be
+ persist: whether to write this sysctl to the config
+ persist_... | [
"def",
"sysctl",
"(",
"state",
",",
"host",
",",
"name",
",",
"value",
",",
"persist",
"=",
"False",
",",
"persist_file",
"=",
"'/etc/sysctl.conf'",
",",
")",
":",
"string_value",
"=",
"(",
"' '",
".",
"join",
"(",
"value",
")",
"if",
"isinstance",
"("... | 28.5 | 0.001131 |
def universal_transformer_depthwise_attention(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
"""universal_transformer with depth-wise attention.
It uses an attention me... | [
"def",
"universal_transformer_depthwise_attention",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
")",
":",
"_",
",",
"inputs",
",",
"memory",
"=",
"layer_inputs",
"all_states",
"=",
"memory",
"# add depth signal",
"if",
... | 31.464286 | 0.009356 |
def singletrial(num_trials, skipstep=1):
""" Single-trial cross-validation schema
Use one trial for training, all others for testing.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
only use every `skipstep` trial for training
Returns
-----... | [
"def",
"singletrial",
"(",
"num_trials",
",",
"skipstep",
"=",
"1",
")",
":",
"for",
"t",
"in",
"range",
"(",
"0",
",",
"num_trials",
",",
"skipstep",
")",
":",
"trainset",
"=",
"[",
"t",
"]",
"testset",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
... | 29.173913 | 0.001443 |
def parse_swag_config_options(config):
"""Ensures that options passed to the backend are valid."""
options = {}
for key, val in config.items():
if key.startswith('swag.backend.'):
options[key[12:]] = val
if key.startswith('swag.'):
options[key[5:]] = val
if optio... | [
"def",
"parse_swag_config_options",
"(",
"config",
")",
":",
"options",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"config",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'swag.backend.'",
")",
":",
"options",
"[",
"key",
"[",
... | 38.666667 | 0.001684 |
def standardised_euclidean(x, y, sigma=_mock_ones):
"""Euclidean distance standardised against a vector of standard
deviations per coordinate.
..math::
D(x, y) = \sqrt{\sum_i \frac{(x_i - y_i)**2}{v_i}}
"""
result = 0.0
for i in range(x.shape[0]):
result += ((x[i] - y[i]) ** 2) ... | [
"def",
"standardised_euclidean",
"(",
"x",
",",
"y",
",",
"sigma",
"=",
"_mock_ones",
")",
":",
"result",
"=",
"0.0",
"for",
"i",
"in",
"range",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
":",
"result",
"+=",
"(",
"(",
"x",
"[",
"i",
"]",
"-",... | 28.916667 | 0.00838 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.