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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateSpan_Week | (*args) | return _misc_.DateSpan_Week(*args) | DateSpan_Week() -> DateSpan | DateSpan_Week() -> DateSpan | [
"DateSpan_Week",
"()",
"-",
">",
"DateSpan"
] | def DateSpan_Week(*args):
"""DateSpan_Week() -> DateSpan"""
return _misc_.DateSpan_Week(*args) | [
"def",
"DateSpan_Week",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Week",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4764-L4766 | |
xiaolonw/caffe-video_triplet | c39ea1ad6e937ccf7deba4510b7e555165abf05f | python/caffe/pycaffe.py | python | _Net_batch | (self, blobs) | Batch blob lists according to net's batch size.
Parameters
----------
blobs: Keys blob names and values are lists of blobs (of any length).
Naturally, all the lists should have the same length.
Yields
------
batch: {blob name: list of blobs} dict for a single batch. | Batch blob lists according to net's batch size. | [
"Batch",
"blob",
"lists",
"according",
"to",
"net",
"s",
"batch",
"size",
"."
] | def _Net_batch(self, blobs):
"""
Batch blob lists according to net's batch size.
Parameters
----------
blobs: Keys blob names and values are lists of blobs (of any length).
Naturally, all the lists should have the same length.
Yields
------
batch: {blob name: list of blobs} dict for a single batch.
"""
num = len(blobs.itervalues().next())
batch_size = self.blobs.itervalues().next().num
remainder = num % batch_size
num_batches = num / batch_size
# Yield full batches.
for b in range(num_batches):
i = b * batch_size
yield {name: blobs[name][i:i + batch_size] for name in blobs}
# Yield last padded batch, if any.
if remainder > 0:
padded_batch = {}
for name in blobs:
padding = np.zeros((batch_size - remainder,)
+ blobs[name].shape[1:])
padded_batch[name] = np.concatenate([blobs[name][-remainder:],
padding])
yield padded_batch | [
"def",
"_Net_batch",
"(",
"self",
",",
"blobs",
")",
":",
"num",
"=",
"len",
"(",
"blobs",
".",
"itervalues",
"(",
")",
".",
"next",
"(",
")",
")",
"batch_size",
"=",
"self",
".",
"blobs",
".",
"itervalues",
"(",
")",
".",
"next",
"(",
")",
".",
... | https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/python/caffe/pycaffe.py#L248-L279 | ||
bastibl/gr-ieee802-15-4 | 1a2999ce2778df279870f028a4ce15d94e60fbd9 | python/bindings/header_utils.py | python | argParse | () | return parser.parse_args() | Parses commandline args. | Parses commandline args. | [
"Parses",
"commandline",
"args",
"."
] | def argParse():
"""Parses commandline args."""
desc='Reads the parameters from the comment block in the pybind files'
parser = ArgumentParser(description=desc)
parser.add_argument("function", help="Operation to perform on comment block of pybind file", choices=["flag_auto","flag_pygccxml","header_filename","header_file_hash","all"])
parser.add_argument("pathname", help="Pathname of pybind c++ file to read, e.g. blockname_python.cc")
return parser.parse_args() | [
"def",
"argParse",
"(",
")",
":",
"desc",
"=",
"'Reads the parameters from the comment block in the pybind files'",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"\"function\"",
",",
"help",
"=",
"\"Operatio... | https://github.com/bastibl/gr-ieee802-15-4/blob/1a2999ce2778df279870f028a4ce15d94e60fbd9/python/bindings/header_utils.py#L53-L61 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/utils/network.py | python | Network.remove_output | (self, *vars: VarNode) | r"""Removes vars from the network output node list | r"""Removes vars from the network output node list | [
"r",
"Removes",
"vars",
"from",
"the",
"network",
"output",
"node",
"list"
] | def remove_output(self, *vars: VarNode):
r"""Removes vars from the network output node list"""
for var in vars:
# use list pop instead of remove to avoid
# compare VarNode use elemwise equal
is_removed = False
for idx, out_var in enumerate(self.output_vars):
if var is out_var:
self.output_vars.pop(idx)
is_removed = True
if not is_removed:
logger.warning(
"Failed to remove {}({}). Please check whether "
"this node is in the output list.".format(var.name, id(var))
) | [
"def",
"remove_output",
"(",
"self",
",",
"*",
"vars",
":",
"VarNode",
")",
":",
"for",
"var",
"in",
"vars",
":",
"# use list pop instead of remove to avoid",
"# compare VarNode use elemwise equal",
"is_removed",
"=",
"False",
"for",
"idx",
",",
"out_var",
"in",
"... | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/utils/network.py#L282-L296 | ||
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | resources/web/server/session_server.py | python | ClientWebSocketHandler.on_message | (self, message) | Log message received from client. | Log message received from client. | [
"Log",
"message",
"received",
"from",
"client",
"."
] | def on_message(self, message):
"""Log message received from client."""
logging.info('[' + self.request.host + '] Ignored client message: ' + str(message)) | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"logging",
".",
"info",
"(",
"'['",
"+",
"self",
".",
"request",
".",
"host",
"+",
"'] Ignored client message: '",
"+",
"str",
"(",
"message",
")",
")"
] | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/web/server/session_server.py#L149-L151 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/struct_types.py | python | _StructTypeInfo.__init__ | (self, struct) | Create a _StructTypeInfo instance. | Create a _StructTypeInfo instance. | [
"Create",
"a",
"_StructTypeInfo",
"instance",
"."
] | def __init__(self, struct):
# type: (ast.Struct) -> None
"""Create a _StructTypeInfo instance."""
self._struct = struct | [
"def",
"__init__",
"(",
"self",
",",
"struct",
")",
":",
"# type: (ast.Struct) -> None",
"self",
".",
"_struct",
"=",
"struct"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/struct_types.py#L241-L244 | ||
Atarity/Lightpack | 4dee73a443cba4c4073291febe450e6c1941f3af | Software/apiexamples/liOSC/OSC.py | python | _readLong | (data) | return (big, rest) | Tries to interpret the next 8 bytes of the data
as a 64-bit signed integer. | Tries to interpret the next 8 bytes of the data
as a 64-bit signed integer. | [
"Tries",
"to",
"interpret",
"the",
"next",
"8",
"bytes",
"of",
"the",
"data",
"as",
"a",
"64",
"-",
"bit",
"signed",
"integer",
"."
] | def _readLong(data):
"""Tries to interpret the next 8 bytes of the data
as a 64-bit signed integer.
"""
high, low = struct.unpack(">ll", data[0:8])
big = (long(high) << 32) + low
rest = data[8:]
return (big, rest) | [
"def",
"_readLong",
"(",
"data",
")",
":",
"high",
",",
"low",
"=",
"struct",
".",
"unpack",
"(",
"\">ll\"",
",",
"data",
"[",
"0",
":",
"8",
"]",
")",
"big",
"=",
"(",
"long",
"(",
"high",
")",
"<<",
"32",
")",
"+",
"low",
"rest",
"=",
"data... | https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/OSC.py#L774-L782 | |
Tokutek/mongo | 0653eabe2c5b9d12b4814617cb7fb2d799937a0f | buildscripts/packager.py | python | httpget | (url, filename) | return filename | Download the contents of url to filename, return filename. | Download the contents of url to filename, return filename. | [
"Download",
"the",
"contents",
"of",
"url",
"to",
"filename",
"return",
"filename",
"."
] | def httpget(url, filename):
"""Download the contents of url to filename, return filename."""
print "Fetching %s to %s." % (url, filename)
conn = None
u=urlparse.urlparse(url)
assert(u.scheme=='http')
try:
conn = httplib.HTTPConnection(u.hostname)
conn.request("GET", u.path)
t=filename+'.TMP'
res = conn.getresponse()
# FIXME: follow redirects
if res.status==200:
f = open(t, 'w')
try:
f.write(res.read())
finally:
f.close()
else:
raise Exception("HTTP error %d" % res.status)
os.rename(t, filename)
finally:
if conn:
conn.close()
return filename | [
"def",
"httpget",
"(",
"url",
",",
"filename",
")",
":",
"print",
"\"Fetching %s to %s.\"",
"%",
"(",
"url",
",",
"filename",
")",
"conn",
"=",
"None",
"u",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"assert",
"(",
"u",
".",
"scheme",
"==",
"... | https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/buildscripts/packager.py#L277-L302 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column.py | python | _LinearModel.cols_to_vars | (self) | return self._cols_to_vars | Returns a dict mapping _FeatureColumns to variables.
See `linear_model` for more information.
This is not populated till `call` is called i.e. layer is built. | Returns a dict mapping _FeatureColumns to variables. | [
"Returns",
"a",
"dict",
"mapping",
"_FeatureColumns",
"to",
"variables",
"."
] | def cols_to_vars(self):
"""Returns a dict mapping _FeatureColumns to variables.
See `linear_model` for more information.
This is not populated till `call` is called i.e. layer is built.
"""
return self._cols_to_vars | [
"def",
"cols_to_vars",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cols_to_vars"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column.py#L664-L670 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | set_learning_phase | (value) | Sets the learning phase to a fixed value.
Arguments:
value: Learning phase value, either 0 or 1 (integers).
Raises:
ValueError: if `value` is neither `0` nor `1`. | Sets the learning phase to a fixed value. | [
"Sets",
"the",
"learning",
"phase",
"to",
"a",
"fixed",
"value",
"."
] | def set_learning_phase(value):
"""Sets the learning phase to a fixed value.
Arguments:
value: Learning phase value, either 0 or 1 (integers).
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned
if value not in {0, 1}:
raise ValueError('Expected learning phase to be ' '0 or 1.')
_GRAPH_LEARNING_PHASES[ops.get_default_graph()] = value | [
"def",
"set_learning_phase",
"(",
"value",
")",
":",
"global",
"_GRAPH_LEARNING_PHASES",
"# pylint: disable=global-variable-not-assigned",
"if",
"value",
"not",
"in",
"{",
"0",
",",
"1",
"}",
":",
"raise",
"ValueError",
"(",
"'Expected learning phase to be '",
"'0 or 1.... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L330-L342 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tty.py | python | setraw | (fd, when=TCSAFLUSH) | Put terminal into a raw mode. | Put terminal into a raw mode. | [
"Put",
"terminal",
"into",
"a",
"raw",
"mode",
"."
] | def setraw(fd, when=TCSAFLUSH):
"""Put terminal into a raw mode."""
mode = tcgetattr(fd)
mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)
mode[OFLAG] = mode[OFLAG] & ~(OPOST)
mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB)
mode[CFLAG] = mode[CFLAG] | CS8
mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG)
mode[CC][VMIN] = 1
mode[CC][VTIME] = 0
tcsetattr(fd, when, mode) | [
"def",
"setraw",
"(",
"fd",
",",
"when",
"=",
"TCSAFLUSH",
")",
":",
"mode",
"=",
"tcgetattr",
"(",
"fd",
")",
"mode",
"[",
"IFLAG",
"]",
"=",
"mode",
"[",
"IFLAG",
"]",
"&",
"~",
"(",
"BRKINT",
"|",
"ICRNL",
"|",
"INPCK",
"|",
"ISTRIP",
"|",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tty.py#L18-L28 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/fcompiler/gnu.py | python | Gnu95FCompiler._universal_flags | (self, cmd) | return arch_flags | Return a list of -arch flags for every supported architecture. | Return a list of -arch flags for every supported architecture. | [
"Return",
"a",
"list",
"of",
"-",
"arch",
"flags",
"for",
"every",
"supported",
"architecture",
"."
] | def _universal_flags(self, cmd):
"""Return a list of -arch flags for every supported architecture."""
if not sys.platform == 'darwin':
return []
arch_flags = []
# get arches the C compiler gets.
c_archs = self._c_arch_flags()
if "i386" in c_archs:
c_archs[c_archs.index("i386")] = "i686"
# check the arches the Fortran compiler supports, and compare with
# arch flags from C compiler
for arch in ["ppc", "i686", "x86_64", "ppc64"]:
if _can_target(cmd, arch) and arch in c_archs:
arch_flags.extend(["-arch", arch])
return arch_flags | [
"def",
"_universal_flags",
"(",
"self",
",",
"cmd",
")",
":",
"if",
"not",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"return",
"[",
"]",
"arch_flags",
"=",
"[",
"]",
"# get arches the C compiler gets.",
"c_archs",
"=",
"self",
".",
"_c_arch_flags",
"(",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/fcompiler/gnu.py#L329-L343 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py | python | Context.set_cipher_list | (self, cipher_list) | Set the list of ciphers to be used in this context.
See the OpenSSL manual for more information (e.g.
:manpage:`ciphers(1)`).
:param bytes cipher_list: An OpenSSL cipher string.
:return: None | Set the list of ciphers to be used in this context. | [
"Set",
"the",
"list",
"of",
"ciphers",
"to",
"be",
"used",
"in",
"this",
"context",
"."
] | def set_cipher_list(self, cipher_list):
"""
Set the list of ciphers to be used in this context.
See the OpenSSL manual for more information (e.g.
:manpage:`ciphers(1)`).
:param bytes cipher_list: An OpenSSL cipher string.
:return: None
"""
cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
if not isinstance(cipher_list, bytes):
raise TypeError("cipher_list must be a byte string.")
_openssl_assert(
_lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
)
# In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
# ciphers even if you pass an invalid cipher. Applications (like
# Twisted) have tests that depend on an error being raised if an
# invalid cipher string is passed, but without the following check
# for the TLS 1.3 specific cipher suites it would never error.
tmpconn = Connection(self, None)
if (
tmpconn.get_cipher_list() == [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256'
]
):
raise Error(
[
(
'SSL routines',
'SSL_CTX_set_cipher_list',
'no cipher match',
),
],
) | [
"def",
"set_cipher_list",
"(",
"self",
",",
"cipher_list",
")",
":",
"cipher_list",
"=",
"_text_to_bytes_and_warn",
"(",
"\"cipher_list\"",
",",
"cipher_list",
")",
"if",
"not",
"isinstance",
"(",
"cipher_list",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py#L1186-L1225 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/jinja2/utils.py | python | LRUCache.copy | (self) | return rv | Return an shallow copy of the instance. | Return an shallow copy of the instance. | [
"Return",
"an",
"shallow",
"copy",
"of",
"the",
"instance",
"."
] | def copy(self):
"""Return an shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv | [
"def",
"copy",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"capacity",
")",
"rv",
".",
"_mapping",
".",
"update",
"(",
"self",
".",
"_mapping",
")",
"rv",
".",
"_queue",
"=",
"deque",
"(",
"self",
".",
"_queue",
... | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/utils.py#L395-L400 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/tools/grit/grit/tool/update_resource_ids/parser.py | python | Tokenize | (data) | Generator to split |data| into tokens.
Each token is specified as |(t, lo, hi)|:
* |t|: Type, with '#' = space / comments, '0' = int, 'S' = string, 'E' = end,
and other characters denoting themselves.
* |lo, hi|: Token's range within |data| (as |data[lo:hi]|). | Generator to split |data| into tokens. | [
"Generator",
"to",
"split",
"|data|",
"into",
"tokens",
"."
] | def Tokenize(data):
"""Generator to split |data| into tokens.
Each token is specified as |(t, lo, hi)|:
* |t|: Type, with '#' = space / comments, '0' = int, 'S' = string, 'E' = end,
and other characters denoting themselves.
* |lo, hi|: Token's range within |data| (as |data[lo:hi]|).
"""
class ctx: # Local context for mutable data shared across inner functions.
pos = 0
def _HasData():
return ctx.pos < len(data)
# Returns True if ended by |not pred()|, or False if ended by EOF.
def _EatWhile(pred):
while _HasData():
if pred(data[ctx.pos]):
ctx.pos += 1
else:
return True
return False
def _NextBlank():
lo = ctx.pos
while True:
if not _EatWhile(_isWhitespace) or data[ctx.pos] != '#':
break
ctx.pos += 1
if not _EatWhile(_isNotNewline):
break
ctx.pos += 1
return None if ctx.pos == lo else (lo, ctx.pos)
def _EatString():
lo = ctx.pos
delim = data[ctx.pos]
is_escaped = False
ctx.pos += 1
while _HasData():
ch = data[ctx.pos]
ctx.pos += 1
if is_escaped:
is_escaped = False
elif ch == '\\':
is_escaped = True
elif ch == delim:
return
raise ValueError('Unterminated string at %s' % _RenderLineCol(data, lo))
while _HasData():
blank = _NextBlank()
if blank is not None:
yield ('#', blank[0], blank[1])
if not _HasData():
break
lo = ctx.pos
ch = data[ctx.pos]
if ch in '{}[],:':
ctx.pos += 1
t = ch
elif ch.isdigit():
_EatWhile(_isDigit)
t = '0'
elif ch in '+-':
ctx.pos += 1
if not _HasData() or not data[ctx.pos].isdigit():
raise ValueError('Invalid int at %s' % _RenderLineCol(data, lo))
_EatWhile(_isDigit)
t = '0'
elif ch in '"\'':
_EatString()
t = 'S'
else:
raise ValueError('Unknown char %s at %s' %
(repr(ch), _RenderLineCol(data, lo)))
yield (t, lo, ctx.pos)
yield ('E', ctx.pos, ctx.pos) | [
"def",
"Tokenize",
"(",
"data",
")",
":",
"class",
"ctx",
":",
"# Local context for mutable data shared across inner functions.",
"pos",
"=",
"0",
"def",
"_HasData",
"(",
")",
":",
"return",
"ctx",
".",
"pos",
"<",
"len",
"(",
"data",
")",
"# Returns True if end... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/tool/update_resource_ids/parser.py#L27-L105 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/errors.py | python | ParserContext._is_node_type | (self, node, node_name, expected_node_type) | return True | Return True if the yaml node type is expected, otherwise returns False and logs an error. | Return True if the yaml node type is expected, otherwise returns False and logs an error. | [
"Return",
"True",
"if",
"the",
"yaml",
"node",
"type",
"is",
"expected",
"otherwise",
"returns",
"False",
"and",
"logs",
"an",
"error",
"."
] | def _is_node_type(self, node, node_name, expected_node_type):
# type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str, str) -> bool
"""Return True if the yaml node type is expected, otherwise returns False and logs an error."""
if not node.id == expected_node_type:
self._add_node_error(
node, ERROR_ID_IS_NODE_TYPE,
"Illegal YAML node type '%s' for '%s', expected YAML node type '%s'" %
(node.id, node_name, expected_node_type))
return False
return True | [
"def",
"_is_node_type",
"(",
"self",
",",
"node",
",",
"node_name",
",",
"expected_node_type",
")",
":",
"# type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str, str) -> bool",
"if",
"not",
"node",
".",
"id",
"==",
"expected_node_type",
":... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L280-L289 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | MaskedArray.__array_finalize__ | (self, obj) | return | Finalizes the masked array. | Finalizes the masked array. | [
"Finalizes",
"the",
"masked",
"array",
"."
] | def __array_finalize__(self, obj):
"""Finalizes the masked array.
"""
# Get main attributes .........
self._update_from(obj)
if isinstance(obj, ndarray):
odtype = obj.dtype
if odtype.names:
_mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype))
else:
_mask = getattr(obj, '_mask', nomask)
else:
_mask = nomask
self._mask = _mask
# Finalize the mask ...........
if self._mask is not nomask:
try:
self._mask.shape = self.shape
except ValueError:
self._mask = nomask
except (TypeError, AttributeError):
# When _mask.shape is not writable (because it's a void)
pass
# Finalize the fill_value for structured arrays
if self.dtype.names:
if self._fill_value is None:
self._fill_value = _check_fill_value(None, self.dtype)
return | [
"def",
"__array_finalize__",
"(",
"self",
",",
"obj",
")",
":",
"# Get main attributes .........",
"self",
".",
"_update_from",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"ndarray",
")",
":",
"odtype",
"=",
"obj",
".",
"dtype",
"if",
"odtype",
"... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L2770-L2797 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/binhex.py | python | hexbin | (inp, out) | hexbin(infilename, outfilename) - Decode binhexed file | hexbin(infilename, outfilename) - Decode binhexed file | [
"hexbin",
"(",
"infilename",
"outfilename",
")",
"-",
"Decode",
"binhexed",
"file"
] | def hexbin(inp, out):
"""hexbin(infilename, outfilename) - Decode binhexed file"""
ifp = HexBin(inp)
finfo = ifp.FInfo
if not out:
out = ifp.FName
with io.open(out, 'wb') as ofp:
# XXXX Do translation on non-mac systems
while True:
d = ifp.read(128000)
if not d: break
ofp.write(d)
ifp.close_data()
d = ifp.read_rsrc(128000)
if d:
ofp = openrsrc(out, 'wb')
ofp.write(d)
while True:
d = ifp.read_rsrc(128000)
if not d: break
ofp.write(d)
ofp.close()
ifp.close() | [
"def",
"hexbin",
"(",
"inp",
",",
"out",
")",
":",
"ifp",
"=",
"HexBin",
"(",
"inp",
")",
"finfo",
"=",
"ifp",
".",
"FInfo",
"if",
"not",
"out",
":",
"out",
"=",
"ifp",
".",
"FName",
"with",
"io",
".",
"open",
"(",
"out",
",",
"'wb'",
")",
"a... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/binhex.py#L454-L479 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTarget.GetTriple | (self) | return _lldb.SBTarget_GetTriple(self) | GetTriple(self) -> str | GetTriple(self) -> str | [
"GetTriple",
"(",
"self",
")",
"-",
">",
"str"
] | def GetTriple(self):
"""GetTriple(self) -> str"""
return _lldb.SBTarget_GetTriple(self) | [
"def",
"GetTriple",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTarget_GetTriple",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8886-L8888 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/operator/_graph_operator.py | python | check_acting_on_subspace | (acting_on_subspace, hilbert, graph) | return acting_on_subspace | Check `acting_on_subspace` argument used by various operators. | Check `acting_on_subspace` argument used by various operators. | [
"Check",
"acting_on_subspace",
"argument",
"used",
"by",
"various",
"operators",
"."
] | def check_acting_on_subspace(acting_on_subspace, hilbert, graph):
"""Check `acting_on_subspace` argument used by various operators."""
if acting_on_subspace is None:
acting_on_subspace = list(range(hilbert.size))
elif isinstance(acting_on_subspace, int):
start = acting_on_subspace
acting_on_subspace = [start + i for i in range(graph.n_nodes)]
elif isinstance(acting_on_subspace, list):
if len(acting_on_subspace) != graph.n_nodes:
raise ValueError(
"acting_on_subspace must be a list of length graph.n_nodes"
)
else:
raise TypeError("acting_on_subspace must be a list or single integer")
return acting_on_subspace | [
"def",
"check_acting_on_subspace",
"(",
"acting_on_subspace",
",",
"hilbert",
",",
"graph",
")",
":",
"if",
"acting_on_subspace",
"is",
"None",
":",
"acting_on_subspace",
"=",
"list",
"(",
"range",
"(",
"hilbert",
".",
"size",
")",
")",
"elif",
"isinstance",
"... | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/operator/_graph_operator.py#L25-L40 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/tools/build/src/util/path.py | python | is_rooted | (path) | return path and path [0] == '/' | Tests if a path is rooted. | Tests if a path is rooted. | [
"Tests",
"if",
"a",
"path",
"is",
"rooted",
"."
] | def is_rooted (path):
""" Tests if a path is rooted.
"""
return path and path [0] == '/' | [
"def",
"is_rooted",
"(",
"path",
")",
":",
"return",
"path",
"and",
"path",
"[",
"0",
"]",
"==",
"'/'"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/util/path.py#L69-L72 | |
wenwei202/caffe | f54a74abaf6951d8485cbdcfa1d74a4c37839466 | scripts/cpp_lint.py | python | PrintUsage | (message) | Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message. | Prints a brief usage string and exits, optionally with an error message. | [
"Prints",
"a",
"brief",
"usage",
"string",
"and",
"exits",
"optionally",
"with",
"an",
"error",
"message",
"."
] | def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1) | [
"def",
"PrintUsage",
"(",
"message",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"_USAGE",
")",
"if",
"message",
":",
"sys",
".",
"exit",
"(",
"'\\nFATAL ERROR: '",
"+",
"message",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/scripts/cpp_lint.py#L4757-L4767 | ||
1989Ryan/Semantic_SLAM | 0284b3f832ca431c494f9c134fe46c40ec86ee38 | Third_Part/PSPNet_Keras_tensorflow/caffe-tensorflow/kaffe/graph.py | python | GraphBuilder.make_node | (self, layer) | return Node(layer.name, kind, layer=layer) | Create a graph node for the given layer. | Create a graph node for the given layer. | [
"Create",
"a",
"graph",
"node",
"for",
"the",
"given",
"layer",
"."
] | def make_node(self, layer):
'''Create a graph node for the given layer.'''
kind = NodeKind.map_raw_kind(layer.type)
if kind is None:
raise KaffeError('Unknown layer type encountered: %s' % layer.type)
# We want to use the layer's top names (the "output" names), rather than the
# name attribute, which is more of readability thing than a functional one.
# Other layers will refer to a node by its "top name".
return Node(layer.name, kind, layer=layer) | [
"def",
"make_node",
"(",
"self",
",",
"layer",
")",
":",
"kind",
"=",
"NodeKind",
".",
"map_raw_kind",
"(",
"layer",
".",
"type",
")",
"if",
"kind",
"is",
"None",
":",
"raise",
"KaffeError",
"(",
"'Unknown layer type encountered: %s'",
"%",
"layer",
".",
"... | https://github.com/1989Ryan/Semantic_SLAM/blob/0284b3f832ca431c494f9c134fe46c40ec86ee38/Third_Part/PSPNet_Keras_tensorflow/caffe-tensorflow/kaffe/graph.py#L172-L180 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiToolBar.GetToolBitmapSize | (*args, **kwargs) | return _aui.AuiToolBar_GetToolBitmapSize(*args, **kwargs) | GetToolBitmapSize(self) -> Size | GetToolBitmapSize(self) -> Size | [
"GetToolBitmapSize",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetToolBitmapSize(*args, **kwargs):
"""GetToolBitmapSize(self) -> Size"""
return _aui.AuiToolBar_GetToolBitmapSize(*args, **kwargs) | [
"def",
"GetToolBitmapSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBar_GetToolBitmapSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L2126-L2128 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pyparsing.py | python | ParseResults.from_dict | (cls, other, name=None) | return ret | Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned | Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned | [
"Helper",
"classmethod",
"to",
"construct",
"a",
"ParseResults",
"from",
"a",
"dict",
"preserving",
"the",
"name",
"-",
"value",
"relations",
"as",
"results",
"names",
".",
"If",
"an",
"optional",
"name",
"argument",
"is",
"given",
"a",
"nested",
"ParseResults... | def from_dict(cls, other, name=None):
"""
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
"""
def is_iterable(obj):
try:
iter(obj)
except Exception:
return False
else:
if PY_3:
return not isinstance(obj, (str, bytes))
else:
return not isinstance(obj, basestring)
ret = cls([])
for k, v in other.items():
if isinstance(v, Mapping):
ret += cls.from_dict(v, name=k)
else:
ret += cls([v], name=k, asList=is_iterable(v))
if name is not None:
ret = cls([ret], name=name)
return ret | [
"def",
"from_dict",
"(",
"cls",
",",
"other",
",",
"name",
"=",
"None",
")",
":",
"def",
"is_iterable",
"(",
"obj",
")",
":",
"try",
":",
"iter",
"(",
"obj",
")",
"except",
"Exception",
":",
"return",
"False",
"else",
":",
"if",
"PY_3",
":",
"retur... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pyparsing.py#L1182-L1207 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/multi_process_runner.py | python | MultiProcessRunner.start | (self) | Starts processes, one for each task in `cluster_spec`.
Note that this is best effort by the applicable multiprocessing library,
and it may take up to seconds for a subprocess to be successfully started. | Starts processes, one for each task in `cluster_spec`. | [
"Starts",
"processes",
"one",
"for",
"each",
"task",
"in",
"cluster_spec",
"."
] | def start(self):
"""Starts processes, one for each task in `cluster_spec`.
Note that this is best effort by the applicable multiprocessing library,
and it may take up to seconds for a subprocess to be successfully started.
"""
with self._process_lock:
if self._processes:
raise ValueError('MultiProcessRunner already started.')
if self._joined:
raise ValueError('cannot start new processes after'
'MultiProcessRunner.join() is called')
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
self._start_subprocess_and_reading_thread(task_type, task_id)
# TODO(rchao): Remove the need of using SIGALRM if possible. At this time,
# without this the tests become very flaky.
if self._max_run_time is not None:
def handler(signum, frame):
del signum, frame
self.terminate_all()
signal.signal(signal.SIGALRM, handler)
signal.alarm(self._max_run_time) | [
"def",
"start",
"(",
"self",
")",
":",
"with",
"self",
".",
"_process_lock",
":",
"if",
"self",
".",
"_processes",
":",
"raise",
"ValueError",
"(",
"'MultiProcessRunner already started.'",
")",
"if",
"self",
".",
"_joined",
":",
"raise",
"ValueError",
"(",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/multi_process_runner.py#L338-L364 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/module/base_module.py | python | BaseModule.output_shapes | (self) | A list of (name, shape) pairs specifying the outputs of this module. | A list of (name, shape) pairs specifying the outputs of this module. | [
"A",
"list",
"of",
"(",
"name",
"shape",
")",
"pairs",
"specifying",
"the",
"outputs",
"of",
"this",
"module",
"."
] | def output_shapes(self):
"""A list of (name, shape) pairs specifying the outputs of this module."""
raise NotImplementedError() | [
"def",
"output_shapes",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/module/base_module.py#L614-L616 | ||
pybox2d/pybox2d | 09643321fd363f0850087d1bde8af3f4afd82163 | library/Box2D/examples/backends/pyqt4_framework.py | python | Pyqt4Framework.ConvertScreenToWorld | (self, x, y) | return b2Vec2(x, y) | PyQt4 gives us transformed positions, so no need to convert | PyQt4 gives us transformed positions, so no need to convert | [
"PyQt4",
"gives",
"us",
"transformed",
"positions",
"so",
"no",
"need",
"to",
"convert"
] | def ConvertScreenToWorld(self, x, y):
"""
PyQt4 gives us transformed positions, so no need to convert
"""
return b2Vec2(x, y) | [
"def",
"ConvertScreenToWorld",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"b2Vec2",
"(",
"x",
",",
"y",
")"
] | https://github.com/pybox2d/pybox2d/blob/09643321fd363f0850087d1bde8af3f4afd82163/library/Box2D/examples/backends/pyqt4_framework.py#L875-L879 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/utils.py | python | consume | (iterable) | Consumes an iterable without doing anything with it. | Consumes an iterable without doing anything with it. | [
"Consumes",
"an",
"iterable",
"without",
"doing",
"anything",
"with",
"it",
"."
] | def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass | [
"def",
"consume",
"(",
"iterable",
")",
":",
"for",
"event",
"in",
"iterable",
":",
"pass"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/utils.py#L101-L104 | ||
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/gyb_syntax_support/__init__.py | python | make_missing_child | (child) | Generates a C++ call to make the raw syntax for a given Child object. | Generates a C++ call to make the raw syntax for a given Child object. | [
"Generates",
"a",
"C",
"++",
"call",
"to",
"make",
"the",
"raw",
"syntax",
"for",
"a",
"given",
"Child",
"object",
"."
] | def make_missing_child(child):
"""
Generates a C++ call to make the raw syntax for a given Child object.
"""
if child.is_token():
token = child.main_token()
tok_kind = token.kind if token else "unknown"
tok_text = token.text if token else ""
return \
'RawSyntax::missing(tok::%s, "%s", Arena)' % \
(tok_kind, tok_text)
else:
missing_kind = "Unknown" if child.syntax_kind == "Syntax" \
else child.syntax_kind
if child.node_choices:
return make_missing_child(child.node_choices[0])
return 'RawSyntax::missing(SyntaxKind::%s, Arena)' % missing_kind | [
"def",
"make_missing_child",
"(",
"child",
")",
":",
"if",
"child",
".",
"is_token",
"(",
")",
":",
"token",
"=",
"child",
".",
"main_token",
"(",
")",
"tok_kind",
"=",
"token",
".",
"kind",
"if",
"token",
"else",
"\"unknown\"",
"tok_text",
"=",
"token",... | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/gyb_syntax_support/__init__.py#L32-L48 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | llvm/utils/lit/lit/ProgressBar.py | python | TerminalController.render | (self, template) | return re.sub(r'\$\$|\${\w+}', self._render_sub, template) | Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not). | Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not). | [
"Replace",
"each",
"$",
"-",
"substitutions",
"in",
"the",
"given",
"template",
"string",
"with",
"the",
"corresponding",
"terminal",
"control",
"string",
"(",
"if",
"it",
"s",
"defined",
")",
"or",
"(",
"if",
"it",
"s",
"not",
")",
"."
] | def render(self, template):
"""
Replace each $-substitutions in the given template string with
the corresponding terminal control string (if it's defined) or
'' (if it's not).
"""
return re.sub(r'\$\$|\${\w+}', self._render_sub, template) | [
"def",
"render",
"(",
"self",
",",
"template",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\\$\\$|\\${\\w+}'",
",",
"self",
".",
"_render_sub",
",",
"template",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/utils/lit/lit/ProgressBar.py#L153-L159 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parsing_ops.py | python | parse_single_sequence_example | (
serialized, context_features=None, sequence_features=None,
example_name=None, name=None) | return _parse_single_sequence_example_raw(
serialized, context_sparse_keys, context_sparse_types,
context_dense_keys, context_dense_types, context_dense_defaults,
context_dense_shapes, feature_list_sparse_keys,
feature_list_sparse_types, feature_list_dense_keys,
feature_list_dense_types, feature_list_dense_shapes,
feature_list_dense_defaults, example_name, name) | Parses a single `SequenceExample` proto.
Parses a single serialized [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto)
proto given in `serialized`.
This op parses a serialized sequence example into a tuple of dictionaries,
each mapping keys to `Tensor` and `SparseTensor` objects.
The first dictionary contains mappings for keys appearing in
`context_features`, and the second dictionary contains mappings for keys
appearing in `sequence_features`.
At least one of `context_features` and `sequence_features` must be provided
and non-empty.
The `context_features` keys are associated with a `SequenceExample` as a
whole, independent of time / frame. In contrast, the `sequence_features` keys
provide a way to access variable-length data within the `FeatureList` section
of the `SequenceExample` proto. While the shapes of `context_features` values
are fixed with respect to frame, the frame dimension (the first dimension)
of `sequence_features` values may vary between `SequenceExample` protos,
and even between `feature_list` keys within the same `SequenceExample`.
`context_features` contains `VarLenFeature` and `FixedLenFeature` objects.
Each `VarLenFeature` is mapped to a `SparseTensor`, and each `FixedLenFeature`
is mapped to a `Tensor`, of the specified type, shape, and default value.
`sequence_features` contains `VarLenFeature` and `FixedLenSequenceFeature`
objects. Each `VarLenFeature` is mapped to a `SparseTensor`, and each
`FixedLenSequenceFeature` is mapped to a `Tensor`, each of the specified type.
The shape will be `(T,) + df.dense_shape` for `FixedLenSequenceFeature` `df`, where
`T` is the length of the associated `FeatureList` in the `SequenceExample`.
For instance, `FixedLenSequenceFeature([])` yields a scalar 1-D `Tensor` of
static shape `[None]` and dynamic shape `[T]`, while
`FixedLenSequenceFeature([k])` (for `int k >= 1`) yields a 2-D matrix `Tensor`
of static shape `[None, k]` and dynamic shape `[T, k]`.
Each `SparseTensor` corresponding to `sequence_features` represents a ragged
vector. Its indices are `[time, index]`, where `time` is the `FeatureList`
entry and `index` is the value's index in the list of values associated with
that time.
`FixedLenFeature` entries with a `default_value` and `FixedLenSequenceFeature`
entries with `allow_missing=True` are optional; otherwise, we will fail if
that `Feature` or `FeatureList` is missing from any example in `serialized`.
`example_name` may contain a descriptive name for the corresponding serialized
proto. This may be useful for debugging purposes, but it has no effect on the
output. If not `None`, `example_name` must be a scalar.
Note that the batch version of this function, `tf.parse_sequence_example`,
is written for better memory efficiency and will be faster on large
`SequenceExample`s.
Args:
serialized: A scalar (0-D Tensor) of type string, a single binary
serialized `SequenceExample` proto.
context_features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values. These features are associated with a
`SequenceExample` as a whole.
sequence_features: A `dict` mapping feature keys to
`FixedLenSequenceFeature` or `VarLenFeature` values. These features are
associated with data within the `FeatureList` section of the
`SequenceExample` proto.
example_name: A scalar (0-D Tensor) of strings (optional), the name of
the serialized proto.
name: A name for this operation (optional).
Returns:
A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s.
The first dict contains the context key/values.
The second dict contains the feature_list key/values.
Raises:
ValueError: if any feature is invalid. | Parses a single `SequenceExample` proto. | [
"Parses",
"a",
"single",
"SequenceExample",
"proto",
"."
] | def parse_single_sequence_example(
serialized, context_features=None, sequence_features=None,
example_name=None, name=None):
# pylint: disable=line-too-long
"""Parses a single `SequenceExample` proto.
Parses a single serialized [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto)
proto given in `serialized`.
This op parses a serialized sequence example into a tuple of dictionaries,
each mapping keys to `Tensor` and `SparseTensor` objects.
The first dictionary contains mappings for keys appearing in
`context_features`, and the second dictionary contains mappings for keys
appearing in `sequence_features`.
At least one of `context_features` and `sequence_features` must be provided
and non-empty.
The `context_features` keys are associated with a `SequenceExample` as a
whole, independent of time / frame. In contrast, the `sequence_features` keys
provide a way to access variable-length data within the `FeatureList` section
of the `SequenceExample` proto. While the shapes of `context_features` values
are fixed with respect to frame, the frame dimension (the first dimension)
of `sequence_features` values may vary between `SequenceExample` protos,
and even between `feature_list` keys within the same `SequenceExample`.
`context_features` contains `VarLenFeature` and `FixedLenFeature` objects.
Each `VarLenFeature` is mapped to a `SparseTensor`, and each `FixedLenFeature`
is mapped to a `Tensor`, of the specified type, shape, and default value.
`sequence_features` contains `VarLenFeature` and `FixedLenSequenceFeature`
objects. Each `VarLenFeature` is mapped to a `SparseTensor`, and each
`FixedLenSequenceFeature` is mapped to a `Tensor`, each of the specified type.
The shape will be `(T,) + df.dense_shape` for `FixedLenSequenceFeature` `df`, where
`T` is the length of the associated `FeatureList` in the `SequenceExample`.
For instance, `FixedLenSequenceFeature([])` yields a scalar 1-D `Tensor` of
static shape `[None]` and dynamic shape `[T]`, while
`FixedLenSequenceFeature([k])` (for `int k >= 1`) yields a 2-D matrix `Tensor`
of static shape `[None, k]` and dynamic shape `[T, k]`.
Each `SparseTensor` corresponding to `sequence_features` represents a ragged
vector. Its indices are `[time, index]`, where `time` is the `FeatureList`
entry and `index` is the value's index in the list of values associated with
that time.
`FixedLenFeature` entries with a `default_value` and `FixedLenSequenceFeature`
entries with `allow_missing=True` are optional; otherwise, we will fail if
that `Feature` or `FeatureList` is missing from any example in `serialized`.
`example_name` may contain a descriptive name for the corresponding serialized
proto. This may be useful for debugging purposes, but it has no effect on the
output. If not `None`, `example_name` must be a scalar.
Note that the batch version of this function, `tf.parse_sequence_example`,
is written for better memory efficiency and will be faster on large
`SequenceExample`s.
Args:
serialized: A scalar (0-D Tensor) of type string, a single binary
serialized `SequenceExample` proto.
context_features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values. These features are associated with a
`SequenceExample` as a whole.
sequence_features: A `dict` mapping feature keys to
`FixedLenSequenceFeature` or `VarLenFeature` values. These features are
associated with data within the `FeatureList` section of the
`SequenceExample` proto.
example_name: A scalar (0-D Tensor) of strings (optional), the name of
the serialized proto.
name: A name for this operation (optional).
Returns:
A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s.
The first dict contains the context key/values.
The second dict contains the feature_list key/values.
Raises:
ValueError: if any feature is invalid.
"""
# pylint: enable=line-too-long
if not (context_features or sequence_features):
raise ValueError("Missing features.")
(context_sparse_keys, context_sparse_types, context_dense_keys,
context_dense_types, context_dense_defaults,
context_dense_shapes) = _features_to_raw_params(
context_features, [VarLenFeature, FixedLenFeature])
(feature_list_sparse_keys, feature_list_sparse_types,
feature_list_dense_keys, feature_list_dense_types,
feature_list_dense_defaults,
feature_list_dense_shapes) = _features_to_raw_params(
sequence_features, [VarLenFeature, FixedLenSequenceFeature])
return _parse_single_sequence_example_raw(
serialized, context_sparse_keys, context_sparse_types,
context_dense_keys, context_dense_types, context_dense_defaults,
context_dense_shapes, feature_list_sparse_keys,
feature_list_sparse_types, feature_list_dense_keys,
feature_list_dense_types, feature_list_dense_shapes,
feature_list_dense_defaults, example_name, name) | [
"def",
"parse_single_sequence_example",
"(",
"serialized",
",",
"context_features",
"=",
"None",
",",
"sequence_features",
"=",
"None",
",",
"example_name",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=line-too-long",
"# pylint: enable=line-too-lo... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parsing_ops.py#L1513-L1610 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/numbers.py | python | Integral.denominator | (self) | return 1 | Integers have a denominator of 1. | Integers have a denominator of 1. | [
"Integers",
"have",
"a",
"denominator",
"of",
"1",
"."
] | def denominator(self):
"""Integers have a denominator of 1."""
return 1 | [
"def",
"denominator",
"(",
"self",
")",
":",
"return",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/numbers.py#L385-L387 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/pycollapsiblepane.py | python | PyCollapsiblePane.HasAGWFlag | (self, flag) | return res | Returns whether a flag is present in the :class:`PyCollapsiblePane` style.
:param `flag`: one of the possible :class:`PyCollapsiblePane` window styles.
:see: :meth:`~PyCollapsiblePane.SetAGWWindowStyleFlag` for a list of possible window style flags. | Returns whether a flag is present in the :class:`PyCollapsiblePane` style. | [
"Returns",
"whether",
"a",
"flag",
"is",
"present",
"in",
"the",
":",
"class",
":",
"PyCollapsiblePane",
"style",
"."
] | def HasAGWFlag(self, flag):
"""
Returns whether a flag is present in the :class:`PyCollapsiblePane` style.
:param `flag`: one of the possible :class:`PyCollapsiblePane` window styles.
:see: :meth:`~PyCollapsiblePane.SetAGWWindowStyleFlag` for a list of possible window style flags.
"""
agwStyle = self.GetAGWWindowStyleFlag()
res = (agwStyle & flag and [True] or [False])[0]
return res | [
"def",
"HasAGWFlag",
"(",
"self",
",",
"flag",
")",
":",
"agwStyle",
"=",
"self",
".",
"GetAGWWindowStyleFlag",
"(",
")",
"res",
"=",
"(",
"agwStyle",
"&",
"flag",
"and",
"[",
"True",
"]",
"or",
"[",
"False",
"]",
")",
"[",
"0",
"]",
"return",
"res... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/pycollapsiblepane.py#L453-L464 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/webchecker/tktools.py | python | flatten | (msg) | return msg | Turn a list or tuple into a single string -- recursively. | Turn a list or tuple into a single string -- recursively. | [
"Turn",
"a",
"list",
"or",
"tuple",
"into",
"a",
"single",
"string",
"--",
"recursively",
"."
] | def flatten(msg):
"""Turn a list or tuple into a single string -- recursively."""
t = type(msg)
if t in (ListType, TupleType):
msg = ' '.join(map(flatten, msg))
elif t is ClassType:
msg = msg.__name__
else:
msg = str(msg)
return msg | [
"def",
"flatten",
"(",
"msg",
")",
":",
"t",
"=",
"type",
"(",
"msg",
")",
"if",
"t",
"in",
"(",
"ListType",
",",
"TupleType",
")",
":",
"msg",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"flatten",
",",
"msg",
")",
")",
"elif",
"t",
"is",
"Cla... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/webchecker/tktools.py#L333-L342 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_base/processes.py | python | Options.set_transdir | (self, **transdir) | Sets a dictionary to translate python compatible
option names into the command line optionnames,
only in case the command line options are not identical
with python attributes (for example if
command line options contain '.' or '-').
Format of transdir is python attribute as key and
command line option (as string, WITH preceeding'--') as value. | Sets a dictionary to translate python compatible
option names into the command line optionnames,
only in case the command line options are not identical
with python attributes (for example if
command line options contain '.' or '-').
Format of transdir is python attribute as key and
command line option (as string, WITH preceeding'--') as value. | [
"Sets",
"a",
"dictionary",
"to",
"translate",
"python",
"compatible",
"option",
"names",
"into",
"the",
"command",
"line",
"optionnames",
"only",
"in",
"case",
"the",
"command",
"line",
"options",
"are",
"not",
"identical",
"with",
"python",
"attributes",
"(",
... | def set_transdir(self, **transdir):
"""
Sets a dictionary to translate python compatible
option names into the command line optionnames,
only in case the command line options are not identical
with python attributes (for example if
command line options contain '.' or '-').
Format of transdir is python attribute as key and
command line option (as string, WITH preceeding'--') as value.
"""
self._transdir = transdir | [
"def",
"set_transdir",
"(",
"self",
",",
"*",
"*",
"transdir",
")",
":",
"self",
".",
"_transdir",
"=",
"transdir"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_base/processes.py#L213-L224 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py | python | Index._maybe_cast_indexer | (self, key) | return key | If we have a float key and are not a floating index, then try to cast
to an int if equivalent. | If we have a float key and are not a floating index, then try to cast
to an int if equivalent. | [
"If",
"we",
"have",
"a",
"float",
"key",
"and",
"are",
"not",
"a",
"floating",
"index",
"then",
"try",
"to",
"cast",
"to",
"an",
"int",
"if",
"equivalent",
"."
] | def _maybe_cast_indexer(self, key):
"""
If we have a float key and are not a floating index, then try to cast
to an int if equivalent.
"""
if is_float(key) and not self.is_floating():
try:
ckey = int(key)
if ckey == key:
key = ckey
except (OverflowError, ValueError, TypeError):
pass
return key | [
"def",
"_maybe_cast_indexer",
"(",
"self",
",",
"key",
")",
":",
"if",
"is_float",
"(",
"key",
")",
"and",
"not",
"self",
".",
"is_floating",
"(",
")",
":",
"try",
":",
"ckey",
"=",
"int",
"(",
"key",
")",
"if",
"ckey",
"==",
"key",
":",
"key",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L4722-L4735 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/layers.py | python | convolution3d_transpose | (
inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=DATA_FORMAT_NDHWC,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None) | Adds a convolution3d_transpose with an optional batch normalization layer.
The function creates a variable called `weights`, representing the
kernel, that is convolved with the input. If `batch_norm_params` is `None`, a
second variable called 'biases' is added to the result of the operation.
Args:
inputs: A 5-D `Tensor` of type `float` and shape
`[batch, depth, height, width, in_channels]` for `NDHWC` data format or
`[batch, in_channels, depth, height, width]` for `NCDHW` data format.
num_outputs: Integer, the number of output filters.
kernel_size: A list of length 3 holding the [kernel_depth, kernel_height, kernel_width] of
of the filters. Can be an int if both values are the same.
stride: A list of length 3: [stride_depth, stride_height, stride_width].
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: One of 'VALID' or 'SAME'.
data_format: A string. `NDHWC` (default) and `NCDHW` are supported.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: Whether or not the variables should be trainable or not.
scope: Optional scope for variable_scope.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If 'kernel_size' is not a list of length 3.
ValueError: If `data_format` is neither `NDHWC` nor `NCDHW`.
ValueError: If `C` dimension of `inputs` is None. | Adds a convolution3d_transpose with an optional batch normalization layer.
The function creates a variable called `weights`, representing the
kernel, that is convolved with the input. If `batch_norm_params` is `None`, a
second variable called 'biases' is added to the result of the operation.
Args:
inputs: A 5-D `Tensor` of type `float` and shape
`[batch, depth, height, width, in_channels]` for `NDHWC` data format or
`[batch, in_channels, depth, height, width]` for `NCDHW` data format.
num_outputs: Integer, the number of output filters.
kernel_size: A list of length 3 holding the [kernel_depth, kernel_height, kernel_width] of
of the filters. Can be an int if both values are the same.
stride: A list of length 3: [stride_depth, stride_height, stride_width].
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: One of 'VALID' or 'SAME'.
data_format: A string. `NDHWC` (default) and `NCDHW` are supported.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: Whether or not the variables should be trainable or not.
scope: Optional scope for variable_scope.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If 'kernel_size' is not a list of length 3.
ValueError: If `data_format` is neither `NDHWC` nor `NCDHW`.
ValueError: If `C` dimension of `inputs` is None. | [
"Adds",
"a",
"convolution3d_transpose",
"with",
"an",
"optional",
"batch",
"normalization",
"layer",
".",
"The",
"function",
"creates",
"a",
"variable",
"called",
"weights",
"representing",
"the",
"kernel",
"that",
"is",
"convolved",
"with",
"the",
"input",
".",
... | def convolution3d_transpose(
inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=DATA_FORMAT_NDHWC,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds a convolution3d_transpose with an optional batch normalization layer.
The function creates a variable called `weights`, representing the
kernel, that is convolved with the input. If `batch_norm_params` is `None`, a
second variable called 'biases' is added to the result of the operation.
Args:
inputs: A 5-D `Tensor` of type `float` and shape
`[batch, depth, height, width, in_channels]` for `NDHWC` data format or
`[batch, in_channels, depth, height, width]` for `NCDHW` data format.
num_outputs: Integer, the number of output filters.
kernel_size: A list of length 3 holding the [kernel_depth, kernel_height, kernel_width] of
of the filters. Can be an int if both values are the same.
stride: A list of length 3: [stride_depth, stride_height, stride_width].
Can be an int if both strides are the same. Note that presently
both strides must have the same value.
padding: One of 'VALID' or 'SAME'.
data_format: A string. `NDHWC` (default) and `NCDHW` are supported.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: Whether or not the variables should be trainable or not.
scope: Optional scope for variable_scope.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If 'kernel_size' is not a list of length 3.
ValueError: If `data_format` is neither `NDHWC` nor `NCDHW`.
ValueError: If `C` dimension of `inputs` is None.
"""
layer_variable_getter = _build_variable_getter(
{'bias': 'biases', 'kernel': 'weights'})
with variable_scope.variable_scope(
scope, 'Conv3d_transpose', [inputs], reuse=reuse,
custom_getter=layer_variable_getter) as sc:
if data_format not in (DATA_FORMAT_NCDHW, DATA_FORMAT_NDHWC):
raise ValueError('data_format has to be either NCDHW or NDHWC.')
inputs = ops.convert_to_tensor(inputs)
df = ('channels_first' if data_format and data_format.startswith('NC')
else 'channels_last')
layer = convolutional_layers.Convolution3DTranspose(
filters=num_outputs,
kernel_size=kernel_size,
strides=stride,
padding=padding,
data_format=df,
activation=None,
use_bias=not normalizer_fn and biases_initializer,
kernel_initializer=weights_initializer,
bias_initializer=biases_initializer,
kernel_regularizer=weights_regularizer,
bias_regularizer=biases_regularizer,
activity_regularizer=None,
trainable=trainable,
name=sc.name,
dtype=inputs.dtype.base_dtype,
_scope=sc,
_reuse=reuse)
outputs = layer.apply(inputs)
# Add variables to collections.
_add_variable_to_collections(layer.kernel, variables_collections, 'weights')
if layer.bias:
_add_variable_to_collections(layer.bias, variables_collections, 'biases')
if normalizer_fn is not None:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections,
sc.original_name_scope, outputs) | [
"def",
"convolution3d_transpose",
"(",
"inputs",
",",
"num_outputs",
",",
"kernel_size",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
",",
"data_format",
"=",
"DATA_FORMAT_NDHWC",
",",
"activation_fn",
"=",
"nn",
".",
"relu",
",",
"normalizer_fn",
"... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/layers.py#L1264-L1370 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/msvs.py | python | _EscapeCppDefineForMSVS | (s) | return s | Escapes a CPP define so that it will reach the compiler unaltered. | Escapes a CPP define so that it will reach the compiler unaltered. | [
"Escapes",
"a",
"CPP",
"define",
"so",
"that",
"it",
"will",
"reach",
"the",
"compiler",
"unaltered",
"."
] | def _EscapeCppDefineForMSVS(s):
"""Escapes a CPP define so that it will reach the compiler unaltered."""
s = _EscapeEnvironmentVariableExpansion(s)
s = _EscapeCommandLineArgumentForMSVS(s)
s = _EscapeVCProjCommandLineArgListItem(s)
# cl.exe replaces literal # characters with = in preprocesor definitions for
# some reason. Octal-encode to work around that.
s = s.replace('#', '\\%03o' % ord('#'))
return s | [
"def",
"_EscapeCppDefineForMSVS",
"(",
"s",
")",
":",
"s",
"=",
"_EscapeEnvironmentVariableExpansion",
"(",
"s",
")",
"s",
"=",
"_EscapeCommandLineArgumentForMSVS",
"(",
"s",
")",
"s",
"=",
"_EscapeVCProjCommandLineArgListItem",
"(",
"s",
")",
"# cl.exe replaces liter... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/msvs.py#L732-L740 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetSelectionStart | (*args, **kwargs) | return _stc.StyledTextCtrl_GetSelectionStart(*args, **kwargs) | GetSelectionStart(self) -> int
Returns the position at the start of the selection. | GetSelectionStart(self) -> int | [
"GetSelectionStart",
"(",
"self",
")",
"-",
">",
"int"
] | def GetSelectionStart(*args, **kwargs):
"""
GetSelectionStart(self) -> int
Returns the position at the start of the selection.
"""
return _stc.StyledTextCtrl_GetSelectionStart(*args, **kwargs) | [
"def",
"GetSelectionStart",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetSelectionStart",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3436-L3442 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/transport/TZlibTransport.py | python | TZlibTransport._init_stats | (self) | Internal method to reset the internal statistics counters
for compression ratios and bandwidth savings. | Internal method to reset the internal statistics counters
for compression ratios and bandwidth savings. | [
"Internal",
"method",
"to",
"reset",
"the",
"internal",
"statistics",
"counters",
"for",
"compression",
"ratios",
"and",
"bandwidth",
"savings",
"."
] | def _init_stats(self):
"""Internal method to reset the internal statistics counters
for compression ratios and bandwidth savings.
"""
self.bytes_in = 0
self.bytes_out = 0
self.bytes_in_comp = 0
self.bytes_out_comp = 0 | [
"def",
"_init_stats",
"(",
"self",
")",
":",
"self",
".",
"bytes_in",
"=",
"0",
"self",
".",
"bytes_out",
"=",
"0",
"self",
".",
"bytes_in_comp",
"=",
"0",
"self",
".",
"bytes_out_comp",
"=",
"0"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/transport/TZlibTransport.py#L103-L110 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/split_benchmark.py | python | SplitBenchmark._run_graph | (self, device, output_shape, variable, num_outputs, axis) | Run the graph and print its execution time.
Args:
device: string, the device to run on.
output_shape: shape of each output tensors.
variable: whether or not the output shape should be fixed
num_outputs: the number of outputs to split the input into
axis: axis to be split
Returns:
The duration of the run in seconds. | Run the graph and print its execution time. | [
"Run",
"the",
"graph",
"and",
"print",
"its",
"execution",
"time",
"."
] | def _run_graph(self, device, output_shape, variable, num_outputs, axis):
"""Run the graph and print its execution time.
Args:
device: string, the device to run on.
output_shape: shape of each output tensors.
variable: whether or not the output shape should be fixed
num_outputs: the number of outputs to split the input into
axis: axis to be split
Returns:
The duration of the run in seconds.
"""
graph = ops.Graph()
with graph.as_default():
if not variable:
if axis == 0:
input_shape = [output_shape[0] * num_outputs, output_shape[1]]
sizes = [output_shape[0] for _ in range(num_outputs)]
else:
input_shape = [output_shape[0], output_shape[1] * num_outputs]
sizes = [output_shape[1] for _ in range(num_outputs)]
else:
sizes = np.random.randint(
low=max(1, output_shape[axis] - 2),
high=output_shape[axis] + 2,
size=num_outputs)
total_size = np.sum(sizes)
if axis == 0:
input_shape = [total_size, output_shape[1]]
else:
input_shape = [output_shape[0], total_size]
outputs = build_graph(device, input_shape, sizes, axis)
config = config_pb2.ConfigProto(graph_options=config_pb2.GraphOptions(
optimizer_options=config_pb2.OptimizerOptions(
opt_level=config_pb2.OptimizerOptions.L0)))
with session_lib.Session(graph=graph, config=config) as session:
logging.set_verbosity("info")
variables.global_variables_initializer().run()
bench = benchmark.TensorFlowBenchmark()
bench.run_op_benchmark(
session,
outputs,
mbs=input_shape[0] * input_shape[1] * 4 * 2 * 100 / 1e6,
extras={
"input_shape": input_shape,
"variable": variable,
"axis": axis
}) | [
"def",
"_run_graph",
"(",
"self",
",",
"device",
",",
"output_shape",
",",
"variable",
",",
"num_outputs",
",",
"axis",
")",
":",
"graph",
"=",
"ops",
".",
"Graph",
"(",
")",
"with",
"graph",
".",
"as_default",
"(",
")",
":",
"if",
"not",
"variable",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/split_benchmark.py#L54-L103 | ||
jeog/TOSDataBridge | 6a5a08ca5cf3883db1f12e9bc89ef374d098df5a | python/tosdb/_win.py | python | init | (dllpath=None, root="C:\\", bypass_check=False) | Initialize the underlying tos-databridge DLL and try to connect.
Returns True if library was successfully loaded, not necessarily that
it was also able to connect. Details are sent to stdout.
init(dllpath=None, root="C:\\", bypass_check=False)
dllpath :: str :: exact path of the DLL -or-
root :: str :: directory to start walking/searching to find the DLL
bypass_check :: bool :: used by virtual layer implemenation (DO NOT SET)
returns -> bool
throws TOSDB_InitError TOSDB_Error | Initialize the underlying tos-databridge DLL and try to connect. | [
"Initialize",
"the",
"underlying",
"tos",
"-",
"databridge",
"DLL",
"and",
"try",
"to",
"connect",
"."
] | def init(dllpath=None, root="C:\\", bypass_check=False):
""" Initialize the underlying tos-databridge DLL and try to connect.
Returns True if library was successfully loaded, not necessarily that
it was also able to connect. Details are sent to stdout.
init(dllpath=None, root="C:\\", bypass_check=False)
dllpath :: str :: exact path of the DLL -or-
root :: str :: directory to start walking/searching to find the DLL
bypass_check :: bool :: used by virtual layer implemenation (DO NOT SET)
returns -> bool
throws TOSDB_InitError TOSDB_Error
"""
global _dll, _dll_depend1
rel = set()
if not bypass_check and dllpath is None and root == "C:\\":
if abort_init_after_warn():
return False
def _remove_older_versions():
nonlocal rel
getver = lambda x: _search(_REGEX_VER_SFFX,x).group().strip('-')
vers = tuple(zip(map(getver, rel), rel))
vers_max = max(vers)[0].split('.')[0]
mtup = tuple(( x[0].split('.')[1],x[1]) \
for x in vers if x[0].split('.')[0] == vers_max )
mtup_max = max(mtup)[0]
rel = set(x[1] for x in mtup if x[0] == mtup_max)
def _get_depends1_dll_path(dllpath):
d = _path.dirname(dllpath)
dbg = _match(_REGEX_DBG_DLL_PATH, dllpath)
base = d + "/" + DLL_DEPENDS1_NAME + "-" + SYS_ARCH_TYPE
path = base + ("_d.dll" if dbg else ".dll")
return path
try:
if dllpath is None:
matcher = _partial(_match, _REGEX_DLL_NAME)
for nfile in map(matcher, _listdir(_curdir)):
if nfile: # try the current dir first
rel.add(_curdir+ _sep + nfile.string)
if not rel: # no luck, walk the dir tree
for root, dirs, files in _walk(root):
for file in map(matcher, files):
if file:
rel.add(root + _sep + file.string)
if not rel: # if still nothing throw
raise TOSDB_InitError(" could not locate DLL")
if len(rel) > 1: # only use the most recent version(s)
_remove_older_versions()
# most recently updated
d = dict(zip(map(lambda x: _stat(x).st_mtime, rel), rel))
rec = max(d)
dllpath = d[rec]
dllpath_depends1 = _get_depends1_dll_path(dllpath)
_dll_depend1 = _CDLL(dllpath_depends1)
_dll = _CDLL(dllpath)
print("+ Using Module(s) ", dllpath)
print(" ", dllpath_depends1)
print("+ Last Update:", _asctime(_localtime(_stat(dllpath).st_mtime)))
print("+ Process ID:", str(_getpid()))
if connect():
print("+ Succesfully Connected to Service\Engine")
if connected():
print("+ Succesfully Connected to TOS")
else:
print("- Failed to Connect to TOS")
else:
print("- Failed to Connect to Service\Engine")
print("- Failed to Connect to TOS")
return True # indicate the lib was loaded (but not if connect succeeded)
except Exception as e:
raise TOSDB_InitError("unable to initialize library:", e) | [
"def",
"init",
"(",
"dllpath",
"=",
"None",
",",
"root",
"=",
"\"C:\\\\\"",
",",
"bypass_check",
"=",
"False",
")",
":",
"global",
"_dll",
",",
"_dll_depend1",
"rel",
"=",
"set",
"(",
")",
"if",
"not",
"bypass_check",
"and",
"dllpath",
"is",
"None",
"a... | https://github.com/jeog/TOSDataBridge/blob/6a5a08ca5cf3883db1f12e9bc89ef374d098df5a/python/tosdb/_win.py#L103-L180 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | is_placeholder | (x) | Returns whether `x` is a placeholder.
Arguments:
x: A candidate placeholder.
Returns:
Boolean. | Returns whether `x` is a placeholder. | [
"Returns",
"whether",
"x",
"is",
"a",
"placeholder",
"."
] | def is_placeholder(x):
"""Returns whether `x` is a placeholder.
Arguments:
x: A candidate placeholder.
Returns:
Boolean.
"""
try:
return x.op.type == 'Placeholder'
except AttributeError:
return False | [
"def",
"is_placeholder",
"(",
"x",
")",
":",
"try",
":",
"return",
"x",
".",
"op",
".",
"type",
"==",
"'Placeholder'",
"except",
"AttributeError",
":",
"return",
"False"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L669-L681 | ||
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/xOpeningSequence.py | python | xOpeningSequence.IStartOrientation | (self) | Inserting this new orientation GUI between movie and help GUI | Inserting this new orientation GUI between movie and help GUI | [
"Inserting",
"this",
"new",
"orientation",
"GUI",
"between",
"movie",
"and",
"help",
"GUI"
] | def IStartOrientation(self):
"Inserting this new orientation GUI between movie and help GUI"
PtFadeOut(kIntroFadeOutSeconds,1)
PtAtTimeCallback(self.key, kIntroFadeOutSeconds, kIntroFadeOutID) | [
"def",
"IStartOrientation",
"(",
"self",
")",
":",
"PtFadeOut",
"(",
"kIntroFadeOutSeconds",
",",
"1",
")",
"PtAtTimeCallback",
"(",
"self",
".",
"key",
",",
"kIntroFadeOutSeconds",
",",
"kIntroFadeOutID",
")"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xOpeningSequence.py#L360-L363 | ||
astra-toolbox/astra-toolbox | 1e7ec8af702e595b76654f2e500f4c00344b273f | python/astra/plugin.py | python | get_help | (name) | return p.get_help(name) | Get help for registered plugin.
:param name: Plugin name to get help for
:type name: :class:`str`
:returns: :class:`str` -- Help string (docstring). | Get help for registered plugin.
:param name: Plugin name to get help for
:type name: :class:`str`
:returns: :class:`str` -- Help string (docstring). | [
"Get",
"help",
"for",
"registered",
"plugin",
".",
":",
"param",
"name",
":",
"Plugin",
"name",
"to",
"get",
"help",
"for",
":",
"type",
"name",
":",
":",
"class",
":",
"str",
":",
"returns",
":",
":",
"class",
":",
"str",
"--",
"Help",
"string",
"... | def get_help(name):
"""Get help for registered plugin.
:param name: Plugin name to get help for
:type name: :class:`str`
:returns: :class:`str` -- Help string (docstring).
"""
return p.get_help(name) | [
"def",
"get_help",
"(",
"name",
")",
":",
"return",
"p",
".",
"get_help",
"(",
"name",
")"
] | https://github.com/astra-toolbox/astra-toolbox/blob/1e7ec8af702e595b76654f2e500f4c00344b273f/python/astra/plugin.py#L112-L120 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/rnn/python/ops/lstm_ops.py | python | _FusedLSTMGrad | (op, *grad) | return [None] + x_grad + [cs_prev_grad, h_prev_grad, w_grad, wci_grad,
wco_grad, wcf_grad, b_grad] | Gradient for FusedLSTM. | Gradient for FusedLSTM. | [
"Gradient",
"for",
"FusedLSTM",
"."
] | def _FusedLSTMGrad(op, *grad):
"""Gradient for FusedLSTM."""
max_len = op.get_attr("max_len")
seq_len_max = op.inputs[0]
x = op.inputs[1:1 + max_len]
cs_prev = op.inputs[-7]
h_prev = op.inputs[-6]
w = op.inputs[-5]
wci = op.inputs[-4]
wco = op.inputs[-3]
wcf = op.inputs[-2]
b = op.inputs[-1]
i = op.outputs[0 * max_len:1 * max_len]
cs = op.outputs[1 * max_len:2 * max_len]
f = op.outputs[2 * max_len:3 * max_len]
o = op.outputs[3 * max_len:4 * max_len]
ci = op.outputs[4 * max_len:5 * max_len]
co = op.outputs[5 * max_len:6 * max_len]
h = op.outputs[6 * max_len:7 * max_len]
cs_grad = grad[-max_len * 2:-max_len]
h_grad = grad[-max_len:]
(x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wco_grad, wcf_grad,
b_grad) = _lstm_ops_so.fused_lstm_grad(
seq_len_max,
x,
cs_prev,
h_prev,
w,
wci,
wco,
wcf,
b,
i,
cs,
f,
o,
ci,
co,
h,
cs_grad,
h_grad,
use_peephole=op.get_attr("use_peephole"))
return [None] + x_grad + [cs_prev_grad, h_prev_grad, w_grad, wci_grad,
wco_grad, wcf_grad, b_grad] | [
"def",
"_FusedLSTMGrad",
"(",
"op",
",",
"*",
"grad",
")",
":",
"max_len",
"=",
"op",
".",
"get_attr",
"(",
"\"max_len\"",
")",
"seq_len_max",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"x",
"=",
"op",
".",
"inputs",
"[",
"1",
":",
"1",
"+",
"max_l... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/rnn/python/ops/lstm_ops.py#L317-L365 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/xcodeproj_file.py | python | PBXGroup.AddOrGetFileByPath | (self, path, hierarchical) | Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned, otherwise, a
new one will be created, added to the correct group, and returned.
If path identifies a directory by virtue of carrying a trailing slash,
this method returns a PBXFileReference of "folder" type. If path
identifies a variant, by virtue of it identifying a file inside a directory
with an ".lproj" extension, this method returns a PBXVariantGroup
containing the variant named by path, and possibly other variants. For
all other paths, a "normal" PBXFileReference will be returned. | Returns an existing or new file reference corresponding to path. | [
"Returns",
"an",
"existing",
"or",
"new",
"file",
"reference",
"corresponding",
"to",
"path",
"."
] | def AddOrGetFileByPath(self, path, hierarchical):
"""Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned, otherwise, a
new one will be created, added to the correct group, and returned.
If path identifies a directory by virtue of carrying a trailing slash,
this method returns a PBXFileReference of "folder" type. If path
identifies a variant, by virtue of it identifying a file inside a directory
with an ".lproj" extension, this method returns a PBXVariantGroup
containing the variant named by path, and possibly other variants. For
all other paths, a "normal" PBXFileReference will be returned.
"""
# Adding or getting a directory? Directories end with a trailing slash.
is_dir = False
if path.endswith('/'):
is_dir = True
path = posixpath.normpath(path)
if is_dir:
path = path + '/'
# Adding or getting a variant? Variants are files inside directories
# with an ".lproj" extension. Xcode uses variants for localization. For
# a variant path/to/Language.lproj/MainMenu.nib, put a variant group named
# MainMenu.nib inside path/to, and give it a variant named Language. In
# this example, grandparent would be set to path/to and parent_root would
# be set to Language.
variant_name = None
parent = posixpath.dirname(path)
grandparent = posixpath.dirname(parent)
parent_basename = posixpath.basename(parent)
(parent_root, parent_ext) = posixpath.splitext(parent_basename)
if parent_ext == '.lproj':
variant_name = parent_root
if grandparent == '':
grandparent = None
# Putting a directory inside a variant group is not currently supported.
assert not is_dir or variant_name is None
path_split = path.split(posixpath.sep)
if len(path_split) == 1 or \
((is_dir or variant_name != None) and len(path_split) == 2) or \
not hierarchical:
# The PBXFileReference or PBXVariantGroup will be added to or gotten from
# this PBXGroup, no recursion necessary.
if variant_name is None:
# Add or get a PBXFileReference.
file_ref = self.GetChildByPath(path)
if file_ref != None:
assert file_ref.__class__ == PBXFileReference
else:
file_ref = PBXFileReference({'path': path})
self.AppendChild(file_ref)
else:
# Add or get a PBXVariantGroup. The variant group name is the same
# as the basename (MainMenu.nib in the example above). grandparent
# specifies the path to the variant group itself, and path_split[-2:]
# is the path of the specific variant relative to its group.
variant_group_name = posixpath.basename(path)
variant_group_ref = self.AddOrGetVariantGroupByNameAndPath(
variant_group_name, grandparent)
variant_path = posixpath.sep.join(path_split[-2:])
variant_ref = variant_group_ref.GetChildByPath(variant_path)
if variant_ref != None:
assert variant_ref.__class__ == PBXFileReference
else:
variant_ref = PBXFileReference({'name': variant_name,
'path': variant_path})
variant_group_ref.AppendChild(variant_ref)
# The caller is interested in the variant group, not the specific
# variant file.
file_ref = variant_group_ref
return file_ref
else:
# Hierarchical recursion. Add or get a PBXGroup corresponding to the
# outermost path component, and then recurse into it, chopping off that
# path component.
next_dir = path_split[0]
group_ref = self.GetChildByPath(next_dir)
if group_ref != None:
assert group_ref.__class__ == PBXGroup
else:
group_ref = PBXGroup({'path': next_dir})
self.AppendChild(group_ref)
return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]),
hierarchical) | [
"def",
"AddOrGetFileByPath",
"(",
"self",
",",
"path",
",",
"hierarchical",
")",
":",
"# Adding or getting a directory? Directories end with a trailing slash.",
"is_dir",
"=",
"False",
"if",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"is_dir",
"=",
"True",
"pat... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/xcodeproj_file.py#L1213-L1304 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Main/glue/vboxapi.py | python | VirtualBoxManager.xcptIsEqual | (self, oXcpt, hrStatus) | return self.platform.xcptIsEqual(oXcpt, hrStatus) | Checks if the exception oXcpt is equal to the COM/XPCOM status code
hrStatus.
The oXcpt parameter can be any kind of object, we'll just return True
if it doesn't behave like a our exception class. If it's None, we'll
query the current exception and examine that.
Will not raise any exception as long as hrStatus and self are not bad. | Checks if the exception oXcpt is equal to the COM/XPCOM status code
hrStatus. | [
"Checks",
"if",
"the",
"exception",
"oXcpt",
"is",
"equal",
"to",
"the",
"COM",
"/",
"XPCOM",
"status",
"code",
"hrStatus",
"."
] | def xcptIsEqual(self, oXcpt, hrStatus):
"""
Checks if the exception oXcpt is equal to the COM/XPCOM status code
hrStatus.
The oXcpt parameter can be any kind of object, we'll just return True
if it doesn't behave like a our exception class. If it's None, we'll
query the current exception and examine that.
Will not raise any exception as long as hrStatus and self are not bad.
"""
if oXcpt is None:
oXcpt = sys.exc_info()[1]
return self.platform.xcptIsEqual(oXcpt, hrStatus) | [
"def",
"xcptIsEqual",
"(",
"self",
",",
"oXcpt",
",",
"hrStatus",
")",
":",
"if",
"oXcpt",
"is",
"None",
":",
"oXcpt",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"return",
"self",
".",
"platform",
".",
"xcptIsEqual",
"(",
"oXcpt",
",",
"... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Main/glue/vboxapi.py#L1215-L1228 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/utils/gc.py | python | union | (lf, rf) | return keep | Creates a filter that keeps the union of two filters.
Args:
lf: first filter
rf: second filter
Returns:
A filter function that keeps the n largest paths. | Creates a filter that keeps the union of two filters. | [
"Creates",
"a",
"filter",
"that",
"keeps",
"the",
"union",
"of",
"two",
"filters",
"."
] | def union(lf, rf):
"""Creates a filter that keeps the union of two filters.
Args:
lf: first filter
rf: second filter
Returns:
A filter function that keeps the n largest paths.
"""
def keep(paths):
l = set(lf(paths))
r = set(rf(paths))
return sorted(list(l|r))
return keep | [
"def",
"union",
"(",
"lf",
",",
"rf",
")",
":",
"def",
"keep",
"(",
"paths",
")",
":",
"l",
"=",
"set",
"(",
"lf",
"(",
"paths",
")",
")",
"r",
"=",
"set",
"(",
"rf",
"(",
"paths",
")",
")",
"return",
"sorted",
"(",
"list",
"(",
"l",
"|",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/utils/gc.py#L149-L163 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py | python | Series.keys | (self) | return self.index | Return alias for index.
Returns
-------
Index
Index of the Series. | Return alias for index. | [
"Return",
"alias",
"for",
"index",
"."
] | def keys(self):
"""
Return alias for index.
Returns
-------
Index
Index of the Series.
"""
return self.index | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"self",
".",
"index"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py#L1514-L1523 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/tf/partial_infer/tf.py | python | generate_feed_dict | (graph: tf_v1.Graph, node: Node) | return all_constants, feed_dict | The first value in the return tuple is True if all inputs for the node has constant values.
The second returned value is mapping of placeholder tensor to the numpy arrays with the values for these
placeholders.
:param graph: the TensorFlow Graph to generate feed dictionary to.
:param node: the node which represents TensorFlow sub-graph of operations.
:return: pair where the first element is a flag that specifies that all node inputs are constants and a dictionary
where key is the input Tensor object and the value is the tensor value. | The first value in the return tuple is True if all inputs for the node has constant values.
The second returned value is mapping of placeholder tensor to the numpy arrays with the values for these
placeholders.
:param graph: the TensorFlow Graph to generate feed dictionary to.
:param node: the node which represents TensorFlow sub-graph of operations.
:return: pair where the first element is a flag that specifies that all node inputs are constants and a dictionary
where key is the input Tensor object and the value is the tensor value. | [
"The",
"first",
"value",
"in",
"the",
"return",
"tuple",
"is",
"True",
"if",
"all",
"inputs",
"for",
"the",
"node",
"has",
"constant",
"values",
".",
"The",
"second",
"returned",
"value",
"is",
"mapping",
"of",
"placeholder",
"tensor",
"to",
"the",
"numpy"... | def generate_feed_dict(graph: tf_v1.Graph, node: Node):
"""
The first value in the return tuple is True if all inputs for the node has constant values.
The second returned value is mapping of placeholder tensor to the numpy arrays with the values for these
placeholders.
:param graph: the TensorFlow Graph to generate feed dictionary to.
:param node: the node which represents TensorFlow sub-graph of operations.
:return: pair where the first element is a flag that specifies that all node inputs are constants and a dictionary
where key is the input Tensor object and the value is the tensor value.
"""
all_constants = True
feed_dict = dict()
for in_data_node_name, edge_attrs in node.get_inputs():
if 'control_flow_edge' in edge_attrs and edge_attrs['control_flow_edge']:
continue
value = node.in_node(edge_attrs['in']).value
if value is None:
all_constants = False
placeholder_pb = node['pbs'][edge_attrs['placeholder_name']]
value = np.ones(shape=tf_tensor_shape(placeholder_pb.attr['shape'].shape),
dtype=tf_dtype_extractor(placeholder_pb.attr['dtype'].type))
feed_dict[graph.get_tensor_by_name(edge_attrs['placeholder_name'] + ":0")] = value
return all_constants, feed_dict | [
"def",
"generate_feed_dict",
"(",
"graph",
":",
"tf_v1",
".",
"Graph",
",",
"node",
":",
"Node",
")",
":",
"all_constants",
"=",
"True",
"feed_dict",
"=",
"dict",
"(",
")",
"for",
"in_data_node_name",
",",
"edge_attrs",
"in",
"node",
".",
"get_inputs",
"("... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/tf/partial_infer/tf.py#L74-L96 | |
alexozer/jankdrone | c4b403eb254b41b832ab2bdfade12ba59c99e5dc | shm/lib/pyratemp/pyratemp.py | python | srow | (string, i) | return string.count('\n', 0, max(0, i)) + 1 | Get line numer of ``string[i]`` in `string`.
:Returns: row, starting at 1
:Note: This works for text-strings with ``\\n`` or ``\\r\\n``. | Get line numer of ``string[i]`` in `string`. | [
"Get",
"line",
"numer",
"of",
"string",
"[",
"i",
"]",
"in",
"string",
"."
] | def srow(string, i):
"""Get line numer of ``string[i]`` in `string`.
:Returns: row, starting at 1
:Note: This works for text-strings with ``\\n`` or ``\\r\\n``.
"""
return string.count('\n', 0, max(0, i)) + 1 | [
"def",
"srow",
"(",
"string",
",",
"i",
")",
":",
"return",
"string",
".",
"count",
"(",
"'\\n'",
",",
"0",
",",
"max",
"(",
"0",
",",
"i",
")",
")",
"+",
"1"
] | https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/shm/lib/pyratemp/pyratemp.py#L210-L216 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/_cpserver.py | python | Server.start | (self) | Start the HTTP server. | Start the HTTP server. | [
"Start",
"the",
"HTTP",
"server",
"."
] | def start(self):
"""Start the HTTP server."""
if not self.httpserver:
self.httpserver, self.bind_addr = self.httpserver_from_self()
ServerAdapter.start(self) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"httpserver",
":",
"self",
".",
"httpserver",
",",
"self",
".",
"bind_addr",
"=",
"self",
".",
"httpserver_from_self",
"(",
")",
"ServerAdapter",
".",
"start",
"(",
"self",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/_cpserver.py#L147-L151 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateSpan.Multiply | (*args, **kwargs) | return _misc_.DateSpan_Multiply(*args, **kwargs) | Multiply(self, int factor) -> DateSpan | Multiply(self, int factor) -> DateSpan | [
"Multiply",
"(",
"self",
"int",
"factor",
")",
"-",
">",
"DateSpan"
] | def Multiply(*args, **kwargs):
"""Multiply(self, int factor) -> DateSpan"""
return _misc_.DateSpan_Multiply(*args, **kwargs) | [
"def",
"Multiply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Multiply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4701-L4703 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py | python | MultivariateNormalOperatorPD.validate_args | (self) | return self._validate_args | `Boolean` describing behavior on invalid input. | `Boolean` describing behavior on invalid input. | [
"Boolean",
"describing",
"behavior",
"on",
"invalid",
"input",
"."
] | def validate_args(self):
"""`Boolean` describing behavior on invalid input."""
return self._validate_args | [
"def",
"validate_args",
"(",
"self",
")",
":",
"return",
"self",
".",
"_validate_args"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py#L174-L176 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | Grid.IsCurrentCellReadOnly | (*args, **kwargs) | return _grid.Grid_IsCurrentCellReadOnly(*args, **kwargs) | IsCurrentCellReadOnly(self) -> bool | IsCurrentCellReadOnly(self) -> bool | [
"IsCurrentCellReadOnly",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsCurrentCellReadOnly(*args, **kwargs):
"""IsCurrentCellReadOnly(self) -> bool"""
return _grid.Grid_IsCurrentCellReadOnly(*args, **kwargs) | [
"def",
"IsCurrentCellReadOnly",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_IsCurrentCellReadOnly",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1366-L1368 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_optskolem | (p) | optskolem : | optskolem : | [
"optskolem",
":"
] | def p_optskolem(p):
'optskolem : '
p[0] = None | [
"def",
"p_optskolem",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"None"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L396-L398 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PowderILLEfficiency.py | python | PowderILLEfficiency._normalise_roi | (self, ws_2d) | Normalises to the regions of interests (ROI)
@param ws_2d : 2D input workspace | Normalises to the regions of interests (ROI) | [
"Normalises",
"to",
"the",
"regions",
"of",
"interests",
"(",
"ROI",
")"
] | def _normalise_roi(self, ws_2d):
"""
Normalises to the regions of interests (ROI)
@param ws_2d : 2D input workspace
"""
y = mtd[ws_2d].extractY()
x = mtd[ws_2d].extractX()
roi_counts_arr = np.ones(self._scan_points)
# typically should be number_rois = 1
number_rois = int(len(self._regions_of_interest)/2)
starts = self._regions_of_interest[0::2]
ends = self._regions_of_interest[1::2]
first_cells = []
last_cells = []
for roi in range(number_rois):
first_cell = np.argmax(x[...,0]>starts[roi])
first_cells.append(first_cell)
last_cell = np.argmin(x[...,0]<ends[roi])
last_cells.append(last_cell)
for time_index in range(self._scan_points):
roi_counts = 0
counts = y[...,time_index]
for roi in range(number_rois):
first_cell = first_cells[roi] - self._bin_offset * time_index
last_cell = last_cells[roi] - self._bin_offset * time_index
roi_counts += np.sum(counts[first_cell:last_cell])
roi_counts_arr[time_index] = roi_counts
roi_ws = self._hide('roi')
ExtractSingleSpectrum(InputWorkspace=ws_2d, WorkspaceIndex=0, OutputWorkspace=roi_ws)
mtd[roi_ws].setY(0, roi_counts_arr)
mtd[roi_ws].setE(0, np.sqrt(roi_counts_arr))
Divide(LHSWorkspace=ws_2d, RHSWorkspace=roi_ws, OutputWorkspace=ws_2d)
DeleteWorkspace(roi_ws) | [
"def",
"_normalise_roi",
"(",
"self",
",",
"ws_2d",
")",
":",
"y",
"=",
"mtd",
"[",
"ws_2d",
"]",
".",
"extractY",
"(",
")",
"x",
"=",
"mtd",
"[",
"ws_2d",
"]",
".",
"extractX",
"(",
")",
"roi_counts_arr",
"=",
"np",
".",
"ones",
"(",
"self",
"."... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PowderILLEfficiency.py#L417-L449 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ToolBarToolBase.GetId | (*args, **kwargs) | return _controls_.ToolBarToolBase_GetId(*args, **kwargs) | GetId(self) -> int | GetId(self) -> int | [
"GetId",
"(",
"self",
")",
"-",
">",
"int"
] | def GetId(*args, **kwargs):
"""GetId(self) -> int"""
return _controls_.ToolBarToolBase_GetId(*args, **kwargs) | [
"def",
"GetId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarToolBase_GetId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3433-L3435 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBListener.StopListeningForEvents | (self, *args) | return _lldb.SBListener_StopListeningForEvents(self, *args) | StopListeningForEvents(self, SBBroadcaster broadcaster, uint32_t event_mask) -> bool | StopListeningForEvents(self, SBBroadcaster broadcaster, uint32_t event_mask) -> bool | [
"StopListeningForEvents",
"(",
"self",
"SBBroadcaster",
"broadcaster",
"uint32_t",
"event_mask",
")",
"-",
">",
"bool"
] | def StopListeningForEvents(self, *args):
"""StopListeningForEvents(self, SBBroadcaster broadcaster, uint32_t event_mask) -> bool"""
return _lldb.SBListener_StopListeningForEvents(self, *args) | [
"def",
"StopListeningForEvents",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBListener_StopListeningForEvents",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5753-L5755 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | _BackupFilters | () | Saves the current filter list to backup storage. | Saves the current filter list to backup storage. | [
"Saves",
"the",
"current",
"filter",
"list",
"to",
"backup",
"storage",
"."
] | def _BackupFilters():
""" Saves the current filter list to backup storage."""
_cpplint_state.BackupFilters() | [
"def",
"_BackupFilters",
"(",
")",
":",
"_cpplint_state",
".",
"BackupFilters",
"(",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L975-L977 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatToolbarItem.GetDisabledBitmap | (self) | return self._disabledImg | Returns the tool disabled bitmap. | Returns the tool disabled bitmap. | [
"Returns",
"the",
"tool",
"disabled",
"bitmap",
"."
] | def GetDisabledBitmap(self):
""" Returns the tool disabled bitmap. """
return self._disabledImg | [
"def",
"GetDisabledBitmap",
"(",
"self",
")",
":",
"return",
"self",
".",
"_disabledImg"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L4632-L4635 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/lib/io/file_io.py | python | FileIO.write | (self, file_content) | Writes file_content to the file. Appends to the end of the file. | Writes file_content to the file. Appends to the end of the file. | [
"Writes",
"file_content",
"to",
"the",
"file",
".",
"Appends",
"to",
"the",
"end",
"of",
"the",
"file",
"."
] | def write(self, file_content):
"""Writes file_content to the file. Appends to the end of the file."""
self._prewrite_check()
pywrap_tensorflow.AppendToFile(
compat.as_bytes(file_content), self._writable_file) | [
"def",
"write",
"(",
"self",
",",
"file_content",
")",
":",
"self",
".",
"_prewrite_check",
"(",
")",
"pywrap_tensorflow",
".",
"AppendToFile",
"(",
"compat",
".",
"as_bytes",
"(",
"file_content",
")",
",",
"self",
".",
"_writable_file",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/lib/io/file_io.py#L104-L108 | ||
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/plasma/pch.py | python | setvar | (vname,value) | set a variable within the instance of the ptModifier class in the selected module | set a variable within the instance of the ptModifier class in the selected module | [
"set",
"a",
"variable",
"within",
"the",
"instance",
"of",
"the",
"ptModifier",
"class",
"in",
"the",
"selected",
"module"
] | def setvar(vname,value):
"set a variable within the instance of the ptModifier class in the selected module"
global __pmods
global __sel
for name in __pmods[__sel][1].__dict__.keys():
ist = __pmods[__sel][1].__dict__[name]
if isinstance(ist,PlasmaTypes.ptModifier):
# first see if there is already a glabal by that name
if vname not in ist.__dict__:
print("Warning: creating new class variable!")
ist.__dict__[vname] = value
print("%s = " % (vname),ist.__dict__[vname]) | [
"def",
"setvar",
"(",
"vname",
",",
"value",
")",
":",
"global",
"__pmods",
"global",
"__sel",
"for",
"name",
"in",
"__pmods",
"[",
"__sel",
"]",
"[",
"1",
"]",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"ist",
"=",
"__pmods",
"[",
"__sel",
"]",
... | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/pch.py#L284-L295 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/nanfunctions.py | python | _nanmedian1d | (arr1d, overwrite_input=False) | return np.median(arr1d, overwrite_input=overwrite_input) | Private function for rank 1 arrays. Compute the median ignoring NaNs.
See nanmedian for parameter usage | Private function for rank 1 arrays. Compute the median ignoring NaNs.
See nanmedian for parameter usage | [
"Private",
"function",
"for",
"rank",
"1",
"arrays",
".",
"Compute",
"the",
"median",
"ignoring",
"NaNs",
".",
"See",
"nanmedian",
"for",
"parameter",
"usage"
] | def _nanmedian1d(arr1d, overwrite_input=False):
"""
Private function for rank 1 arrays. Compute the median ignoring NaNs.
See nanmedian for parameter usage
"""
arr1d, overwrite_input = _remove_nan_1d(arr1d,
overwrite_input=overwrite_input)
if arr1d.size == 0:
return np.nan
return np.median(arr1d, overwrite_input=overwrite_input) | [
"def",
"_nanmedian1d",
"(",
"arr1d",
",",
"overwrite_input",
"=",
"False",
")",
":",
"arr1d",
",",
"overwrite_input",
"=",
"_remove_nan_1d",
"(",
"arr1d",
",",
"overwrite_input",
"=",
"overwrite_input",
")",
"if",
"arr1d",
".",
"size",
"==",
"0",
":",
"retur... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/nanfunctions.py#L926-L936 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | PyPreviewFrame.CreateCanvas | (*args, **kwargs) | return _windows_.PyPreviewFrame_CreateCanvas(*args, **kwargs) | CreateCanvas(self) | CreateCanvas(self) | [
"CreateCanvas",
"(",
"self",
")"
] | def CreateCanvas(*args, **kwargs):
"""CreateCanvas(self)"""
return _windows_.PyPreviewFrame_CreateCanvas(*args, **kwargs) | [
"def",
"CreateCanvas",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PyPreviewFrame_CreateCanvas",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5756-L5758 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.CenterOnParent | (*args, **kwargs) | return _core_.Window_CenterOnParent(*args, **kwargs) | CenterOnParent(self, int dir=BOTH)
Center with respect to the the parent window | CenterOnParent(self, int dir=BOTH) | [
"CenterOnParent",
"(",
"self",
"int",
"dir",
"=",
"BOTH",
")"
] | def CenterOnParent(*args, **kwargs):
"""
CenterOnParent(self, int dir=BOTH)
Center with respect to the the parent window
"""
return _core_.Window_CenterOnParent(*args, **kwargs) | [
"def",
"CenterOnParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_CenterOnParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9669-L9675 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | tools/bootstrap.py | python | set_cudnn_version | (environ_cp) | Set TF_CUDNN_VERSION. | Set TF_CUDNN_VERSION. | [
"Set",
"TF_CUDNN_VERSION",
"."
] | def set_cudnn_version(environ_cp):
"""Set TF_CUDNN_VERSION."""
ask_cudnn_version = (
'Please specify the cuDNN version you want to use. '
'[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
tf_cudnn_version = get_from_env_or_user_or_default(
environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
_DEFAULT_CUDNN_VERSION)
environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version | [
"def",
"set_cudnn_version",
"(",
"environ_cp",
")",
":",
"ask_cudnn_version",
"=",
"(",
"'Please specify the cuDNN version you want to use. '",
"'[Leave empty to default to cuDNN %s]: '",
")",
"%",
"_DEFAULT_CUDNN_VERSION",
"tf_cudnn_version",
"=",
"get_from_env_or_user_or_default",
... | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/tools/bootstrap.py#L640-L648 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/utils/fleet_util.py | python | FleetUtil.write_xbox_donefile | (self,
output_path,
day,
pass_id,
xbox_base_key,
data_path,
hadoop_fs_name,
hadoop_fs_ugi,
monitor_data={},
hadoop_home="$HADOOP_HOME",
donefile_name=None) | write delta donefile or xbox base donefile
Args:
output_path(str): output path
day(str|int): training day of model
pass_id(str|int): training pass id of model
xbox_base_key(str|int): xbox base key
data_path(str|list): training data path
hadoop_fs_name(str): hdfs/afs fs name
hadoop_fs_ugi(str): hdfs/afs fs ugi
monitor_data(dict): metrics
hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
donefile_name(str): donefile name, default is None"
Examples:
.. code-block:: python
from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
fleet_util = FleetUtil()
fleet_util.write_xbox_donefile(
output_path="hdfs:/my/output/",
model_path="hdfs:/my/output/20190722/01",
day=20190722,
pass_id=1,
xbox_base_key=int(time.time()),
data_path="hdfs:/my/data/",
hadoop_fs_name="hdfs://xxx",
hadoop_fs_ugi="user,passwd",
monitor_data={}
) | write delta donefile or xbox base donefile | [
"write",
"delta",
"donefile",
"or",
"xbox",
"base",
"donefile"
] | def write_xbox_donefile(self,
output_path,
day,
pass_id,
xbox_base_key,
data_path,
hadoop_fs_name,
hadoop_fs_ugi,
monitor_data={},
hadoop_home="$HADOOP_HOME",
donefile_name=None):
"""
write delta donefile or xbox base donefile
Args:
output_path(str): output path
day(str|int): training day of model
pass_id(str|int): training pass id of model
xbox_base_key(str|int): xbox base key
data_path(str|list): training data path
hadoop_fs_name(str): hdfs/afs fs name
hadoop_fs_ugi(str): hdfs/afs fs ugi
monitor_data(dict): metrics
hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
donefile_name(str): donefile name, default is None"
Examples:
.. code-block:: python
from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
fleet_util = FleetUtil()
fleet_util.write_xbox_donefile(
output_path="hdfs:/my/output/",
model_path="hdfs:/my/output/20190722/01",
day=20190722,
pass_id=1,
xbox_base_key=int(time.time()),
data_path="hdfs:/my/data/",
hadoop_fs_name="hdfs://xxx",
hadoop_fs_ugi="user,passwd",
monitor_data={}
)
"""
day = str(day)
pass_id = str(pass_id)
xbox_base_key = int(xbox_base_key)
mode = None
if pass_id != "-1":
mode = "patch"
suffix_name = "/%s/delta-%s/" % (day, pass_id)
model_path = output_path.rstrip("/") + suffix_name
if donefile_name is None:
donefile_name = "xbox_patch_done.txt"
else:
mode = "base"
suffix_name = "/%s/base/" % day
model_path = output_path.rstrip("/") + suffix_name
if donefile_name is None:
donefile_name = "xbox_base_done.txt"
if isinstance(data_path, list):
data_path = ",".join(data_path)
if fleet.worker_index() == 0:
donefile_path = output_path + "/" + donefile_name
xbox_str = self._get_xbox_str(output_path, day, model_path, \
xbox_base_key, data_path, hadoop_fs_name, monitor_data={},
mode=mode)
configs = {
"fs.default.name": hadoop_fs_name,
"hadoop.job.ugi": hadoop_fs_ugi
}
client = HDFSClient(hadoop_home, configs)
if client.is_file(donefile_path):
pre_content = client.cat(donefile_path)
last_dict = json.loads(pre_content.split("\n")[-1])
last_day = last_dict["input"].split("/")[-3]
last_pass = last_dict["input"].split("/")[-2].split("-")[-1]
exist = False
if int(day) < int(last_day) or \
int(day) == int(last_day) and \
int(pass_id) <= int(last_pass):
exist = True
if not exist:
with open(donefile_name, "w") as f:
f.write(pre_content + "\n")
f.write(xbox_str + "\n")
client.delete(donefile_path)
client.upload(donefile_name, output_path)
self.rank0_error("write %s/%s %s succeed" % \
(day, pass_id, donefile_name))
else:
self.rank0_error("not write %s because %s/%s already "
"exists" % (donefile_name, day, pass_id))
else:
with open(donefile_name, "w") as f:
f.write(xbox_str + "\n")
client.upload(donefile_name, output_path)
self.rank0_error("write %s/%s %s succeed" % \
(day, pass_id, donefile_name))
fleet._role_maker._barrier_worker() | [
"def",
"write_xbox_donefile",
"(",
"self",
",",
"output_path",
",",
"day",
",",
"pass_id",
",",
"xbox_base_key",
",",
"data_path",
",",
"hadoop_fs_name",
",",
"hadoop_fs_ugi",
",",
"monitor_data",
"=",
"{",
"}",
",",
"hadoop_home",
"=",
"\"$HADOOP_HOME\"",
",",
... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/utils/fleet_util.py#L452-L554 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/labelbook.py | python | ImageContainer.OnMouseLeftDown | (self, event) | Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`ImageContainer`.
:param `event`: a :class:`MouseEvent` event to be processed. | Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`ImageContainer`. | [
"Handles",
"the",
"wx",
".",
"EVT_LEFT_DOWN",
"event",
"for",
":",
"class",
":",
"ImageContainer",
"."
] | def OnMouseLeftDown(self, event):
"""
Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`ImageContainer`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
ImageContainerBase.OnMouseLeftDown(self, event)
event.Skip() | [
"def",
"OnMouseLeftDown",
"(",
"self",
",",
"event",
")",
":",
"ImageContainerBase",
".",
"OnMouseLeftDown",
"(",
"self",
",",
"event",
")",
"event",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/labelbook.py#L1134-L1142 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/scons/getversion.py | python | _CheckGitAvailable | () | return True | Try the most basic of git commands, to see if there is
currently any access to a repository. | Try the most basic of git commands, to see if there is
currently any access to a repository. | [
"Try",
"the",
"most",
"basic",
"of",
"git",
"commands",
"to",
"see",
"if",
"there",
"is",
"currently",
"any",
"access",
"to",
"a",
"repository",
"."
] | def _CheckGitAvailable():
"""Try the most basic of git commands, to see if there is
currently any access to a repository."""
try:
repo = _GetRepository()
except git.exc.InvalidGitRepositoryError:
return False
return True | [
"def",
"_CheckGitAvailable",
"(",
")",
":",
"try",
":",
"repo",
"=",
"_GetRepository",
"(",
")",
"except",
"git",
".",
"exc",
".",
"InvalidGitRepositoryError",
":",
"return",
"False",
"return",
"True"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/scons/getversion.py#L257-L265 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DirSelector | (*args, **kwargs) | return _misc_.DirSelector(*args, **kwargs) | DirSelector(String message=DirSelectorPromptStr, String defaultPath=EmptyString,
long style=wxDD_DEFAULT_STYLE,
Point pos=DefaultPosition, Window parent=None) -> String | DirSelector(String message=DirSelectorPromptStr, String defaultPath=EmptyString,
long style=wxDD_DEFAULT_STYLE,
Point pos=DefaultPosition, Window parent=None) -> String | [
"DirSelector",
"(",
"String",
"message",
"=",
"DirSelectorPromptStr",
"String",
"defaultPath",
"=",
"EmptyString",
"long",
"style",
"=",
"wxDD_DEFAULT_STYLE",
"Point",
"pos",
"=",
"DefaultPosition",
"Window",
"parent",
"=",
"None",
")",
"-",
">",
"String"
] | def DirSelector(*args, **kwargs):
"""
DirSelector(String message=DirSelectorPromptStr, String defaultPath=EmptyString,
long style=wxDD_DEFAULT_STYLE,
Point pos=DefaultPosition, Window parent=None) -> String
"""
return _misc_.DirSelector(*args, **kwargs) | [
"def",
"DirSelector",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DirSelector",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L446-L452 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/imputils.py | python | for_iter | (context, builder, iterable_type, val) | Simulate a for loop on the given iterable. Yields a namedtuple with
the given members:
- `value` is the value being yielded
- `do_break` is a callable to early out of the loop | Simulate a for loop on the given iterable. Yields a namedtuple with
the given members:
- `value` is the value being yielded
- `do_break` is a callable to early out of the loop | [
"Simulate",
"a",
"for",
"loop",
"on",
"the",
"given",
"iterable",
".",
"Yields",
"a",
"namedtuple",
"with",
"the",
"given",
"members",
":",
"-",
"value",
"is",
"the",
"value",
"being",
"yielded",
"-",
"do_break",
"is",
"a",
"callable",
"to",
"early",
"ou... | def for_iter(context, builder, iterable_type, val):
"""
Simulate a for loop on the given iterable. Yields a namedtuple with
the given members:
- `value` is the value being yielded
- `do_break` is a callable to early out of the loop
"""
iterator_type = iterable_type.iterator_type
iterval = call_getiter(context, builder, iterable_type, val)
bb_body = builder.append_basic_block('for_iter.body')
bb_end = builder.append_basic_block('for_iter.end')
def do_break():
builder.branch(bb_end)
builder.branch(bb_body)
with builder.goto_block(bb_body):
res = call_iternext(context, builder, iterator_type, iterval)
with builder.if_then(builder.not_(res.is_valid()), likely=False):
builder.branch(bb_end)
yield _ForIterLoop(res.yielded_value(), do_break)
builder.branch(bb_body)
builder.position_at_end(bb_end)
if context.enable_nrt:
context.nrt.decref(builder, iterator_type, iterval) | [
"def",
"for_iter",
"(",
"context",
",",
"builder",
",",
"iterable_type",
",",
"val",
")",
":",
"iterator_type",
"=",
"iterable_type",
".",
"iterator_type",
"iterval",
"=",
"call_getiter",
"(",
"context",
",",
"builder",
",",
"iterable_type",
",",
"val",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/imputils.py#L392-L419 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/kde4.py | python | apply_msgfmt | (self) | Process all languages to create .mo files and to install them::
def build(bld):
bld(features='msgfmt', langs='es de fr', appname='myapp', install_path='${KDE4_LOCALE_INSTALL_DIR}') | Process all languages to create .mo files and to install them:: | [
"Process",
"all",
"languages",
"to",
"create",
".",
"mo",
"files",
"and",
"to",
"install",
"them",
"::"
] | def apply_msgfmt(self):
"""
Process all languages to create .mo files and to install them::
def build(bld):
bld(features='msgfmt', langs='es de fr', appname='myapp', install_path='${KDE4_LOCALE_INSTALL_DIR}')
"""
for lang in self.to_list(self.langs):
node = self.path.find_resource(lang+'.po')
task = self.create_task('msgfmt', node, node.change_ext('.mo'))
langname = lang.split('/')
langname = langname[-1]
inst = getattr(self, 'install_path', '${KDE4_LOCALE_INSTALL_DIR}')
self.bld.install_as(
inst + os.sep + langname + os.sep + 'LC_MESSAGES' + os.sep + getattr(self, 'appname', 'set_your_appname') + '.mo',
task.outputs[0],
chmod = getattr(self, 'chmod', Utils.O644)) | [
"def",
"apply_msgfmt",
"(",
"self",
")",
":",
"for",
"lang",
"in",
"self",
".",
"to_list",
"(",
"self",
".",
"langs",
")",
":",
"node",
"=",
"self",
".",
"path",
".",
"find_resource",
"(",
"lang",
"+",
"'.po'",
")",
"task",
"=",
"self",
".",
"creat... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/kde4.py#L14-L33 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/ansic/cparse.py | python | p_direct_abstract_declarator_2 | (t) | direct_abstract_declarator : direct_abstract_declarator LBRACKET constant_expression_opt RBRACKET | direct_abstract_declarator : direct_abstract_declarator LBRACKET constant_expression_opt RBRACKET | [
"direct_abstract_declarator",
":",
"direct_abstract_declarator",
"LBRACKET",
"constant_expression_opt",
"RBRACKET"
] | def p_direct_abstract_declarator_2(t):
'direct_abstract_declarator : direct_abstract_declarator LBRACKET constant_expression_opt RBRACKET'
pass | [
"def",
"p_direct_abstract_declarator_2",
"(",
"t",
")",
":",
"pass"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L417-L419 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/file.py | python | Storage.locked_put | (self, credentials) | Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
Raises:
CredentialsFileSymbolicLinkError if the file is a symbolic link. | Write Credentials to file. | [
"Write",
"Credentials",
"to",
"file",
"."
] | def locked_put(self, credentials):
"""Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
Raises:
CredentialsFileSymbolicLinkError if the file is a symbolic link.
"""
self._create_file_if_needed()
self._validate_file()
f = open(self._filename, 'w')
f.write(credentials.to_json())
f.close() | [
"def",
"locked_put",
"(",
"self",
",",
"credentials",
")",
":",
"self",
".",
"_create_file_if_needed",
"(",
")",
"self",
".",
"_validate_file",
"(",
")",
"f",
"=",
"open",
"(",
"self",
".",
"_filename",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"credent... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/file.py#L99-L113 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/ops/variables.py | python | get_or_create_global_step | (graph=None) | return training_util.get_or_create_global_step(graph) | Returns and create (if necessary) the global step tensor.
Args:
graph: The graph in which to create the global step tensor. If missing, use
default graph.
Returns:
The global step tensor. | Returns and create (if necessary) the global step tensor. | [
"Returns",
"and",
"create",
"(",
"if",
"necessary",
")",
"the",
"global",
"step",
"tensor",
"."
] | def get_or_create_global_step(graph=None):
"""Returns and create (if necessary) the global step tensor.
Args:
graph: The graph in which to create the global step tensor. If missing, use
default graph.
Returns:
The global step tensor.
"""
return training_util.get_or_create_global_step(graph) | [
"def",
"get_or_create_global_step",
"(",
"graph",
"=",
"None",
")",
":",
"return",
"training_util",
".",
"get_or_create_global_step",
"(",
"graph",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/framework/python/ops/variables.py#L148-L158 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/models.py | python | Response.is_redirect | (self) | return ('location' in self.headers and self.status_code in REDIRECT_STATI) | True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`). | True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`). | [
"True",
"if",
"this",
"Response",
"is",
"a",
"well",
"-",
"formed",
"HTTP",
"redirect",
"that",
"could",
"have",
"been",
"processed",
"automatically",
"(",
"by",
":",
"meth",
":",
"Session",
".",
"resolve_redirects",
")",
"."
] | def is_redirect(self):
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return ('location' in self.headers and self.status_code in REDIRECT_STATI) | [
"def",
"is_redirect",
"(",
"self",
")",
":",
"return",
"(",
"'location'",
"in",
"self",
".",
"headers",
"and",
"self",
".",
"status_code",
"in",
"REDIRECT_STATI",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/requests/models.py#L703-L707 | |
NVIDIA-Merlin/HugeCTR | b596bcc44e14bb0c62c4f7e9c0b55301d94f2154 | sparse_operation_kit/sparse_operation_kit/core/embedding_variable_v2.py | python | EmbeddingVariable.sparse_read | (self, indices, name=None) | not called | not called | [
"not",
"called"
] | def sparse_read(self, indices, name=None):
""""not called"""
raise NotImplementedError("sparse_read not implemented.") | [
"def",
"sparse_read",
"(",
"self",
",",
"indices",
",",
"name",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"sparse_read not implemented.\"",
")"
] | https://github.com/NVIDIA-Merlin/HugeCTR/blob/b596bcc44e14bb0c62c4f7e9c0b55301d94f2154/sparse_operation_kit/sparse_operation_kit/core/embedding_variable_v2.py#L231-L233 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/common/walterWidgets/itemStyle.py | python | ItemStyle.drawComplexControl | (self, control, option, painter, widget=None) | return self.__parent.drawComplexControl(
control, option, painter, widget) | Draw the given control using the provided painter with the style
options specified by option. | Draw the given control using the provided painter with the style
options specified by option. | [
"Draw",
"the",
"given",
"control",
"using",
"the",
"provided",
"painter",
"with",
"the",
"style",
"options",
"specified",
"by",
"option",
"."
] | def drawComplexControl(self, control, option, painter, widget=None):
"""
Draw the given control using the provided painter with the style
options specified by option.
"""
return self.__parent.drawComplexControl(
control, option, painter, widget) | [
"def",
"drawComplexControl",
"(",
"self",
",",
"control",
",",
"option",
",",
"painter",
",",
"widget",
"=",
"None",
")",
":",
"return",
"self",
".",
"__parent",
".",
"drawComplexControl",
"(",
"control",
",",
"option",
",",
"painter",
",",
"widget",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/itemStyle.py#L24-L30 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/models.py | python | Sequential.add | (self, layer) | Adds a layer instance on top of the layer stack.
Arguments:
layer: layer instance.
Raises:
TypeError: If `layer` is not a layer instance.
ValueError: In case the `layer` argument does not
know its input shape.
ValueError: In case the `layer` argument has
multiple output tensors, or is already connected
somewhere else (forbidden in `Sequential` models). | Adds a layer instance on top of the layer stack. | [
"Adds",
"a",
"layer",
"instance",
"on",
"top",
"of",
"the",
"layer",
"stack",
"."
] | def add(self, layer):
"""Adds a layer instance on top of the layer stack.
Arguments:
layer: layer instance.
Raises:
TypeError: If `layer` is not a layer instance.
ValueError: In case the `layer` argument does not
know its input shape.
ValueError: In case the `layer` argument has
multiple output tensors, or is already connected
somewhere else (forbidden in `Sequential` models).
"""
if not isinstance(layer, Layer):
raise TypeError('The added layer must be '
'an instance of class Layer. '
'Found: ' + str(layer))
if not self.outputs:
# first layer in model: check that it is an input layer
if not layer.inbound_nodes:
# create an input layer
if not hasattr(layer, 'batch_input_shape'):
raise ValueError('The first layer in a '
'Sequential model must '
'get an `input_shape` or '
'`batch_input_shape` argument.')
# Instantiate the input layer.
x = Input(
batch_shape=layer.batch_input_shape,
dtype=layer.dtype,
name=layer.name + '_input')
# This will build the current layer
# and create the node connecting the current layer
# to the input layer we just created.
layer(x)
if len(layer.inbound_nodes) != 1:
raise ValueError('A layer added to a Sequential model must '
'not already be connected somewhere else. '
'Model received layer ' + layer.name + ' which has ' +
str(len(layer.inbound_nodes)) +
' pre-existing inbound connections.')
if len(layer.inbound_nodes[0].output_tensors) != 1:
raise ValueError('All layers in a Sequential model '
'should have a single output tensor. '
'For multi-output layers, '
'use the functional API.')
self.outputs = [layer.inbound_nodes[0].output_tensors[0]]
self.inputs = topology.get_source_inputs(self.outputs[0])
# We create an input node, which we will keep updated
# as we add more layers
topology.Node(
outbound_layer=self,
inbound_layers=[],
node_indices=[],
tensor_indices=[],
input_tensors=self.inputs,
output_tensors=self.outputs,
# no model-level masking for now
input_masks=[None for _ in self.inputs],
output_masks=[None])
else:
output_tensor = layer(self.outputs[0])
if isinstance(output_tensor, list):
raise TypeError('All layers in a Sequential model '
'should have a single output tensor. '
'For multi-output layers, '
'use the functional API.')
self.outputs = [output_tensor]
# update self.inbound_nodes
self.inbound_nodes[0].output_tensors = self.outputs
self.inbound_nodes[0].output_shapes = [K.int_shape(self.outputs[0])]
self.layers.append(layer)
self.built = False | [
"def",
"add",
"(",
"self",
",",
"layer",
")",
":",
"if",
"not",
"isinstance",
"(",
"layer",
",",
"Layer",
")",
":",
"raise",
"TypeError",
"(",
"'The added layer must be '",
"'an instance of class Layer. '",
"'Found: '",
"+",
"str",
"(",
"layer",
")",
")",
"i... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/models.py#L443-L521 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Variables/PathVariable.py | python | _PathVariableClass.__call__ | (self, key, help, default, validator=None) | The input parameters describe a 'path list' option, thus they
are returned with the correct converter and validator appended. The
result is usable for input to opts.Add() .
The 'default' option specifies the default path to use if the
user does not specify an override with this option.
validator is a validator, see this file for examples | The input parameters describe a 'path list' option, thus they
are returned with the correct converter and validator appended. The
result is usable for input to opts.Add() . | [
"The",
"input",
"parameters",
"describe",
"a",
"path",
"list",
"option",
"thus",
"they",
"are",
"returned",
"with",
"the",
"correct",
"converter",
"and",
"validator",
"appended",
".",
"The",
"result",
"is",
"usable",
"for",
"input",
"to",
"opts",
".",
"Add",... | def __call__(self, key, help, default, validator=None):
"""
The input parameters describe a 'path list' option, thus they
are returned with the correct converter and validator appended. The
result is usable for input to opts.Add() .
The 'default' option specifies the default path to use if the
user does not specify an override with this option.
validator is a validator, see this file for examples
"""
if validator is None:
validator = self.PathExists
if SCons.Util.is_List(key) or SCons.Util.is_Tuple(key):
return (key, '%s ( /path/to/%s )' % (help, key[0]), default,
validator, None)
else:
return (key, '%s ( /path/to/%s )' % (help, key), default,
validator, None) | [
"def",
"__call__",
"(",
"self",
",",
"key",
",",
"help",
",",
"default",
",",
"validator",
"=",
"None",
")",
":",
"if",
"validator",
"is",
"None",
":",
"validator",
"=",
"self",
".",
"PathExists",
"if",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"key... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Variables/PathVariable.py#L117-L136 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/cppcheck/prepare_filelist_for_cppcheck.py | python | matches_any_of | (filename, masks) | return False | :param filename: Filename to check.
:param masks: List of masks against which to check the filename.
:return: True if filename matches any of the masks. | :param filename: Filename to check.
:param masks: List of masks against which to check the filename.
:return: True if filename matches any of the masks. | [
":",
"param",
"filename",
":",
"Filename",
"to",
"check",
".",
":",
"param",
"masks",
":",
"List",
"of",
"masks",
"against",
"which",
"to",
"check",
"the",
"filename",
".",
":",
"return",
":",
"True",
"if",
"filename",
"matches",
"any",
"of",
"the",
"m... | def matches_any_of(filename, masks):
"""
:param filename: Filename to check.
:param masks: List of masks against which to check the filename.
:return: True if filename matches any of the masks.
"""
name = filename.lower().replace('\\', '/')
for mask in masks:
mask = mask.lower().replace('\\', '/')
if fnmatch.fnmatch(name, mask):
print("{} matches {}".format(name, mask))
return True
return False | [
"def",
"matches_any_of",
"(",
"filename",
",",
"masks",
")",
":",
"name",
"=",
"filename",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"for",
"mask",
"in",
"masks",
":",
"mask",
"=",
"mask",
".",
"lower",
"(",
")",
".",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/cppcheck/prepare_filelist_for_cppcheck.py#L11-L23 | |
BUSEC/TumbleBit | 55829dc75c36554e710e723dedb510d62a57ca0c | reference_implementation/tumblebit/puzzle_promise.py | python | PuzzlePromise.encrypt | (key, sig) | return xor_bytes(sha512(key), sig) | Encrypts the sig by xoring it with sha512 hash of `key`.
Args:
key (str): A key that will be hashed
sig (str): The signature to be encrypted.
Returns:
str: The encrypted msg.
Raises:
ValueError: If `sig` is not 64 bytes | Encrypts the sig by xoring it with sha512 hash of `key`. | [
"Encrypts",
"the",
"sig",
"by",
"xoring",
"it",
"with",
"sha512",
"hash",
"of",
"key",
"."
] | def encrypt(key, sig):
""" Encrypts the sig by xoring it with sha512 hash of `key`.
Args:
key (str): A key that will be hashed
sig (str): The signature to be encrypted.
Returns:
str: The encrypted msg.
Raises:
ValueError: If `sig` is not 64 bytes
"""
if len(sig) != 64:
raise ValueError('sig must be 64 bytes')
return xor_bytes(sha512(key), sig) | [
"def",
"encrypt",
"(",
"key",
",",
"sig",
")",
":",
"if",
"len",
"(",
"sig",
")",
"!=",
"64",
":",
"raise",
"ValueError",
"(",
"'sig must be 64 bytes'",
")",
"return",
"xor_bytes",
"(",
"sha512",
"(",
"key",
")",
",",
"sig",
")"
] | https://github.com/BUSEC/TumbleBit/blob/55829dc75c36554e710e723dedb510d62a57ca0c/reference_implementation/tumblebit/puzzle_promise.py#L78-L94 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/MSCommon/vc.py | python | find_vc_pdir | (env, msvc_version) | return None | Find the MSVC product directory for the given version.
Tries to look up the path using a registry key from the table
_VCVER_TO_PRODUCT_DIR; if there is no key, calls find_vc_pdir_wshere
for help instead.
Args:
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Returns:
str: Path found in registry, or None
Raises:
UnsupportedVersion: if the version is not known by this file.
MissingConfiguration: found version but the directory is missing.
Both exceptions inherit from VisualCException. | Find the MSVC product directory for the given version. | [
"Find",
"the",
"MSVC",
"product",
"directory",
"for",
"the",
"given",
"version",
"."
] | def find_vc_pdir(env, msvc_version):
"""Find the MSVC product directory for the given version.
Tries to look up the path using a registry key from the table
_VCVER_TO_PRODUCT_DIR; if there is no key, calls find_vc_pdir_wshere
for help instead.
Args:
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Returns:
str: Path found in registry, or None
Raises:
UnsupportedVersion: if the version is not known by this file.
MissingConfiguration: found version but the directory is missing.
Both exceptions inherit from VisualCException.
"""
root = 'Software\\'
try:
hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
for hkroot, key in hkeys:
try:
comps = None
if not key:
comps = find_vc_pdir_vswhere(msvc_version, env)
if not comps:
debug('no VC found for version {}'.format(repr(msvc_version)))
raise SCons.Util.WinError
debug('VC found: {}'.format(repr(msvc_version)))
return comps
else:
if common.is_win64():
try:
# ordinarily at win64, try Wow6432Node first.
comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot)
except SCons.Util.WinError as e:
# at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node
pass
if not comps:
# not Win64, or Microsoft Visual Studio for Python 2.7
comps = common.read_reg(root + key, hkroot)
except SCons.Util.WinError as e:
debug('no VC registry key {}'.format(repr(key)))
else:
debug('found VC in registry: {}'.format(comps))
if os.path.exists(comps):
return comps
else:
debug('reg says dir is {}, but it does not exist. (ignoring)'.format(comps))
raise MissingConfiguration("registry dir {} not found on the filesystem".format(comps))
return None | [
"def",
"find_vc_pdir",
"(",
"env",
",",
"msvc_version",
")",
":",
"root",
"=",
"'Software\\\\'",
"try",
":",
"hkeys",
"=",
"_VCVER_TO_PRODUCT_DIR",
"[",
"msvc_version",
"]",
"except",
"KeyError",
":",
"debug",
"(",
"\"Unknown version of MSVC: %s\"",
"%",
"msvc_ver... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/MSCommon/vc.py#L415-L473 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py | python | DatetimeLikeArrayMixin._addsub_offset_array | (self, other, op) | return self._from_sequence(res_values, **kwargs) | Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self | Add or subtract array-like of DateOffset objects | [
"Add",
"or",
"subtract",
"array",
"-",
"like",
"of",
"DateOffset",
"objects"
] | def _addsub_offset_array(self, other, op):
"""
Add or subtract array-like of DateOffset objects
Parameters
----------
other : Index, np.ndarray
object-dtype containing pd.DateOffset objects
op : {operator.add, operator.sub}
Returns
-------
result : same class as self
"""
assert op in [operator.add, operator.sub]
if len(other) == 1:
return op(self, other[0])
warnings.warn("Adding/subtracting array of DateOffsets to "
"{cls} not vectorized"
.format(cls=type(self).__name__), PerformanceWarning)
# For EA self.astype('O') returns a numpy array, not an Index
left = lib.values_from_object(self.astype('O'))
res_values = op(left, np.array(other))
kwargs = {}
if not is_period_dtype(self):
kwargs['freq'] = 'infer'
return self._from_sequence(res_values, **kwargs) | [
"def",
"_addsub_offset_array",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"assert",
"op",
"in",
"[",
"operator",
".",
"add",
",",
"operator",
".",
"sub",
"]",
"if",
"len",
"(",
"other",
")",
"==",
"1",
":",
"return",
"op",
"(",
"self",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py#L1109-L1138 | |
bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | thirdparty/pyratemp/pyratemp.py | python | dummy_raise | (exception, value) | return mydummy | Create an exception-raising dummy function.
:Returns: dummy function, raising ``exception(value)`` | Create an exception-raising dummy function. | [
"Create",
"an",
"exception",
"-",
"raising",
"dummy",
"function",
"."
] | def dummy_raise(exception, value):
"""Create an exception-raising dummy function.
:Returns: dummy function, raising ``exception(value)``
"""
def mydummy(*_, **__):
raise exception(value)
return mydummy | [
"def",
"dummy_raise",
"(",
"exception",
",",
"value",
")",
":",
"def",
"mydummy",
"(",
"*",
"_",
",",
"*",
"*",
"__",
")",
":",
"raise",
"exception",
"(",
"value",
")",
"return",
"mydummy"
] | https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/thirdparty/pyratemp/pyratemp.py#L257-L264 | |
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | txjsonrpc/jsonrpc.py | python | BaseSubhandler._getFunction | (self, functionPath) | Given a string, return a function, or raise jsonrpclib.NoSuchFunction.
This returned function will be called, and should return the result
of the call, a Deferred, or a Fault instance.
Override in subclasses if you want your own policy. The default
policy is that given functionPath 'foo', return the method at
self.jsonrpc_foo, i.e. getattr(self, "jsonrpc_" + functionPath).
If functionPath contains self.separator, the sub-handler for
the initial prefix is used to search for the remaining path. | Given a string, return a function, or raise jsonrpclib.NoSuchFunction. | [
"Given",
"a",
"string",
"return",
"a",
"function",
"or",
"raise",
"jsonrpclib",
".",
"NoSuchFunction",
"."
] | def _getFunction(self, functionPath):
"""
Given a string, return a function, or raise jsonrpclib.NoSuchFunction.
This returned function will be called, and should return the result
of the call, a Deferred, or a Fault instance.
Override in subclasses if you want your own policy. The default
policy is that given functionPath 'foo', return the method at
self.jsonrpc_foo, i.e. getattr(self, "jsonrpc_" + functionPath).
If functionPath contains self.separator, the sub-handler for
the initial prefix is used to search for the remaining path.
"""
if functionPath.find(self.separator) != -1:
prefix, functionPath = functionPath.split(self.separator, 1)
handler = self.getSubHandler(prefix)
if handler is None:
raise jsonrpclib.NoSuchFunction(jsonrpclib.METHOD_NOT_FOUND,
"no such sub-handler %s" % prefix)
return handler._getFunction(functionPath)
f = getattr(self, "jsonrpc_%s" % functionPath, None)
if not f:
raise jsonrpclib.NoSuchFunction(jsonrpclib.METHOD_NOT_FOUND,
"function %s not found" % functionPath)
elif not callable(f):
raise jsonrpclib.NoSuchFunction(jsonrpclib.METHOD_NOT_CALLABLE,
"function %s not callable" % functionPath)
else:
return f | [
"def",
"_getFunction",
"(",
"self",
",",
"functionPath",
")",
":",
"if",
"functionPath",
".",
"find",
"(",
"self",
".",
"separator",
")",
"!=",
"-",
"1",
":",
"prefix",
",",
"functionPath",
"=",
"functionPath",
".",
"split",
"(",
"self",
".",
"separator"... | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/txjsonrpc/jsonrpc.py#L27-L56 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/autograph/pyct/static_analysis/type_inference.py | python | Resolver.res_arg | (self, ns, types_ns, f_name, name, type_anno, f_is_local) | Resolves the type of a (possibly annotated) function argument.
Args:
ns: namespace
types_ns: types namespace
f_name: str, the function name
name: str, the argument name
type_anno: the type annotating the argument, if any
f_is_local: bool, whether the function is a local function
Returns:
Set of the argument types. | Resolves the type of a (possibly annotated) function argument. | [
"Resolves",
"the",
"type",
"of",
"a",
"(",
"possibly",
"annotated",
")",
"function",
"argument",
"."
] | def res_arg(self, ns, types_ns, f_name, name, type_anno, f_is_local):
"""Resolves the type of a (possibly annotated) function argument.
Args:
ns: namespace
types_ns: types namespace
f_name: str, the function name
name: str, the argument name
type_anno: the type annotating the argument, if any
f_is_local: bool, whether the function is a local function
Returns:
Set of the argument types.
"""
raise NotImplementedError('subclasses must implement') | [
"def",
"res_arg",
"(",
"self",
",",
"ns",
",",
"types_ns",
",",
"f_name",
",",
"name",
",",
"type_anno",
",",
"f_is_local",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses must implement'",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/pyct/static_analysis/type_inference.py#L77-L90 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/ndimage/filters.py | python | laplace | (input, output=None, mode="reflect", cval=0.0) | return generic_laplace(input, derivative2, output, mode, cval) | N-dimensional Laplace filter based on approximate second derivatives.
Parameters
----------
%(input)s
%(output)s
%(mode_multiple)s
%(cval)s
Examples
--------
>>> from scipy import ndimage, misc
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> plt.gray() # show the filtered result in grayscale
>>> ax1 = fig.add_subplot(121) # left side
>>> ax2 = fig.add_subplot(122) # right side
>>> ascent = misc.ascent()
>>> result = ndimage.laplace(ascent)
>>> ax1.imshow(ascent)
>>> ax2.imshow(result)
>>> plt.show() | N-dimensional Laplace filter based on approximate second derivatives. | [
"N",
"-",
"dimensional",
"Laplace",
"filter",
"based",
"on",
"approximate",
"second",
"derivatives",
"."
] | def laplace(input, output=None, mode="reflect", cval=0.0):
"""N-dimensional Laplace filter based on approximate second derivatives.
Parameters
----------
%(input)s
%(output)s
%(mode_multiple)s
%(cval)s
Examples
--------
>>> from scipy import ndimage, misc
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> plt.gray() # show the filtered result in grayscale
>>> ax1 = fig.add_subplot(121) # left side
>>> ax2 = fig.add_subplot(122) # right side
>>> ascent = misc.ascent()
>>> result = ndimage.laplace(ascent)
>>> ax1.imshow(ascent)
>>> ax2.imshow(result)
>>> plt.show()
"""
def derivative2(input, axis, output, mode, cval):
return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
return generic_laplace(input, derivative2, output, mode, cval) | [
"def",
"laplace",
"(",
"input",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"\"reflect\"",
",",
"cval",
"=",
"0.0",
")",
":",
"def",
"derivative2",
"(",
"input",
",",
"axis",
",",
"output",
",",
"mode",
",",
"cval",
")",
":",
"return",
"correlate1d... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/ndimage/filters.py#L413-L439 | |
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | python/caffe/draw.py | python | get_layer_label | (layer, rankdir) | return node_label | Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer | Define node label based on layer type. | [
"Define",
"node",
"label",
"based",
"on",
"layer",
"type",
"."
] | def get_layer_label(layer, rankdir):
"""Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer
"""
if rankdir in ('TB', 'BT'):
# If graph orientation is vertical, horizontal space is free and
# vertical space is not; separate words with spaces
separator = ' '
else:
# If graph orientation is horizontal, vertical space is free and
# horizontal space is not; separate words with newlines
separator = '\\n'
if layer.type == 'Convolution' or layer.type == 'Deconvolution':
# Outer double quotes needed or else colon characters don't parse
# properly
node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
layer.type,
separator,
layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size) else 1,
separator,
layer.convolution_param.stride[0] if len(layer.convolution_param.stride) else 1,
separator,
layer.convolution_param.pad[0] if len(layer.convolution_param.pad) else 0)
elif layer.type == 'Pooling':
pooling_types_dict = get_pooling_types_dict()
node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
pooling_types_dict[layer.pooling_param.pool],
layer.type,
separator,
layer.pooling_param.kernel_size,
separator,
layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label | [
"def",
"get_layer_label",
"(",
"layer",
",",
"rankdir",
")",
":",
"if",
"rankdir",
"in",
"(",
"'TB'",
",",
"'BT'",
")",
":",
"# If graph orientation is vertical, horizontal space is free and",
"# vertical space is not; separate words with spaces",
"separator",
"=",
"' '",
... | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/draw.py#L62-L114 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/difflib.py | python | diff_bytes | (dfunc, a, b, fromfile=b'', tofile=b'',
fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n') | r"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded
back to bytes on return. This is necessary to compare files with
unknown or inconsistent encoding. All other inputs (except `n`) must be
bytes rather than str. | r"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded
back to bytes on return. This is necessary to compare files with
unknown or inconsistent encoding. All other inputs (except `n`) must be
bytes rather than str. | [
"r",
"Compare",
"a",
"and",
"b",
"two",
"sequences",
"of",
"lines",
"represented",
"as",
"bytes",
"rather",
"than",
"str",
".",
"This",
"is",
"a",
"wrapper",
"for",
"dfunc",
"which",
"is",
"typically",
"either",
"unified_diff",
"()",
"or",
"context_diff",
... | def diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',
fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n'):
r"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded
back to bytes on return. This is necessary to compare files with
unknown or inconsistent encoding. All other inputs (except `n`) must be
bytes rather than str.
"""
def decode(s):
try:
return s.decode('ascii', 'surrogateescape')
except AttributeError as err:
msg = ('all arguments must be bytes, not %s (%r)' %
(type(s).__name__, s))
raise TypeError(msg) from err
a = list(map(decode, a))
b = list(map(decode, b))
fromfile = decode(fromfile)
tofile = decode(tofile)
fromfiledate = decode(fromfiledate)
tofiledate = decode(tofiledate)
lineterm = decode(lineterm)
lines = dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)
for line in lines:
yield line.encode('ascii', 'surrogateescape') | [
"def",
"diff_bytes",
"(",
"dfunc",
",",
"a",
",",
"b",
",",
"fromfile",
"=",
"b''",
",",
"tofile",
"=",
"b''",
",",
"fromfiledate",
"=",
"b''",
",",
"tofiledate",
"=",
"b''",
",",
"n",
"=",
"3",
",",
"lineterm",
"=",
"b'\\n'",
")",
":",
"def",
"d... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/difflib.py#L1314-L1342 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/tools/create_nmf.py | python | NmfUtils._GenerateManifest | (self, runnable=True) | Create a JSON formatted dict containing the files
NaCl will map url requests based on architecture. The startup NEXE
can always be found under the top key PROGRAM. Additional files are under
the FILES key further mapped by file name. In the case of 'runnable' the
PROGRAM key is populated with urls pointing the runnable-ld.so which acts
as the startup nexe. The application itself, is then placed under the
FILES key mapped as 'main.exe' instead of it's original name so that the
loader can find it. | Create a JSON formatted dict containing the files
NaCl will map url requests based on architecture. The startup NEXE
can always be found under the top key PROGRAM. Additional files are under
the FILES key further mapped by file name. In the case of 'runnable' the
PROGRAM key is populated with urls pointing the runnable-ld.so which acts
as the startup nexe. The application itself, is then placed under the
FILES key mapped as 'main.exe' instead of it's original name so that the
loader can find it. | [
"Create",
"a",
"JSON",
"formatted",
"dict",
"containing",
"the",
"files",
"NaCl",
"will",
"map",
"url",
"requests",
"based",
"on",
"architecture",
".",
"The",
"startup",
"NEXE",
"can",
"always",
"be",
"found",
"under",
"the",
"top",
"key",
"PROGRAM",
".",
... | def _GenerateManifest(self, runnable=True):
'''Create a JSON formatted dict containing the files
NaCl will map url requests based on architecture. The startup NEXE
can always be found under the top key PROGRAM. Additional files are under
the FILES key further mapped by file name. In the case of 'runnable' the
PROGRAM key is populated with urls pointing the runnable-ld.so which acts
as the startup nexe. The application itself, is then placed under the
FILES key mapped as 'main.exe' instead of it's original name so that the
loader can find it.'''
manifest = { FILES_KEY: {}, PROGRAM_KEY: {} }
needed = self.GetNeeded()
for need in needed:
archinfo = needed[need]
urlinfo = { URL_KEY: archinfo.url }
name = archinfo.name
# If starting with runnable-ld.so, make that the main executable.
if runnable:
if need.endswith(RUNNABLE_LD):
manifest[PROGRAM_KEY][archinfo.arch] = urlinfo
continue
# For the main nexes:
if need.endswith('.nexe') and need in self.main_files:
# Place it under program if we aren't using the runnable-ld.so.
if not runnable:
manifest[PROGRAM_KEY][archinfo.arch] = urlinfo
continue
# Otherwise, treat it like another another file named main.nexe.
name = MAIN_NEXE
fileinfo = manifest[FILES_KEY].get(name, {})
fileinfo[archinfo.arch] = urlinfo
manifest[FILES_KEY][name] = fileinfo
self.manifest = manifest | [
"def",
"_GenerateManifest",
"(",
"self",
",",
"runnable",
"=",
"True",
")",
":",
"manifest",
"=",
"{",
"FILES_KEY",
":",
"{",
"}",
",",
"PROGRAM_KEY",
":",
"{",
"}",
"}",
"needed",
"=",
"self",
".",
"GetNeeded",
"(",
")",
"for",
"need",
"in",
"needed... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/tools/create_nmf.py#L240-L277 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WriteLink | (self, spec, config_name, config, link_deps, compile_deps) | Write out a link step. Fills out target.binary. | Write out a link step. Fills out target.binary. | [
"Write",
"out",
"a",
"link",
"step",
".",
"Fills",
"out",
"target",
".",
"binary",
"."
] | def WriteLink(self, spec, config_name, config, link_deps, compile_deps):
"""Write out a link step. Fills out target.binary. """
if self.flavor != 'mac' or len(self.archs) == 1:
return self.WriteLinkForArch(
self.ninja, spec, config_name, config, link_deps, compile_deps)
else:
output = self.ComputeOutput(spec)
inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec,
config_name, config, link_deps[arch],
compile_deps, arch=arch)
for arch in self.archs]
extra_bindings = []
build_output = output
if not self.is_mac_bundle:
self.AppendPostbuildVariable(extra_bindings, spec, output, output)
# TODO(yyanagisawa): more work needed to fix:
# https://code.google.com/p/gyp/issues/detail?id=411
if (spec['type'] in ('shared_library', 'loadable_module') and
not self.is_mac_bundle):
extra_bindings.append(('lib', output))
self.ninja.build([output, output + '.TOC'], 'solipo', inputs,
variables=extra_bindings)
else:
self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings)
return output | [
"def",
"WriteLink",
"(",
"self",
",",
"spec",
",",
"config_name",
",",
"config",
",",
"link_deps",
",",
"compile_deps",
")",
":",
"if",
"self",
".",
"flavor",
"!=",
"'mac'",
"or",
"len",
"(",
"self",
".",
"archs",
")",
"==",
"1",
":",
"return",
"self... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py#L1103-L1128 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_operators.py | python | _dummy_bool | (_) | Dummy method to prevent a RaggedTensor from being used as a Python bool. | Dummy method to prevent a RaggedTensor from being used as a Python bool. | [
"Dummy",
"method",
"to",
"prevent",
"a",
"RaggedTensor",
"from",
"being",
"used",
"as",
"a",
"Python",
"bool",
"."
] | def _dummy_bool(_):
"""Dummy method to prevent a RaggedTensor from being used as a Python bool."""
raise TypeError("RaggedTensor may not be used as a boolean.") | [
"def",
"_dummy_bool",
"(",
"_",
")",
":",
"raise",
"TypeError",
"(",
"\"RaggedTensor may not be used as a boolean.\"",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_operators.py#L85-L87 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/ops/__init__.py | python | _comp_method_SERIES | (cls, op, special) | return wrapper | Wrapper function for Series arithmetic operations, to avoid
code duplication. | Wrapper function for Series arithmetic operations, to avoid
code duplication. | [
"Wrapper",
"function",
"for",
"Series",
"arithmetic",
"operations",
"to",
"avoid",
"code",
"duplication",
"."
] | def _comp_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
@unpack_zerodim_and_defer(op_name)
def wrapper(self, other):
res_name = get_op_result_name(self, other)
if isinstance(other, ABCSeries) and not self._indexed_same(other):
raise ValueError("Can only compare identically-labeled Series objects")
lvalues = extract_array(self, extract_numpy=True)
rvalues = extract_array(other, extract_numpy=True)
res_values = comparison_op(lvalues, rvalues, op)
return _construct_result(self, res_values, index=self.index, name=res_name)
wrapper.__name__ = op_name
return wrapper | [
"def",
"_comp_method_SERIES",
"(",
"cls",
",",
"op",
",",
"special",
")",
":",
"op_name",
"=",
"_get_op_name",
"(",
"op",
",",
"special",
")",
"@",
"unpack_zerodim_and_defer",
"(",
"op_name",
")",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"r... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/ops/__init__.py#L511-L534 | |
commaai/openpilot | 4416c21b1e738ab7d04147c5ae52b5135e0cdb40 | pyextra/acados_template/acados_ocp.py | python | AcadosOcpCost.Vu_0 | (self) | return self.__Vu_0 | :math:`V_u^0` - u matrix coefficient at initial shooting node (0).
Default: :code:`None`. | :math:`V_u^0` - u matrix coefficient at initial shooting node (0).
Default: :code:`None`. | [
":",
"math",
":",
"V_u^0",
"-",
"u",
"matrix",
"coefficient",
"at",
"initial",
"shooting",
"node",
"(",
"0",
")",
".",
"Default",
":",
":",
"code",
":",
"None",
"."
] | def Vu_0(self):
""":math:`V_u^0` - u matrix coefficient at initial shooting node (0).
Default: :code:`None`.
"""
return self.__Vu_0 | [
"def",
"Vu_0",
"(",
"self",
")",
":",
"return",
"self",
".",
"__Vu_0"
] | https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L575-L579 | |
fredakilla/GPlayEngine | ae6b45f4c68f696fcd171ce6996a5a4e80aee09e | thirdparty/freetype/src/tools/docmaker/sources.py | python | SourceProcessor.reset | ( self ) | Reset a block processor and clean up all its blocks. | Reset a block processor and clean up all its blocks. | [
"Reset",
"a",
"block",
"processor",
"and",
"clean",
"up",
"all",
"its",
"blocks",
"."
] | def reset( self ):
"""Reset a block processor and clean up all its blocks."""
self.blocks = []
self.format = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"blocks",
"=",
"[",
"]",
"self",
".",
"format",
"=",
"None"
] | https://github.com/fredakilla/GPlayEngine/blob/ae6b45f4c68f696fcd171ce6996a5a4e80aee09e/thirdparty/freetype/src/tools/docmaker/sources.py#L337-L340 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/rcnn/rcnn/dataset/imdb.py | python | IMDB.__init__ | (self, name, image_set, root_path, dataset_path) | basic information about an image database
:param name: name of image database will be used for any output
:param root_path: root path store cache and proposal data
:param dataset_path: dataset path store images and image lists | basic information about an image database
:param name: name of image database will be used for any output
:param root_path: root path store cache and proposal data
:param dataset_path: dataset path store images and image lists | [
"basic",
"information",
"about",
"an",
"image",
"database",
":",
"param",
"name",
":",
"name",
"of",
"image",
"database",
"will",
"be",
"used",
"for",
"any",
"output",
":",
"param",
"root_path",
":",
"root",
"path",
"store",
"cache",
"and",
"proposal",
"da... | def __init__(self, name, image_set, root_path, dataset_path):
"""
basic information about an image database
:param name: name of image database will be used for any output
:param root_path: root path store cache and proposal data
:param dataset_path: dataset path store images and image lists
"""
self.name = name + '_' + image_set
self.image_set = image_set
self.root_path = root_path
self.data_path = dataset_path
# abstract attributes
self.classes = []
self.num_classes = 0
self.image_set_index = []
self.num_images = 0
self.config = {} | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"image_set",
",",
"root_path",
",",
"dataset_path",
")",
":",
"self",
".",
"name",
"=",
"name",
"+",
"'_'",
"+",
"image_set",
"self",
".",
"image_set",
"=",
"image_set",
"self",
".",
"root_path",
"=",
"... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/rcnn/rcnn/dataset/imdb.py#L37-L55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.