text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def from_signature(klass, sig, recid, h, curve):
""" See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """
from ecdsa import util, numbertheory
import msqr
curveFp = curve.curve
G = curve.generator
order = G.order()
# extract r,s from signature
... | [
"def",
"from_signature",
"(",
"klass",
",",
"sig",
",",
"recid",
",",
"h",
",",
"curve",
")",
":",
"from",
"ecdsa",
"import",
"util",
",",
"numbertheory",
"import",
"msqr",
"curveFp",
"=",
"curve",
".",
"curve",
"G",
"=",
"curve",
".",
"generator",
"or... | 41.208333 | 11.916667 |
def make_view(robot):
"""
为一个 BaseRoBot 生成 Django view。
:param robot: 一个 BaseRoBot 实例。
:return: 一个标准的 Django view
"""
assert isinstance(robot, BaseRoBot),\
"RoBot should be an BaseRoBot instance."
@csrf_exempt
def werobot_view(request):
timestamp = request.GET.get("time... | [
"def",
"make_view",
"(",
"robot",
")",
":",
"assert",
"isinstance",
"(",
"robot",
",",
"BaseRoBot",
")",
",",
"\"RoBot should be an BaseRoBot instance.\"",
"@",
"csrf_exempt",
"def",
"werobot_view",
"(",
"request",
")",
":",
"timestamp",
"=",
"request",
".",
"GE... | 31.735294 | 13.088235 |
def _update_doc_in_index(self, index_writer, doc):
"""
Add/Update a document in the index
"""
all_labels = set(self.label_list)
doc_labels = set(doc.labels)
new_labels = doc_labels.difference(all_labels)
# can happen when we recreate the index from scratch
... | [
"def",
"_update_doc_in_index",
"(",
"self",
",",
"index_writer",
",",
"doc",
")",
":",
"all_labels",
"=",
"set",
"(",
"self",
".",
"label_list",
")",
"doc_labels",
"=",
"set",
"(",
"doc",
".",
"labels",
")",
"new_labels",
"=",
"doc_labels",
".",
"differenc... | 30.769231 | 14.307692 |
def report_pairs(data, cutoff=0, mateorientation=None,
pairsfile=None, insertsfile=None, rclip=1, ascii=False, bins=20,
distmode="ss", mpcutoff=1000):
"""
This subroutine is used by the pairs function in blast.py and cas.py.
Reports number of fragments and pairs as well as linked pairs
"... | [
"def",
"report_pairs",
"(",
"data",
",",
"cutoff",
"=",
"0",
",",
"mateorientation",
"=",
"None",
",",
"pairsfile",
"=",
"None",
",",
"insertsfile",
"=",
"None",
",",
"rclip",
"=",
"1",
",",
"ascii",
"=",
"False",
",",
"bins",
"=",
"20",
",",
"distmo... | 35.373913 | 20.782609 |
def parse_pip_file(path):
"""Parse pip requirements file."""
# requirement lines sorted by importance
# also collect other pip commands
rdev = dict()
rnormal = []
stuff = []
try:
with open(path) as f:
for line in f:
line = line.strip()
# ... | [
"def",
"parse_pip_file",
"(",
"path",
")",
":",
"# requirement lines sorted by importance",
"# also collect other pip commands",
"rdev",
"=",
"dict",
"(",
")",
"rnormal",
"=",
"[",
"]",
"stuff",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"path",
")",
"as"... | 33.302326 | 17.348837 |
def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
t... | [
"def",
"rm_files_in_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"except",
"PermissionError",
":",
"os",
".",
"chmod",
"(",
"f",
",",
"0o777",
")",
"tr... | 24.9375 | 15.3125 |
def add_user(self, workspace, params={}, **options):
"""The user can be referenced by their globally unique user ID or their email address.
Returns the full user record for the invited user.
Parameters
----------
workspace : {Id} The workspace or organization to invite the user... | [
"def",
"add_user",
"(",
"self",
",",
"workspace",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/workspaces/%s/addUser\"",
"%",
"(",
"workspace",
")",
"return",
"self",
".",
"client",
".",
"post",
"(",
"path",
",",
... | 50.214286 | 20.428571 |
def _cleanup_tempdir(tempdir):
"""Clean up temp directory ignoring ENOENT errors."""
try:
shutil.rmtree(tempdir)
except OSError as err:
if err.errno != errno.ENOENT:
raise | [
"def",
"_cleanup_tempdir",
"(",
"tempdir",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"tempdir",
")",
"except",
"OSError",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] | 29.285714 | 13.142857 |
def resolve_extensions(bot: commands.Bot, name: str) -> list:
"""
Tries to resolve extension queries into a list of extension names.
"""
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
pa... | [
"def",
"resolve_extensions",
"(",
"bot",
":",
"commands",
".",
"Bot",
",",
"name",
":",
"str",
")",
"->",
"list",
":",
"if",
"name",
".",
"endswith",
"(",
"'.*'",
")",
":",
"module_parts",
"=",
"name",
"[",
":",
"-",
"2",
"]",
".",
"split",
"(",
... | 24.611111 | 18.833333 |
def _process_infohash_list(infohash_list):
"""
Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash.
"""
if isinstance(infohash_list, list):
data = {'hashes': '|'.join([h.lower() for h in infohash_list])}
... | [
"def",
"_process_infohash_list",
"(",
"infohash_list",
")",
":",
"if",
"isinstance",
"(",
"infohash_list",
",",
"list",
")",
":",
"data",
"=",
"{",
"'hashes'",
":",
"'|'",
".",
"join",
"(",
"[",
"h",
".",
"lower",
"(",
")",
"for",
"h",
"in",
"infohash_... | 35.636364 | 16.909091 |
def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
... | [
"def",
"PopupGetFolder",
"(",
"message",
",",
"default_path",
"=",
"''",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"Non... | 37.730769 | 28.576923 |
def metadata_remove_all_endpoints(self):
""" Metadata: remove all endpoints from all groups """
metadata = load_mpe_service_metadata(self.args.metadata_file)
metadata.remove_all_endpoints()
metadata.save_pretty(self.args.metadata_file) | [
"def",
"metadata_remove_all_endpoints",
"(",
"self",
")",
":",
"metadata",
"=",
"load_mpe_service_metadata",
"(",
"self",
".",
"args",
".",
"metadata_file",
")",
"metadata",
".",
"remove_all_endpoints",
"(",
")",
"metadata",
".",
"save_pretty",
"(",
"self",
".",
... | 52.6 | 8.6 |
def random_id(size=8, chars=string.ascii_letters + string.digits):
"""Generates a random string of given size from the given chars.
@param size: The size of the random string.
@param chars: Constituent pool of characters to draw random characters from.
@type size: number
@type chars: string
@rtype: str... | [
"def",
"random_id",
"(",
"size",
"=",
"8",
",",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"_",
"in",
"range",
"(",
"siz... | 38.636364 | 17.272727 |
def _set_igmps_prefix_list(self, v, load=False):
"""
Setter method for igmps_prefix_list, mapped from YANG variable /igmp_snooping/ip/igmp/ssm_map/igmps_prefix_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmps_prefix_list is considered as a private
me... | [
"def",
"_set_igmps_prefix_list",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",... | 122.090909 | 59 |
def make_path(phase) -> str:
"""
Create the path to the folder at which the metadata and optimizer pickle should be saved
"""
return "{}/{}{}{}".format(conf.instance.output_path, phase.phase_path, phase.phase_name, phase.phase_tag) | [
"def",
"make_path",
"(",
"phase",
")",
"->",
"str",
":",
"return",
"\"{}/{}{}{}\"",
".",
"format",
"(",
"conf",
".",
"instance",
".",
"output_path",
",",
"phase",
".",
"phase_path",
",",
"phase",
".",
"phase_name",
",",
"phase",
".",
"phase_tag",
")"
] | 48.6 | 26.6 |
def when_i_send_the_request(context, method):
"""
:type method: str
:type context: behave.runner.Context
"""
data = context.apiRequestData
context.apiRequest = context.apiClient.generic(
method,
data['url'],
data=json.dumps(data['params']),
content_type=... | [
"def",
"when_i_send_the_request",
"(",
"context",
",",
"method",
")",
":",
"data",
"=",
"context",
".",
"apiRequestData",
"context",
".",
"apiRequest",
"=",
"context",
".",
"apiClient",
".",
"generic",
"(",
"method",
",",
"data",
"[",
"'url'",
"]",
",",
"d... | 28.307692 | 10.307692 |
def online(cls, payload, ip, req_sig):
"""
Receive and analyze request from payment service with information on payment status change.
"""
from getpaid.models import Payment
params = json.loads(payload)
order_data = params.get('order', {})
pos_id = order_data.ge... | [
"def",
"online",
"(",
"cls",
",",
"payload",
",",
"ip",
",",
"req_sig",
")",
":",
"from",
"getpaid",
".",
"models",
"import",
"Payment",
"params",
"=",
"json",
".",
"loads",
"(",
"payload",
")",
"order_data",
"=",
"params",
".",
"get",
"(",
"'order'",
... | 41.76087 | 21.891304 |
def multiplicative_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
""" Computes multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [... | [
"def",
"multiplicative_self_attention",
"(",
"units",
",",
"n_hidden",
"=",
"None",
",",
"n_output_features",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"n_input_features",
"=",
"units",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
... | 55.296296 | 30.074074 |
def split_extension(file_name, special=['tar.bz2', 'tar.gz']):
"""
Find the file extension of a file name, including support for
special case multipart file extensions (like .tar.gz)
Parameters
----------
file_name: str, file name
special: list of str, multipart extensions
... | [
"def",
"split_extension",
"(",
"file_name",
",",
"special",
"=",
"[",
"'tar.bz2'",
",",
"'tar.gz'",
"]",
")",
":",
"file_name",
"=",
"str",
"(",
"file_name",
")",
"if",
"file_name",
".",
"endswith",
"(",
"tuple",
"(",
"special",
")",
")",
":",
"for",
"... | 28.608696 | 16.173913 |
def search_url(self, var=DEFAULT_SEARCH_ENV, default=NOTSET, engine=None):
"""Returns a config dictionary, defaulting to SEARCH_URL.
:rtype: dict
"""
return self.search_url_config(self.url(var, default=default), engine=engine) | [
"def",
"search_url",
"(",
"self",
",",
"var",
"=",
"DEFAULT_SEARCH_ENV",
",",
"default",
"=",
"NOTSET",
",",
"engine",
"=",
"None",
")",
":",
"return",
"self",
".",
"search_url_config",
"(",
"self",
".",
"url",
"(",
"var",
",",
"default",
"=",
"default",... | 42.333333 | 23 |
def ping(allow_failure=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Test connection to Elasticsearch instance. This method does not fail if not explicitly specified.
allow_failure
Throw exception if ping fails
CLI example::
salt myminion elasticsearch.ping all... | [
"def",
"ping",
"(",
"allow_failure",
"=",
"False",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"except",
"CommandExecutionError",
"as",
"e",
":",
"if",
"allow_failure",
... | 26.714286 | 25.095238 |
def quick_marshal(*args, **kwargs):
"""In some case, one view functions may return different model in different situation.
Use `marshal_with_model` to handle this situation was tedious.
This function can simplify this process.
Usage:
quick_marshal(args_to_marshal_with_model)(db_instance_or_query)
... | [
"def",
"quick_marshal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"marshal_with_model",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"def",
"fn",
"(",
"value",
")",
":",
"return",
"value",
"return",
"fn"
] | 34.166667 | 16.75 |
def referencesGenerator(self, request):
"""
Returns a generator over the (reference, nextPageToken) pairs
defined by the specified request.
"""
referenceSet = self.getDataRepository().getReferenceSet(
request.reference_set_id)
results = []
for obj in r... | [
"def",
"referencesGenerator",
"(",
"self",
",",
"request",
")",
":",
"referenceSet",
"=",
"self",
".",
"getDataRepository",
"(",
")",
".",
"getReferenceSet",
"(",
"request",
".",
"reference_set_id",
")",
"results",
"=",
"[",
"]",
"for",
"obj",
"in",
"referen... | 39.631579 | 11.315789 |
def prompt(question, validator=None,
choices=None, default_key=NotImplemented,
normalizer=str.lower,
_stdin=None, _stdout=None):
"""
Prompt user for question, maybe choices, and get answer.
Arguments:
question
The question to prompt. It will only be prompted o... | [
"def",
"prompt",
"(",
"question",
",",
"validator",
"=",
"None",
",",
"choices",
"=",
"None",
",",
"default_key",
"=",
"NotImplemented",
",",
"normalizer",
"=",
"str",
".",
"lower",
",",
"_stdin",
"=",
"None",
",",
"_stdout",
"=",
"None",
")",
":",
"de... | 31.172414 | 18.735632 |
def fit_zyz(target_gate):
"""
Tensorflow 2.0 example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate.
"""
steps = 1000
dev = '/gpu:0' if bk.DEVICE == 'gpu' else '/cpu:0'
with tf.device(dev):
t = tf.Variable(tf.r... | [
"def",
"fit_zyz",
"(",
"target_gate",
")",
":",
"steps",
"=",
"1000",
"dev",
"=",
"'/gpu:0'",
"if",
"bk",
".",
"DEVICE",
"==",
"'gpu'",
"else",
"'/cpu:0'",
"with",
"tf",
".",
"device",
"(",
"dev",
")",
":",
"t",
"=",
"tf",
".",
"Variable",
"(",
"tf... | 26.242424 | 19.090909 |
def datetime_match(data, dts):
"""
matching of datetimes in time columns for data filtering
"""
dts = dts if islistable(dts) else [dts]
if any([not isinstance(i, datetime.datetime) for i in dts]):
error_msg = (
"`time` can only be filtered by datetimes"
)
raise Ty... | [
"def",
"datetime_match",
"(",
"data",
",",
"dts",
")",
":",
"dts",
"=",
"dts",
"if",
"islistable",
"(",
"dts",
")",
"else",
"[",
"dts",
"]",
"if",
"any",
"(",
"[",
"not",
"isinstance",
"(",
"i",
",",
"datetime",
".",
"datetime",
")",
"for",
"i",
... | 32.181818 | 12.909091 |
def apply_translation(self, translation):
"""
Translate the current mesh.
Parameters
----------
translation : (3,) float
Translation in XYZ
"""
translation = np.asanyarray(translation, dtype=np.float64)
if translation.shape != (3,):
... | [
"def",
"apply_translation",
"(",
"self",
",",
"translation",
")",
":",
"translation",
"=",
"np",
".",
"asanyarray",
"(",
"translation",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"translation",
".",
"shape",
"!=",
"(",
"3",
",",
")",
":",
"rai... | 28.1875 | 13.6875 |
def _hstr(hours, places=2):
"""Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan'
"""
if isnan(hours):
return 'nan'
sgn, h, m, s, etc = _sexagesimalize... | [
"def",
"_hstr",
"(",
"hours",
",",
"places",
"=",
"2",
")",
":",
"if",
"isnan",
"(",
"hours",
")",
":",
"return",
"'nan'",
"sgn",
",",
"h",
",",
"m",
",",
"s",
",",
"etc",
"=",
"_sexagesimalize_to_int",
"(",
"hours",
",",
"places",
")",
"sign",
"... | 27 | 18.5625 |
def get_port_channel_detail_output_lacp_aggr_member_sync(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_deta... | [
"def",
"get_port_channel_detail_output_lacp_aggr_member_sync",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_channel_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_channel_detail\"",
")",... | 43 | 13.5 |
def _to_fulldict(self):
"""
Write to dict including data frames. All sample dicts
are combined in save() to dump JSON output """
##
returndict = OrderedDict([
("name", self.name),
("barcode", self.barcode),
("files", self.files),
... | [
"def",
"_to_fulldict",
"(",
"self",
")",
":",
"## ",
"returndict",
"=",
"OrderedDict",
"(",
"[",
"(",
"\"name\"",
",",
"self",
".",
"name",
")",
",",
"(",
"\"barcode\"",
",",
"self",
".",
"barcode",
")",
",",
"(",
"\"files\"",
",",
"self",
".",
"file... | 33.363636 | 14.363636 |
def git_versions_from_vcs(tag_prefix, root, verbose=False):
"""Return a dictionary of values derived directly from the VCS. This is the
third attempt to find information by get_versions().
"""
# this runs 'git' from the root of the source tree. This only gets called
# if the git-archive 'subst' key... | [
"def",
"git_versions_from_vcs",
"(",
"tag_prefix",
",",
"root",
",",
"verbose",
"=",
"False",
")",
":",
"# this runs 'git' from the root of the source tree. This only gets called",
"# if the git-archive 'subst' keywords were *not* expanded, and",
"# _version.py hasn't already been rewrit... | 37.296703 | 18.989011 |
def getInstructions(self):
'''
The same as calling ``client.getInstructions(build.setID)``
:returns: A list of instructions.
:rtype: list
'''
self._instructions = self._client.getInstructions(self.setID)
return self._instructions | [
"def",
"getInstructions",
"(",
"self",
")",
":",
"self",
".",
"_instructions",
"=",
"self",
".",
"_client",
".",
"getInstructions",
"(",
"self",
".",
"setID",
")",
"return",
"self",
".",
"_instructions"
] | 27.8 | 23.6 |
def cached(f):
"""
Cache decorator for functions taking one or more arguments.
:param f: The function to be cached.
:return: The cached value.
"""
cache = f.cache = {}
@functools.wraps(f)
def decorator(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:... | [
"def",
"cached",
"(",
"f",
")",
":",
"cache",
"=",
"f",
".",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"str",
"(",
"args",
")",
... | 24.75 | 14.375 |
def get_parameters(self):
"""Return a list of parameters."""
parenthesis = self.tokens[-1]
for token in parenthesis.tokens:
if isinstance(token, IdentifierList):
return token.get_identifiers()
elif imt(token, i=(Function, Identifier), t=T.Literal):
... | [
"def",
"get_parameters",
"(",
"self",
")",
":",
"parenthesis",
"=",
"self",
".",
"tokens",
"[",
"-",
"1",
"]",
"for",
"token",
"in",
"parenthesis",
".",
"tokens",
":",
"if",
"isinstance",
"(",
"token",
",",
"IdentifierList",
")",
":",
"return",
"token",
... | 39.444444 | 10.111111 |
def _determine_rule_types(self, metamodel):
"""Determine textX rule/metaclass types"""
def _determine_rule_type(cls):
"""
Determine rule type (abstract, match, common) and inherited
classes.
"""
if cls in resolved_classes:
ret... | [
"def",
"_determine_rule_types",
"(",
"self",
",",
"metamodel",
")",
":",
"def",
"_determine_rule_type",
"(",
"cls",
")",
":",
"\"\"\"\n Determine rule type (abstract, match, common) and inherited\n classes.\n \"\"\"",
"if",
"cls",
"in",
"resolved_... | 43.463415 | 18.658537 |
def _proxy_connect(name, method_name, kwargs, econtext):
"""
Implements the target portion of Router._proxy_connect() by upgrading the
local context to a parent if it was not already, then calling back into
Router._connect() using the arguments passed to the parent's
Router.connect().
:returns:... | [
"def",
"_proxy_connect",
"(",
"name",
",",
"method_name",
",",
"kwargs",
",",
"econtext",
")",
":",
"upgrade_router",
"(",
"econtext",
")",
"try",
":",
"context",
"=",
"econtext",
".",
"router",
".",
"_connect",
"(",
"klass",
"=",
"stream_by_method_name",
"(... | 29.861111 | 20.416667 |
def _atexit__register(self, func, *targs, **kwargs):
"""
Intercept :func:`atexit.register` calls, diverting any to
:func:`shutil.rmtree` into a private list.
"""
if func == shutil.rmtree:
self.deferred.append((func, targs, kwargs))
return
self.ori... | [
"def",
"_atexit__register",
"(",
"self",
",",
"func",
",",
"*",
"targs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"func",
"==",
"shutil",
".",
"rmtree",
":",
"self",
".",
"deferred",
".",
"append",
"(",
"(",
"func",
",",
"targs",
",",
"kwargs",
")"... | 35.2 | 14.8 |
async def call_command(bot: NoneBot, ctx: Context_T,
name: Union[str, CommandName_T], *,
current_arg: str = '',
args: Optional[CommandArgs_T] = None,
check_perm: bool = True,
disable_interaction: bool = Fa... | [
"async",
"def",
"call_command",
"(",
"bot",
":",
"NoneBot",
",",
"ctx",
":",
"Context_T",
",",
"name",
":",
"Union",
"[",
"str",
",",
"CommandName_T",
"]",
",",
"*",
",",
"current_arg",
":",
"str",
"=",
"''",
",",
"args",
":",
"Optional",
"[",
"Comma... | 43.848485 | 20.212121 |
def remote_set(self, url, name='origin'):
"""Set remote with name and URL like git remote add.
:param url: defines the remote URL
:type url: str
:param name: defines the remote name.
:type name: str
"""
url = self.chomp_protocol(url)
if self.remote_get(... | [
"def",
"remote_set",
"(",
"self",
",",
"url",
",",
"name",
"=",
"'origin'",
")",
":",
"url",
"=",
"self",
".",
"chomp_protocol",
"(",
"url",
")",
"if",
"self",
".",
"remote_get",
"(",
"name",
")",
":",
"self",
".",
"run",
"(",
"[",
"'remote'",
",",... | 28.125 | 14.1875 |
def _getW(self):
"""
Gets a value of `w` for use in generating a pattern.
"""
w = self._w
if type(w) is list:
return w[self._random.getUInt32(len(w))]
else:
return w | [
"def",
"_getW",
"(",
"self",
")",
":",
"w",
"=",
"self",
".",
"_w",
"if",
"type",
"(",
"w",
")",
"is",
"list",
":",
"return",
"w",
"[",
"self",
".",
"_random",
".",
"getUInt32",
"(",
"len",
"(",
"w",
")",
")",
"]",
"else",
":",
"return",
"w"
... | 19.3 | 18.5 |
def search_code(self, query, sort=github.GithubObject.NotSet, order=github.GithubObject.NotSet, highlight=False, **qualifiers):
"""
:calls: `GET /search/code <http://developer.github.com/v3/search>`_
:param query: string
:param sort: string ('indexed')
:param order: string ('asc'... | [
"def",
"search_code",
"(",
"self",
",",
"query",
",",
"sort",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"order",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"highlight",
"=",
"False",
",",
"*",
"*",
"qualifiers",
")",
":",
"as... | 42.868421 | 21.236842 |
def query(self):
"""
Begin a fluent query
:return: A QueryBuilder instance
:rtype: QueryBuilder
"""
query = self._builder_class(
self,
self._query_grammar,
self._post_processor,
**self._builder_default_kwargs
)
... | [
"def",
"query",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"_builder_class",
"(",
"self",
",",
"self",
".",
"_query_grammar",
",",
"self",
".",
"_post_processor",
",",
"*",
"*",
"self",
".",
"_builder_default_kwargs",
")",
"return",
"query"
] | 21.533333 | 14.866667 |
def get_parser():
"""Get parser for mpu."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--version',
action='version'... | [
"def",
"get_parser",
"(",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
",",
"ArgumentDefaultsHelpFormatter",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
... | 47.166667 | 16.416667 |
def send_voice_message(self, user_id, media_id, kf_account=None):
"""
发送语音消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
... | [
"def",
"send_voice_message",
"(",
"self",
",",
"user_id",
",",
"media_id",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"voice\"",
",",
"\"voice\"",
":",
"{",
"\"media_id\"",
":",
"med... | 31.363636 | 18.545455 |
def cid(self):
"""The PubChem Compound Identifier (CID).
.. note::
When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an
automatically generated record may be returned that contains properties that have been calculated on the
... | [
"def",
"cid",
"(",
"self",
")",
":",
"if",
"'id'",
"in",
"self",
".",
"record",
"and",
"'id'",
"in",
"self",
".",
"record",
"[",
"'id'",
"]",
"and",
"'cid'",
"in",
"self",
".",
"record",
"[",
"'id'",
"]",
"[",
"'id'",
"]",
":",
"return",
"self",
... | 47.909091 | 33.181818 |
def parse_routing_info(cls, records):
""" Parse the records returned from a getServers call and
return a new RoutingTable instance.
"""
if len(records) != 1:
raise RoutingProtocolError("Expected exactly one record")
record = records[0]
routers = []
rea... | [
"def",
"parse_routing_info",
"(",
"cls",
",",
"records",
")",
":",
"if",
"len",
"(",
"records",
")",
"!=",
"1",
":",
"raise",
"RoutingProtocolError",
"(",
"\"Expected exactly one record\"",
")",
"record",
"=",
"records",
"[",
"0",
"]",
"routers",
"=",
"[",
... | 38.178571 | 11.607143 |
async def get_reply(self, message=None, *, timeout=None):
"""
Returns a coroutine that will resolve once a reply
(that is, a message being a reply) arrives. The
arguments are the same as those for `get_response`.
"""
return await self._get_message(
message, se... | [
"async",
"def",
"get_reply",
"(",
"self",
",",
"message",
"=",
"None",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"await",
"self",
".",
"_get_message",
"(",
"message",
",",
"self",
".",
"_reply_indices",
",",
"self",
".",
"_pending_replie... | 41.9 | 14.1 |
def parseEntity(filename):
"""parse an XML external entity out of context and build a
tree. [78] extParsedEnt ::= TextDecl? content This
correspond to a "Well Balanced" chunk """
ret = libxml2mod.xmlParseEntity(filename)
if ret is None:raise parserError('xmlParseEntity() failed')
return x... | [
"def",
"parseEntity",
"(",
"filename",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlParseEntity",
"(",
"filename",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlParseEntity() failed'",
")",
"return",
"xmlDoc",
"(",
"_obj",
"=",
"ret"... | 47 | 10.428571 |
def is_self(addr):
'''
check if this host is this addr
'''
ips = []
for i in netifaces.interfaces():
entry = netifaces.ifaddresses(i)
if netifaces.AF_INET in entry:
for ipv4 in entry[netifaces.AF_INET]:
if "addr" in ipv4:
ips.append(ipv4["addr"])
return addr in ips or addr ==... | [
"def",
"is_self",
"(",
"addr",
")",
":",
"ips",
"=",
"[",
"]",
"for",
"i",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"entry",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"i",
")",
"if",
"netifaces",
".",
"AF_INET",
"in",
"entry",
":",
"fo... | 27.416667 | 14.916667 |
def parse(self, stream):
"""Parses the keys and values from a config file."""
yaml = self._load_yaml()
try:
parsed_obj = yaml.safe_load(stream)
except Exception as e:
raise ConfigFileParserException("Couldn't parse config file: %s" % e)
if not isinstance... | [
"def",
"parse",
"(",
"self",
",",
"stream",
")",
":",
"yaml",
"=",
"self",
".",
"_load_yaml",
"(",
")",
"try",
":",
"parsed_obj",
"=",
"yaml",
".",
"safe_load",
"(",
"stream",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ConfigFileParserExceptio... | 37.347826 | 20.826087 |
def visit_global(self, node):
"""check names imported exists in the global scope"""
frame = node.frame()
if isinstance(frame, astroid.Module):
self.add_message("global-at-module-level", node=node)
return
module = frame.root()
default_message = True
... | [
"def",
"visit_global",
"(",
"self",
",",
"node",
")",
":",
"frame",
"=",
"node",
".",
"frame",
"(",
")",
"if",
"isinstance",
"(",
"frame",
",",
"astroid",
".",
"Module",
")",
":",
"self",
".",
"add_message",
"(",
"\"global-at-module-level\"",
",",
"node"... | 38.636364 | 17.386364 |
def getEditorBinary(self, cmdVersion=False):
"""
Determines the location of the UE4Editor binary
"""
return os.path.join(self.getEngineRoot(), 'Engine', 'Binaries', self.getPlatformIdentifier(), 'UE4Editor' + self._editorPathSuffix(cmdVersion)) | [
"def",
"getEditorBinary",
"(",
"self",
",",
"cmdVersion",
"=",
"False",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"getEngineRoot",
"(",
")",
",",
"'Engine'",
",",
"'Binaries'",
",",
"self",
".",
"getPlatformIdentifier",
"(",
"... | 49.6 | 23.6 |
def pageSizePicked( self, pageSize ):
"""
Updates when the user picks a page size.
:param pageSize | <str>
"""
try:
pageSize = int(self._pageSizeCombo.currentText())
except ValueError:
pageSize = 0
self.set... | [
"def",
"pageSizePicked",
"(",
"self",
",",
"pageSize",
")",
":",
"try",
":",
"pageSize",
"=",
"int",
"(",
"self",
".",
"_pageSizeCombo",
".",
"currentText",
"(",
")",
")",
"except",
"ValueError",
":",
"pageSize",
"=",
"0",
"self",
".",
"setPageSize",
"("... | 28.538462 | 12.384615 |
def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext='.png'):
"""
Iterating all icon dirs, try to find a file called like the node's
extension / mime subtype / mime type (in that order).
For instance, for an MP3 file ("audio/mpeg"), this would look for:
"mp3.png" / "au... | [
"def",
"find",
"(",
"file_node",
",",
"dirs",
"=",
"ICON_DIRS",
",",
"default_name",
"=",
"None",
",",
"file_ext",
"=",
"'.png'",
")",
":",
"names",
"=",
"[",
"]",
"for",
"attr_name",
"in",
"(",
"'extension'",
",",
"'mimetype'",
",",
"'mime_supertype'",
... | 43.823529 | 17.235294 |
def compute_volume(sizes, centers, normals):
"""
Compute the numerical volume of a convex mesh
:parameter array sizes: array of sizes of triangles
:parameter array centers: array of centers of triangles (x,y,z)
:parameter array normals: array of normals of triangles (will normalize if not already)
... | [
"def",
"compute_volume",
"(",
"sizes",
",",
"centers",
",",
"normals",
")",
":",
"# the volume of a slanted triangular cone is A_triangle * (r_vec dot norm_vec) / 3.",
"# TODO: implement normalizing normals into meshing routines (or at least have them supply normal_mags to the mesh)",
"# TOD... | 47 | 29.444444 |
def _format_variant(self, case_id, gemini_variant, individual_objs,
index=0, add_all_info=False):
"""Make a puzzle variant from a gemini variant
Args:
case_id (str): related case id
gemini_variant (GeminiQueryRow): The gemini variant
... | [
"def",
"_format_variant",
"(",
"self",
",",
"case_id",
",",
"gemini_variant",
",",
"individual_objs",
",",
"index",
"=",
"0",
",",
"add_all_info",
"=",
"False",
")",
":",
"chrom",
"=",
"gemini_variant",
"[",
"'chrom'",
"]",
"if",
"chrom",
".",
"startswith",
... | 35.517241 | 16.54023 |
def reset_and_halt(self, reset_type=None):
"""
perform a reset and stop the core on the reset handler
"""
delegateResult = self.call_delegate('set_reset_catch', core=self, reset_type=reset_type)
# halt the target
if not delegateResult:
self.h... | [
"def",
"reset_and_halt",
"(",
"self",
",",
"reset_type",
"=",
"None",
")",
":",
"delegateResult",
"=",
"self",
".",
"call_delegate",
"(",
"'set_reset_catch'",
",",
"core",
"=",
"self",
",",
"reset_type",
"=",
"reset_type",
")",
"# halt the target",
"if",
"not"... | 33.594595 | 20.621622 |
def write_screen(self, font, color, screen_pos, text, align="left",
valign="top"):
"""Write to the screen in font.size relative coordinates."""
pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize()
text_surf = font.render(str(text), True, color)
rect = text_surf.... | [
"def",
"write_screen",
"(",
"self",
",",
"font",
",",
"color",
",",
"screen_pos",
",",
"text",
",",
"align",
"=",
"\"left\"",
",",
"valign",
"=",
"\"top\"",
")",
":",
"pos",
"=",
"point",
".",
"Point",
"(",
"*",
"screen_pos",
")",
"*",
"point",
".",
... | 39.8 | 16.866667 |
def bend_rounded_Crane(Di, angle, rc=None, bend_diameters=None):
r'''Calculates the loss coefficient for any rounded bend in a pipe
according to the Crane TP 410M [1]_ method. This method effectively uses
an interpolation from tabulated values in [1]_ for friction factor
multipliers vs. curvature radius... | [
"def",
"bend_rounded_Crane",
"(",
"Di",
",",
"angle",
",",
"rc",
"=",
"None",
",",
"bend_diameters",
"=",
"None",
")",
":",
"if",
"not",
"rc",
":",
"if",
"bend_diameters",
"is",
"None",
":",
"bend_diameters",
"=",
"5.0",
"rc",
"=",
"Di",
"*",
"bend_dia... | 29.491803 | 24.016393 |
def create(cls, data=None, api_key=None, endpoint=None, add_headers=None,
data_key=None, response_data_key=None, method='POST', **kwargs):
"""
Create an instance of the Entity model by calling to the API endpoint.
This ensures that server knows about the creation before returning... | [
"def",
"create",
"(",
"cls",
",",
"data",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"add_headers",
"=",
"None",
",",
"data_key",
"=",
"None",
",",
"response_data_key",
"=",
"None",
",",
"method",
"=",
"'POST'",
",",
... | 37.606061 | 22.393939 |
def set_id(self, identifier):
"""Set the id of the given reftrack
This will set the id on the refobject
:param identifier: the identifier number
:type identifier: int
:returns: None
:rtype: None
:raises: None
"""
self._id = identifier
ref... | [
"def",
"set_id",
"(",
"self",
",",
"identifier",
")",
":",
"self",
".",
"_id",
"=",
"identifier",
"refobj",
"=",
"self",
".",
"get_refobj",
"(",
")",
"if",
"refobj",
":",
"self",
".",
"get_refobjinter",
"(",
")",
".",
"set_id",
"(",
"refobj",
",",
"i... | 27.333333 | 15.466667 |
def login(self, username: str, password: str, course: int) -> requests.Response:
"""
登入課程
"""
try:
# 操作所需資訊
payload = {
'name': username,
'passwd': password,
'rdoCourse': course
}
# 回傳嘗試登入的回應
... | [
"def",
"login",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"course",
":",
"int",
")",
"->",
"requests",
".",
"Response",
":",
"try",
":",
"# 操作所需資訊",
"payload",
"=",
"{",
"'name'",
":",
"username",
",",
"'passwd'",
":... | 28.941176 | 17.294118 |
def get_table(self):
'''
Hook point for overriding how the CounterPool transforms table_name
into a boto DynamoDB Table object.
'''
if hasattr(self, '_table'):
table = self._table
else:
try:
table = self.conn.get_table(self.get_tabl... | [
"def",
"get_table",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_table'",
")",
":",
"table",
"=",
"self",
".",
"_table",
"else",
":",
"try",
":",
"table",
"=",
"self",
".",
"conn",
".",
"get_table",
"(",
"self",
".",
"get_table_name",... | 29.578947 | 19.684211 |
def path_size(p: tcod.path.AStar) -> int:
"""Return the current length of the computed path.
Args:
p (AStar): An AStar instance.
Returns:
int: Length of the path.
"""
return int(lib.TCOD_path_size(p._path_c)) | [
"def",
"path_size",
"(",
"p",
":",
"tcod",
".",
"path",
".",
"AStar",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_path_size",
"(",
"p",
".",
"_path_c",
")",
")"
] | 26.333333 | 12.888889 |
def low(self, fun, low):
'''
Pass the cloud function and low data structure to run
'''
l_fun = getattr(self, fun)
f_call = salt.utils.args.format_call(l_fun, low)
return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {})) | [
"def",
"low",
"(",
"self",
",",
"fun",
",",
"low",
")",
":",
"l_fun",
"=",
"getattr",
"(",
"self",
",",
"fun",
")",
"f_call",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"format_call",
"(",
"l_fun",
",",
"low",
")",
"return",
"l_fun",
"(",
"*",
... | 38.571429 | 21.428571 |
def get_subgraph_by_node_search(graph: BELGraph, query: Strings) -> BELGraph:
"""Get a sub-graph induced over all nodes matching the query string.
:param graph: A BEL Graph
:param query: A query string or iterable of query strings for node names
Thinly wraps :func:`search_node_names` and :func:`get_su... | [
"def",
"get_subgraph_by_node_search",
"(",
"graph",
":",
"BELGraph",
",",
"query",
":",
"Strings",
")",
"->",
"BELGraph",
":",
"nodes",
"=",
"search_node_names",
"(",
"graph",
",",
"query",
")",
"return",
"get_subgraph_by_induction",
"(",
"graph",
",",
"nodes",
... | 43.5 | 21.8 |
def split_pdb_residue(s):
'''Splits a PDB residue into the numeric and insertion code components.'''
if s.isdigit():
return (int(s), ' ')
else:
assert(s[:-1].isdigit())
return ((s[:-1], s[-1])) | [
"def",
"split_pdb_residue",
"(",
"s",
")",
":",
"if",
"s",
".",
"isdigit",
"(",
")",
":",
"return",
"(",
"int",
"(",
"s",
")",
",",
"' '",
")",
"else",
":",
"assert",
"(",
"s",
"[",
":",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
")",
"return",... | 31.857143 | 19 |
def _parseTagName(self):
"""
Parse name of the tag.
Result is saved to the :attr:`_tagname` property.
"""
for el in self._element.split():
el = el.replace("/", "").replace("<", "").replace(">", "")
if el.strip():
self._tagname = el.rstrip... | [
"def",
"_parseTagName",
"(",
"self",
")",
":",
"for",
"el",
"in",
"self",
".",
"_element",
".",
"split",
"(",
")",
":",
"el",
"=",
"el",
".",
"replace",
"(",
"\"/\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"<\"",
",",
"\"\"",
")",
".",
"replace... | 27.833333 | 15.666667 |
def id_pools_vsn_ranges(self):
"""
Gets the IdPoolsRanges API Client for VSN Ranges.
Returns:
IdPoolsRanges:
"""
if not self.__id_pools_vsn_ranges:
self.__id_pools_vsn_ranges = IdPoolsRanges('vsn', self.__connection)
return self.__id_pools_vsn_ran... | [
"def",
"id_pools_vsn_ranges",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__id_pools_vsn_ranges",
":",
"self",
".",
"__id_pools_vsn_ranges",
"=",
"IdPoolsRanges",
"(",
"'vsn'",
",",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__id_pools_vsn_r... | 31.4 | 14.8 |
def _update_pop(self, pop_size):
"""Updates population according to crossover and fitness criteria."""
self.toolbox.generate()
# simple bound checking
for i in range(len(self.population)):
for j in range(len(self.population[i])):
if self.population[i][j] > 1:
... | [
"def",
"_update_pop",
"(",
"self",
",",
"pop_size",
")",
":",
"self",
".",
"toolbox",
".",
"generate",
"(",
")",
"# simple bound checking",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"population",
")",
")",
":",
"for",
"j",
"in",
"range",... | 43.071429 | 7.857143 |
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
"""Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt():
N must be a power of two larger than 1 but no larger than 2 ** 31
r and p m... | [
"def",
"scrypt_mcf",
"(",
"password",
",",
"salt",
"=",
"None",
",",
"N",
"=",
"SCRYPT_N",
",",
"r",
"=",
"SCRYPT_r",
",",
"p",
"=",
"SCRYPT_p",
",",
"prefix",
"=",
"SCRYPT_MCF_PREFIX_DEFAULT",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"unicode... | 43.761905 | 20.952381 |
def cget(self, key):
"""
Query widget option.
:param key: option name
:type key: str
:return: value of the option
To get the list of options for this widget, call the method :meth:`~Table.keys`.
"""
if key == 'sortable':
return self._sortable... | [
"def",
"cget",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"==",
"'sortable'",
":",
"return",
"self",
".",
"_sortable",
"elif",
"key",
"==",
"'drag_cols'",
":",
"return",
"self",
".",
"_drag_cols",
"elif",
"key",
"==",
"'drag_rows'",
":",
"return",
... | 27.833333 | 15.055556 |
def get_name(self, obj=None, withext=True):
"""Return the filename
:param obj: the fileinfo with information. If None, this will use the stored object of JB_File
:type obj: :class:`FileInfo`
:param withext: If True, return with the fileextension.
:type withext: bool
:ret... | [
"def",
"get_name",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"withext",
"=",
"True",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"self",
".",
"_obj",
"chunks",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"_elements",
":",
"c",
"=",... | 33.454545 | 16.5 |
def maxCtxContextualRule(maxCtx, st, chain):
"""Calculate usMaxContext based on a contextual feature rule."""
if not chain:
return max(maxCtx, st.GlyphCount)
elif chain == 'Reverse':
return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount)
return max(maxCtx, st.InputGlyphCount + st.Lo... | [
"def",
"maxCtxContextualRule",
"(",
"maxCtx",
",",
"st",
",",
"chain",
")",
":",
"if",
"not",
"chain",
":",
"return",
"max",
"(",
"maxCtx",
",",
"st",
".",
"GlyphCount",
")",
"elif",
"chain",
"==",
"'Reverse'",
":",
"return",
"max",
"(",
"maxCtx",
",",... | 41.375 | 16.625 |
def setup(self, proxystr='', prompting=True):
"""
Sets the proxy handler given the option passed on the command
line. If an empty string is passed it looks at the HTTP_PROXY
environment variable.
"""
self.prompting = prompting
proxy = self.get_proxy(proxystr)
... | [
"def",
"setup",
"(",
"self",
",",
"proxystr",
"=",
"''",
",",
"prompting",
"=",
"True",
")",
":",
"self",
".",
"prompting",
"=",
"prompting",
"proxy",
"=",
"self",
".",
"get_proxy",
"(",
"proxystr",
")",
"if",
"proxy",
":",
"proxy_support",
"=",
"urlli... | 44 | 15.5 |
def AddIndex(node, index=None):
"""
Recursively add the current index (with respect to a repeated section) in all
data dictionaries.
"""
if isinstance(node, list):
for i, item in enumerate(node):
AddIndex(item, index=i)
elif isinstance(node, dict):
if index is not None:
node['index'] = i... | [
"def",
"AddIndex",
"(",
"node",
",",
"index",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"list",
")",
":",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"node",
")",
":",
"AddIndex",
"(",
"item",
",",
"index",
"=",
"i",
")",
... | 27.615385 | 13 |
def get_news(self):
'''Get all the news from first page'''
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent}
req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=heade... | [
"def",
"get_news",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencoded\"",
",",
"\"Accept\"",
":",
"\"text/plain\"",
",",
"'Referer'",
":",
"'http://'",
"+",
"self",
".",
"domain",
"+",
"'/login.phtml'",
",",
... | 55.444444 | 33.444444 |
def job(self, name):
"""
Method for searching specific job by it's name.
:param name: name of the job to search.
:return: found job or None.
:rtype: yagocd.resources.job.JobInstance
"""
for job in self.jobs():
if job.data.name == name:
... | [
"def",
"job",
"(",
"self",
",",
"name",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
"(",
")",
":",
"if",
"job",
".",
"data",
".",
"name",
"==",
"name",
":",
"return",
"job"
] | 29.181818 | 11 |
def _get_stat(self):
"""
Get statistics from devfile in list of lists of words
"""
def dev_filter(x):
# get first word and remove trailing interface number
x = x.strip().split(" ")[0][:-1]
if x in self.interfaces_blacklist:
return Fal... | [
"def",
"_get_stat",
"(",
"self",
")",
":",
"def",
"dev_filter",
"(",
"x",
")",
":",
"# get first word and remove trailing interface number",
"x",
"=",
"x",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"[",
"0",
"]",
"[",
":",
"-",
"1",
"]",... | 26.310345 | 20.931034 |
def remove_summaries():
"""Remove summaries from the default graph."""
g = tf.get_default_graph()
key = tf.GraphKeys.SUMMARIES
log_debug("Remove summaries %s" % str(g.get_collection(key)))
del g.get_collection_ref(key)[:]
assert not g.get_collection(key) | [
"def",
"remove_summaries",
"(",
")",
":",
"g",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
"key",
"=",
"tf",
".",
"GraphKeys",
".",
"SUMMARIES",
"log_debug",
"(",
"\"Remove summaries %s\"",
"%",
"str",
"(",
"g",
".",
"get_collection",
"(",
"key",
")",
... | 37.142857 | 10.571429 |
def subnet_distance(self):
"""
Specific subnet administrative distances
:return: list of tuple (subnet, distance)
"""
return [(Element.from_href(entry.get('subnet')), entry.get('distance'))
for entry in self.data.get('distance_entry')] | [
"def",
"subnet_distance",
"(",
"self",
")",
":",
"return",
"[",
"(",
"Element",
".",
"from_href",
"(",
"entry",
".",
"get",
"(",
"'subnet'",
")",
")",
",",
"entry",
".",
"get",
"(",
"'distance'",
")",
")",
"for",
"entry",
"in",
"self",
".",
"data",
... | 35.625 | 16.375 |
def get_interfaces(self):
"""Returns a set of VIFs from `get_instances` return value."""
LOG.debug("Getting interfaces from Xapi")
with self.sessioned() as session:
instances = self.get_instances(session)
recs = session.xenapi.VIF.get_all_records()
interfaces = ... | [
"def",
"get_interfaces",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Getting interfaces from Xapi\"",
")",
"with",
"self",
".",
"sessioned",
"(",
")",
"as",
"session",
":",
"instances",
"=",
"self",
".",
"get_instances",
"(",
"session",
")",
"recs",
... | 35.0625 | 14.0625 |
def snake_case(string):
"""
Converts a string to snake case. For example::
snake_case('OneTwoThree') -> 'one_two_three'
"""
if not string:
return string
string = string.replace('-', '_').replace(' ', '_')
return de_camel(string) | [
"def",
"snake_case",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"return",
"string",
"string",
"=",
"string",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"return",
"de_camel",
"(",
"string",
")"
... | 26 | 14.8 |
def countrate(self,binned=True,range=None,force=False):
"""Calculate effective stimulus in count/s.
Also see :ref:`pysynphot-formula-countrate` and
:ref:`pysynphot-formula-effstim`.
.. note::
This is the calculation performed when the ETC invokes
``countrate``.
... | [
"def",
"countrate",
"(",
"self",
",",
"binned",
"=",
"True",
",",
"range",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_binflux",
"is",
"None",
":",
"self",
".",
"initbinflux",
"(",
")",
"myfluxunits",
"=",
"self",
".",
"... | 35.526316 | 23.652632 |
def find_files(filenames, recursive, exclude):
"""Yield filenames."""
while filenames:
name = filenames.pop(0)
if recursive and os.path.isdir(name):
for root, directories, children in os.walk(name):
filenames += [os.path.join(root, f) for f in children
... | [
"def",
"find_files",
"(",
"filenames",
",",
"recursive",
",",
"exclude",
")",
":",
"while",
"filenames",
":",
"name",
"=",
"filenames",
".",
"pop",
"(",
"0",
")",
"if",
"recursive",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"name",
")",
":",
"for"... | 45.933333 | 16.2 |
def guess_payload_class(self, payload):
# type: (str) -> base_classes.Packet_metaclass
""" guess_payload_class returns the Class object to use for parsing a payload
This function uses the H2Frame.type field value to decide which payload to parse. The implement cannot be # noqa: E501
per... | [
"def",
"guess_payload_class",
"(",
"self",
",",
"payload",
")",
":",
"# type: (str) -> base_classes.Packet_metaclass",
"if",
"len",
"(",
"payload",
")",
"==",
"0",
":",
"return",
"packet",
".",
"NoPayload",
"t",
"=",
"self",
".",
"getfieldval",
"(",
"'type'",
... | 40 | 22.5 |
def collect_cmd(self, args, ret):
"""Collect analytics info from a CLI command."""
from dvc.command.daemon import CmdDaemonAnalytics
assert isinstance(ret, int) or ret is None
if ret is not None:
self.info[self.PARAM_CMD_RETURN_CODE] = ret
if args is not None and h... | [
"def",
"collect_cmd",
"(",
"self",
",",
"args",
",",
"ret",
")",
":",
"from",
"dvc",
".",
"command",
".",
"daemon",
"import",
"CmdDaemonAnalytics",
"assert",
"isinstance",
"(",
"ret",
",",
"int",
")",
"or",
"ret",
"is",
"None",
"if",
"ret",
"is",
"not"... | 37.166667 | 19.166667 |
def write(self, val, sig: SimSignal)-> None:
"""
Write value to signal or interface.
"""
# get target RtlSignal
try:
simSensProcs = sig.simSensProcs
except AttributeError:
sig = sig._sigInside
simSensProcs = sig.simSensProcs
# ... | [
"def",
"write",
"(",
"self",
",",
"val",
",",
"sig",
":",
"SimSignal",
")",
"->",
"None",
":",
"# get target RtlSignal",
"try",
":",
"simSensProcs",
"=",
"sig",
".",
"simSensProcs",
"except",
"AttributeError",
":",
"sig",
"=",
"sig",
".",
"_sigInside",
"si... | 35.184211 | 13.868421 |
def get_aggregation_timestamp(self, timestamp, granularity='second'):
"""
Return a timestamp from the raw epoch time based on the granularity preferences passed in.
:param string timestamp: timestamp from the log line
:param string granularity: aggregation granularity used for plots.
:return: strin... | [
"def",
"get_aggregation_timestamp",
"(",
"self",
",",
"timestamp",
",",
"granularity",
"=",
"'second'",
")",
":",
"if",
"granularity",
"is",
"None",
"or",
"granularity",
".",
"lower",
"(",
")",
"==",
"'none'",
":",
"return",
"int",
"(",
"timestamp",
")",
"... | 45.75 | 22 |
def retrieve(self):
"""
Retrieves all data for this document and saves it.
"""
data = self.resource(self.id).get()
self.data = data
return data | [
"def",
"retrieve",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"resource",
"(",
"self",
".",
"id",
")",
".",
"get",
"(",
")",
"self",
".",
"data",
"=",
"data",
"return",
"data"
] | 21 | 18.111111 |
def service_create(name, service_type, description=None, profile=None,
**connection_args):
'''
Add service to Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_create nova compute \
'OpenStack Compute Service'
'''
kstone = auth(pr... | [
"def",
"service_create",
"(",
"name",
",",
"service_type",
",",
"description",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"*",
"*",
"connection_args",
")",
"service",
... | 32.266667 | 24.266667 |
def _create_figure(kwargs: Mapping[str, Any]) -> dict:
"""Create basic dictionary object with figure properties."""
return {
"$schema": "https://vega.github.io/schema/vega/v3.json",
"width": kwargs.pop("width", DEFAULT_WIDTH),
"height": kwargs.pop("height", DEFAULT_HEIGHT),
"padd... | [
"def",
"_create_figure",
"(",
"kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"dict",
":",
"return",
"{",
"\"$schema\"",
":",
"\"https://vega.github.io/schema/vega/v3.json\"",
",",
"\"width\"",
":",
"kwargs",
".",
"pop",
"(",
"\"width\"",
","... | 45.375 | 18.125 |
def send_connect_signal(self, request, user, profile, client):
"""
Send a signal that a user connected a social profile to his Django
account. This signal should be sent *only* when the a new social
connection was created.
"""
signals.connect.send(sender=profile.__class__... | [
"def",
"send_connect_signal",
"(",
"self",
",",
"request",
",",
"user",
",",
"profile",
",",
"client",
")",
":",
"signals",
".",
"connect",
".",
"send",
"(",
"sender",
"=",
"profile",
".",
"__class__",
",",
"user",
"=",
"user",
",",
"profile",
"=",
"pr... | 48.25 | 17.75 |
def _send_socket_request(self, xml_request):
""" Send a request via protobuf.
Args:
xml_request -- A fully formed xml request string for the CPS.
Returns:
The raw xml response string.
"""
def to_variant(number):
buff = []
... | [
"def",
"_send_socket_request",
"(",
"self",
",",
"xml_request",
")",
":",
"def",
"to_variant",
"(",
"number",
")",
":",
"buff",
"=",
"[",
"]",
"while",
"number",
":",
"byte",
"=",
"number",
"%",
"128",
"number",
"=",
"number",
"//",
"128",
"if",
"numbe... | 36.266667 | 14.792593 |
def sort_values(self, by, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
"""Sort by the values along either axis
Wrapper around the :meth:`pandas.DataFrame.sort_values` method.
"""
if inplace:
self._frame.sort_values(
... | [
"def",
"sort_values",
"(",
"self",
",",
"by",
",",
"axis",
"=",
"0",
",",
"ascending",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"kind",
"=",
"'quicksort'",
",",
"na_position",
"=",
"'last'",
")",
":",
"if",
"inplace",
":",
"self",
".",
"_frame... | 43.588235 | 17.823529 |
def open_zarr(store, group=None, synchronizer=None, chunks='auto',
decode_cf=True, mask_and_scale=True, decode_times=True,
concat_characters=True, decode_coords=True,
drop_variables=None, consolidated=False,
overwrite_encoded_chunks=False, **kwargs):
"""Load a... | [
"def",
"open_zarr",
"(",
"store",
",",
"group",
"=",
"None",
",",
"synchronizer",
"=",
"None",
",",
"chunks",
"=",
"'auto'",
",",
"decode_cf",
"=",
"True",
",",
"mask_and_scale",
"=",
"True",
",",
"decode_times",
"=",
"True",
",",
"concat_characters",
"=",... | 41.224719 | 22.168539 |
def bail_out(self, message, from_error=False):
"""
In case if the transport pipes are closed and the sanic app encounters
an error while writing data to the transport pipe, we log the error
with proper details.
:param message: Error message to display
:param from_error: ... | [
"def",
"bail_out",
"(",
"self",
",",
"message",
",",
"from_error",
"=",
"False",
")",
":",
"if",
"from_error",
"or",
"self",
".",
"transport",
"is",
"None",
"or",
"self",
".",
"transport",
".",
"is_closing",
"(",
")",
":",
"logger",
".",
"error",
"(",
... | 35.310345 | 19.034483 |
async def handle_agent_hello(self, agent_addr, message: AgentHello):
"""
Handle an AgentAvailable message. Add agent_addr to the list of available agents
"""
self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name)
if agent_addr in self._registered_agents... | [
"async",
"def",
"handle_agent_hello",
"(",
"self",
",",
"agent_addr",
",",
"message",
":",
"AgentHello",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Agent %s (%s) said hello\"",
",",
"agent_addr",
",",
"message",
".",
"friendly_name",
")",
"if",
"ag... | 65.296296 | 36.407407 |
def username_access_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
name_key = ET.SubElement(username, "name")
name_key.text = kwargs.pop('name')
... | [
"def",
"username_access_time",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"username",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"username\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:... | 42.083333 | 14 |
def pressHoldRelease(*args):
'''
press and hold passed in strings. Once held, release
accepts as many arguments as you want.
e.g. pressAndHold('left_arrow', 'a','b').
this is useful for issuing shortcut command or shift commands.
e.g. pressHoldRelease('ctrl', 'alt', 'del'), pressHoldRelease('sh... | [
"def",
"pressHoldRelease",
"(",
"*",
"args",
")",
":",
"for",
"i",
"in",
"args",
":",
"win32api",
".",
"keybd_event",
"(",
"VK_CODE",
"[",
"i",
"]",
",",
"0",
",",
"0",
",",
"0",
")",
"time",
".",
"sleep",
"(",
".05",
")",
"for",
"i",
"in",
"ar... | 34.25 | 21.875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.