nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py | python | TextDoc.docmodule | (self, object, name=None, mod=None) | return result | Produce text documentation for a given module object. | Produce text documentation for a given module object. | [
"Produce",
"text",
"documentation",
"for",
"a",
"given",
"module",
"object",
"."
] | def docmodule(self, object, name=None, mod=None):
"""Produce text documentation for a given module object."""
name = object.__name__ # ignore the passed-in name
synop, desc = splitdoc(getdoc(object))
result = self.section('NAME', name + (synop and ' - ' + synop))
try:
all = object.__all__
except AttributeError:
all = None
try:
file = inspect.getabsfile(object)
except TypeError:
file = '(built-in)'
result = result + self.section('FILE', file)
docloc = self.getdocloc(object)
if docloc is not None:
result = result + self.section('MODULE DOCS', docloc)
if desc:
result = result + self.section('DESCRIPTION', desc)
classes = []
for key, value in inspect.getmembers(object, inspect.isclass):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None
or (inspect.getmodule(value) or object) is object):
if visiblename(key, all, object):
classes.append((key, value))
funcs = []
for key, value in inspect.getmembers(object, inspect.isroutine):
# if __all__ exists, believe it. Otherwise use old heuristic.
if (all is not None or
inspect.isbuiltin(value) or inspect.getmodule(value) is object):
if visiblename(key, all, object):
funcs.append((key, value))
data = []
for key, value in inspect.getmembers(object, isdata):
if visiblename(key, all, object):
data.append((key, value))
modpkgs = []
modpkgs_names = set()
if hasattr(object, '__path__'):
for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
modpkgs_names.add(modname)
if ispkg:
modpkgs.append(modname + ' (package)')
else:
modpkgs.append(modname)
modpkgs.sort()
result = result + self.section(
'PACKAGE CONTENTS', join(modpkgs, '\n'))
# Detect submodules as sometimes created by C extensions
submodules = []
for key, value in inspect.getmembers(object, inspect.ismodule):
if value.__name__.startswith(name + '.') and key not in modpkgs_names:
submodules.append(key)
if submodules:
submodules.sort()
result = result + self.section(
'SUBMODULES', join(submodules, '\n'))
if classes:
classlist = map(lambda key_value: key_value[1], classes)
contents = [self.formattree(
inspect.getclasstree(classlist, 1), name)]
for key, value in classes:
contents.append(self.document(value, key, name))
result = result + self.section('CLASSES', join(contents, '\n'))
if funcs:
contents = []
for key, value in funcs:
contents.append(self.document(value, key, name))
result = result + self.section('FUNCTIONS', join(contents, '\n'))
if data:
contents = []
for key, value in data:
contents.append(self.docother(value, key, name, maxlen=70))
result = result + self.section('DATA', join(contents, '\n'))
if hasattr(object, '__version__'):
version = str(object.__version__)
if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
version = strip(version[11:-1])
result = result + self.section('VERSION', version)
if hasattr(object, '__date__'):
result = result + self.section('DATE', str(object.__date__))
if hasattr(object, '__author__'):
result = result + self.section('AUTHOR', str(object.__author__))
if hasattr(object, '__credits__'):
result = result + self.section('CREDITS', str(object.__credits__))
return result | [
"def",
"docmodule",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
")",
":",
"name",
"=",
"object",
".",
"__name__",
"# ignore the passed-in name",
"synop",
",",
"desc",
"=",
"splitdoc",
"(",
"getdoc",
"(",
"object",
")",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py#L1031-L1129 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/data_flow_grad.py | python | _DynamicPartitionGrads | (op, *grads) | return [reconstructed, None] | Gradients for DynamicPartition. | Gradients for DynamicPartition. | [
"Gradients",
"for",
"DynamicPartition",
"."
] | def _DynamicPartitionGrads(op, *grads):
"""Gradients for DynamicPartition."""
data = op.inputs[0]
indices = op.inputs[1]
num_partitions = op.get_attr("num_partitions")
prefix_shape = array_ops.shape(indices)
original_indices = array_ops.reshape(
math_ops.range(math_ops.reduce_prod(prefix_shape)), prefix_shape)
partitioned_indices = data_flow_ops.dynamic_partition(
original_indices, indices, num_partitions)
reconstructed = data_flow_ops.dynamic_stitch(partitioned_indices, grads)
reconstructed = array_ops.reshape(reconstructed, array_ops.shape(data))
return [reconstructed, None] | [
"def",
"_DynamicPartitionGrads",
"(",
"op",
",",
"*",
"grads",
")",
":",
"data",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"indices",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"num_partitions",
"=",
"op",
".",
"get_attr",
"(",
"\"num_partitions\"",
")",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_grad.py#L31-L44 | |
blockchain-foundry/gcoin-community | c8da4d550efd5f6eb9c54af4fdfdc0451689f94f | contrib/linearize/linearize-data.py | python | BlockDataCopier.fetchBlock | (self, extent) | Fetch block contents from disk given extents | Fetch block contents from disk given extents | [
"Fetch",
"block",
"contents",
"from",
"disk",
"given",
"extents"
] | def fetchBlock(self, extent):
'''Fetch block contents from disk given extents'''
with open(self.inFileName(extent.fn), "rb") as f:
f.seek(extent.offset)
return f.read(extent.size) | [
"def",
"fetchBlock",
"(",
"self",
",",
"extent",
")",
":",
"with",
"open",
"(",
"self",
".",
"inFileName",
"(",
"extent",
".",
"fn",
")",
",",
"\"rb\"",
")",
"as",
"f",
":",
"f",
".",
"seek",
"(",
"extent",
".",
"offset",
")",
"return",
"f",
".",... | https://github.com/blockchain-foundry/gcoin-community/blob/c8da4d550efd5f6eb9c54af4fdfdc0451689f94f/contrib/linearize/linearize-data.py#L172-L176 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/lib/auth_digest.py | python | www_authenticate | (realm, key, algorithm='MD5', nonce=None, qop=qop_auth, stale=False) | return s | Constructs a WWW-Authenticate header for Digest authentication. | Constructs a WWW-Authenticate header for Digest authentication. | [
"Constructs",
"a",
"WWW",
"-",
"Authenticate",
"header",
"for",
"Digest",
"authentication",
"."
] | def www_authenticate(realm, key, algorithm='MD5', nonce=None, qop=qop_auth, stale=False):
"""Constructs a WWW-Authenticate header for Digest authentication."""
if qop not in valid_qops:
raise ValueError("Unsupported value for qop: '%s'" % qop)
if algorithm not in valid_algorithms:
raise ValueError("Unsupported value for algorithm: '%s'" % algorithm)
if nonce is None:
nonce = synthesize_nonce(realm, key)
s = 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"' % (
realm, nonce, algorithm, qop)
if stale:
s += ', stale="true"'
return s | [
"def",
"www_authenticate",
"(",
"realm",
",",
"key",
",",
"algorithm",
"=",
"'MD5'",
",",
"nonce",
"=",
"None",
",",
"qop",
"=",
"qop_auth",
",",
"stale",
"=",
"False",
")",
":",
"if",
"qop",
"not",
"in",
"valid_qops",
":",
"raise",
"ValueError",
"(",
... | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/auth_digest.py#L286-L299 | |
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/python/cpplint/cpplint.py | python | FileInfo.BaseName | (self) | return self.Split()[1] | File base name - text after the final slash, before the final period. | File base name - text after the final slash, before the final period. | [
"File",
"base",
"name",
"-",
"text",
"after",
"the",
"final",
"slash",
"before",
"the",
"final",
"period",
"."
] | def BaseName(self):
"""File base name - text after the final slash, before the final period."""
return self.Split()[1] | [
"def",
"BaseName",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"1",
"]"
] | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/python/cpplint/cpplint.py#L1048-L1050 | |
gklz1982/caffe-yolov2 | ebb27029db4ddc0d40e520634633b0fa9cdcc10d | tools/yolo_extra/extract_seconds.py | python | get_start_time | (line_iterable, year) | return start_datetime | Find start time from group of lines | Find start time from group of lines | [
"Find",
"start",
"time",
"from",
"group",
"of",
"lines"
] | def get_start_time(line_iterable, year):
"""Find start time from group of lines
"""
start_datetime = None
for line in line_iterable:
line = line.strip()
if line.find('Solving') != -1:
start_datetime = extract_datetime_from_line(line, year)
break
return start_datetime | [
"def",
"get_start_time",
"(",
"line_iterable",
",",
"year",
")",
":",
"start_datetime",
"=",
"None",
"for",
"line",
"in",
"line_iterable",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"find",
"(",
"'Solving'",
")",
"!=",
"-",
"1... | https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/tools/yolo_extra/extract_seconds.py#L31-L41 | |
YosysHQ/nextpnr | 74c99f9195eeb47d106ca74b7abb894cfd47cc03 | 3rdparty/pybind11/pybind11/setup_helpers.py | python | has_flag | (compiler, flag) | Return the flag if a flag name is supported on the
specified compiler, otherwise None (can be used as a boolean).
If multiple flags are passed, return the first that matches. | Return the flag if a flag name is supported on the
specified compiler, otherwise None (can be used as a boolean).
If multiple flags are passed, return the first that matches. | [
"Return",
"the",
"flag",
"if",
"a",
"flag",
"name",
"is",
"supported",
"on",
"the",
"specified",
"compiler",
"otherwise",
"None",
"(",
"can",
"be",
"used",
"as",
"a",
"boolean",
")",
".",
"If",
"multiple",
"flags",
"are",
"passed",
"return",
"the",
"firs... | def has_flag(compiler, flag):
"""
Return the flag if a flag name is supported on the
specified compiler, otherwise None (can be used as a boolean).
If multiple flags are passed, return the first that matches.
"""
with tmp_chdir():
fname = "flagcheck.cpp"
with open(fname, "w") as f:
f.write("int main (int argc, char **argv) { return 0; }")
try:
compiler.compile([fname], extra_postargs=[flag])
except distutils.errors.CompileError:
return False
return True | [
"def",
"has_flag",
"(",
"compiler",
",",
"flag",
")",
":",
"with",
"tmp_chdir",
"(",
")",
":",
"fname",
"=",
"\"flagcheck.cpp\"",
"with",
"open",
"(",
"fname",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"int main (int argc, char **argv) {... | https://github.com/YosysHQ/nextpnr/blob/74c99f9195eeb47d106ca74b7abb894cfd47cc03/3rdparty/pybind11/pybind11/setup_helpers.py#L225-L241 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | tuple | (tensors, name=None, control_inputs=None) | Group tensors together.
This creates a tuple of tensors with the same values as the `tensors`
argument, except that the value of each tensor is only returned after the
values of all tensors have been computed.
`control_inputs` contains additional ops that have to finish before this op
finishes, but whose outputs are not returned.
This can be used as a "join" mechanism for parallel computations: all the
argument tensors can be computed in parallel, but the values of any tensor
returned by `tuple` are only available after all the parallel computations
are done.
See also `group` and `with_dependencies`.
Args:
tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`.
name: (optional) A name to use as a `name_scope` for the operation.
control_inputs: List of additional ops to finish before returning.
Returns:
Same as `tensors`.
Raises:
ValueError: If `tensors` does not contain any `Tensor` or `IndexedSlices`.
TypeError: If `control_inputs` is not a list of `Operation` or `Tensor`
objects. | Group tensors together. | [
"Group",
"tensors",
"together",
"."
] | def tuple(tensors, name=None, control_inputs=None):
"""Group tensors together.
This creates a tuple of tensors with the same values as the `tensors`
argument, except that the value of each tensor is only returned after the
values of all tensors have been computed.
`control_inputs` contains additional ops that have to finish before this op
finishes, but whose outputs are not returned.
This can be used as a "join" mechanism for parallel computations: all the
argument tensors can be computed in parallel, but the values of any tensor
returned by `tuple` are only available after all the parallel computations
are done.
See also `group` and `with_dependencies`.
Args:
tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`.
name: (optional) A name to use as a `name_scope` for the operation.
control_inputs: List of additional ops to finish before returning.
Returns:
Same as `tensors`.
Raises:
ValueError: If `tensors` does not contain any `Tensor` or `IndexedSlices`.
TypeError: If `control_inputs` is not a list of `Operation` or `Tensor`
objects.
"""
with ops.op_scope(tensors, name, "tuple") as name:
gating_ops = [t.op for t in tensors if t is not None]
if control_inputs:
for c in control_inputs:
if isinstance(c, ops.Tensor):
c = c.op
elif not isinstance(c, ops.Operation):
raise TypeError("Control input must be Operation or Tensor: %s" % c)
gating_ops.append(c)
# Note that in order to ensure ordering in the pbtxt, we must take care to
# ensure the order here.
gating_ops = sorted(set(gating_ops), key=lambda op: op._id) # Uniquify ops.
if not gating_ops:
raise ValueError("Must have at least one Tensor: %s" % tensors)
gate = group(*gating_ops)
tpl = []
for t in tensors:
if t is not None:
tpl.append(with_dependencies([gate], t))
else:
tpl.append(None)
return tpl | [
"def",
"tuple",
"(",
"tensors",
",",
"name",
"=",
"None",
",",
"control_inputs",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"tensors",
",",
"name",
",",
"\"tuple\"",
")",
"as",
"name",
":",
"gating_ops",
"=",
"[",
"t",
".",
"op",
"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L2145-L2197 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py | python | RedisCache.close | (self) | Redis uses connection pooling, no need to close the connection. | Redis uses connection pooling, no need to close the connection. | [
"Redis",
"uses",
"connection",
"pooling",
"no",
"need",
"to",
"close",
"the",
"connection",
"."
] | def close(self):
"""Redis uses connection pooling, no need to close the connection."""
pass | [
"def",
"close",
"(",
"self",
")",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py#L61-L65 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_data.py | python | DebugDumpDir.nodes | (self, device_name=None) | Get a list of all nodes from the partition graphs.
Args:
device_name: (`str`) name of device. If None, all nodes from all available
devices will be included.
Returns:
All nodes' names, as a list of str.
Raises:
LookupError: If no partition graphs have been loaded.
ValueError: If specified node name does not exist. | Get a list of all nodes from the partition graphs. | [
"Get",
"a",
"list",
"of",
"all",
"nodes",
"from",
"the",
"partition",
"graphs",
"."
] | def nodes(self, device_name=None):
"""Get a list of all nodes from the partition graphs.
Args:
device_name: (`str`) name of device. If None, all nodes from all available
devices will be included.
Returns:
All nodes' names, as a list of str.
Raises:
LookupError: If no partition graphs have been loaded.
ValueError: If specified node name does not exist.
"""
if not self._debug_graphs:
raise LookupError("No partition graphs have been loaded.")
if device_name is None:
nodes = []
for device_name in self._debug_graphs:
nodes.extend(self._debug_graphs[device_name].node_inputs.keys())
return nodes
else:
if device_name not in self._debug_graphs:
raise ValueError("Invalid device name: %s" % device_name)
return self._debug_graphs[device_name].node_inputs.keys() | [
"def",
"nodes",
"(",
"self",
",",
"device_name",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_debug_graphs",
":",
"raise",
"LookupError",
"(",
"\"No partition graphs have been loaded.\"",
")",
"if",
"device_name",
"is",
"None",
":",
"nodes",
"=",
"[",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/debug_data.py#L1022-L1046 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py | python | ParserElement.setResultsName | ( self, name, listAllMatches=False ) | return newself | Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
C{expr("name")} in place of C{expr.setResultsName("name")} -
see L{I{__call__}<__call__>}.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") | Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names. | [
"Define",
"name",
"for",
"referencing",
"matching",
"tokens",
"as",
"a",
"nested",
"attribute",
"of",
"the",
"returned",
"parse",
"results",
".",
"NOTE",
":",
"this",
"returns",
"a",
"*",
"copy",
"*",
"of",
"the",
"original",
"C",
"{",
"ParserElement",
"}"... | def setResultsName( self, name, listAllMatches=False ):
"""
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
C{expr("name")} in place of C{expr.setResultsName("name")} -
see L{I{__call__}<__call__>}.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
"""
newself = self.copy()
if name.endswith("*"):
name = name[:-1]
listAllMatches=True
newself.resultsName = name
newself.modalResults = not listAllMatches
return newself | [
"def",
"setResultsName",
"(",
"self",
",",
"name",
",",
"listAllMatches",
"=",
"False",
")",
":",
"newself",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"name",
".",
"endswith",
"(",
"\"*\"",
")",
":",
"name",
"=",
"name",
"[",
":",
"-",
"1",
"]",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L1204-L1230 | |
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | src/kudu/scripts/backup-perf.py | python | parse_args | () | return parser.parse_args() | Parse command-line arguments | Parse command-line arguments | [
"Parse",
"command",
"-",
"line",
"arguments"
] | def parse_args():
""" Parse command-line arguments """
parser = argparse.ArgumentParser(description='Run a Kudu backup and restore performance test',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Kudu Configuration
parser.add_argument('--master-addresses', required=True, help='The Kudu master addresses')
# Impala Configuration
parser.add_argument('--impalad-address', required=True, help='The Impala daemon address')
parser.add_argument('--table-prefix', default='impala::default.',
help='Kudu table name prefix in the Hive metastore')
# Spark Job Configuration
parser.add_argument('--spark-submit-command', default='spark-submit',
help='The name of the spark-submit binary')
## Spark Loader Configuration
parser.add_argument('--kudu-spark-tools-jar', default='kudu-spark*-tools*.jar',
help='The path to the kudu-spark-tools jar (for --load-table)')
parser.add_argument('--load-num-tasks', type=int, default=20,
help='Number of Spark tasks to create when loading data')
parser.add_argument('--load-policy', default='sequential', choices=['sequential', 'random'],
help='The data loading policy for the data generator')
parser.add_argument('--string-field-len', type=int, default=128,
help='The length, in bytes, of generated string column values')
## Spark Backup/Restore Job Configuration
parser.add_argument('--kudu-backup-jar', default='kudu-backup*.jar',
help='The path to the kudu-backup jar')
parser.add_argument('--backup-path', default='hdfs:///kudu-backup-tests',
help='The Hadoop-compatible path at which to store the backup')
parser.add_argument('--backup-file-format', default='parquet',
help='The file format of the backup: must be parquet')
parser.add_argument('--scan-request-timeout-ms', type=int, default=30000,
help='The default scan timeout for backup, in milliseconds')
parser.add_argument('--table-restore-suffix', default='-restore',
help='Kudu table name suffix to append on restore')
# Table Configuration
parser.add_argument('--columns', type=int, default=10,
help='The number of columns in the Kudu table')
parser.add_argument('--num-string-columns', type=int, default=9,
help='The number of string columns in the table; the rest will be bigints')
parser.add_argument('--partitions', type=int, default=10,
help='The number of hash partitions of the table. '
'This script only supports hash partitions')
parser.add_argument('--table-data-size-mb', type=int, default=1024,
help='The uncompressed data size of the table, in MB')
parser.add_argument('--replication-factor', type=int, default=3,
help='The replication factor of the table')
# Positional
parser.add_argument('table_name', help='The name of the Kudu table to create/backup')
# Actions
parser.add_argument('--create-table', type=parse_bool, choices=[True, False], default=False,
help='Whether to create the table for loading')
parser.add_argument('--drop-created-table', type=parse_bool, choices=[True, False], default=False,
help='Whether to drop the created table after a successful test run')
parser.add_argument('--load-table', type=parse_bool, choices=[True, False], default=False,
help='Whether to load the table with data')
parser.add_argument('--backup-table', type=parse_bool, choices=[True, False], default=False,
help='Whether to back up the table')
parser.add_argument('--restore-table', type=parse_bool, choices=[True, False], default=False,
help='Whether to restore the table')
parser.add_argument('--drop-restored-table', type=parse_bool, choices=[True, False], default=False,
help='Whether to drop the restored table after a successful test run')
# Utility
parser.add_argument('--dryrun', action='store_true',
help='Do not execute any commands, only print what would be executed')
return parser.parse_args() | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run a Kudu backup and restore performance test'",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"# Kudu Configuration",
"... | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/src/kudu/scripts/backup-perf.py#L205-L277 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/tlslite/utils/RSAKey.py | python | RSAKey.hashAndVerify | (self, sigBytes, bytes) | return self.verify(sigBytes, prefixedHashBytes) | Hash and verify the passed-in bytes with the signature.
This verifies a PKCS1-SHA1 signature on the passed-in data.
@type sigBytes: L{array.array} of unsigned bytes
@param sigBytes: A PKCS1-SHA1 signature.
@type bytes: str or L{array.array} of unsigned bytes
@param bytes: The value which will be hashed and verified.
@rtype: bool
@return: Whether the signature matches the passed-in data. | Hash and verify the passed-in bytes with the signature. | [
"Hash",
"and",
"verify",
"the",
"passed",
"-",
"in",
"bytes",
"with",
"the",
"signature",
"."
] | def hashAndVerify(self, sigBytes, bytes):
"""Hash and verify the passed-in bytes with the signature.
This verifies a PKCS1-SHA1 signature on the passed-in data.
@type sigBytes: L{array.array} of unsigned bytes
@param sigBytes: A PKCS1-SHA1 signature.
@type bytes: str or L{array.array} of unsigned bytes
@param bytes: The value which will be hashed and verified.
@rtype: bool
@return: Whether the signature matches the passed-in data.
"""
if not isinstance(bytes, type("")):
bytes = bytesToString(bytes)
hashBytes = stringToBytes(sha.sha(bytes).digest())
prefixedHashBytes = self._addPKCS1SHA1Prefix(hashBytes)
return self.verify(sigBytes, prefixedHashBytes) | [
"def",
"hashAndVerify",
"(",
"self",
",",
"sigBytes",
",",
"bytes",
")",
":",
"if",
"not",
"isinstance",
"(",
"bytes",
",",
"type",
"(",
"\"\"",
")",
")",
":",
"bytes",
"=",
"bytesToString",
"(",
"bytes",
")",
"hashBytes",
"=",
"stringToBytes",
"(",
"s... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/tlslite/utils/RSAKey.py#L81-L99 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/dask_cudf/dask_cudf/core.py | python | DataFrame.repartition | (self, *args, **kwargs) | return super().repartition(*args, **kwargs) | Wraps dask.dataframe DataFrame.repartition method.
Uses DataFrame.shuffle if `columns=` is specified. | Wraps dask.dataframe DataFrame.repartition method.
Uses DataFrame.shuffle if `columns=` is specified. | [
"Wraps",
"dask",
".",
"dataframe",
"DataFrame",
".",
"repartition",
"method",
".",
"Uses",
"DataFrame",
".",
"shuffle",
"if",
"columns",
"=",
"is",
"specified",
"."
] | def repartition(self, *args, **kwargs):
"""Wraps dask.dataframe DataFrame.repartition method.
Uses DataFrame.shuffle if `columns=` is specified.
"""
# TODO: Remove this function in future(0.17 release)
columns = kwargs.pop("columns", None)
if columns:
warnings.warn(
"The columns argument will be removed from repartition in "
"future versions of dask_cudf. Use DataFrame.shuffle().",
FutureWarning,
)
warnings.warn(
"Rearranging data by column hash. Divisions will lost. "
"Set ignore_index=False to preserve Index values."
)
ignore_index = kwargs.pop("ignore_index", True)
return self.shuffle(
on=columns, ignore_index=ignore_index, **kwargs
)
return super().repartition(*args, **kwargs) | [
"def",
"repartition",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Remove this function in future(0.17 release)",
"columns",
"=",
"kwargs",
".",
"pop",
"(",
"\"columns\"",
",",
"None",
")",
"if",
"columns",
":",
"warnings",
".",
... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/dask_cudf/dask_cudf/core.py#L305-L325 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBAttachInfo.GetProcessPluginName | (self) | return _lldb.SBAttachInfo_GetProcessPluginName(self) | GetProcessPluginName(SBAttachInfo self) -> char const * | GetProcessPluginName(SBAttachInfo self) -> char const * | [
"GetProcessPluginName",
"(",
"SBAttachInfo",
"self",
")",
"-",
">",
"char",
"const",
"*"
] | def GetProcessPluginName(self):
"""GetProcessPluginName(SBAttachInfo self) -> char const *"""
return _lldb.SBAttachInfo_GetProcessPluginName(self) | [
"def",
"GetProcessPluginName",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBAttachInfo_GetProcessPluginName",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1112-L1114 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | GBSpan.SetColspan | (*args, **kwargs) | return _core_.GBSpan_SetColspan(*args, **kwargs) | SetColspan(self, int colspan) | SetColspan(self, int colspan) | [
"SetColspan",
"(",
"self",
"int",
"colspan",
")"
] | def SetColspan(*args, **kwargs):
"""SetColspan(self, int colspan)"""
return _core_.GBSpan_SetColspan(*args, **kwargs) | [
"def",
"SetColspan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"GBSpan_SetColspan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15668-L15670 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/searchbase.py | python | SearchDialogBase.create_command_buttons | (self) | Place buttons in vertical command frame gridded on right. | Place buttons in vertical command frame gridded on right. | [
"Place",
"buttons",
"in",
"vertical",
"command",
"frame",
"gridded",
"on",
"right",
"."
] | def create_command_buttons(self):
"Place buttons in vertical command frame gridded on right."
f = self.buttonframe = Frame(self.top)
f.grid(row=0,column=2,padx=2,pady=2,ipadx=2,ipady=2)
b = self.make_button("Close", self.close)
b.lower() | [
"def",
"create_command_buttons",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"buttonframe",
"=",
"Frame",
"(",
"self",
".",
"top",
")",
"f",
".",
"grid",
"(",
"row",
"=",
"0",
",",
"column",
"=",
"2",
",",
"padx",
"=",
"2",
",",
"pady",
"=",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/searchbase.py#L172-L178 | ||
lukasmonk/lucaschess | 13e2e5cb13b38a720ccf897af649054a64bcb914 | Code/QT/Columnas.py | python | ListaColumnas.nuevaClave | (self) | Crea una clave nueva de columna, en base a un modelo = CALC_<numero> | Crea una clave nueva de columna, en base a un modelo = CALC_<numero> | [
"Crea",
"una",
"clave",
"nueva",
"de",
"columna",
"en",
"base",
"a",
"un",
"modelo",
"=",
"CALC_<numero",
">"
] | def nuevaClave(self):
"""
Crea una clave nueva de columna, en base a un modelo = CALC_<numero>
"""
liActual = [columna.clave for columna in self.liColumnas if columna.siFormula]
numero = 1
while True:
clave = "CALC_%d" % numero
if clave not in liActual:
return clave
numero += 1 | [
"def",
"nuevaClave",
"(",
"self",
")",
":",
"liActual",
"=",
"[",
"columna",
".",
"clave",
"for",
"columna",
"in",
"self",
".",
"liColumnas",
"if",
"columna",
".",
"siFormula",
"]",
"numero",
"=",
"1",
"while",
"True",
":",
"clave",
"=",
"\"CALC_%d\"",
... | https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/QT/Columnas.py#L294-L304 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/inline_closurecall.py | python | _inline_arraycall | (func_ir, cfg, visited, loop, swapped, enable_prange=False,
typed=False) | return True | Look for array(list) call in the exit block of a given loop, and turn list operations into
array operations in the loop if the following conditions are met:
1. The exit block contains an array call on the list;
2. The list variable is no longer live after array call;
3. The list is created in the loop entry block;
4. The loop is created from an range iterator whose length is known prior to the loop;
5. There is only one list_append operation on the list variable in the loop body;
6. The block that contains list_append dominates the loop head, which ensures list
length is the same as loop length;
If any condition check fails, no modification will be made to the incoming IR. | Look for array(list) call in the exit block of a given loop, and turn list operations into
array operations in the loop if the following conditions are met:
1. The exit block contains an array call on the list;
2. The list variable is no longer live after array call;
3. The list is created in the loop entry block;
4. The loop is created from an range iterator whose length is known prior to the loop;
5. There is only one list_append operation on the list variable in the loop body;
6. The block that contains list_append dominates the loop head, which ensures list
length is the same as loop length;
If any condition check fails, no modification will be made to the incoming IR. | [
"Look",
"for",
"array",
"(",
"list",
")",
"call",
"in",
"the",
"exit",
"block",
"of",
"a",
"given",
"loop",
"and",
"turn",
"list",
"operations",
"into",
"array",
"operations",
"in",
"the",
"loop",
"if",
"the",
"following",
"conditions",
"are",
"met",
":"... | def _inline_arraycall(func_ir, cfg, visited, loop, swapped, enable_prange=False,
typed=False):
"""Look for array(list) call in the exit block of a given loop, and turn list operations into
array operations in the loop if the following conditions are met:
1. The exit block contains an array call on the list;
2. The list variable is no longer live after array call;
3. The list is created in the loop entry block;
4. The loop is created from an range iterator whose length is known prior to the loop;
5. There is only one list_append operation on the list variable in the loop body;
6. The block that contains list_append dominates the loop head, which ensures list
length is the same as loop length;
If any condition check fails, no modification will be made to the incoming IR.
"""
debug_print = _make_debug_print("inline_arraycall")
# There should only be one loop exit
require(len(loop.exits) == 1)
exit_block = next(iter(loop.exits))
list_var, array_call_index, array_kws = _find_arraycall(func_ir, func_ir.blocks[exit_block])
# check if dtype is present in array call
dtype_def = None
dtype_mod_def = None
if 'dtype' in array_kws:
require(isinstance(array_kws['dtype'], ir.Var))
# We require that dtype argument to be a constant of getattr Expr, and we'll
# remember its definition for later use.
dtype_def = get_definition(func_ir, array_kws['dtype'])
require(isinstance(dtype_def, ir.Expr) and dtype_def.op == 'getattr')
dtype_mod_def = get_definition(func_ir, dtype_def.value)
list_var_def = get_definition(func_ir, list_var)
debug_print("list_var = ", list_var, " def = ", list_var_def)
if isinstance(list_var_def, ir.Expr) and list_var_def.op == 'cast':
list_var_def = get_definition(func_ir, list_var_def.value)
# Check if the definition is a build_list
require(isinstance(list_var_def, ir.Expr) and list_var_def.op == 'build_list')
# Look for list_append in "last" block in loop body, which should be a block that is
# a post-dominator of the loop header.
list_append_stmts = []
for label in loop.body:
# We have to consider blocks of this loop, but not sub-loops.
# To achieve this, we require the set of "in_loops" of "label" to be visited loops.
in_visited_loops = [l.header in visited for l in cfg.in_loops(label)]
if not all(in_visited_loops):
continue
block = func_ir.blocks[label]
debug_print("check loop body block ", label)
for stmt in block.find_insts(ir.Assign):
lhs = stmt.target
expr = stmt.value
if isinstance(expr, ir.Expr) and expr.op == 'call':
func_def = get_definition(func_ir, expr.func)
if isinstance(func_def, ir.Expr) and func_def.op == 'getattr' \
and func_def.attr == 'append':
list_def = get_definition(func_ir, func_def.value)
debug_print("list_def = ", list_def, list_def is list_var_def)
if list_def is list_var_def:
# found matching append call
list_append_stmts.append((label, block, stmt))
# Require only one list_append, otherwise we won't know the indices
require(len(list_append_stmts) == 1)
append_block_label, append_block, append_stmt = list_append_stmts[0]
# Check if append_block (besides loop entry) dominates loop header.
# Since CFG doesn't give us this info without loop entry, we approximate
# by checking if the predecessor set of the header block is the same
# as loop_entries plus append_block, which is certainly more restrictive
# than necessary, and can be relaxed if needed.
preds = set(l for l, b in cfg.predecessors(loop.header))
debug_print("preds = ", preds, (loop.entries | set([append_block_label])))
require(preds == (loop.entries | set([append_block_label])))
# Find iterator in loop header
iter_vars = []
iter_first_vars = []
loop_header = func_ir.blocks[loop.header]
for stmt in loop_header.find_insts(ir.Assign):
expr = stmt.value
if isinstance(expr, ir.Expr):
if expr.op == 'iternext':
iter_def = get_definition(func_ir, expr.value)
debug_print("iter_def = ", iter_def)
iter_vars.append(expr.value)
elif expr.op == 'pair_first':
iter_first_vars.append(stmt.target)
# Require only one iterator in loop header
require(len(iter_vars) == 1 and len(iter_first_vars) == 1)
iter_var = iter_vars[0] # variable that holds the iterator object
iter_first_var = iter_first_vars[0] # variable that holds the value out of iterator
# Final requirement: only one loop entry, and we're going to modify it by:
# 1. replacing the list definition with an array definition;
# 2. adding a counter for the array iteration.
require(len(loop.entries) == 1)
loop_entry = func_ir.blocks[next(iter(loop.entries))]
terminator = loop_entry.terminator
scope = loop_entry.scope
loc = loop_entry.loc
stmts = []
removed = []
def is_removed(val, removed):
if isinstance(val, ir.Var):
for x in removed:
if x.name == val.name:
return True
return False
# Skip list construction and skip terminator, add the rest to stmts
for i in range(len(loop_entry.body) - 1):
stmt = loop_entry.body[i]
if isinstance(stmt, ir.Assign) and (stmt.value is list_def or is_removed(stmt.value, removed)):
removed.append(stmt.target)
else:
stmts.append(stmt)
debug_print("removed variables: ", removed)
# Define an index_var to index the array.
# If the range happens to be single step ranges like range(n), or range(m, n),
# then the index_var correlates to iterator index; otherwise we'll have to
# define a new counter.
range_def = guard(_find_iter_range, func_ir, iter_var, swapped)
index_var = ir.Var(scope, mk_unique_var("index"), loc)
if range_def and range_def[0] == 0:
# iterator starts with 0, index_var can just be iter_first_var
index_var = iter_first_var
else:
# index_var = -1 # starting the index with -1 since it will incremented in loop header
stmts.append(_new_definition(func_ir, index_var, ir.Const(value=-1, loc=loc), loc))
# Insert statement to get the size of the loop iterator
size_var = ir.Var(scope, mk_unique_var("size"), loc)
if range_def:
start, stop, range_func_def = range_def
if start == 0:
size_val = stop
else:
size_val = ir.Expr.binop(fn=operator.sub, lhs=stop, rhs=start, loc=loc)
# we can parallelize this loop if enable_prange = True, by changing
# range function from range, to prange.
if enable_prange and isinstance(range_func_def, ir.Global):
range_func_def.name = 'internal_prange'
range_func_def.value = internal_prange
else:
# this doesn't work in objmode as it's effectively untyped
if typed:
len_func_var = ir.Var(scope, mk_unique_var("len_func"), loc)
stmts.append(_new_definition(func_ir, len_func_var,
ir.Global('range_iter_len', range_iter_len, loc=loc),
loc))
size_val = ir.Expr.call(len_func_var, (iter_var,), (), loc=loc)
else:
raise GuardException
stmts.append(_new_definition(func_ir, size_var, size_val, loc))
size_tuple_var = ir.Var(scope, mk_unique_var("size_tuple"), loc)
stmts.append(_new_definition(func_ir, size_tuple_var,
ir.Expr.build_tuple(items=[size_var], loc=loc), loc))
# Insert array allocation
array_var = ir.Var(scope, mk_unique_var("array"), loc)
empty_func = ir.Var(scope, mk_unique_var("empty_func"), loc)
if dtype_def and dtype_mod_def:
# when dtype is present, we'll call empty with dtype
dtype_mod_var = ir.Var(scope, mk_unique_var("dtype_mod"), loc)
dtype_var = ir.Var(scope, mk_unique_var("dtype"), loc)
stmts.append(_new_definition(func_ir, dtype_mod_var, dtype_mod_def, loc))
stmts.append(_new_definition(func_ir, dtype_var,
ir.Expr.getattr(dtype_mod_var, dtype_def.attr, loc), loc))
stmts.append(_new_definition(func_ir, empty_func,
ir.Global('empty', np.empty, loc=loc), loc))
array_kws = [('dtype', dtype_var)]
else:
# this doesn't work in objmode as it's effectively untyped
if typed:
# otherwise we'll call unsafe_empty_inferred
stmts.append(_new_definition(func_ir, empty_func,
ir.Global('unsafe_empty_inferred',
unsafe_empty_inferred, loc=loc), loc))
array_kws = []
else:
raise GuardException
# array_var = empty_func(size_tuple_var)
stmts.append(_new_definition(func_ir, array_var,
ir.Expr.call(empty_func, (size_tuple_var,), list(array_kws), loc=loc), loc))
# Add back removed just in case they are used by something else
for var in removed:
stmts.append(_new_definition(func_ir, var, array_var, loc))
# Add back terminator
stmts.append(terminator)
# Modify loop_entry
loop_entry.body = stmts
if range_def:
if range_def[0] != 0:
# when range doesn't start from 0, index_var becomes loop index
# (iter_first_var) minus an offset (range_def[0])
terminator = loop_header.terminator
assert(isinstance(terminator, ir.Branch))
# find the block in the loop body that header jumps to
block_id = terminator.truebr
blk = func_ir.blocks[block_id]
loc = blk.loc
blk.body.insert(0, _new_definition(func_ir, index_var,
ir.Expr.binop(fn=operator.sub, lhs=iter_first_var,
rhs=range_def[0], loc=loc),
loc))
else:
# Insert index_var increment to the end of loop header
loc = loop_header.loc
terminator = loop_header.terminator
stmts = loop_header.body[0:-1]
next_index_var = ir.Var(scope, mk_unique_var("next_index"), loc)
one = ir.Var(scope, mk_unique_var("one"), loc)
# one = 1
stmts.append(_new_definition(func_ir, one,
ir.Const(value=1,loc=loc), loc))
# next_index_var = index_var + 1
stmts.append(_new_definition(func_ir, next_index_var,
ir.Expr.binop(fn=operator.add, lhs=index_var, rhs=one, loc=loc), loc))
# index_var = next_index_var
stmts.append(_new_definition(func_ir, index_var, next_index_var, loc))
stmts.append(terminator)
loop_header.body = stmts
# In append_block, change list_append into array assign
for i in range(len(append_block.body)):
if append_block.body[i] is append_stmt:
debug_print("Replace append with SetItem")
append_block.body[i] = ir.SetItem(target=array_var, index=index_var,
value=append_stmt.value.args[0], loc=append_stmt.loc)
# replace array call, by changing "a = array(b)" to "a = b"
stmt = func_ir.blocks[exit_block].body[array_call_index]
# stmt can be either array call or SetItem, we only replace array call
if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr):
stmt.value = array_var
func_ir._definitions[stmt.target.name] = [stmt.value]
return True | [
"def",
"_inline_arraycall",
"(",
"func_ir",
",",
"cfg",
",",
"visited",
",",
"loop",
",",
"swapped",
",",
"enable_prange",
"=",
"False",
",",
"typed",
"=",
"False",
")",
":",
"debug_print",
"=",
"_make_debug_print",
"(",
"\"inline_arraycall\"",
")",
"# There s... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/inline_closurecall.py#L636-L882 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol_doc.py | python | SymbolDoc.get_output_shape | (sym, **input_shapes) | return dict(zip(sym.list_outputs(), s_outputs)) | Get user friendly information of the output shapes. | Get user friendly information of the output shapes. | [
"Get",
"user",
"friendly",
"information",
"of",
"the",
"output",
"shapes",
"."
] | def get_output_shape(sym, **input_shapes):
"""Get user friendly information of the output shapes."""
_, s_outputs, _ = sym.infer_shape(**input_shapes)
return dict(zip(sym.list_outputs(), s_outputs)) | [
"def",
"get_output_shape",
"(",
"sym",
",",
"*",
"*",
"input_shapes",
")",
":",
"_",
",",
"s_outputs",
",",
"_",
"=",
"sym",
".",
"infer_shape",
"(",
"*",
"*",
"input_shapes",
")",
"return",
"dict",
"(",
"zip",
"(",
"sym",
".",
"list_outputs",
"(",
"... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol_doc.py#L56-L59 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/parallel/distributed.py | python | DistributedDataParallel._set_static_graph | (self) | It is recommended to set static graph in the DDP constructor, which will
call this private API internally. | It is recommended to set static graph in the DDP constructor, which will
call this private API internally. | [
"It",
"is",
"recommended",
"to",
"set",
"static",
"graph",
"in",
"the",
"DDP",
"constructor",
"which",
"will",
"call",
"this",
"private",
"API",
"internally",
"."
] | def _set_static_graph(self):
"""
It is recommended to set static graph in the DDP constructor, which will
call this private API internally.
"""
# If self.static_graph has been set, no need to set it again
if self.static_graph:
warnings.warn(
"You've set static_graph to be True, no need to set it again."
)
return
self.static_graph = True
self.reducer._set_static_graph()
self.logger._set_static_graph()
if self.find_unused_parameters:
warnings.warn(
"You passed find_unused_parameters=true to DistributedDataParallel, "
"`_set_static_graph` will detect unused parameters automatically, so "
"you do not need to set find_unused_parameters=true, just be sure these "
"unused parameters will not change during training loop while calling "
"`_set_static_graph`."
) | [
"def",
"_set_static_graph",
"(",
"self",
")",
":",
"# If self.static_graph has been set, no need to set it again",
"if",
"self",
".",
"static_graph",
":",
"warnings",
".",
"warn",
"(",
"\"You've set static_graph to be True, no need to set it again.\"",
")",
"return",
"self",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/parallel/distributed.py#L1738-L1759 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/toolkits/_model.py | python | Model._get_wrapper | (self) | Return a lambda function: UnityModel -> M, for constructing model
class M from a UnityModel proxy. | Return a lambda function: UnityModel -> M, for constructing model
class M from a UnityModel proxy. | [
"Return",
"a",
"lambda",
"function",
":",
"UnityModel",
"-",
">",
"M",
"for",
"constructing",
"model",
"class",
"M",
"from",
"a",
"UnityModel",
"proxy",
"."
] | def _get_wrapper(self):
"""Return a lambda function: UnityModel -> M, for constructing model
class M from a UnityModel proxy."""
raise NotImplementedError | [
"def",
"_get_wrapper",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/toolkits/_model.py#L544-L547 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/calendar.py | python | CalendarCtrlBase.SetDate | (*args, **kwargs) | return _calendar.CalendarCtrlBase_SetDate(*args, **kwargs) | SetDate(self, DateTime date) -> bool
Sets the current date. | SetDate(self, DateTime date) -> bool | [
"SetDate",
"(",
"self",
"DateTime",
"date",
")",
"-",
">",
"bool"
] | def SetDate(*args, **kwargs):
"""
SetDate(self, DateTime date) -> bool
Sets the current date.
"""
return _calendar.CalendarCtrlBase_SetDate(*args, **kwargs) | [
"def",
"SetDate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarCtrlBase_SetDate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/calendar.py#L269-L275 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/rbd_support/module.py | python | Module.task_add_trash_remove | (self, image_id_spec: str) | Remove an image from the trash asynchronously in the background | Remove an image from the trash asynchronously in the background | [
"Remove",
"an",
"image",
"from",
"the",
"trash",
"asynchronously",
"in",
"the",
"background"
] | def task_add_trash_remove(self, image_id_spec: str) -> Tuple[int, str, str]:
"""
Remove an image from the trash asynchronously in the background
"""
with self.task.lock:
return self.task.queue_trash_remove(image_id_spec) | [
"def",
"task_add_trash_remove",
"(",
"self",
",",
"image_id_spec",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
",",
"str",
"]",
":",
"with",
"self",
".",
"task",
".",
"lock",
":",
"return",
"self",
".",
"task",
".",
"queue_trash_remove",
"(... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/rbd_support/module.py#L172-L177 | ||
jeog/TDAmeritradeAPI | 91c738afd7d57b54f6231170bd64c2550fafd34d | python/tdma_api/execute.py | python | OrderTicket.add_child | (self, child) | return self | Add child order (class OrderTicket) to order. Returns self. | Add child order (class OrderTicket) to order. Returns self. | [
"Add",
"child",
"order",
"(",
"class",
"OrderTicket",
")",
"to",
"order",
".",
"Returns",
"self",
"."
] | def add_child(self, child):
"""Add child order (class OrderTicket) to order. Returns self."""
self._check_objects(OrderTicket, (child,))
clib.call('OrderTicket_AddChild_ABI', _REF(self._obj),
_REF(child._obj))
return self | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"self",
".",
"_check_objects",
"(",
"OrderTicket",
",",
"(",
"child",
",",
")",
")",
"clib",
".",
"call",
"(",
"'OrderTicket_AddChild_ABI'",
",",
"_REF",
"(",
"self",
".",
"_obj",
")",
",",
"_REF... | https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/execute.py#L444-L449 | |
9miao/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | CursorKind.is_translation_unit | (self) | return conf.lib.clang_isTranslationUnit(self) | Test if this is a translation unit kind. | Test if this is a translation unit kind. | [
"Test",
"if",
"this",
"is",
"a",
"translation",
"unit",
"kind",
"."
] | def is_translation_unit(self):
"""Test if this is a translation unit kind."""
return conf.lib.clang_isTranslationUnit(self) | [
"def",
"is_translation_unit",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isTranslationUnit",
"(",
"self",
")"
] | https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L543-L545 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/util.py | python | module_for_loader | (fxn) | return module_for_loader_wrapper | Decorator to handle selecting the proper module for loaders.
The decorated function is passed the module to use instead of the module
name. The module passed in to the function is either from sys.modules if
it already exists or is a new module. If the module is new, then __name__
is set the first argument to the method, __loader__ is set to self, and
__package__ is set accordingly (if self.is_package() is defined) will be set
before it is passed to the decorated function (if self.is_package() does
not work for the module it will be set post-load).
If an exception is raised and the decorator created the module it is
subsequently removed from sys.modules.
The decorator assumes that the decorated function takes the module name as
the second argument. | Decorator to handle selecting the proper module for loaders. | [
"Decorator",
"to",
"handle",
"selecting",
"the",
"proper",
"module",
"for",
"loaders",
"."
] | def module_for_loader(fxn):
"""Decorator to handle selecting the proper module for loaders.
The decorated function is passed the module to use instead of the module
name. The module passed in to the function is either from sys.modules if
it already exists or is a new module. If the module is new, then __name__
is set the first argument to the method, __loader__ is set to self, and
__package__ is set accordingly (if self.is_package() is defined) will be set
before it is passed to the decorated function (if self.is_package() does
not work for the module it will be set post-load).
If an exception is raised and the decorator created the module it is
subsequently removed from sys.modules.
The decorator assumes that the decorated function takes the module name as
the second argument.
"""
warnings.warn('The import system now takes care of this automatically.',
DeprecationWarning, stacklevel=2)
@functools.wraps(fxn)
def module_for_loader_wrapper(self, fullname, *args, **kwargs):
with _module_to_load(fullname) as module:
module.__loader__ = self
try:
is_package = self.is_package(fullname)
except (ImportError, AttributeError):
pass
else:
if is_package:
module.__package__ = fullname
else:
module.__package__ = fullname.rpartition('.')[0]
# If __package__ was not set above, __import__() will do it later.
return fxn(self, module, *args, **kwargs)
return module_for_loader_wrapper | [
"def",
"module_for_loader",
"(",
"fxn",
")",
":",
"warnings",
".",
"warn",
"(",
"'The import system now takes care of this automatically.'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"@",
"functools",
".",
"wraps",
"(",
"fxn",
")",
"def",
"modul... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/util.py#L180-L216 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/gromacsgrofile.py | python | GromacsGroFile.__init__ | (self, file) | Load a .gro file.
The atom positions can be retrieved by calling getPositions().
Parameters
----------
file : string
the name of the file to load | Load a .gro file. | [
"Load",
"a",
".",
"gro",
"file",
"."
] | def __init__(self, file):
"""Load a .gro file.
The atom positions can be retrieved by calling getPositions().
Parameters
----------
file : string
the name of the file to load
"""
xyzs = []
elements = [] # The element, most useful for quantum chemistry calculations
atomname = [] # The atom name, for instance 'HW1'
comms = []
resid = []
resname = []
boxes = []
xyz = []
ln = 0
frame = 0
with open(file) as grofile:
for line in grofile:
if ln == 0:
comms.append(line.strip())
elif ln == 1:
na = int(line.strip())
elif _is_gro_coord(line):
if frame == 0: # Create the list of residues, atom names etc. only if it's the first frame.
(thisresnum, thisresname, thisatomname) = [line[i*5:i*5+5].strip() for i in range(3)]
resname.append(thisresname)
resid.append(int(thisresnum))
atomname.append(thisatomname)
thiselem = thisatomname
if len(thiselem) > 1:
thiselem = thiselem[0] + sub('[A-Z0-9]','',thiselem[1:])
try:
elements.append(elem.get_by_symbol(thiselem))
except KeyError:
elements.append(None)
firstDecimalPos = line.index('.', 20)
secondDecimalPos = line.index('.', firstDecimalPos+1)
digits = secondDecimalPos-firstDecimalPos
pos = [float(line[20+i*digits:20+(i+1)*digits]) for i in range(3)]
xyz.append(Vec3(pos[0], pos[1], pos[2]))
elif _is_gro_box(line) and ln == na + 2:
boxes.append(_construct_box_vectors(line))
xyzs.append(xyz*nanometers)
xyz = []
ln = -1
frame += 1
else:
raise Exception("Unexpected line in .gro file: "+line)
ln += 1
## The atom positions read from the file. If the file contains multiple frames, these are the positions in the first frame.
self.positions = xyzs[0]
## A list containing the element of each atom stored in the file
self.elements = elements
## A list containing the name of each atom stored in the file
self.atomNames = atomname
## A list containing the ID of the residue that each atom belongs to
self.residueIds = resid
## A list containing the name of the residue that each atom belongs to
self.residueNames = resname
self._positions = xyzs
self._periodicBoxVectors = boxes
self._numpyPositions = None | [
"def",
"__init__",
"(",
"self",
",",
"file",
")",
":",
"xyzs",
"=",
"[",
"]",
"elements",
"=",
"[",
"]",
"# The element, most useful for quantum chemistry calculations",
"atomname",
"=",
"[",
"]",
"# The atom name, for instance 'HW1'",
"comms",
"=",
"[",
"]",
"res... | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/gromacsgrofile.py#L114-L180 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/variables.py | python | Variable.name | (self) | return self._variable.name | The name of this variable. | The name of this variable. | [
"The",
"name",
"of",
"this",
"variable",
"."
] | def name(self):
"""The name of this variable."""
return self._variable.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_variable",
".",
"name"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/variables.py#L645-L647 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/framework/ops.py | python | Operation.run | (self, feed_dict=None, session=None) | Runs this operation in a `Session`.
Calling this method will execute all preceding operations that
produce the inputs needed for this operation.
*N.B.* Before invoking `Operation.run()`, its graph must have been
launched in a session, and either a default session must be
available, or `session` must be specified explicitly.
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
See @{tf.Session.run}
for a description of the valid feed values.
session: (Optional.) The `Session` to be used to run to this operation. If
none, the default session will be used. | Runs this operation in a `Session`. | [
"Runs",
"this",
"operation",
"in",
"a",
"Session",
"."
] | def run(self, feed_dict=None, session=None):
"""Runs this operation in a `Session`.
Calling this method will execute all preceding operations that
produce the inputs needed for this operation.
*N.B.* Before invoking `Operation.run()`, its graph must have been
launched in a session, and either a default session must be
available, or `session` must be specified explicitly.
Args:
feed_dict: A dictionary that maps `Tensor` objects to feed values.
See @{tf.Session.run}
for a description of the valid feed values.
session: (Optional.) The `Session` to be used to run to this operation. If
none, the default session will be used.
"""
_run_using_default_session(self, feed_dict, self.graph, session) | [
"def",
"run",
"(",
"self",
",",
"feed_dict",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"_run_using_default_session",
"(",
"self",
",",
"feed_dict",
",",
"self",
".",
"graph",
",",
"session",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L1727-L1744 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/multiarray.py | python | unravel_index | (indices, shape=None, order=None, dims=None) | return (indices,) | unravel_index(indices, shape, order='C')
Converts a flat index or array of flat indices into a tuple
of coordinate arrays.
Parameters
----------
indices : array_like
An integer array whose elements are indices into the flattened
version of an array of dimensions ``shape``. Before version 1.6.0,
this function accepted just one index value.
shape : tuple of ints
The shape of the array to use for unraveling ``indices``.
.. versionchanged:: 1.16.0
Renamed from ``dims`` to ``shape``.
order : {'C', 'F'}, optional
Determines whether the indices should be viewed as indexing in
row-major (C-style) or column-major (Fortran-style) order.
.. versionadded:: 1.6.0
Returns
-------
unraveled_coords : tuple of ndarray
Each array in the tuple has the same shape as the ``indices``
array.
See Also
--------
ravel_multi_index
Examples
--------
>>> np.unravel_index([22, 41, 37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index([31, 41, 13], (7,6), order='F')
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index(1621, (6,7,8,9))
(3, 1, 4, 1) | unravel_index(indices, shape, order='C') | [
"unravel_index",
"(",
"indices",
"shape",
"order",
"=",
"C",
")"
] | def unravel_index(indices, shape=None, order=None, dims=None):
"""
unravel_index(indices, shape, order='C')
Converts a flat index or array of flat indices into a tuple
of coordinate arrays.
Parameters
----------
indices : array_like
An integer array whose elements are indices into the flattened
version of an array of dimensions ``shape``. Before version 1.6.0,
this function accepted just one index value.
shape : tuple of ints
The shape of the array to use for unraveling ``indices``.
.. versionchanged:: 1.16.0
Renamed from ``dims`` to ``shape``.
order : {'C', 'F'}, optional
Determines whether the indices should be viewed as indexing in
row-major (C-style) or column-major (Fortran-style) order.
.. versionadded:: 1.6.0
Returns
-------
unraveled_coords : tuple of ndarray
Each array in the tuple has the same shape as the ``indices``
array.
See Also
--------
ravel_multi_index
Examples
--------
>>> np.unravel_index([22, 41, 37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index([31, 41, 13], (7,6), order='F')
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index(1621, (6,7,8,9))
(3, 1, 4, 1)
"""
if dims is not None:
warnings.warn("'shape' argument should be used instead of 'dims'",
DeprecationWarning, stacklevel=3)
return (indices,) | [
"def",
"unravel_index",
"(",
"indices",
",",
"shape",
"=",
"None",
",",
"order",
"=",
"None",
",",
"dims",
"=",
"None",
")",
":",
"if",
"dims",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"'shape' argument should be used instead of 'dims'\"",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/multiarray.py#L991-L1040 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py | python | ValueRef.add_function_attribute | (self, attr) | Only works on function value
Parameters
-----------
attr : str
attribute name | Only works on function value | [
"Only",
"works",
"on",
"function",
"value"
] | def add_function_attribute(self, attr):
"""Only works on function value
Parameters
-----------
attr : str
attribute name
"""
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
attrname = str(attr)
attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName(
_encode_string(attrname), len(attrname))
if attrval == 0:
raise ValueError('no such attribute {!r}'.format(attrname))
ffi.lib.LLVMPY_AddFunctionAttr(self, attrval) | [
"def",
"add_function_attribute",
"(",
"self",
",",
"attr",
")",
":",
"if",
"not",
"self",
".",
"is_function",
":",
"raise",
"ValueError",
"(",
"'expected function value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"attrname",
"=",
"str",
"(",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/value.py#L181-L196 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/egt/utils.py | python | grid_simplex | (step=.1, boundary=False) | Generator for regular 'lattice' on the 2-simplex.
Args:
step: Defines spacing along one dimension.
boundary: Include points on the boundary/face of the simplex.
Yields:
Next point on the grid. | Generator for regular 'lattice' on the 2-simplex. | [
"Generator",
"for",
"regular",
"lattice",
"on",
"the",
"2",
"-",
"simplex",
"."
] | def grid_simplex(step=.1, boundary=False):
"""Generator for regular 'lattice' on the 2-simplex.
Args:
step: Defines spacing along one dimension.
boundary: Include points on the boundary/face of the simplex.
Yields:
Next point on the grid.
"""
eps = 1e-8
start = 0. if boundary else step
stop = 1. + eps if boundary else 1. - step + eps
for a in np.arange(start, stop, step, dtype=np.double):
for b in np.arange(start, stop - a, step, dtype=np.double):
yield [a, b, 1. - a - b] | [
"def",
"grid_simplex",
"(",
"step",
"=",
".1",
",",
"boundary",
"=",
"False",
")",
":",
"eps",
"=",
"1e-8",
"start",
"=",
"0.",
"if",
"boundary",
"else",
"step",
"stop",
"=",
"1.",
"+",
"eps",
"if",
"boundary",
"else",
"1.",
"-",
"step",
"+",
"eps"... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/egt/utils.py#L35-L50 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/javac.py | python | generate | (env) | Add Builders and construction variables for javac to an Environment. | Add Builders and construction variables for javac to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"javac",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for javac to an Environment."""
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_class = SCons.Tool.CreateJavaClassFileBuilder(env)
java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env)
java_class.add_emitter(None, emit_java_classes)
java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes)
java_class_dir.emitter = emit_java_classes
env.AddMethod(Java)
env['JAVAC'] = 'javac'
env['JAVACFLAGS'] = SCons.Util.CLVar('')
env['JAVABOOTCLASSPATH'] = []
env['JAVACLASSPATH'] = []
env['JAVASOURCEPATH'] = []
env['_javapathopt'] = pathopt
env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} '
env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} '
env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} '
env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}'
env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES'
env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}"
env['JAVACLASSSUFFIX'] = '.class'
env['JAVASUFFIX'] = '.java' | [
"def",
"generate",
"(",
"env",
")",
":",
"java_file",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaFileBuilder",
"(",
"env",
")",
"java_class",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaClassFileBuilder",
"(",
"env",
")",
"java_class_dir",
"=",
"SCons",
".",
... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/javac.py#L199-L223 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/validators.py | python | check_penn_treebank_dataset | (method) | return new_method | A wrapper that wraps a parameter checker around the original Dataset(PennTreebankDataset). | A wrapper that wraps a parameter checker around the original Dataset(PennTreebankDataset). | [
"A",
"wrapper",
"that",
"wraps",
"a",
"parameter",
"checker",
"around",
"the",
"original",
"Dataset",
"(",
"PennTreebankDataset",
")",
"."
] | def check_penn_treebank_dataset(method):
"""A wrapper that wraps a parameter checker around the original Dataset(PennTreebankDataset)."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id']
# check dataset_dir; required argument
dataset_dir = param_dict.get('dataset_dir')
check_dir(dataset_dir)
# check usage
usage = param_dict.get('usage')
if usage is not None:
check_valid_str(usage, ["train", "valid", "test", "all"], "usage")
validate_dataset_param_value(nreq_param_int, param_dict, int)
check_sampler_shuffle_shard_options(param_dict)
cache = param_dict.get('cache')
check_cache_option(cache)
return method(self, *args, **kwargs)
return new_method | [
"def",
"check_penn_treebank_dataset",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
",",
"param_dict",
"=",
"parse_user_args",
"(",
"method",
",",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1486-L1512 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pickletools.py | python | dis | (pickle, out=None, memo=None, indentlevel=4) | Produce a symbolic disassembly of a pickle.
'pickle' is a file-like object, or string, containing a (at least one)
pickle. The pickle is disassembled from the current position, through
the first STOP opcode encountered.
Optional arg 'out' is a file-like object to which the disassembly is
printed. It defaults to sys.stdout.
Optional arg 'memo' is a Python dict, used as the pickle's memo. It
may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
Passing the same memo object to another dis() call then allows disassembly
to proceed across multiple pickles that were all created by the same
pickler with the same memo. Ordinarily you don't need to worry about this.
Optional arg indentlevel is the number of blanks by which to indent
a new MARK level. It defaults to 4.
In addition to printing the disassembly, some sanity checks are made:
+ All embedded opcode arguments "make sense".
+ Explicit and implicit pop operations have enough items on the stack.
+ When an opcode implicitly refers to a markobject, a markobject is
actually on the stack.
+ A memo entry isn't referenced before it's defined.
+ The markobject isn't stored in the memo.
+ A memo entry isn't redefined. | Produce a symbolic disassembly of a pickle. | [
"Produce",
"a",
"symbolic",
"disassembly",
"of",
"a",
"pickle",
"."
] | def dis(pickle, out=None, memo=None, indentlevel=4):
"""Produce a symbolic disassembly of a pickle.
'pickle' is a file-like object, or string, containing a (at least one)
pickle. The pickle is disassembled from the current position, through
the first STOP opcode encountered.
Optional arg 'out' is a file-like object to which the disassembly is
printed. It defaults to sys.stdout.
Optional arg 'memo' is a Python dict, used as the pickle's memo. It
may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
Passing the same memo object to another dis() call then allows disassembly
to proceed across multiple pickles that were all created by the same
pickler with the same memo. Ordinarily you don't need to worry about this.
Optional arg indentlevel is the number of blanks by which to indent
a new MARK level. It defaults to 4.
In addition to printing the disassembly, some sanity checks are made:
+ All embedded opcode arguments "make sense".
+ Explicit and implicit pop operations have enough items on the stack.
+ When an opcode implicitly refers to a markobject, a markobject is
actually on the stack.
+ A memo entry isn't referenced before it's defined.
+ The markobject isn't stored in the memo.
+ A memo entry isn't redefined.
"""
# Most of the hair here is for sanity checks, but most of it is needed
# anyway to detect when a protocol 0 POP takes a MARK off the stack
# (which in turn is needed to indent MARK blocks correctly).
stack = [] # crude emulation of unpickler stack
if memo is None:
memo = {} # crude emulation of unpicker memo
maxproto = -1 # max protocol number seen
markstack = [] # bytecode positions of MARK opcodes
indentchunk = ' ' * indentlevel
errormsg = None
for opcode, arg, pos in genops(pickle):
if pos is not None:
print >> out, "%5d:" % pos,
line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
indentchunk * len(markstack),
opcode.name)
maxproto = max(maxproto, opcode.proto)
before = opcode.stack_before # don't mutate
after = opcode.stack_after # don't mutate
numtopop = len(before)
# See whether a MARK should be popped.
markmsg = None
if markobject in before or (opcode.name == "POP" and
stack and
stack[-1] is markobject):
assert markobject not in after
if __debug__:
if markobject in before:
assert before[-1] is stackslice
if markstack:
markpos = markstack.pop()
if markpos is None:
markmsg = "(MARK at unknown opcode offset)"
else:
markmsg = "(MARK at %d)" % markpos
# Pop everything at and after the topmost markobject.
while stack[-1] is not markobject:
stack.pop()
stack.pop()
# Stop later code from popping too much.
try:
numtopop = before.index(markobject)
except ValueError:
assert opcode.name == "POP"
numtopop = 0
else:
errormsg = markmsg = "no MARK exists on stack"
# Check for correct memo usage.
if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
assert arg is not None
if arg in memo:
errormsg = "memo key %r already defined" % arg
elif not stack:
errormsg = "stack is empty -- can't store into memo"
elif stack[-1] is markobject:
errormsg = "can't store markobject in the memo"
else:
memo[arg] = stack[-1]
elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
if arg in memo:
assert len(after) == 1
after = [memo[arg]] # for better stack emulation
else:
errormsg = "memo key %r has never been stored into" % arg
if arg is not None or markmsg:
# make a mild effort to align arguments
line += ' ' * (10 - len(opcode.name))
if arg is not None:
line += ' ' + repr(arg)
if markmsg:
line += ' ' + markmsg
print >> out, line
if errormsg:
# Note that we delayed complaining until the offending opcode
# was printed.
raise ValueError(errormsg)
# Emulate the stack effects.
if len(stack) < numtopop:
raise ValueError("tries to pop %d items from stack with "
"only %d items" % (numtopop, len(stack)))
if numtopop:
del stack[-numtopop:]
if markobject in after:
assert markobject not in before
markstack.append(pos)
stack.extend(after)
print >> out, "highest protocol among opcodes =", maxproto
if stack:
raise ValueError("stack not empty after STOP: %r" % stack) | [
"def",
"dis",
"(",
"pickle",
",",
"out",
"=",
"None",
",",
"memo",
"=",
"None",
",",
"indentlevel",
"=",
"4",
")",
":",
"# Most of the hair here is for sanity checks, but most of it is needed",
"# anyway to detect when a protocol 0 POP takes a MARK off the stack",
"# (which i... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pickletools.py#L1891-L2025 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/magic.py | python | MagicsManager.register | (self, *magic_objects) | Register one or more instances of Magics.
Take one or more classes or instances of classes that subclass the main
`core.Magic` class, and register them with IPython to use the magic
functions they provide. The registration process will then ensure that
any methods that have decorated to provide line and/or cell magics will
be recognized with the `%x`/`%%x` syntax as a line/cell magic
respectively.
If classes are given, they will be instantiated with the default
constructor. If your classes need a custom constructor, you should
instanitate them first and pass the instance.
The provided arguments can be an arbitrary mix of classes and instances.
Parameters
----------
magic_objects : one or more classes or instances | Register one or more instances of Magics. | [
"Register",
"one",
"or",
"more",
"instances",
"of",
"Magics",
"."
] | def register(self, *magic_objects):
"""Register one or more instances of Magics.
Take one or more classes or instances of classes that subclass the main
`core.Magic` class, and register them with IPython to use the magic
functions they provide. The registration process will then ensure that
any methods that have decorated to provide line and/or cell magics will
be recognized with the `%x`/`%%x` syntax as a line/cell magic
respectively.
If classes are given, they will be instantiated with the default
constructor. If your classes need a custom constructor, you should
instanitate them first and pass the instance.
The provided arguments can be an arbitrary mix of classes and instances.
Parameters
----------
magic_objects : one or more classes or instances
"""
# Start by validating them to ensure they have all had their magic
# methods registered at the instance level
for m in magic_objects:
if not m.registered:
raise ValueError("Class of magics %r was constructed without "
"the @register_magics class decorator")
if isinstance(m, type):
# If we're given an uninstantiated class
m = m(shell=self.shell)
# Now that we have an instance, we can register it and update the
# table of callables
self.registry[m.__class__.__name__] = m
for mtype in magic_kinds:
self.magics[mtype].update(m.magics[mtype]) | [
"def",
"register",
"(",
"self",
",",
"*",
"magic_objects",
")",
":",
"# Start by validating them to ensure they have all had their magic",
"# methods registered at the instance level",
"for",
"m",
"in",
"magic_objects",
":",
"if",
"not",
"m",
".",
"registered",
":",
"rais... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/magic.py#L359-L393 | ||
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | scripts/plot_multiple_learning_curves.py | python | initialize_plot | (title) | Initializes the plotting canvas for plotting the learning curves.
Input:
title: Title of the plot | Initializes the plotting canvas for plotting the learning curves. | [
"Initializes",
"the",
"plotting",
"canvas",
"for",
"plotting",
"the",
"learning",
"curves",
"."
] | def initialize_plot(title):
"""
Initializes the plotting canvas for plotting the learning curves.
Input:
title: Title of the plot
"""
# Equal error rate line
plt.grid()
plt.xlabel('iteration')
plt.ylabel('loss')
plt.title(title) | [
"def",
"initialize_plot",
"(",
"title",
")",
":",
"# Equal error rate line",
"plt",
".",
"grid",
"(",
")",
"plt",
".",
"xlabel",
"(",
"'iteration'",
")",
"plt",
".",
"ylabel",
"(",
"'loss'",
")",
"plt",
".",
"title",
"(",
"title",
")"
] | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/plot_multiple_learning_curves.py#L70-L82 | ||
stitchEm/stitchEm | 0f399501d41ab77933677f2907f41f80ceb704d7 | lib/doc/doxy2swig/doxy2swig.py | python | Doxy2SWIG.parse_Comment | (self, node) | return | Parse a `COMMENT_NODE`. This does nothing for now. | Parse a `COMMENT_NODE`. This does nothing for now. | [
"Parse",
"a",
"COMMENT_NODE",
".",
"This",
"does",
"nothing",
"for",
"now",
"."
] | def parse_Comment(self, node):
"""Parse a `COMMENT_NODE`. This does nothing for now."""
return | [
"def",
"parse_Comment",
"(",
"self",
",",
"node",
")",
":",
"return"
] | https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/doc/doxy2swig/doxy2swig.py#L198-L200 | |
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/internal/encoder.py | python | _ModifiedEncoder | (wire_type, encode_value, compute_value_size, modify_value) | return SpecificEncoder | Like SimpleEncoder but additionally invokes modify_value on every value
before passing it to encode_value. Usually modify_value is ZigZagEncode. | Like SimpleEncoder but additionally invokes modify_value on every value
before passing it to encode_value. Usually modify_value is ZigZagEncode. | [
"Like",
"SimpleEncoder",
"but",
"additionally",
"invokes",
"modify_value",
"on",
"every",
"value",
"before",
"passing",
"it",
"to",
"encode_value",
".",
"Usually",
"modify_value",
"is",
"ZigZagEncode",
"."
] | def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value):
"""Like SimpleEncoder but additionally invokes modify_value on every value
before passing it to encode_value. Usually modify_value is ZigZagEncode."""
def SpecificEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
size = 0
for element in value:
size += compute_value_size(modify_value(element))
local_EncodeVarint(write, size)
for element in value:
encode_value(write, modify_value(element))
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
encode_value(write, modify_value(element))
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
return encode_value(write, modify_value(value))
return EncodeField
return SpecificEncoder | [
"def",
"_ModifiedEncoder",
"(",
"wire_type",
",",
"encode_value",
",",
"compute_value_size",
",",
"modify_value",
")",
":",
"def",
"SpecificEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"if",
"is_packed",
":",
"tag_bytes",
"=",
"... | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/encoder.py#L448-L479 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | LanguageInfo.GetLocaleName | (*args, **kwargs) | return _gdi_.LanguageInfo_GetLocaleName(*args, **kwargs) | GetLocaleName(self) -> String | GetLocaleName(self) -> String | [
"GetLocaleName",
"(",
"self",
")",
"-",
">",
"String"
] | def GetLocaleName(*args, **kwargs):
"""GetLocaleName(self) -> String"""
return _gdi_.LanguageInfo_GetLocaleName(*args, **kwargs) | [
"def",
"GetLocaleName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"LanguageInfo_GetLocaleName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L2945-L2947 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_tensor_shape.py | python | RaggedTensorDynamicShape.from_tensor | (cls, rt_input, dim_size_dtype=None) | Constructs a ragged shape for a potentially ragged tensor. | Constructs a ragged shape for a potentially ragged tensor. | [
"Constructs",
"a",
"ragged",
"shape",
"for",
"a",
"potentially",
"ragged",
"tensor",
"."
] | def from_tensor(cls, rt_input, dim_size_dtype=None):
"""Constructs a ragged shape for a potentially ragged tensor."""
with ops.name_scope(None, 'RaggedTensorDynamicShapeFromTensor', [rt_input]):
rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt_input)
if not ragged_tensor.is_ragged(rt_input):
return cls([], array_ops.shape(rt_input))
else:
partitioned_dim_sizes = (
(rt_input.nrows(),) + rt_input.nested_row_lengths())
return RaggedTensorDynamicShape(
partitioned_dim_sizes,
array_ops.shape(rt_input.flat_values)[1:],
dim_size_dtype=dim_size_dtype) | [
"def",
"from_tensor",
"(",
"cls",
",",
"rt_input",
",",
"dim_size_dtype",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"'RaggedTensorDynamicShapeFromTensor'",
",",
"[",
"rt_input",
"]",
")",
":",
"rt_input",
"=",
"ragged_tensor",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_tensor_shape.py#L181-L193 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imputil.py | python | ImportManager.install | (self, namespace=vars(__builtin__)) | Install this ImportManager into the specified namespace. | Install this ImportManager into the specified namespace. | [
"Install",
"this",
"ImportManager",
"into",
"the",
"specified",
"namespace",
"."
] | def install(self, namespace=vars(__builtin__)):
"Install this ImportManager into the specified namespace."
if isinstance(namespace, _ModuleType):
namespace = vars(namespace)
# Note: we have no notion of "chaining"
# Record the previous import hook, then install our own.
self.previous_importer = namespace['__import__']
self.namespace = namespace
namespace['__import__'] = self._import_hook | [
"def",
"install",
"(",
"self",
",",
"namespace",
"=",
"vars",
"(",
"__builtin__",
")",
")",
":",
"if",
"isinstance",
"(",
"namespace",
",",
"_ModuleType",
")",
":",
"namespace",
"=",
"vars",
"(",
"namespace",
")",
"# Note: we have no notion of \"chaining\"",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imputil.py#L33-L44 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/grokdump.py | python | InspectionShell.do_do | (self, address) | Interpret memory at the given address as a V8 object. Automatic
alignment makes sure that you can pass tagged as well as un-tagged
addresses. | Interpret memory at the given address as a V8 object. Automatic
alignment makes sure that you can pass tagged as well as un-tagged
addresses. | [
"Interpret",
"memory",
"at",
"the",
"given",
"address",
"as",
"a",
"V8",
"object",
".",
"Automatic",
"alignment",
"makes",
"sure",
"that",
"you",
"can",
"pass",
"tagged",
"as",
"well",
"as",
"un",
"-",
"tagged",
"addresses",
"."
] | def do_do(self, address):
"""
Interpret memory at the given address as a V8 object. Automatic
alignment makes sure that you can pass tagged as well as un-tagged
addresses.
"""
address = int(address, 16)
if (address & self.heap.ObjectAlignmentMask()) == 0:
address = address + 1
elif (address & self.heap.ObjectAlignmentMask()) != 1:
print "Address doesn't look like a valid pointer!"
return
heap_object = self.padawan.SenseObject(address)
if heap_object:
heap_object.Print(Printer())
else:
print "Address cannot be interpreted as object!" | [
"def",
"do_do",
"(",
"self",
",",
"address",
")",
":",
"address",
"=",
"int",
"(",
"address",
",",
"16",
")",
"if",
"(",
"address",
"&",
"self",
".",
"heap",
".",
"ObjectAlignmentMask",
"(",
")",
")",
"==",
"0",
":",
"address",
"=",
"address",
"+",... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/grokdump.py#L2938-L2954 | ||
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | scripts/cpp_lint.py | python | CheckCaffeAlternatives | (filename, clean_lines, linenum, error) | Checks for C(++) functions for which a Caffe substitute should be used.
For certain native C functions (memset, memcpy), there is a Caffe alternative
which should be used instead.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for C(++) functions for which a Caffe substitute should be used. | [
"Checks",
"for",
"C",
"(",
"++",
")",
"functions",
"for",
"which",
"a",
"Caffe",
"substitute",
"should",
"be",
"used",
"."
] | def CheckCaffeAlternatives(filename, clean_lines, linenum, error):
"""Checks for C(++) functions for which a Caffe substitute should be used.
For certain native C functions (memset, memcpy), there is a Caffe alternative
which should be used instead.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function, alts in caffe_alt_function_list:
ix = line.find(function + '(')
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
disp_alts = ['%s(...)' % alt for alt in alts]
error(filename, linenum, 'caffe/alt_fn', 2,
'Use Caffe function %s instead of %s(...).' %
(' or '.join(disp_alts), function)) | [
"def",
"CheckCaffeAlternatives",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"function",
",",
"alts",
"in",
"caffe_alt_function_list",
":",
"ix",
"=",
"li... | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L1572-L1592 | ||
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/chull.py | python | Hull.VolumeSign | (f,p) | return 0 | VolumeSign returns the sign of the volume of the tetrahedron determined by f
and p. VolumeSign is +1 iff p is on the negative side of f,
where the positive side is determined by the rh-rule. So the volume
is positive if the ccw normal to f points outside the tetrahedron.
The final fewer-multiplications form is due to Bob Williamson.
This implementation differs from the one in the book in that it does not assume that
coordinates are integers. | VolumeSign returns the sign of the volume of the tetrahedron determined by f
and p. VolumeSign is +1 iff p is on the negative side of f,
where the positive side is determined by the rh-rule. So the volume
is positive if the ccw normal to f points outside the tetrahedron.
The final fewer-multiplications form is due to Bob Williamson.
This implementation differs from the one in the book in that it does not assume that
coordinates are integers. | [
"VolumeSign",
"returns",
"the",
"sign",
"of",
"the",
"volume",
"of",
"the",
"tetrahedron",
"determined",
"by",
"f",
"and",
"p",
".",
"VolumeSign",
"is",
"+",
"1",
"iff",
"p",
"is",
"on",
"the",
"negative",
"side",
"of",
"f",
"where",
"the",
"positive",
... | def VolumeSign(f,p):
"""
VolumeSign returns the sign of the volume of the tetrahedron determined by f
and p. VolumeSign is +1 iff p is on the negative side of f,
where the positive side is determined by the rh-rule. So the volume
is positive if the ccw normal to f points outside the tetrahedron.
The final fewer-multiplications form is due to Bob Williamson.
This implementation differs from the one in the book in that it does not assume that
coordinates are integers.
"""
a=f.vertex[0].v - p.v
b=f.vertex[1].v - p.v
c=f.vertex[2].v - p.v
vol = ( a.x * (b.y*c.z - b.z*c.y)
+ a.y * (b.z*c.x - b.x*c.z)
+ a.z * (b.x*c.y - b.y*c.x) )
# If the volume should be an integer, make epsilon 0.5
epsilon = 1e-10
if vol > epsilon: return 1
if vol < -epsilon: return -1
return 0 | [
"def",
"VolumeSign",
"(",
"f",
",",
"p",
")",
":",
"a",
"=",
"f",
".",
"vertex",
"[",
"0",
"]",
".",
"v",
"-",
"p",
".",
"v",
"b",
"=",
"f",
".",
"vertex",
"[",
"1",
"]",
".",
"v",
"-",
"p",
".",
"v",
"c",
"=",
"f",
".",
"vertex",
"["... | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/chull.py#L225-L248 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Scrollbar.delta | (self, deltax, deltay) | return self.tk.getdouble(
self.tk.call(self._w, 'delta', deltax, deltay)) | Return the fractional change of the scrollbar setting if it
would be moved by DELTAX or DELTAY pixels. | Return the fractional change of the scrollbar setting if it
would be moved by DELTAX or DELTAY pixels. | [
"Return",
"the",
"fractional",
"change",
"of",
"the",
"scrollbar",
"setting",
"if",
"it",
"would",
"be",
"moved",
"by",
"DELTAX",
"or",
"DELTAY",
"pixels",
"."
] | def delta(self, deltax, deltay):
"""Return the fractional change of the scrollbar setting if it
would be moved by DELTAX or DELTAY pixels."""
return self.tk.getdouble(
self.tk.call(self._w, 'delta', deltax, deltay)) | [
"def",
"delta",
"(",
"self",
",",
"deltax",
",",
"deltay",
")",
":",
"return",
"self",
".",
"tk",
".",
"getdouble",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'delta'",
",",
"deltax",
",",
"deltay",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3052-L3056 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_strptime.py | python | TimeRE.__seqToRE | (self, to_convert, directive) | return '%s)' % regex | Convert a list to a regex string for matching a directive.
Want possible matching values to be from longest to shortest. This
prevents the possibility of a match occuring for a value that also
a substring of a larger value that should have matched (e.g., 'abc'
matching when 'abcdef' should have been the match). | Convert a list to a regex string for matching a directive. | [
"Convert",
"a",
"list",
"to",
"a",
"regex",
"string",
"for",
"matching",
"a",
"directive",
"."
] | def __seqToRE(self, to_convert, directive):
"""Convert a list to a regex string for matching a directive.
Want possible matching values to be from longest to shortest. This
prevents the possibility of a match occuring for a value that also
a substring of a larger value that should have matched (e.g., 'abc'
matching when 'abcdef' should have been the match).
"""
to_convert = sorted(to_convert, key=len, reverse=True)
for value in to_convert:
if value != '':
break
else:
return ''
regex = '|'.join(re_escape(stuff) for stuff in to_convert)
regex = '(?P<%s>%s' % (directive, regex)
return '%s)' % regex | [
"def",
"__seqToRE",
"(",
"self",
",",
"to_convert",
",",
"directive",
")",
":",
"to_convert",
"=",
"sorted",
"(",
"to_convert",
",",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"for",
"value",
"in",
"to_convert",
":",
"if",
"value",
"!=",
"''"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_strptime.py#L221-L238 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap_external.py | python | _validate_timestamp_pyc | (data, source_mtime, source_size, name,
exc_details) | Validate a pyc against the source last-modified time.
*data* is the contents of the pyc file. (Only the first 16 bytes are
required.)
*source_mtime* is the last modified timestamp of the source file.
*source_size* is None or the size of the source file in bytes.
*name* is the name of the module being imported. It is used for logging.
*exc_details* is a dictionary passed to ImportError if it raised for
improved debugging.
An ImportError is raised if the bytecode is stale. | Validate a pyc against the source last-modified time. | [
"Validate",
"a",
"pyc",
"against",
"the",
"source",
"last",
"-",
"modified",
"time",
"."
] | def _validate_timestamp_pyc(data, source_mtime, source_size, name,
exc_details):
"""Validate a pyc against the source last-modified time.
*data* is the contents of the pyc file. (Only the first 16 bytes are
required.)
*source_mtime* is the last modified timestamp of the source file.
*source_size* is None or the size of the source file in bytes.
*name* is the name of the module being imported. It is used for logging.
*exc_details* is a dictionary passed to ImportError if it raised for
improved debugging.
An ImportError is raised if the bytecode is stale.
"""
if _r_long(data[8:12]) != (source_mtime & 0xFFFFFFFF):
message = f'bytecode is stale for {name!r}'
_bootstrap._verbose_message('{}', message)
raise ImportError(message, **exc_details)
if (source_size is not None and
_r_long(data[12:16]) != (source_size & 0xFFFFFFFF)):
raise ImportError(f'bytecode is stale for {name!r}', **exc_details) | [
"def",
"_validate_timestamp_pyc",
"(",
"data",
",",
"source_mtime",
",",
"source_size",
",",
"name",
",",
"exc_details",
")",
":",
"if",
"_r_long",
"(",
"data",
"[",
"8",
":",
"12",
"]",
")",
"!=",
"(",
"source_mtime",
"&",
"0xFFFFFFFF",
")",
":",
"messa... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap_external.py#L471-L496 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/backends/form_based_credentials_backend.py | python | FormBasedCredentialsBackend.LoginNeeded | (self, tab, action_runner, config) | Logs in to a test account.
Raises:
RuntimeError: if could not get credential information. | Logs in to a test account. | [
"Logs",
"in",
"to",
"a",
"test",
"account",
"."
] | def LoginNeeded(self, tab, action_runner, config):
"""Logs in to a test account.
Raises:
RuntimeError: if could not get credential information.
"""
if self._logged_in:
return True
if 'username' not in config or 'password' not in config:
message = ('Credentials for "%s" must include username and password.' %
self.credentials_type)
raise RuntimeError(message)
logging.debug('Logging into %s account...' % self.credentials_type)
if 'url' in config:
url = config['url']
else:
url = self.url
try:
logging.info('Loading %s...', url)
tab.Navigate(url)
self._WaitForLoginState(action_runner)
if self.IsAlreadyLoggedIn(tab):
self._logged_in = True
return True
self._SubmitLoginFormAndWait(
action_runner, tab, config['username'], config['password'])
self._logged_in = True
return True
except exceptions.TimeoutException:
logging.warning('Timed out while loading: %s', url)
return False | [
"def",
"LoginNeeded",
"(",
"self",
",",
"tab",
",",
"action_runner",
",",
"config",
")",
":",
"if",
"self",
".",
"_logged_in",
":",
"return",
"True",
"if",
"'username'",
"not",
"in",
"config",
"or",
"'password'",
"not",
"in",
"config",
":",
"message",
"=... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/form_based_credentials_backend.py#L86-L123 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py | python | _FindRuleTriggerFiles | (rule, sources) | return rule.get("rule_sources", []) | Find the list of files which a particular rule applies to.
Arguments:
rule: the rule in question
sources: the set of all known source files for this project
Returns:
The list of sources that trigger a particular rule. | Find the list of files which a particular rule applies to. | [
"Find",
"the",
"list",
"of",
"files",
"which",
"a",
"particular",
"rule",
"applies",
"to",
"."
] | def _FindRuleTriggerFiles(rule, sources):
"""Find the list of files which a particular rule applies to.
Arguments:
rule: the rule in question
sources: the set of all known source files for this project
Returns:
The list of sources that trigger a particular rule.
"""
return rule.get("rule_sources", []) | [
"def",
"_FindRuleTriggerFiles",
"(",
"rule",
",",
"sources",
")",
":",
"return",
"rule",
".",
"get",
"(",
"\"rule_sources\"",
",",
"[",
"]",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py#L580-L589 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/parallel/distributed.py | python | DistributedDataParallel._get_ddp_logging_data | (self) | return {**ddp_logging_data.strs_map, **ddp_logging_data.ints_map} | r"""
This interface can be called after DistributedDataParallel() is
constructed. It returns a dictionary of logging data. It could help
for debugging and analysis. The loggind data includes DistributedDataParallel
constructor input parameters, some internal states of DistributedDataParallel
and performance metrics. Simply print the dictorinary and see what
these metrics are.
This is a prototype interface and subject to change in the future. | r"""
This interface can be called after DistributedDataParallel() is
constructed. It returns a dictionary of logging data. It could help
for debugging and analysis. The loggind data includes DistributedDataParallel
constructor input parameters, some internal states of DistributedDataParallel
and performance metrics. Simply print the dictorinary and see what
these metrics are.
This is a prototype interface and subject to change in the future. | [
"r",
"This",
"interface",
"can",
"be",
"called",
"after",
"DistributedDataParallel",
"()",
"is",
"constructed",
".",
"It",
"returns",
"a",
"dictionary",
"of",
"logging",
"data",
".",
"It",
"could",
"help",
"for",
"debugging",
"and",
"analysis",
".",
"The",
"... | def _get_ddp_logging_data(self):
r"""
This interface can be called after DistributedDataParallel() is
constructed. It returns a dictionary of logging data. It could help
for debugging and analysis. The loggind data includes DistributedDataParallel
constructor input parameters, some internal states of DistributedDataParallel
and performance metrics. Simply print the dictorinary and see what
these metrics are.
This is a prototype interface and subject to change in the future.
"""
ddp_logging_data = self.logger._get_ddp_logging_data()
return {**ddp_logging_data.strs_map, **ddp_logging_data.ints_map} | [
"def",
"_get_ddp_logging_data",
"(",
"self",
")",
":",
"ddp_logging_data",
"=",
"self",
".",
"logger",
".",
"_get_ddp_logging_data",
"(",
")",
"return",
"{",
"*",
"*",
"ddp_logging_data",
".",
"strs_map",
",",
"*",
"*",
"ddp_logging_data",
".",
"ints_map",
"}"... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/parallel/distributed.py#L1707-L1718 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/nanfunctions.py | python | _divide_by_count | (a, b, out=None) | Compute a/b ignoring invalid results. If `a` is an array the division
is done in place. If `a` is a scalar, then its type is preserved in the
output. If out is None, then then a is used instead so that the
division is in place. Note that this is only called with `a` an inexact
type.
Parameters
----------
a : {ndarray, numpy scalar}
Numerator. Expected to be of inexact type but not checked.
b : {ndarray, numpy scalar}
Denominator.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary.
Returns
-------
ret : {ndarray, numpy scalar}
The return value is a/b. If `a` was an ndarray the division is done
in place. If `a` is a numpy scalar, the division preserves its type. | Compute a/b ignoring invalid results. If `a` is an array the division
is done in place. If `a` is a scalar, then its type is preserved in the
output. If out is None, then then a is used instead so that the
division is in place. Note that this is only called with `a` an inexact
type. | [
"Compute",
"a",
"/",
"b",
"ignoring",
"invalid",
"results",
".",
"If",
"a",
"is",
"an",
"array",
"the",
"division",
"is",
"done",
"in",
"place",
".",
"If",
"a",
"is",
"a",
"scalar",
"then",
"its",
"type",
"is",
"preserved",
"in",
"the",
"output",
"."... | def _divide_by_count(a, b, out=None):
"""
Compute a/b ignoring invalid results. If `a` is an array the division
is done in place. If `a` is a scalar, then its type is preserved in the
output. If out is None, then then a is used instead so that the
division is in place. Note that this is only called with `a` an inexact
type.
Parameters
----------
a : {ndarray, numpy scalar}
Numerator. Expected to be of inexact type but not checked.
b : {ndarray, numpy scalar}
Denominator.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary.
Returns
-------
ret : {ndarray, numpy scalar}
The return value is a/b. If `a` was an ndarray the division is done
in place. If `a` is a numpy scalar, the division preserves its type.
"""
with np.errstate(invalid='ignore'):
if isinstance(a, np.ndarray):
if out is None:
return np.divide(a, b, out=a, casting='unsafe')
else:
return np.divide(a, b, out=out, casting='unsafe')
else:
if out is None:
return a.dtype.type(a / b)
else:
# This is questionable, but currently a numpy scalar can
# be output to a zero dimensional array.
return np.divide(a, b, out=out, casting='unsafe') | [
"def",
"_divide_by_count",
"(",
"a",
",",
"b",
",",
"out",
"=",
"None",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"out",
"is",
"Non... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/nanfunctions.py#L96-L134 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | python/lammps/pylammps.py | python | Atom.angular_momentum | (self) | return self.get("angmom", self.index) | Return the angular momentum of the particle
:type: numpy.array (float, float, float) | Return the angular momentum of the particle | [
"Return",
"the",
"angular",
"momentum",
"of",
"the",
"particle"
] | def angular_momentum(self):
"""
Return the angular momentum of the particle
:type: numpy.array (float, float, float)
"""
return self.get("angmom", self.index) | [
"def",
"angular_momentum",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"angmom\"",
",",
"self",
".",
"index",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/python/lammps/pylammps.py#L273-L279 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/bindings/python/clang/cindex.py | python | Token.kind | (self) | return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) | Obtain the TokenKind of the current token. | Obtain the TokenKind of the current token. | [
"Obtain",
"the",
"TokenKind",
"of",
"the",
"current",
"token",
"."
] | def kind(self):
"""Obtain the TokenKind of the current token."""
return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"TokenKind",
".",
"from_value",
"(",
"conf",
".",
"lib",
".",
"clang_getTokenKind",
"(",
"self",
")",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L3295-L3297 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBPlatformConnectOptions.GetRsyncEnabled | (self) | return _lldb.SBPlatformConnectOptions_GetRsyncEnabled(self) | GetRsyncEnabled(SBPlatformConnectOptions self) -> bool | GetRsyncEnabled(SBPlatformConnectOptions self) -> bool | [
"GetRsyncEnabled",
"(",
"SBPlatformConnectOptions",
"self",
")",
"-",
">",
"bool"
] | def GetRsyncEnabled(self):
"""GetRsyncEnabled(SBPlatformConnectOptions self) -> bool"""
return _lldb.SBPlatformConnectOptions_GetRsyncEnabled(self) | [
"def",
"GetRsyncEnabled",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBPlatformConnectOptions_GetRsyncEnabled",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L7956-L7958 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py | python | MergeManifests._FindMergerParent | (self, tag_to_copy, destination_tag_name, mergee_dom) | Finds merger parent node, or appends mergee equivalent node if none. | Finds merger parent node, or appends mergee equivalent node if none. | [
"Finds",
"merger",
"parent",
"node",
"or",
"appends",
"mergee",
"equivalent",
"node",
"if",
"none",
"."
] | def _FindMergerParent(self, tag_to_copy, destination_tag_name, mergee_dom):
"""Finds merger parent node, or appends mergee equivalent node if none."""
# Merger parent element to which to add merged elements.
if self._merger_dom.getElementsByTagName(destination_tag_name):
return self._merger_dom.getElementsByTagName(destination_tag_name)[0]
else:
mergee_element = mergee_dom.getElementsByTagName(destination_tag_name)[0]
# find the parent
parents = self._merger_dom.getElementsByTagName(
mergee_element.parentNode.tagName)
if not parents:
raise MalformedManifestException(
'Malformed manifest has tag %s but no parent tag %s',
(tag_to_copy, destination_tag_name))
# append the mergee child as the first child.
return parents[0].insertBefore(mergee_element, parents[0].firstChild) | [
"def",
"_FindMergerParent",
"(",
"self",
",",
"tag_to_copy",
",",
"destination_tag_name",
",",
"mergee_dom",
")",
":",
"# Merger parent element to which to add merged elements.",
"if",
"self",
".",
"_merger_dom",
".",
"getElementsByTagName",
"(",
"destination_tag_name",
")"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py#L310-L325 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TextAttr.HasLeftIndent | (*args, **kwargs) | return _controls_.TextAttr_HasLeftIndent(*args, **kwargs) | HasLeftIndent(self) -> bool | HasLeftIndent(self) -> bool | [
"HasLeftIndent",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasLeftIndent(*args, **kwargs):
"""HasLeftIndent(self) -> bool"""
return _controls_.TextAttr_HasLeftIndent(*args, **kwargs) | [
"def",
"HasLeftIndent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasLeftIndent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1784-L1786 | |
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/build_source_release.py | python | gen_sha_file | (tarball_path) | Create a sha checksum file of the tarball.
The output format is compatible with command line tools like 'sha512sum' so it
can be used to verify the checksum. | Create a sha checksum file of the tarball. | [
"Create",
"a",
"sha",
"checksum",
"file",
"of",
"the",
"tarball",
"."
] | def gen_sha_file(tarball_path):
"""
Create a sha checksum file of the tarball.
The output format is compatible with command line tools like 'sha512sum' so it
can be used to verify the checksum.
"""
digest = checksum_file(hashlib.sha512(), tarball_path)
path = tarball_path + ".sha512"
with open(path, "w") as f:
f.write("%s %s\n" % (digest, os.path.basename(tarball_path)))
print(Colors.GREEN + "Generated sha:\t\t" + Colors.RESET + path) | [
"def",
"gen_sha_file",
"(",
"tarball_path",
")",
":",
"digest",
"=",
"checksum_file",
"(",
"hashlib",
".",
"sha512",
"(",
")",
",",
"tarball_path",
")",
"path",
"=",
"tarball_path",
"+",
"\".sha512\"",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
... | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/build_source_release.py#L124-L135 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHelpSourceEdit.py | python | GetHelpSourceDialog.__init__ | (self, parent, title, menuItem='', filePath='') | Get menu entry and url/ local file location for Additional Help
User selects a name for the Help resource and provides a web url
or a local file as its source. The user can enter a url or browse
for the file. | Get menu entry and url/ local file location for Additional Help | [
"Get",
"menu",
"entry",
"and",
"url",
"/",
"local",
"file",
"location",
"for",
"Additional",
"Help"
] | def __init__(self, parent, title, menuItem='', filePath=''):
"""Get menu entry and url/ local file location for Additional Help
User selects a name for the Help resource and provides a web url
or a local file as its source. The user can enter a url or browse
for the file.
"""
Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.Cancel)
self.parent = parent
self.result = None
self.CreateWidgets()
self.menu.set(menuItem)
self.path.set(filePath)
self.withdraw() #hide while setting geometry
#needs to be done here so that the winfo_reqwidth is valid
self.update_idletasks()
#centre dialog over parent:
self.geometry("+%d+%d" %
((parent.winfo_rootx() + ((parent.winfo_width()/2)
-(self.winfo_reqwidth()/2)),
parent.winfo_rooty() + ((parent.winfo_height()/2)
-(self.winfo_reqheight()/2)))))
self.deiconify() #geometry set, unhide
self.bind('<Return>', self.Ok)
self.wait_window() | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"title",
",",
"menuItem",
"=",
"''",
",",
"filePath",
"=",
"''",
")",
":",
"Toplevel",
".",
"__init__",
"(",
"self",
",",
"parent",
")",
"self",
".",
"configure",
"(",
"borderwidth",
"=",
"5",
")",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHelpSourceEdit.py#L11-L42 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/synxml.py | python | EditraXml.GetEndTag | (self) | return u"</%s>" % self.name | Get the closing tag
@return: string | Get the closing tag
@return: string | [
"Get",
"the",
"closing",
"tag",
"@return",
":",
"string"
] | def GetEndTag(self):
"""Get the closing tag
@return: string
"""
return u"</%s>" % self.name | [
"def",
"GetEndTag",
"(",
"self",
")",
":",
"return",
"u\"</%s>\"",
"%",
"self",
".",
"name"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/synxml.py#L181-L186 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/ParameterSet/python/VarParsing.py | python | VarParsing.register | (self, name,
default = "",
mult = multiplicity.singleton,
mytype = varType.int,
info = "",
**kwargs) | Register a variable | Register a variable | [
"Register",
"a",
"variable"
] | def register (self, name,
default = "",
mult = multiplicity.singleton,
mytype = varType.int,
info = "",
**kwargs):
"""Register a variable"""
# is type ok?
if not VarParsing.multiplicity.isValidValue (mult):
print("Error: VarParsing.register() must use ",\
"VarParsing.multiplicity.")
raise RuntimeError("Improper 'mult' value")
if not VarParsing.varType.isValidValue (mytype):
print("Error: VarParsing.register() must use ",\
"VarParsing.varType.")
raise RuntimeError("Improper 'type' value %s" % mytype)
if VarParsing.multiplicity.list == mult and \
VarParsing.varType.tagString == mytype:
print("Error: 'tagString' can only be used with 'singleton'")
raise RuntimeError("Improper registration")
# is the name ok
if name.count ("_"):
print("Error: Name can not contain '_': %s" % name)
raise RuntimeError("Improper 'name'")
# has this been registered before?
if name in self._register:
# Uh oh
print("Error: You can not register a name twice, '%s'" \
% name)
raise RuntimeError("Attempt to re-register variable")
self._register[name] = mult
self._beenSet[name] = False
self._info[name] = info
self._types[name] = mytype
if len (name) > self._maxLength:
self._maxLength = len (name)
if VarParsing.multiplicity.singleton == mult:
self._singletons[name] = default
else:
self._lists[name] = []
# if it's a list, we only want to use the default if it
# does exist.
if len (default):
self._lists[name].append (default)
#######################################
## Process any additional directives ##
#######################################
# do we want to tell the list to not split command line
# arguments by commas?
if kwargs.get ('noCommaSplit'):
self._noCommaSplit[name] = bool( kwargs['noCommaSplit'] )
del kwargs['noCommaSplit']
if kwargs.get ('noDefaultClear'):
self._noDefaultClear[name] = bool( kwargs['noDefaultClear'] )
del kwargs['noDefaultClear']
if len (kwargs):
raise RuntimeError("register() Unknown arguments %s" % kwargs) | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"default",
"=",
"\"\"",
",",
"mult",
"=",
"multiplicity",
".",
"singleton",
",",
"mytype",
"=",
"varType",
".",
"int",
",",
"info",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"# is type ok?",
"if... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/VarParsing.py#L374-L430 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Misc.winfo_visual | (self) | return self.tk.call('winfo', 'visual', self._w) | Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget. | Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget. | [
"Return",
"one",
"of",
"the",
"strings",
"directcolor",
"grayscale",
"pseudocolor",
"staticcolor",
"staticgray",
"or",
"truecolor",
"for",
"the",
"colormodel",
"of",
"this",
"widget",
"."
] | def winfo_visual(self):
"""Return one of the strings directcolor, grayscale, pseudocolor,
staticcolor, staticgray, or truecolor for the
colormodel of this widget."""
return self.tk.call('winfo', 'visual', self._w) | [
"def",
"winfo_visual",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'visual'",
",",
"self",
".",
"_w",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L1115-L1119 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/position.py | python | Position.current_timestamp | (self, current_timestamp) | Sets the current_timestamp of this Position.
:param current_timestamp: The current_timestamp of this Position. # noqa: E501
:type: datetime | Sets the current_timestamp of this Position. | [
"Sets",
"the",
"current_timestamp",
"of",
"this",
"Position",
"."
] | def current_timestamp(self, current_timestamp):
"""Sets the current_timestamp of this Position.
:param current_timestamp: The current_timestamp of this Position. # noqa: E501
:type: datetime
"""
self._current_timestamp = current_timestamp | [
"def",
"current_timestamp",
"(",
"self",
",",
"current_timestamp",
")",
":",
"self",
".",
"_current_timestamp",
"=",
"current_timestamp"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L1207-L1215 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/thermostats.py | python | Thermostat.step | (self) | Dummy thermostat step. | Dummy thermostat step. | [
"Dummy",
"thermostat",
"step",
"."
] | def step(self):
"""Dummy thermostat step."""
pass | [
"def",
"step",
"(",
"self",
")",
":",
"pass"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/thermostats.py#L155-L158 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/ioloop.py | python | IOLoop._discard_future_result | (self, future: Future) | Avoid unhandled-exception warnings from spawned coroutines. | Avoid unhandled-exception warnings from spawned coroutines. | [
"Avoid",
"unhandled",
"-",
"exception",
"warnings",
"from",
"spawned",
"coroutines",
"."
] | def _discard_future_result(self, future: Future) -> None:
"""Avoid unhandled-exception warnings from spawned coroutines."""
future.result() | [
"def",
"_discard_future_result",
"(",
"self",
",",
"future",
":",
"Future",
")",
"->",
"None",
":",
"future",
".",
"result",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/ioloop.py#L763-L765 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/control_flow_ops.py | python | cond | (pred, true_fn=None, false_fn=None, strict=False, name=None,
fn1=None, fn2=None) | Return `true_fn()` if the predicate `pred` is true else `false_fn()`.
`true_fn` and `false_fn` both return lists of output tensors. `true_fn` and
`false_fn` must have the same non-zero number and type of outputs.
Note that the conditional execution applies only to the operations defined in
`true_fn` and `false_fn`. Consider the following simple program:
```python
z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
```
If `x < y`, the `tf.add` operation will be executed and `tf.square`
operation will not be executed. Since `z` is needed for at least one
branch of the `cond`, the `tf.multiply` operation is always executed,
unconditionally.
Although this behavior is consistent with the dataflow model of TensorFlow,
it has occasionally surprised some users who expected a lazier semantics.
Note that `cond` calls `true_fn` and `false_fn` *exactly once* (inside the
call to `cond`, and not at all during `Session.run()`). `cond`
stitches together the graph fragments created during the `true_fn` and
`false_fn` calls with some additional graph nodes to ensure that the right
branch gets executed depending on the value of `pred`.
`tf.cond` supports nested structures as implemented in
`tensorflow.python.util.nest`. Both `true_fn` and `false_fn` must return the
same (possibly nested) value structure of lists, tuples, and/or named tuples.
Singleton lists and tuples form the only exceptions to this: when returned by
`true_fn` and/or `false_fn`, they are implicitly unpacked to single values.
This behavior is disabled by passing `strict=True`.
Args:
pred: A scalar determining whether to return the result of `true_fn` or
`false_fn`.
true_fn: The callable to be performed if pred is true.
false_fn: The callable to be performed if pred is false.
strict: A boolean that enables/disables 'strict' mode; see above.
name: Optional name prefix for the returned tensors.
Returns:
Tensors returned by the call to either `true_fn` or `false_fn`. If the
callables return a singleton list, the element is extracted from the list.
Raises:
TypeError: if `true_fn` or `false_fn` is not callable.
ValueError: if `true_fn` and `false_fn` do not return the same number of
tensors, or return tensors of different types.
Example:
```python
x = tf.constant(2)
y = tf.constant(5)
def f1(): return tf.multiply(x, 17)
def f2(): return tf.add(y, 23)
r = tf.cond(tf.less(x, y), f1, f2)
# r is set to f1().
# Operations in f2 (e.g., tf.add) are not executed.
``` | Return `true_fn()` if the predicate `pred` is true else `false_fn()`. | [
"Return",
"true_fn",
"()",
"if",
"the",
"predicate",
"pred",
"is",
"true",
"else",
"false_fn",
"()",
"."
] | def cond(pred, true_fn=None, false_fn=None, strict=False, name=None,
fn1=None, fn2=None):
"""Return `true_fn()` if the predicate `pred` is true else `false_fn()`.
`true_fn` and `false_fn` both return lists of output tensors. `true_fn` and
`false_fn` must have the same non-zero number and type of outputs.
Note that the conditional execution applies only to the operations defined in
`true_fn` and `false_fn`. Consider the following simple program:
```python
z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
```
If `x < y`, the `tf.add` operation will be executed and `tf.square`
operation will not be executed. Since `z` is needed for at least one
branch of the `cond`, the `tf.multiply` operation is always executed,
unconditionally.
Although this behavior is consistent with the dataflow model of TensorFlow,
it has occasionally surprised some users who expected a lazier semantics.
Note that `cond` calls `true_fn` and `false_fn` *exactly once* (inside the
call to `cond`, and not at all during `Session.run()`). `cond`
stitches together the graph fragments created during the `true_fn` and
`false_fn` calls with some additional graph nodes to ensure that the right
branch gets executed depending on the value of `pred`.
`tf.cond` supports nested structures as implemented in
`tensorflow.python.util.nest`. Both `true_fn` and `false_fn` must return the
same (possibly nested) value structure of lists, tuples, and/or named tuples.
Singleton lists and tuples form the only exceptions to this: when returned by
`true_fn` and/or `false_fn`, they are implicitly unpacked to single values.
This behavior is disabled by passing `strict=True`.
Args:
pred: A scalar determining whether to return the result of `true_fn` or
`false_fn`.
true_fn: The callable to be performed if pred is true.
false_fn: The callable to be performed if pred is false.
strict: A boolean that enables/disables 'strict' mode; see above.
name: Optional name prefix for the returned tensors.
Returns:
Tensors returned by the call to either `true_fn` or `false_fn`. If the
callables return a singleton list, the element is extracted from the list.
Raises:
TypeError: if `true_fn` or `false_fn` is not callable.
ValueError: if `true_fn` and `false_fn` do not return the same number of
tensors, or return tensors of different types.
Example:
```python
x = tf.constant(2)
y = tf.constant(5)
def f1(): return tf.multiply(x, 17)
def f2(): return tf.add(y, 23)
r = tf.cond(tf.less(x, y), f1, f2)
# r is set to f1().
# Operations in f2 (e.g., tf.add) are not executed.
```
"""
# We needed to make true_fn/false_fn keyword arguments for
# backwards-compatibility. This check exists so that we can convert back to
# having them be positional arguments.
# TODO(josh11b): Make `true_fn` and `false_fn` positional arguments after
# `fn1` and `fn2` are deleted.
if fn1 is not None:
if true_fn is not None:
raise TypeError("cond(): true_fn and fn1 may not be set simultaneously.")
true_fn = fn1
elif true_fn is None:
raise TypeError("cond(): true_fn argument required")
if fn2 is not None:
if false_fn is not None:
raise TypeError("cond(): false_fn and fn2 may not be set simultaneously.")
false_fn = fn2
elif false_fn is None:
raise TypeError("cond(): false_fn argument required")
if not callable(true_fn):
raise TypeError("true_fn must be callable.")
if not callable(false_fn):
raise TypeError("false_fn must be callable.")
with ops.name_scope(name, "cond", [pred]) as name:
# Add the Switch to the graph.
if isinstance(pred, bool):
raise TypeError("pred must not be a Python bool")
p_2, p_1 = switch(pred, pred)
pivot_1 = array_ops.identity(p_1, name="switch_t")
pivot_2 = array_ops.identity(p_2, name="switch_f")
pred = array_ops.identity(pred, name="pred_id")
# Disable the fetching of tensors that are only on one branch of cond.
for tensor in [p_1, p_2, pivot_1, pivot_2, pred]:
tensor.op.graph.prevent_fetching(tensor.op)
# Build the graph for the true branch in a new context.
context_t = CondContext(pred, pivot_1, branch=1)
context_t.Enter()
orig_res_t, res_t = context_t.BuildCondBranch(true_fn)
if orig_res_t is None:
raise ValueError("true_fn must have a return value.")
context_t.ExitResult(res_t)
context_t.Exit()
# Build the graph for the false branch in a new context.
context_f = CondContext(pred, pivot_2, branch=0)
context_f.Enter()
orig_res_f, res_f = context_f.BuildCondBranch(false_fn)
if orig_res_f is None:
raise ValueError("false_fn must have a return value.")
context_f.ExitResult(res_f)
context_f.Exit()
if not strict:
orig_res_t = _UnpackIfSingleton(orig_res_t)
orig_res_f = _UnpackIfSingleton(orig_res_f)
# Check that the return values of the two branches have the same structure.
try:
nest.assert_same_structure(orig_res_t, orig_res_f)
except TypeError as e:
raise TypeError(
"Incompatible return types of true_fn and false_fn: {}".format(e))
except ValueError as e:
raise ValueError(
"Incompatible return values of true_fn and false_fn: {}".format(e))
# Add the final merge to the graph.
if not res_t:
raise ValueError("true_fn and false_fn must return at least one result.")
res_t_flat = nest.flatten(res_t)
res_f_flat = nest.flatten(res_f)
for x, y in zip(res_t_flat, res_f_flat):
assert ((isinstance(x, ops.IndexedSlices) and
isinstance(y, ops.IndexedSlices)) or
(isinstance(x, sparse_tensor.SparseTensor) and
isinstance(y, sparse_tensor.SparseTensor)) or
(isinstance(x, ops.Tensor) and isinstance(y, ops.Tensor)))
val_x = x if isinstance(x, ops.Tensor) else x.values
val_y = y if isinstance(y, ops.Tensor) else y.values
if val_x.dtype.base_dtype != val_y.dtype.base_dtype:
raise ValueError(
"Outputs of true_fn and false_fn must have the same type: %s, %s" %
(val_x.dtype.name, val_y.dtype.name))
merges = [merge(pair)[0] for pair in zip(res_f_flat, res_t_flat)]
merges = _convert_flows_to_tensorarrays(nest.flatten(orig_res_t), merges)
# Add to collections
ops.add_to_collection(ops.GraphKeys.COND_CONTEXT, context_t)
ops.add_to_collection(ops.GraphKeys.COND_CONTEXT, context_f)
merges = nest.pack_sequence_as(structure=orig_res_t, flat_sequence=merges)
# Singleton lists and tuples are automatically unpacked if strict == False.
if not strict:
merges = _UnpackIfSingleton(merges)
return merges | [
"def",
"cond",
"(",
"pred",
",",
"true_fn",
"=",
"None",
",",
"false_fn",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"name",
"=",
"None",
",",
"fn1",
"=",
"None",
",",
"fn2",
"=",
"None",
")",
":",
"# We needed to make true_fn/false_fn keyword argument... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L1716-L1880 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/apiclient/googleapiclient/schema.py | python | _SchemaToStruct.undent | (self) | Decrease indentation level. | Decrease indentation level. | [
"Decrease",
"indentation",
"level",
"."
] | def undent(self):
"""Decrease indentation level."""
self.dent -= 1 | [
"def",
"undent",
"(",
"self",
")",
":",
"self",
".",
"dent",
"-=",
"1"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/apiclient/googleapiclient/schema.py#L236-L238 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/bandwidth.py | python | BandwidthRateTracker.record_consumption_rate | (self, amt, time_at_consumption) | Record the consumption rate based off amount and time point
:type amt: int
:param amt: The amount that got consumed
:type time_at_consumption: float
:param time_at_consumption: The time at which the amount was consumed | Record the consumption rate based off amount and time point | [
"Record",
"the",
"consumption",
"rate",
"based",
"off",
"amount",
"and",
"time",
"point"
] | def record_consumption_rate(self, amt, time_at_consumption):
"""Record the consumption rate based off amount and time point
:type amt: int
:param amt: The amount that got consumed
:type time_at_consumption: float
:param time_at_consumption: The time at which the amount was consumed
"""
if self._last_time is None:
self._last_time = time_at_consumption
self._current_rate = 0.0
return
self._current_rate = self._calculate_exponential_moving_average_rate(
amt, time_at_consumption)
self._last_time = time_at_consumption | [
"def",
"record_consumption_rate",
"(",
"self",
",",
"amt",
",",
"time_at_consumption",
")",
":",
"if",
"self",
".",
"_last_time",
"is",
"None",
":",
"self",
".",
"_last_time",
"=",
"time_at_consumption",
"self",
".",
"_current_rate",
"=",
"0.0",
"return",
"sel... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/bandwidth.py#L386-L401 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/valgrind/tsan_analyze.py | python | TsanAnalyzer.Report | (self, files, testcase, check_sanity=False) | return 0 | Reads in a set of files and prints ThreadSanitizer report.
Args:
files: A list of filenames.
check_sanity: if true, search for SANITY_TEST_SUPPRESSIONS | Reads in a set of files and prints ThreadSanitizer report. | [
"Reads",
"in",
"a",
"set",
"of",
"files",
"and",
"prints",
"ThreadSanitizer",
"report",
"."
] | def Report(self, files, testcase, check_sanity=False):
'''Reads in a set of files and prints ThreadSanitizer report.
Args:
files: A list of filenames.
check_sanity: if true, search for SANITY_TEST_SUPPRESSIONS
'''
# We set up _cur_testcase class-wide variable to avoid passing it through
# about 5 functions.
self._cur_testcase = testcase
reports = self.GetReports(files)
self._cur_testcase = None # just in case, shouldn't be used anymore
common.PrintUsedSuppressionsList(self.used_suppressions)
retcode = 0
if reports:
sys.stdout.flush()
sys.stderr.flush()
logging.info("FAIL! Found %i report(s)" % len(reports))
for report in reports:
logging.info('\n' + report)
sys.stdout.flush()
retcode = -1
# Report tool's insanity even if there were errors.
if (check_sanity and
TsanAnalyzer.SANITY_TEST_SUPPRESSION not in self.used_suppressions):
logging.error("FAIL! Sanity check failed!")
retcode = -3
if retcode != 0:
return retcode
logging.info("PASS: No reports found")
return 0 | [
"def",
"Report",
"(",
"self",
",",
"files",
",",
"testcase",
",",
"check_sanity",
"=",
"False",
")",
":",
"# We set up _cur_testcase class-wide variable to avoid passing it through",
"# about 5 functions.",
"self",
".",
"_cur_testcase",
"=",
"testcase",
"reports",
"=",
... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/valgrind/tsan_analyze.py#L220-L257 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextParagraphLayoutBox.GetLineSizeAtPosition | (*args, **kwargs) | return _richtext.RichTextParagraphLayoutBox_GetLineSizeAtPosition(*args, **kwargs) | GetLineSizeAtPosition(self, long pos, bool caretPosition=False) -> Size | GetLineSizeAtPosition(self, long pos, bool caretPosition=False) -> Size | [
"GetLineSizeAtPosition",
"(",
"self",
"long",
"pos",
"bool",
"caretPosition",
"=",
"False",
")",
"-",
">",
"Size"
] | def GetLineSizeAtPosition(*args, **kwargs):
"""GetLineSizeAtPosition(self, long pos, bool caretPosition=False) -> Size"""
return _richtext.RichTextParagraphLayoutBox_GetLineSizeAtPosition(*args, **kwargs) | [
"def",
"GetLineSizeAtPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraphLayoutBox_GetLineSizeAtPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1680-L1682 | |
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/banks/bank_operations.py | python | remove_bank_member | (
banks_table: BanksTable,
bank_member_id: str,
) | Remove bank member. Marks the member as removed and all its signals are
removed from the GSI used to build HMA indexes.
NOTE: If we ever start incremental updates to HMA indexes, removing bank
members will stop working. | Remove bank member. Marks the member as removed and all its signals are
removed from the GSI used to build HMA indexes. | [
"Remove",
"bank",
"member",
".",
"Marks",
"the",
"member",
"as",
"removed",
"and",
"all",
"its",
"signals",
"are",
"removed",
"from",
"the",
"GSI",
"used",
"to",
"build",
"HMA",
"indexes",
"."
] | def remove_bank_member(
banks_table: BanksTable,
bank_member_id: str,
):
"""
Remove bank member. Marks the member as removed and all its signals are
removed from the GSI used to build HMA indexes.
NOTE: If we ever start incremental updates to HMA indexes, removing bank
members will stop working.
"""
banks_table.remove_bank_member_signals_to_process(bank_member_id=bank_member_id)
banks_table.remove_bank_member(bank_member_id=bank_member_id) | [
"def",
"remove_bank_member",
"(",
"banks_table",
":",
"BanksTable",
",",
"bank_member_id",
":",
"str",
",",
")",
":",
"banks_table",
".",
"remove_bank_member_signals_to_process",
"(",
"bank_member_id",
"=",
"bank_member_id",
")",
"banks_table",
".",
"remove_bank_member"... | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/banks/bank_operations.py#L62-L74 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBCommunication.GetBroadcasterClass | () | return _lldb.SBCommunication_GetBroadcasterClass() | GetBroadcasterClass() -> str | GetBroadcasterClass() -> str | [
"GetBroadcasterClass",
"()",
"-",
">",
"str"
] | def GetBroadcasterClass():
"""GetBroadcasterClass() -> str"""
return _lldb.SBCommunication_GetBroadcasterClass() | [
"def",
"GetBroadcasterClass",
"(",
")",
":",
"return",
"_lldb",
".",
"SBCommunication_GetBroadcasterClass",
"(",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L2433-L2435 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.referenced | (self) | return self._referenced | For a cursor that is a reference, returns a cursor
representing the entity that it references. | For a cursor that is a reference, returns a cursor
representing the entity that it references. | [
"For",
"a",
"cursor",
"that",
"is",
"a",
"reference",
"returns",
"a",
"cursor",
"representing",
"the",
"entity",
"that",
"it",
"references",
"."
] | def referenced(self):
"""
For a cursor that is a reference, returns a cursor
representing the entity that it references.
"""
if not hasattr(self, '_referenced'):
self._referenced = conf.lib.clang_getCursorReferenced(self)
return self._referenced | [
"def",
"referenced",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_referenced'",
")",
":",
"self",
".",
"_referenced",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorReferenced",
"(",
"self",
")",
"return",
"self",
".",
"_referenced"
] | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L1472-L1480 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py | python | Text.window_configure | (self, index, cnf=None, **kw) | return self._configure(('window', 'configure', index), cnf, kw) | Configure an embedded window at INDEX. | Configure an embedded window at INDEX. | [
"Configure",
"an",
"embedded",
"window",
"at",
"INDEX",
"."
] | def window_configure(self, index, cnf=None, **kw):
"""Configure an embedded window at INDEX."""
return self._configure(('window', 'configure', index), cnf, kw) | [
"def",
"window_configure",
"(",
"self",
",",
"index",
",",
"cnf",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_configure",
"(",
"(",
"'window'",
",",
"'configure'",
",",
"index",
")",
",",
"cnf",
",",
"kw",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L3415-L3417 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/main.py | python | main | (args) | Everything Starts from Here | Everything Starts from Here | [
"Everything",
"Starts",
"from",
"Here"
] | def main(args):
"""Everything Starts from Here"""
if __builtin__.DBUS_OK is True:
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
try:
session_bus = dbus.SessionBus()
except:
__builtin__.DBUS_OK = False
args.filepath = arg_filepath_fix(args.filepath)
if args.export_to_html_dir or args.export_to_txt_dir or args.export_to_pdf_path:
args.export_to_html_dir = arg_filepath_fix(args.export_to_html_dir)
args.export_to_txt_dir = arg_filepath_fix(args.export_to_txt_dir)
args.export_to_pdf_path = arg_filepath_fix(args.export_to_pdf_path)
lang_str = initializations()
CherryTreeHandler(args, lang_str)
elif __builtin__.DBUS_OK is True:
try:
# client
remote_object = session_bus.get_object("com.giuspen.CherryTreeService", "/CherryTreeObject")
if not args.node: ret_val = remote_object.Send("ct*=%s" % args.filepath)
else: ret_val = remote_object.Send("ct*=%s\x03%s" % (args.filepath, args.node))
if ret_val != "okz": raise
except:
#raise
# server + core
lang_str = initializations()
name = dbus.service.BusName("com.giuspen.CherryTreeService", session_bus)
object = CherryTreeObject(session_bus, '/CherryTreeObject')
CherryTreeHandler(args, lang_str)
gtk.main()
if cons.IS_WIN_OS:
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
sys.stderr = os.devnull
subprocess.check_output(["TASKKILL", "/F", "/IM", "dbus-daemon.exe", "/T"], startupinfo=si)
else:
print "dbus fail, maybe a firewall problem, centralized instances disabled"
lang_str = initializations()
CherryTreeHandler(args, lang_str)
gtk.main() | [
"def",
"main",
"(",
"args",
")",
":",
"if",
"__builtin__",
".",
"DBUS_OK",
"is",
"True",
":",
"dbus",
".",
"mainloop",
".",
"glib",
".",
"DBusGMainLoop",
"(",
"set_as_default",
"=",
"True",
")",
"try",
":",
"session_bus",
"=",
"dbus",
".",
"SessionBus",
... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/main.py#L228-L268 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | build/plugins/res.py | python | onresource_files | (unit, *args) | @usage: RESOURCE_FILES([DONT_PARSE] [PREFIX {prefix}] [STRIP prefix_to_strip] {path})
This macro expands into
RESOURCE([DONT_PARSE] {path} resfs/file/{prefix}{path}
- resfs/src/resfs/file/{prefix}{remove_prefix(path, prefix_to_strip)}={rootrel_arc_src(path)}
)
resfs/src/{key} stores a source root (or build root) relative path of the
source of the value of the {key} resource.
resfs/file/{key} stores any value whose source was a file on a filesystem.
resfs/src/resfs/file/{key} must store its path.
DONT_PARSE disables parsing for source code files (determined by extension)
Please don't abuse: use separate DONT_PARSE macro call only for files subject to parsing
This form is for use from other plugins:
RESOURCE_FILES([DEST {dest}] {path}) expands into RESOURCE({path} resfs/file/{dest})
@see: https://wiki.yandex-team.ru/devtools/commandsandvars/resourcefiles/ | @usage: RESOURCE_FILES([DONT_PARSE] [PREFIX {prefix}] [STRIP prefix_to_strip] {path}) | [
"@usage",
":",
"RESOURCE_FILES",
"(",
"[",
"DONT_PARSE",
"]",
"[",
"PREFIX",
"{",
"prefix",
"}",
"]",
"[",
"STRIP",
"prefix_to_strip",
"]",
"{",
"path",
"}",
")"
] | def onresource_files(unit, *args):
"""
@usage: RESOURCE_FILES([DONT_PARSE] [PREFIX {prefix}] [STRIP prefix_to_strip] {path})
This macro expands into
RESOURCE([DONT_PARSE] {path} resfs/file/{prefix}{path}
- resfs/src/resfs/file/{prefix}{remove_prefix(path, prefix_to_strip)}={rootrel_arc_src(path)}
)
resfs/src/{key} stores a source root (or build root) relative path of the
source of the value of the {key} resource.
resfs/file/{key} stores any value whose source was a file on a filesystem.
resfs/src/resfs/file/{key} must store its path.
DONT_PARSE disables parsing for source code files (determined by extension)
Please don't abuse: use separate DONT_PARSE macro call only for files subject to parsing
This form is for use from other plugins:
RESOURCE_FILES([DEST {dest}] {path}) expands into RESOURCE({path} resfs/file/{dest})
@see: https://wiki.yandex-team.ru/devtools/commandsandvars/resourcefiles/
"""
prefix = ''
prefix_to_strip = None
dest = None
res = []
first = 0
if args and not unit.enabled('_GO_MODULE'):
# GO_RESOURCE currently doesn't support DONT_PARSE
res.append('DONT_PARSE')
if args and args[0] == 'DONT_PARSE':
first = 1
args = iter(args[first:])
for arg in args:
if arg == 'PREFIX':
prefix, dest = next(args), None
elif arg == 'DEST':
dest, prefix = next(args), None
elif arg == 'STRIP':
prefix_to_strip = next(args)
else:
path = arg
key = 'resfs/file/' + (dest or (prefix + (path if not prefix_to_strip else remove_prefix(path, prefix_to_strip))))
src = 'resfs/src/{}={}'.format(key, rootrel_arc_src(path, unit))
res += ['-', src, path, key]
if unit.enabled('_GO_MODULE'):
unit.on_go_resource(res)
else:
unit.onresource(res) | [
"def",
"onresource_files",
"(",
"unit",
",",
"*",
"args",
")",
":",
"prefix",
"=",
"''",
"prefix_to_strip",
"=",
"None",
"dest",
"=",
"None",
"res",
"=",
"[",
"]",
"first",
"=",
"0",
"if",
"args",
"and",
"not",
"unit",
".",
"enabled",
"(",
"'_GO_MODU... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/build/plugins/res.py#L53-L106 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/393.utf-8-validation.py | python | Solution.validUtf8 | (self, data) | return True | :type data: List[int]
:rtype: bool | :type data: List[int]
:rtype: bool | [
":",
"type",
"data",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"bool"
] | def validUtf8(self, data):
"""
:type data: List[int]
:rtype: bool
"""
if data is None or len(data) == 0:
return False
i = 0
while i < len(data):
n = self.byteLength(data[i])
if n == 0 or n + i - 1 >= len(data):
return False
for j in range(i + 1, n + i):
if (data[j] >> 6) != 0b10:
return False
i = i + n
return True | [
"def",
"validUtf8",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
"or",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"False",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"data",
")",
":",
"n",
"=",
"self",
".",
"byte... | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/393.utf-8-validation.py#L2-L22 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py | python | lineno | (loc,strg) | return strg.count("\n",0,loc) + 1 | Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string. | Returns current line number within a string, counting newlines as line separators.
The first line is number 1. | [
"Returns",
"current",
"line",
"number",
"within",
"a",
"string",
"counting",
"newlines",
"as",
"line",
"separators",
".",
"The",
"first",
"line",
"is",
"number",
"1",
"."
] | def lineno(loc,strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
return strg.count("\n",0,loc) + 1 | [
"def",
"lineno",
"(",
"loc",
",",
"strg",
")",
":",
"return",
"strg",
".",
"count",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"+",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L981-L991 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/debug/cli/profile_analyzer_cli.py | python | _list_profile_filter | (
profile_datum,
node_name_regex,
file_path_regex,
op_type_regex,
op_time_interval,
exec_time_interval,
min_lineno=-1,
max_lineno=-1) | return True | Filter function for list_profile command.
Args:
profile_datum: A `ProfileDatum` object.
node_name_regex: Regular expression pattern object to filter by name.
file_path_regex: Regular expression pattern object to filter by file path.
op_type_regex: Regular expression pattern object to filter by op type.
op_time_interval: `Interval` for filtering op time.
exec_time_interval: `Interval` for filtering exec time.
min_lineno: Lower bound for 1-based line number, inclusive.
If <= 0, has no effect.
max_lineno: Upper bound for 1-based line number, exclusive.
If <= 0, has no effect.
# TODO(cais): Maybe filter by function name.
Returns:
True iff profile_datum should be included. | Filter function for list_profile command. | [
"Filter",
"function",
"for",
"list_profile",
"command",
"."
] | def _list_profile_filter(
profile_datum,
node_name_regex,
file_path_regex,
op_type_regex,
op_time_interval,
exec_time_interval,
min_lineno=-1,
max_lineno=-1):
"""Filter function for list_profile command.
Args:
profile_datum: A `ProfileDatum` object.
node_name_regex: Regular expression pattern object to filter by name.
file_path_regex: Regular expression pattern object to filter by file path.
op_type_regex: Regular expression pattern object to filter by op type.
op_time_interval: `Interval` for filtering op time.
exec_time_interval: `Interval` for filtering exec time.
min_lineno: Lower bound for 1-based line number, inclusive.
If <= 0, has no effect.
max_lineno: Upper bound for 1-based line number, exclusive.
If <= 0, has no effect.
# TODO(cais): Maybe filter by function name.
Returns:
True iff profile_datum should be included.
"""
if node_name_regex and not node_name_regex.match(
profile_datum.node_exec_stats.node_name):
return False
if file_path_regex:
if (not profile_datum.file_path or
not file_path_regex.match(profile_datum.file_path)):
return False
if (min_lineno > 0 and profile_datum.line_number and
profile_datum.line_number < min_lineno):
return False
if (max_lineno > 0 and profile_datum.line_number and
profile_datum.line_number >= max_lineno):
return False
if (profile_datum.op_type is not None and op_type_regex and
not op_type_regex.match(profile_datum.op_type)):
return False
if op_time_interval is not None and not op_time_interval.contains(
profile_datum.op_time):
return False
if exec_time_interval and not exec_time_interval.contains(
profile_datum.node_exec_stats.all_end_rel_micros):
return False
return True | [
"def",
"_list_profile_filter",
"(",
"profile_datum",
",",
"node_name_regex",
",",
"file_path_regex",
",",
"op_type_regex",
",",
"op_time_interval",
",",
"exec_time_interval",
",",
"min_lineno",
"=",
"-",
"1",
",",
"max_lineno",
"=",
"-",
"1",
")",
":",
"if",
"no... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/profile_analyzer_cli.py#L146-L195 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewListCtrl.SelectRow | (*args, **kwargs) | return _dataview.DataViewListCtrl_SelectRow(*args, **kwargs) | SelectRow(self, unsigned int row) | SelectRow(self, unsigned int row) | [
"SelectRow",
"(",
"self",
"unsigned",
"int",
"row",
")"
] | def SelectRow(*args, **kwargs):
"""SelectRow(self, unsigned int row)"""
return _dataview.DataViewListCtrl_SelectRow(*args, **kwargs) | [
"def",
"SelectRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewListCtrl_SelectRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L2104-L2106 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/binary-tree-coloring-game.py | python | Solution.btreeGameWinningMove | (self, root, n, x) | return blue > n-blue | :type root: TreeNode
:type n: int
:type x: int
:rtype: bool | :type root: TreeNode
:type n: int
:type x: int
:rtype: bool | [
":",
"type",
"root",
":",
"TreeNode",
":",
"type",
"n",
":",
"int",
":",
"type",
"x",
":",
"int",
":",
"rtype",
":",
"bool"
] | def btreeGameWinningMove(self, root, n, x):
"""
:type root: TreeNode
:type n: int
:type x: int
:rtype: bool
"""
def count(node, x, left_right):
if not node:
return 0
left, right = count(node.left, x, left_right), count(node.right, x, left_right)
if node.val == x:
left_right[0], left_right[1] = left, right
return left + right + 1
left_right = [0, 0]
count(root, x, left_right)
blue = max(max(left_right), n-(sum(left_right)+1))
return blue > n-blue | [
"def",
"btreeGameWinningMove",
"(",
"self",
",",
"root",
",",
"n",
",",
"x",
")",
":",
"def",
"count",
"(",
"node",
",",
"x",
",",
"left_right",
")",
":",
"if",
"not",
"node",
":",
"return",
"0",
"left",
",",
"right",
"=",
"count",
"(",
"node",
"... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/binary-tree-coloring-game.py#L13-L31 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Rect2D.MoveLeftBottomTo | (*args, **kwargs) | return _core_.Rect2D_MoveLeftBottomTo(*args, **kwargs) | MoveLeftBottomTo(self, Point2D pt) | MoveLeftBottomTo(self, Point2D pt) | [
"MoveLeftBottomTo",
"(",
"self",
"Point2D",
"pt",
")"
] | def MoveLeftBottomTo(*args, **kwargs):
"""MoveLeftBottomTo(self, Point2D pt)"""
return _core_.Rect2D_MoveLeftBottomTo(*args, **kwargs) | [
"def",
"MoveLeftBottomTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect2D_MoveLeftBottomTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L1923-L1925 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/coprocessing.py | python | CoProcessor.WriteImages | (self, datadescription, rescale_lookuptable=False,
image_quality=None, padding_amount=0) | This method will update all views, if present and write output
images, as needed.
**Parameters**
datadescription
Catalyst data-description object
rescale_lookuptable (bool, optional)
If True, when all lookup tables
are rescaled using current data ranges before saving the images.
Defaults to False.
image_quality (int, optional)
If specified, should be a value in
the range (0, 100) that specifies the image quality. For JPEG, 0
is low quality i.e. max compression, 100 is best quality i.e.
least compression. For legacy reasons, this is inverted for PNG
(which uses lossless compression). For PNG, 0 is no compression
i.e maximum image size, while 100 is most compressed and hence
least image size.
If not specified, for saving PNGs 0 is assumed to minimize
performance impact.
padding_amount (int, optional)
Amount to pad the time index by. | This method will update all views, if present and write output
images, as needed. | [
"This",
"method",
"will",
"update",
"all",
"views",
"if",
"present",
"and",
"write",
"output",
"images",
"as",
"needed",
"."
] | def WriteImages(self, datadescription, rescale_lookuptable=False,
image_quality=None, padding_amount=0):
"""This method will update all views, if present and write output
images, as needed.
**Parameters**
datadescription
Catalyst data-description object
rescale_lookuptable (bool, optional)
If True, when all lookup tables
are rescaled using current data ranges before saving the images.
Defaults to False.
image_quality (int, optional)
If specified, should be a value in
the range (0, 100) that specifies the image quality. For JPEG, 0
is low quality i.e. max compression, 100 is best quality i.e.
least compression. For legacy reasons, this is inverted for PNG
(which uses lossless compression). For PNG, 0 is no compression
i.e maximum image size, while 100 is most compressed and hence
least image size.
If not specified, for saving PNGs 0 is assumed to minimize
performance impact.
padding_amount (int, optional)
Amount to pad the time index by.
"""
timestep = datadescription.GetTimeStep()
cinema_dirs = []
for view in self.__ViewsList:
if (view.cpFrequency and self.NeedToOutput(datadescription, view.cpFrequency)) or \
datadescription.GetForceOutput() == True:
fname = view.cpFileName
ts = str(timestep).rjust(padding_amount, '0')
fname = fname.replace("%t", ts)
if view.cpFitToScreen != 0:
view.ViewTime = datadescription.GetTime()
if view.IsA("vtkSMRenderViewProxy") == True:
view.ResetCamera()
elif view.IsA("vtkSMContextViewProxy") == True:
view.ResetDisplay()
else:
print (' do not know what to do with a ', view.GetClassName())
view.ViewTime = datadescription.GetTime()
if rescale_lookuptable:
self.RescaleDataRange(view, datadescription.GetTime())
cinemaOptions = view.cpCinemaOptions
if cinemaOptions and 'camera' in cinemaOptions:
if 'composite' in view.cpCinemaOptions and view.cpCinemaOptions['composite'] == True:
dirname, filelist = self.UpdateCinema(view, datadescription,
specLevel="B")
else:
dirname, filelist = self.UpdateCinema(view, datadescription,
specLevel="A")
if dirname:
self.__AppendCViewToCinemaDTable(timestep, "view_%s" % self.__ViewsList.index(view), filelist)
cinema_dirs.append(dirname)
else:
if '/' in fname and createDirectoriesIfNeeded:
oktowrite = [1.]
import vtk
comm = vtk.vtkMultiProcessController.GetGlobalController()
if comm.GetLocalProcessId() == 0:
import os
newDir = fname[0:fname.rfind('/')]
try:
os.makedirs(newDir)
except OSError:
if not os.path.isdir(newDir):
print ("ERROR: Cannot make directory for", fname, ". No image will be output.")
oktowrite[0] = 0.
comm.Broadcast(oktowrite, 1, 0)
if oktowrite[0] == 0:
# we can't make the directory so no reason to update the pipeline
return
if image_quality is None and fname.endswith('png'):
# for png quality = 0 means no compression. compression can be a potentially
# very costly serial operation on process 0
quality = 0
elif image_quality is not None:
quality = int(image_quality)
else:
# let simple.SaveScreenshot pick a default.
quality = None
if fname.endswith('png') and view.cpCompression is not None and view.cpCompression != -1 :
simple.SaveScreenshot(fname, view,
CompressionLevel=view.cpCompression,
ImageResolution=view.ViewSize)
else:
simple.SaveScreenshot(fname, view,
magnification=view.cpMagnification,
quality=quality)
self.__AppendToCinemaDTable(timestep, "view_%s" % self.__ViewsList.index(view), fname)
if len(cinema_dirs) > 1:
import paraview.tpl.cinema_python.adaptors.paraview.pv_introspect as pv_introspect
pv_introspect.make_workspace_file("cinema\\", cinema_dirs)
self.__FinalizeCinemaDTable() | [
"def",
"WriteImages",
"(",
"self",
",",
"datadescription",
",",
"rescale_lookuptable",
"=",
"False",
",",
"image_quality",
"=",
"None",
",",
"padding_amount",
"=",
"0",
")",
":",
"timestep",
"=",
"datadescription",
".",
"GetTimeStep",
"(",
")",
"cinema_dirs",
... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/coprocessing.py#L268-L373 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/timeseries/python/timeseries/ar_model.py | python | ARModel.prediction_ops | (self, times, values) | return {"activations": activations,
"mean": predicted_mean,
"covariance": predicted_covariance} | Compute model predictions given input data.
Args:
times: A [batch size, self.window_size] integer Tensor, the first
self.input_window_size times in each part of the batch indicating
input features, and the last self.output_window_size times indicating
prediction times.
values: A [batch size, self.input_window_size, self.num_features] Tensor
with input features.
Returns:
Tuple (predicted_mean, predicted_covariance), where each element is a
Tensor with shape [batch size, self.output_window_size,
self.num_features]. | Compute model predictions given input data. | [
"Compute",
"model",
"predictions",
"given",
"input",
"data",
"."
] | def prediction_ops(self, times, values):
"""Compute model predictions given input data.
Args:
times: A [batch size, self.window_size] integer Tensor, the first
self.input_window_size times in each part of the batch indicating
input features, and the last self.output_window_size times indicating
prediction times.
values: A [batch size, self.input_window_size, self.num_features] Tensor
with input features.
Returns:
Tuple (predicted_mean, predicted_covariance), where each element is a
Tensor with shape [batch size, self.output_window_size,
self.num_features].
"""
times.get_shape().assert_is_compatible_with([None, self.window_size])
activations = []
if self.input_window_size:
values.get_shape().assert_is_compatible_with(
[None, self.input_window_size, self.num_features])
# Create input features.
if self._periods:
_, time_features = self._compute_time_features(times)
activation_size = self.window_size * self._buckets * len(self._periods)
activation = array_ops.reshape(time_features, [-1, activation_size])
else:
activation_size = 0
activation = None
if self.input_window_size:
inp = array_ops.slice(values, [0, 0, 0], [-1, self.input_window_size, -1])
inp_size = self.input_window_size * self.num_features
inp = array_ops.reshape(inp, [-1, inp_size])
if activation is not None:
activation = array_ops.concat([inp, activation], 1)
else:
activation = inp
activation_size += inp_size
assert activation_size
activations.append((activation, activation_size))
# Create hidden layers.
activations += self._create_hidden_stack(activation, activation_size)
# Create mean and convariance ops.
predicted_mean = self._predicted_mean_op(activations)
predicted_covariance = self._predicted_covariance_op(activations,
self.num_features)
return {"activations": activations,
"mean": predicted_mean,
"covariance": predicted_covariance} | [
"def",
"prediction_ops",
"(",
"self",
",",
"times",
",",
"values",
")",
":",
"times",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"[",
"None",
",",
"self",
".",
"window_size",
"]",
")",
"activations",
"=",
"[",
"]",
"if",
"self",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/ar_model.py#L194-L242 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | transpose | (a, axes=None) | Permute the dimensions of an array.
This function is exactly equivalent to `numpy.transpose`.
See Also
--------
numpy.transpose : Equivalent function in top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>>> x
masked_array(data =
[[0 1]
[2 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)
>>> ma.transpose(x)
masked_array(data =
[[0 2]
[1 --]],
mask =
[[False False]
[False True]],
fill_value = 999999) | Permute the dimensions of an array. | [
"Permute",
"the",
"dimensions",
"of",
"an",
"array",
"."
] | def transpose(a, axes=None):
"""
Permute the dimensions of an array.
This function is exactly equivalent to `numpy.transpose`.
See Also
--------
numpy.transpose : Equivalent function in top-level NumPy module.
Examples
--------
>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>>> x
masked_array(data =
[[0 1]
[2 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)
>>> ma.transpose(x)
masked_array(data =
[[0 2]
[1 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)
"""
#We can't use 'frommethod', as 'transpose' doesn't take keywords
try:
return a.transpose(axes)
except AttributeError:
return narray(a, copy=False).transpose(axes).view(MaskedArray) | [
"def",
"transpose",
"(",
"a",
",",
"axes",
"=",
"None",
")",
":",
"#We can't use 'frommethod', as 'transpose' doesn't take keywords",
"try",
":",
"return",
"a",
".",
"transpose",
"(",
"axes",
")",
"except",
"AttributeError",
":",
"return",
"narray",
"(",
"a",
",... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L6348-L6385 | ||
lattice/quda | 7d04db018e01718e80cf32d78f44e8cdffdbe46e | lib/generate/wrap.py | python | Param.setDeclaration | (self, decl) | Needs to be called by Declaration to finish initing the arg. | Needs to be called by Declaration to finish initing the arg. | [
"Needs",
"to",
"be",
"called",
"by",
"Declaration",
"to",
"finish",
"initing",
"the",
"arg",
"."
] | def setDeclaration(self, decl):
"""Needs to be called by Declaration to finish initing the arg."""
self.decl = decl | [
"def",
"setDeclaration",
"(",
"self",
",",
"decl",
")",
":",
"self",
".",
"decl",
"=",
"decl"
] | https://github.com/lattice/quda/blob/7d04db018e01718e80cf32d78f44e8cdffdbe46e/lib/generate/wrap.py#L338-L340 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/losses/__init__.py | python | lambda_rank | (output, gain, group, name='') | return lambda_rank(output, gain, group, name) | r'''
Groups samples according to ``group``, sorts
them within each group based on ``output`` and
computes the Normalized Discounted Cumulative Gain
(NDCG) at infinity for each group. Concretely,
the Discounted Cumulative Gain (DCG) at infinity is:
:math:`\mathrm{DCG_{\infty}}()=\sum_{i=0}^{\infty} \frac{gain_{(i)}}{\log(i+2)}`
where :math:`gain_{(i)}` means the gain of the :math:`i`-th ranked sample.
The NDCG is just the DCG divided by the maximum achievable DCG (obtained
by placing the samples with the largest gain at the top of the ranking).
Samples in the same group must appear in order of decreasing gain.
It returns 1 minus the average NDCG across all the groups in the minibatch
multiplied by 100 times the number of samples in the minibatch.
In the backward direction it back-propagates LambdaRank gradients.
Example:
>>> group = C.input_variable((1,))
>>> score = C.input_variable((1,), needs_gradient=True)
>>> gain = C.input_variable((1,))
>>> g = np.array([1, 1, 2, 2], dtype=np.float32).reshape(4,1)
>>> s = np.array([1, 2, 3, 4], dtype=np.float32).reshape(4,1)
>>> n = np.array([7, 1, 3, 1], dtype=np.float32).reshape(4,1)
>>> f = C.lambda_rank(score, gain, group)
>>> np.round(f.grad({score:s, gain:n, group: g}, wrt=[score]),4)
array([[-0.2121],
<BLANKLINE>
[ 0.2121],
<BLANKLINE>
[-0.1486],
<BLANKLINE>
[ 0.1486]], dtype=float32)
Args:
output: score of each sample
gain: gain of each sample
group: group of each sample
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function` | r'''
Groups samples according to ``group``, sorts
them within each group based on ``output`` and
computes the Normalized Discounted Cumulative Gain
(NDCG) at infinity for each group. Concretely,
the Discounted Cumulative Gain (DCG) at infinity is: | [
"r",
"Groups",
"samples",
"according",
"to",
"group",
"sorts",
"them",
"within",
"each",
"group",
"based",
"on",
"output",
"and",
"computes",
"the",
"Normalized",
"Discounted",
"Cumulative",
"Gain",
"(",
"NDCG",
")",
"at",
"infinity",
"for",
"each",
"group",
... | def lambda_rank(output, gain, group, name=''):
r'''
Groups samples according to ``group``, sorts
them within each group based on ``output`` and
computes the Normalized Discounted Cumulative Gain
(NDCG) at infinity for each group. Concretely,
the Discounted Cumulative Gain (DCG) at infinity is:
:math:`\mathrm{DCG_{\infty}}()=\sum_{i=0}^{\infty} \frac{gain_{(i)}}{\log(i+2)}`
where :math:`gain_{(i)}` means the gain of the :math:`i`-th ranked sample.
The NDCG is just the DCG divided by the maximum achievable DCG (obtained
by placing the samples with the largest gain at the top of the ranking).
Samples in the same group must appear in order of decreasing gain.
It returns 1 minus the average NDCG across all the groups in the minibatch
multiplied by 100 times the number of samples in the minibatch.
In the backward direction it back-propagates LambdaRank gradients.
Example:
>>> group = C.input_variable((1,))
>>> score = C.input_variable((1,), needs_gradient=True)
>>> gain = C.input_variable((1,))
>>> g = np.array([1, 1, 2, 2], dtype=np.float32).reshape(4,1)
>>> s = np.array([1, 2, 3, 4], dtype=np.float32).reshape(4,1)
>>> n = np.array([7, 1, 3, 1], dtype=np.float32).reshape(4,1)
>>> f = C.lambda_rank(score, gain, group)
>>> np.round(f.grad({score:s, gain:n, group: g}, wrt=[score]),4)
array([[-0.2121],
<BLANKLINE>
[ 0.2121],
<BLANKLINE>
[-0.1486],
<BLANKLINE>
[ 0.1486]], dtype=float32)
Args:
output: score of each sample
gain: gain of each sample
group: group of each sample
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
'''
from cntk.cntk_py import lambda_rank
dtype = get_data_type(output, gain, group)
output = sanitize_input(output, dtype)
gain = sanitize_input(gain, dtype)
group = sanitize_input(group, dtype)
return lambda_rank(output, gain, group, name) | [
"def",
"lambda_rank",
"(",
"output",
",",
"gain",
",",
"group",
",",
"name",
"=",
"''",
")",
":",
"from",
"cntk",
".",
"cntk_py",
"import",
"lambda_rank",
"dtype",
"=",
"get_data_type",
"(",
"output",
",",
"gain",
",",
"group",
")",
"output",
"=",
"san... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/losses/__init__.py#L213-L265 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/incubate/nn/functional/fused_transformer.py | python | fused_multi_head_attention | (x,
qkv_weight,
linear_weight,
pre_layer_norm=False,
pre_ln_scale=None,
pre_ln_bias=None,
ln_scale=None,
ln_bias=None,
pre_ln_epsilon=1e-05,
qkv_bias=None,
linear_bias=None,
attn_mask=None,
dropout_rate=0.5,
attn_dropout_rate=0.5,
ln_epsilon=1e-05,
training=True,
mode='upscale_in_train',
name=None) | Attention mapps queries and a set of key-value pairs to outputs, and
Multi-Head Attention performs multiple parallel attention to jointly attending
to information from different representation subspaces. This API only
support self_attention. The pseudo code is as follows:
.. code-block:: python
if pre_layer_norm:
out = layer_norm(x)
out = linear(out) + qkv) + bias
else:
out = linear(x) + bias
out = transpose(out, perm=[2, 0, 3, 1, 4])
# extract q, k and v from out.
q = out[0:1,::]
k = out[1:2,::]
v = out[2:3,::]
out = q * k^t
out = attn_mask + out
out = softmax(out)
out = dropout(out)
out = out * v
out = transpose(out, perm=[0, 2, 1, 3])
out = out_linear(out)
if pre_layer_norm:
out = x + dropout(linear_bias + out)
else:
out = layer_norm(x + dropout(linear_bias + out))
Parameters:
x (Tensor): The input tensor of fused_multi_head_attention. The shape is
`[batch\_size, sequence\_len, embed\_dim]`.
qkv_weight (Tensor): The qkv weight tensor. The shape is `[3, num_head, dim_head, dim_embed]`.
linear_weight (Tensor): The linear weight tensor. The shape is `[embed_dim, embed_dim]`.
pre_layer_norm (bool, optional): whether it is pre_layer_norm (True) or post_layer_norm architecture
(False). Default False.
pre_ln_scale (Tensor, optional): The weight tensor of pre layernorm. Default None.
pre_ln_bias (Tensor, optional): The bias tensor of pre layernorm. Default None.
ln_scale (Tensor, optional): The weight tensor of layernorm. Default None.
ln_bias (Tensor, optional): The bias tensor of layernorm. Default None.
pre_ln_epsilon (float, optional): Small float value added to denominator of the pre layer_norm
to avoid dividing by zero. Default is 1e-5.
qkv_bias (Tensor, optional): The bias of qkv computation. The shape is `[3, num_head, dim_head]`.
Default None.
linear_bias (Tensor, optional): The bias of linear. The shape is `[embed_dim]`. Default None.
attn_mask (Tensor, optional): A tensor used in multi-head attention to prevents attention to
some unwanted positions, usually the paddings or the subsequent positions. It is a tensor
with shape broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. When the
data type is bool, the unwanted positions have `False` values and the others have `True` values.
When the data type is int, the unwanted positions have 0 values and the others have 1 values.
When the data type is float, the unwanted positions have `-INF` values and the others have 0 values.
It can be None when nothing wanted or needed to be prevented attention to. Default None.
dropout_rate (float, optional): The dropout probability used on attention
weights to drop some attention targets for the dropout after attention.
0 for no dropout. Default 0.5.
attn_dropout_rate (float, optional): The dropout probability used on attention
weights to drop some attention targets for the dropout in attention.
0 for no dropout. Default 0.5.
ln_epsilon (float, optional): Small float value added to denominator of layer_norm
to avoid dividing by zero. Default is 1e-5.
training (bool, optional): A flag indicating whether it is in train phrase or not. Default True.
mode (str, optional): ['upscale_in_train'(default) | 'downscale_in_infer']
1. upscale_in_train(default), upscale the output at training time
- train: out = input * mask / ( 1.0 - p )
- inference: out = input
2. downscale_in_infer, downscale the output at inference
- train: out = input * mask
- inference: out = input * (1.0 - p)
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: The output Tensor, the data type and shape is same as `x`.
Examples:
.. code-block:: python
# required: gpu
import paddle
import paddle.incubate.nn.functional as F
# input: [batch_size, seq_len, embed_dim]
x = paddle.rand(shape=(2, 4, 128), dtype="float32")
# qkv_weight: [3, num_head, head_dim, embed_dim]
qkv_weight = paddle.rand(shape=(3, 4, 32, 128), dtype="float32")
# qkv_bias: [3, num_head, head_dim]
qkv_bias = paddle.rand(shape=(3, 4, 32), dtype="float32")
# linear_weight: [embed_dim, embed_dim]
linear_weight = paddle.rand(shape=(128, 128), dtype="float32")
# linear_bias: [embed_dim]
linear_bias = paddle.rand(shape=[128], dtype="float32")
# self attention mask: [batch_size, num_heads, seq_len, seq_len]
attn_mask = paddle.rand(shape=(2, 4, 4, 4), dtype="float32")
# output: [batch_size, seq_len, embed_dim]
output = F.fused_multi_head_attention(
x, qkv_weight, linear_weight, False,
None, None, None, None, 1e-5, qkv_bias,
linear_bias, attn_mask)
# [2, 4, 128]
print(output.shape) | Attention mapps queries and a set of key-value pairs to outputs, and
Multi-Head Attention performs multiple parallel attention to jointly attending
to information from different representation subspaces. This API only
support self_attention. The pseudo code is as follows: | [
"Attention",
"mapps",
"queries",
"and",
"a",
"set",
"of",
"key",
"-",
"value",
"pairs",
"to",
"outputs",
"and",
"Multi",
"-",
"Head",
"Attention",
"performs",
"multiple",
"parallel",
"attention",
"to",
"jointly",
"attending",
"to",
"information",
"from",
"diff... | def fused_multi_head_attention(x,
qkv_weight,
linear_weight,
pre_layer_norm=False,
pre_ln_scale=None,
pre_ln_bias=None,
ln_scale=None,
ln_bias=None,
pre_ln_epsilon=1e-05,
qkv_bias=None,
linear_bias=None,
attn_mask=None,
dropout_rate=0.5,
attn_dropout_rate=0.5,
ln_epsilon=1e-05,
training=True,
mode='upscale_in_train',
name=None):
"""
Attention mapps queries and a set of key-value pairs to outputs, and
Multi-Head Attention performs multiple parallel attention to jointly attending
to information from different representation subspaces. This API only
support self_attention. The pseudo code is as follows:
.. code-block:: python
if pre_layer_norm:
out = layer_norm(x)
out = linear(out) + qkv) + bias
else:
out = linear(x) + bias
out = transpose(out, perm=[2, 0, 3, 1, 4])
# extract q, k and v from out.
q = out[0:1,::]
k = out[1:2,::]
v = out[2:3,::]
out = q * k^t
out = attn_mask + out
out = softmax(out)
out = dropout(out)
out = out * v
out = transpose(out, perm=[0, 2, 1, 3])
out = out_linear(out)
if pre_layer_norm:
out = x + dropout(linear_bias + out)
else:
out = layer_norm(x + dropout(linear_bias + out))
Parameters:
x (Tensor): The input tensor of fused_multi_head_attention. The shape is
`[batch\_size, sequence\_len, embed\_dim]`.
qkv_weight (Tensor): The qkv weight tensor. The shape is `[3, num_head, dim_head, dim_embed]`.
linear_weight (Tensor): The linear weight tensor. The shape is `[embed_dim, embed_dim]`.
pre_layer_norm (bool, optional): whether it is pre_layer_norm (True) or post_layer_norm architecture
(False). Default False.
pre_ln_scale (Tensor, optional): The weight tensor of pre layernorm. Default None.
pre_ln_bias (Tensor, optional): The bias tensor of pre layernorm. Default None.
ln_scale (Tensor, optional): The weight tensor of layernorm. Default None.
ln_bias (Tensor, optional): The bias tensor of layernorm. Default None.
pre_ln_epsilon (float, optional): Small float value added to denominator of the pre layer_norm
to avoid dividing by zero. Default is 1e-5.
qkv_bias (Tensor, optional): The bias of qkv computation. The shape is `[3, num_head, dim_head]`.
Default None.
linear_bias (Tensor, optional): The bias of linear. The shape is `[embed_dim]`. Default None.
attn_mask (Tensor, optional): A tensor used in multi-head attention to prevents attention to
some unwanted positions, usually the paddings or the subsequent positions. It is a tensor
with shape broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. When the
data type is bool, the unwanted positions have `False` values and the others have `True` values.
When the data type is int, the unwanted positions have 0 values and the others have 1 values.
When the data type is float, the unwanted positions have `-INF` values and the others have 0 values.
It can be None when nothing wanted or needed to be prevented attention to. Default None.
dropout_rate (float, optional): The dropout probability used on attention
weights to drop some attention targets for the dropout after attention.
0 for no dropout. Default 0.5.
attn_dropout_rate (float, optional): The dropout probability used on attention
weights to drop some attention targets for the dropout in attention.
0 for no dropout. Default 0.5.
ln_epsilon (float, optional): Small float value added to denominator of layer_norm
to avoid dividing by zero. Default is 1e-5.
training (bool, optional): A flag indicating whether it is in train phrase or not. Default True.
mode (str, optional): ['upscale_in_train'(default) | 'downscale_in_infer']
1. upscale_in_train(default), upscale the output at training time
- train: out = input * mask / ( 1.0 - p )
- inference: out = input
2. downscale_in_infer, downscale the output at inference
- train: out = input * mask
- inference: out = input * (1.0 - p)
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: The output Tensor, the data type and shape is same as `x`.
Examples:
.. code-block:: python
# required: gpu
import paddle
import paddle.incubate.nn.functional as F
# input: [batch_size, seq_len, embed_dim]
x = paddle.rand(shape=(2, 4, 128), dtype="float32")
# qkv_weight: [3, num_head, head_dim, embed_dim]
qkv_weight = paddle.rand(shape=(3, 4, 32, 128), dtype="float32")
# qkv_bias: [3, num_head, head_dim]
qkv_bias = paddle.rand(shape=(3, 4, 32), dtype="float32")
# linear_weight: [embed_dim, embed_dim]
linear_weight = paddle.rand(shape=(128, 128), dtype="float32")
# linear_bias: [embed_dim]
linear_bias = paddle.rand(shape=[128], dtype="float32")
# self attention mask: [batch_size, num_heads, seq_len, seq_len]
attn_mask = paddle.rand(shape=(2, 4, 4, 4), dtype="float32")
# output: [batch_size, seq_len, embed_dim]
output = F.fused_multi_head_attention(
x, qkv_weight, linear_weight, False,
None, None, None, None, 1e-5, qkv_bias,
linear_bias, attn_mask)
# [2, 4, 128]
print(output.shape)
"""
seed = None
if mode not in ('downscale_in_infer', 'upscale_in_train'):
raise ValueError(
"mode argument should be 'downscale_in_infer' or 'upscale_in_train'")
mode = 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode #semantic transfer
if in_dygraph_mode():
if default_main_program().random_seed != 0:
seed = default_main_program().random_seed
# pre_ln_mean, pre_ln_variance, pre_ln_out, qkv_out, qkv_bias_out, transpose_out, qk_out,
# qktv_out, softmax_out, attn_dropout_mask_out, attn_dropout_out, attn_mask_out, fmha_out,
# linear_out, dropout_mask_out, ln_mean_out, ln_var_out, bias_dropout_residual_out, final_out
assert len(qkv_weight.shape
) == 4, "The dims of the shape of qkv_weight should be 4."
assert qkv_weight.shape[
0] == 3, "The shape of qkv_weight should be [3, num_head, head_dim, embed_dim]."
assert qkv_weight.shape[3] == x.shape[
2], "The 3rd dim of qkv_weight and 2nd dim of x should be the same, i.e., embed_dim."
assert qkv_weight.shape[1] * qkv_weight.shape[2] == qkv_weight.shape[
3], "embed_dim must be divisible by num_heads."
_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, final_out = _C_ops.fused_attention(
x, pre_ln_scale, pre_ln_bias, qkv_weight, qkv_bias, attn_mask,
linear_weight, linear_bias, ln_scale, ln_bias, 'pre_layer_norm',
pre_layer_norm, 'epsilon', pre_ln_epsilon, 'dropout_rate',
dropout_rate, 'attn_dropout_rate', attn_dropout_rate, 'ln_epsilon',
ln_epsilon, 'attn_dropout_is_test', not training, 'dropout_is_test',
not training, 'attn_dropout_fix_seed', seed is not None,
'dropout_fix_seed', seed is not None, 'attn_dropout_seed', seed
if seed is not None else 0, 'dropout_seed', seed
if seed is not None else 0, 'attn_dropout_implementation', mode,
'dropout_implementation', mode)
return final_out
else:
helper = LayerHelper('fused_multi_head_attention', **locals())
dtype = x.dtype
# check dtypes
check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'],
'fused_multihead_attention')
check_dtype(dtype, 'dtype', ['float16', 'float32', 'float64'],
'fused_multi_head_attention')
# set inputs
inputs = dict()
inputs['X'] = [x]
if pre_ln_scale:
inputs['LnScale'] = [pre_ln_scale]
if pre_ln_bias:
inputs['LnBias'] = [pre_ln_bias]
inputs['QKVW'] = [qkv_weight]
if qkv_bias is not None:
inputs['QKVBias'] = [qkv_bias]
inputs['SrcMask'] = attn_mask
inputs['OutLinearW'] = [linear_weight]
if linear_bias is not None:
inputs['OutLinearBias'] = [linear_bias]
if ln_scale:
inputs['Ln2Scale'] = [ln_scale]
if ln_bias:
inputs['Ln2Bias'] = [ln_bias]
if (seed is None or seed == 0) and helper.main_program.random_seed != 0:
seed = helper.main_program.random_seed
# set attrs
attrs = {
'pre_layer_norm': pre_layer_norm,
'epsilon': pre_ln_epsilon,
'ln_epsilon': ln_epsilon,
'dropout_rate': dropout_rate,
'attn_dropout_rate': attn_dropout_rate,
'attn_dropout_is_test': not training,
'dropout_is_test': not training,
'attn_dropout_fix_seed': seed is not None,
'dropout_fix_seed': seed is not None,
'attn_dropout_seed': seed if seed is not None else 0,
'dropout_seed': seed if seed is not None else 0,
'attn_dropout_implementation': mode,
'dropout_implementation': mode,
}
# set outputs
pre_ln_mean_out = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=True)
pre_ln_variance_out = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=True)
pre_ln_out = helper.create_variable_for_type_inference(dtype=dtype)
qkv_out = helper.create_variable_for_type_inference(dtype=dtype)
qkv_bias_out = helper.create_variable_for_type_inference(dtype=dtype)
transpose_out = helper.create_variable_for_type_inference(dtype=dtype)
qk_out = helper.create_variable_for_type_inference(dtype=dtype)
qktv_out = helper.create_variable_for_type_inference(dtype=dtype)
softmax_out = helper.create_variable_for_type_inference(dtype=dtype)
attn_dropout_mask_out = helper.create_variable_for_type_inference(
dtype=core.VarDesc.VarType.UINT8, stop_gradient=True)
attn_dropout_out = helper.create_variable_for_type_inference(
dtype=dtype)
attn_mask_out = helper.create_variable_for_type_inference(dtype=dtype)
fmha_out = helper.create_variable_for_type_inference(dtype=dtype)
out_linear_out = helper.create_variable_for_type_inference(dtype=dtype)
dropout_mask_out = helper.create_variable_for_type_inference(
dtype=core.VarDesc.VarType.UINT8, stop_gradient=True)
ln_mean_out = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=True)
ln_variance_out = helper.create_variable_for_type_inference(
dtype=dtype, stop_gradient=True)
bias_dropout_residual_out = helper.create_variable_for_type_inference(
dtype=dtype)
final_out = helper.create_variable_for_type_inference(dtype=dtype)
helper.append_op(
type='fused_attention',
inputs=inputs,
outputs={
"LnMean": pre_ln_mean_out,
"LnVariance": pre_ln_variance_out,
"LnOut": pre_ln_out,
"QKVOut": qkv_out,
"QKVBiasOut": qkv_bias_out,
"TransposeOut2": transpose_out,
"QKOut": qk_out,
"QKTVOut": qktv_out,
"SoftmaxOut": softmax_out,
"AttnDropoutMaskOut": attn_dropout_mask_out,
"AttnDropoutOut": attn_dropout_out,
"SrcMaskOut": attn_mask_out,
"FMHAOut": fmha_out,
"OutLinearOut": out_linear_out,
"DropoutMaskOut": dropout_mask_out,
"Ln2Mean": ln_mean_out,
"Ln2Variance": ln_variance_out,
"BiasDropoutResidualOut": bias_dropout_residual_out,
'Y': final_out
},
attrs=attrs)
return final_out | [
"def",
"fused_multi_head_attention",
"(",
"x",
",",
"qkv_weight",
",",
"linear_weight",
",",
"pre_layer_norm",
"=",
"False",
",",
"pre_ln_scale",
"=",
"None",
",",
"pre_ln_bias",
"=",
"None",
",",
"ln_scale",
"=",
"None",
",",
"ln_bias",
"=",
"None",
",",
"p... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/incubate/nn/functional/fused_transformer.py#L215-L478 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | core/src/plugins/filed/python/ovirt/BareosFdPluginOvirt.py | python | BareosFdPluginOvirt.parse_plugin_definition | (self, plugindef) | return bareosfd.bRC_OK | Parses the plugin arguments | Parses the plugin arguments | [
"Parses",
"the",
"plugin",
"arguments"
] | def parse_plugin_definition(self, plugindef):
"""
Parses the plugin arguments
"""
super(BareosFdPluginOvirt, self).parse_plugin_definition(plugindef)
bareosfd.DebugMessage(
100,
"BareosFdPluginOvirt:parse_plugin_definition() called with options '%s' \n"
% str(self.options),
)
# if the option config_file is present, parse the given file
config_file = self.options.get("config_file")
if config_file:
if not self.parse_config_file():
return bareosfd.bRC_Error
self.ovirt.set_options(self.options)
return bareosfd.bRC_OK | [
"def",
"parse_plugin_definition",
"(",
"self",
",",
"plugindef",
")",
":",
"super",
"(",
"BareosFdPluginOvirt",
",",
"self",
")",
".",
"parse_plugin_definition",
"(",
"plugindef",
")",
"bareosfd",
".",
"DebugMessage",
"(",
"100",
",",
"\"BareosFdPluginOvirt:parse_pl... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/ovirt/BareosFdPluginOvirt.py#L96-L115 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/multiprocessing/sharedctypes.py | python | Array | (typecode_or_type, size_or_initializer, **kwds) | return synchronized(obj, lock) | Return a synchronization wrapper for a RawArray | Return a synchronization wrapper for a RawArray | [
"Return",
"a",
"synchronization",
"wrapper",
"for",
"a",
"RawArray"
] | def Array(typecode_or_type, size_or_initializer, **kwds):
'''
Return a synchronization wrapper for a RawArray
'''
lock = kwds.pop('lock', None)
if kwds:
raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys())
obj = RawArray(typecode_or_type, size_or_initializer)
if lock is False:
return obj
if lock in (True, None):
lock = RLock()
if not hasattr(lock, 'acquire'):
raise AttributeError("'%r' has no method 'acquire'" % lock)
return synchronized(obj, lock) | [
"def",
"Array",
"(",
"typecode_or_type",
",",
"size_or_initializer",
",",
"*",
"*",
"kwds",
")",
":",
"lock",
"=",
"kwds",
".",
"pop",
"(",
"'lock'",
",",
"None",
")",
"if",
"kwds",
":",
"raise",
"ValueError",
"(",
"'unrecognized keyword argument(s): %s'",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/multiprocessing/sharedctypes.py#L108-L122 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_cocoa/gizmos.py | python | TreeListCtrl.GetItemBold | (*args, **kwargs) | return _gizmos.TreeListCtrl_GetItemBold(*args, **kwargs) | GetItemBold(self, TreeItemId item) -> bool | GetItemBold(self, TreeItemId item) -> bool | [
"GetItemBold",
"(",
"self",
"TreeItemId",
"item",
")",
"-",
">",
"bool"
] | def GetItemBold(*args, **kwargs):
"""GetItemBold(self, TreeItemId item) -> bool"""
return _gizmos.TreeListCtrl_GetItemBold(*args, **kwargs) | [
"def",
"GetItemBold",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_GetItemBold",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L685-L687 | |
abforce/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | tools/checker/match/line.py | python | splitAtSeparators | (expressions) | return splitExpressions | Splits a list of TestExpressions at separators. | Splits a list of TestExpressions at separators. | [
"Splits",
"a",
"list",
"of",
"TestExpressions",
"at",
"separators",
"."
] | def splitAtSeparators(expressions):
""" Splits a list of TestExpressions at separators. """
splitExpressions = []
wordStart = 0
for index, expression in enumerate(expressions):
if expression.variant == TestExpression.Variant.Separator:
splitExpressions.append(expressions[wordStart:index])
wordStart = index + 1
splitExpressions.append(expressions[wordStart:])
return splitExpressions | [
"def",
"splitAtSeparators",
"(",
"expressions",
")",
":",
"splitExpressions",
"=",
"[",
"]",
"wordStart",
"=",
"0",
"for",
"index",
",",
"expression",
"in",
"enumerate",
"(",
"expressions",
")",
":",
"if",
"expression",
".",
"variant",
"==",
"TestExpression",
... | https://github.com/abforce/xposed_art_n/blob/ec3fbe417d74d4664cec053d91dd4e3881176374/tools/checker/match/line.py#L23-L32 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/signal/fft_ops.py | python | _rfft_grad_helper | (rank, irfft_fn) | return _grad | Returns a gradient function for an RFFT of the provided rank. | Returns a gradient function for an RFFT of the provided rank. | [
"Returns",
"a",
"gradient",
"function",
"for",
"an",
"RFFT",
"of",
"the",
"provided",
"rank",
"."
] | def _rfft_grad_helper(rank, irfft_fn):
"""Returns a gradient function for an RFFT of the provided rank."""
# Can't happen because we don't register a gradient for RFFT3D.
assert rank in (1, 2), "Gradient for RFFT3D is not implemented."
def _grad(op, grad):
"""A gradient function for RFFT with the provided `rank` and `irfft_fn`."""
fft_length = op.inputs[1]
complex_dtype = grad.dtype
real_dtype = complex_dtype.real_dtype
input_shape = _array_ops.shape(op.inputs[0])
is_even = _math_ops.cast(1 - (fft_length[-1] % 2), complex_dtype)
def _tile_for_broadcasting(matrix, t):
expanded = _array_ops.reshape(
matrix,
_array_ops.concat([
_array_ops.ones([_array_ops.rank(t) - 2], _dtypes.int32),
_array_ops.shape(matrix)
], 0))
return _array_ops.tile(
expanded, _array_ops.concat([_array_ops.shape(t)[:-2], [1, 1]], 0))
def _mask_matrix(length):
"""Computes t_n = exp(sqrt(-1) * pi * n^2 / line_len)."""
# TODO(rjryan): Speed up computation of twiddle factors using the
# following recurrence relation and cache them across invocations of RFFT.
#
# t_n = exp(sqrt(-1) * pi * n^2 / line_len)
# for n = 0, 1,..., line_len-1.
# For n > 2, use t_n = t_{n-1}^2 / t_{n-2} * t_1^2
a = _array_ops.tile(
_array_ops.expand_dims(_math_ops.range(length), 0), (length, 1))
b = _array_ops.transpose(a, [1, 0])
return _math_ops.exp(
-2j * np.pi * _math_ops.cast(a * b, complex_dtype) /
_math_ops.cast(length, complex_dtype))
def _ymask(length):
"""A sequence of [1+0j, -1+0j, 1+0j, -1+0j, ...] with length `length`."""
return _math_ops.cast(1 - 2 * (_math_ops.range(length) % 2),
complex_dtype)
y0 = grad[..., 0:1]
if rank == 1:
ym = grad[..., -1:]
extra_terms = y0 + is_even * ym * _ymask(input_shape[-1])
elif rank == 2:
# Create a mask matrix for y0 and ym.
base_mask = _mask_matrix(input_shape[-2])
# Tile base_mask to match y0 in shape so that we can batch-matmul the
# inner 2 dimensions.
tiled_mask = _tile_for_broadcasting(base_mask, y0)
y0_term = _math_ops.matmul(tiled_mask, _math_ops.conj(y0))
extra_terms = y0_term
ym = grad[..., -1:]
ym_term = _math_ops.matmul(tiled_mask, _math_ops.conj(ym))
inner_dim = input_shape[-1]
ym_term = _array_ops.tile(
ym_term,
_array_ops.concat([
_array_ops.ones([_array_ops.rank(grad) - 1], _dtypes.int32),
[inner_dim]
], 0)) * _ymask(inner_dim)
extra_terms += is_even * ym_term
# The gradient of RFFT is the IRFFT of the incoming gradient times a scaling
# factor, plus some additional terms to make up for the components dropped
# due to Hermitian symmetry.
input_size = _math_ops.cast(
_fft_size_for_grad(op.inputs[0], rank), real_dtype)
the_irfft = irfft_fn(grad, fft_length)
return 0.5 * (the_irfft * input_size + _math_ops.real(extra_terms)), None
return _grad | [
"def",
"_rfft_grad_helper",
"(",
"rank",
",",
"irfft_fn",
")",
":",
"# Can't happen because we don't register a gradient for RFFT3D.",
"assert",
"rank",
"in",
"(",
"1",
",",
"2",
")",
",",
"\"Gradient for RFFT3D is not implemented.\"",
"def",
"_grad",
"(",
"op",
",",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/signal/fft_ops.py#L248-L327 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/command/sdist.py | python | sdist.checking_metadata | (self) | return self.metadata_check | Callable used for the check sub-command.
Placed here so user_options can view it | Callable used for the check sub-command. | [
"Callable",
"used",
"for",
"the",
"check",
"sub",
"-",
"command",
"."
] | def checking_metadata(self):
"""Callable used for the check sub-command.
Placed here so user_options can view it"""
return self.metadata_check | [
"def",
"checking_metadata",
"(",
"self",
")",
":",
"return",
"self",
".",
"metadata_check"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/sdist.py#L40-L44 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/bucket.py | python | Bucket.delete_website_configuration | (self, headers=None) | Remove the website configuration from this bucket.
:param dict headers: Additional headers to send with the request. | Remove the website configuration from this bucket. | [
"Remove",
"the",
"website",
"configuration",
"from",
"this",
"bucket",
"."
] | def delete_website_configuration(self, headers=None):
"""Remove the website configuration from this bucket.
:param dict headers: Additional headers to send with the request.
"""
self.configure_website(headers=headers) | [
"def",
"delete_website_configuration",
"(",
"self",
",",
"headers",
"=",
"None",
")",
":",
"self",
".",
"configure_website",
"(",
"headers",
"=",
"headers",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/bucket.py#L912-L917 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[<':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
if startchar == '<': endchar = '>'
# Check first line
(end_pos, num_open) = FindEndOfExpressionInLine(
line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, num_open) = FindEndOfExpressionInLine(
line, 0, num_open, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"startchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"startchar",
"not",
"in",
"'({[<'",
":",
"return",
"(",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L1254-L1297 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py | python | BasicFittingView.number_of_datasets | (self) | return self.workspace_selector.number_of_datasets() | Returns the number of dataset names loaded into the widget. | Returns the number of dataset names loaded into the widget. | [
"Returns",
"the",
"number",
"of",
"dataset",
"names",
"loaded",
"into",
"the",
"widget",
"."
] | def number_of_datasets(self) -> int:
"""Returns the number of dataset names loaded into the widget."""
return self.workspace_selector.number_of_datasets() | [
"def",
"number_of_datasets",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"workspace_selector",
".",
"number_of_datasets",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py#L178-L180 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/packages/six.py | python | add_metaclass | (metaclass) | return wrapper | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass",
"."
] | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/packages/six.py#L812-L825 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/interpolate/_bsplines.py | python | BSpline.__call__ | (self, x, nu=0, extrapolate=None) | return out | Evaluate a spline function.
Parameters
----------
x : array_like
points to evaluate the spline at.
nu: int, optional
derivative to evaluate (default is 0).
extrapolate : bool or 'periodic', optional
whether to extrapolate based on the first and last intervals
or return nans. If 'periodic', periodic extrapolation is used.
Default is `self.extrapolate`.
Returns
-------
y : array_like
Shape is determined by replacing the interpolation axis
in the coefficient array with the shape of `x`. | Evaluate a spline function. | [
"Evaluate",
"a",
"spline",
"function",
"."
] | def __call__(self, x, nu=0, extrapolate=None):
"""
Evaluate a spline function.
Parameters
----------
x : array_like
points to evaluate the spline at.
nu: int, optional
derivative to evaluate (default is 0).
extrapolate : bool or 'periodic', optional
whether to extrapolate based on the first and last intervals
or return nans. If 'periodic', periodic extrapolation is used.
Default is `self.extrapolate`.
Returns
-------
y : array_like
Shape is determined by replacing the interpolation axis
in the coefficient array with the shape of `x`.
"""
if extrapolate is None:
extrapolate = self.extrapolate
x = np.asarray(x)
x_shape, x_ndim = x.shape, x.ndim
x = np.ascontiguousarray(x.ravel(), dtype=np.float_)
# With periodic extrapolation we map x to the segment
# [self.t[k], self.t[n]].
if extrapolate == 'periodic':
n = self.t.size - self.k - 1
x = self.t[self.k] + (x - self.t[self.k]) % (self.t[n] -
self.t[self.k])
extrapolate = False
out = np.empty((len(x), prod(self.c.shape[1:])), dtype=self.c.dtype)
self._ensure_c_contiguous()
self._evaluate(x, nu, extrapolate, out)
out = out.reshape(x_shape + self.c.shape[1:])
if self.axis != 0:
# transpose to move the calculated values to the interpolation axis
l = list(range(out.ndim))
l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
out = out.transpose(l)
return out | [
"def",
"__call__",
"(",
"self",
",",
"x",
",",
"nu",
"=",
"0",
",",
"extrapolate",
"=",
"None",
")",
":",
"if",
"extrapolate",
"is",
"None",
":",
"extrapolate",
"=",
"self",
".",
"extrapolate",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"x_shap... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/_bsplines.py#L310-L355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.