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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/telnetlib.py | python | Telnet.process_rawq | (self) | Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence. | Transfer from raw queue to cooked queue. | [
"Transfer",
"from",
"raw",
"queue",
"to",
"cooked",
"queue",
"."
] | def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = ['', '']
try:
while self.rawq:
c = self.rawq_getchar()
if not self.iacseq:
if c == theNULL:
continue
if c == "\021":
continue
if c != IAC:
buf[self.sb] = buf[self.sb] + c
continue
else:
self.iacseq += c
elif len(self.iacseq) == 1:
# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = ''
if c == IAC:
buf[self.sb] = buf[self.sb] + c
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = ''
elif c == SE:
self.sb = 0
self.sbdataq = self.sbdataq + buf[1]
buf[1] = ''
if self.option_callback:
# Callback is supposed to look into
# the sbdataq
self.option_callback(self.sock, c, NOOPT)
else:
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd = self.iacseq[1]
self.iacseq = ''
opt = c
if cmd in (DO, DONT):
self.msg('IAC %s %d',
cmd == DO and 'DO' or 'DONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
self.msg('IAC %s %d',
cmd == WILL and 'WILL' or 'WONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = '' # Reset on EOF
self.sb = 0
pass
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1] | [
"def",
"process_rawq",
"(",
"self",
")",
":",
"buf",
"=",
"[",
"''",
",",
"''",
"]",
"try",
":",
"while",
"self",
".",
"rawq",
":",
"c",
"=",
"self",
".",
"rawq_getchar",
"(",
")",
"if",
"not",
"self",
".",
"iacseq",
":",
"if",
"c",
"==",
"theNULL",
":",
"continue",
"if",
"c",
"==",
"\"\\021\"",
":",
"continue",
"if",
"c",
"!=",
"IAC",
":",
"buf",
"[",
"self",
".",
"sb",
"]",
"=",
"buf",
"[",
"self",
".",
"sb",
"]",
"+",
"c",
"continue",
"else",
":",
"self",
".",
"iacseq",
"+=",
"c",
"elif",
"len",
"(",
"self",
".",
"iacseq",
")",
"==",
"1",
":",
"# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'",
"if",
"c",
"in",
"(",
"DO",
",",
"DONT",
",",
"WILL",
",",
"WONT",
")",
":",
"self",
".",
"iacseq",
"+=",
"c",
"continue",
"self",
".",
"iacseq",
"=",
"''",
"if",
"c",
"==",
"IAC",
":",
"buf",
"[",
"self",
".",
"sb",
"]",
"=",
"buf",
"[",
"self",
".",
"sb",
"]",
"+",
"c",
"else",
":",
"if",
"c",
"==",
"SB",
":",
"# SB ... SE start.",
"self",
".",
"sb",
"=",
"1",
"self",
".",
"sbdataq",
"=",
"''",
"elif",
"c",
"==",
"SE",
":",
"self",
".",
"sb",
"=",
"0",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"buf",
"[",
"1",
"]",
"buf",
"[",
"1",
"]",
"=",
"''",
"if",
"self",
".",
"option_callback",
":",
"# Callback is supposed to look into",
"# the sbdataq",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"c",
",",
"NOOPT",
")",
"else",
":",
"# We can't offer automatic processing of",
"# suboptions. Alas, we should not get any",
"# unless we did a WILL/DO before.",
"self",
".",
"msg",
"(",
"'IAC %d not recognized'",
"%",
"ord",
"(",
"c",
")",
")",
"elif",
"len",
"(",
"self",
".",
"iacseq",
")",
"==",
"2",
":",
"cmd",
"=",
"self",
".",
"iacseq",
"[",
"1",
"]",
"self",
".",
"iacseq",
"=",
"''",
"opt",
"=",
"c",
"if",
"cmd",
"in",
"(",
"DO",
",",
"DONT",
")",
":",
"self",
".",
"msg",
"(",
"'IAC %s %d'",
",",
"cmd",
"==",
"DO",
"and",
"'DO'",
"or",
"'DONT'",
",",
"ord",
"(",
"opt",
")",
")",
"if",
"self",
".",
"option_callback",
":",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"cmd",
",",
"opt",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"IAC",
"+",
"WONT",
"+",
"opt",
")",
"elif",
"cmd",
"in",
"(",
"WILL",
",",
"WONT",
")",
":",
"self",
".",
"msg",
"(",
"'IAC %s %d'",
",",
"cmd",
"==",
"WILL",
"and",
"'WILL'",
"or",
"'WONT'",
",",
"ord",
"(",
"opt",
")",
")",
"if",
"self",
".",
"option_callback",
":",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"cmd",
",",
"opt",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"IAC",
"+",
"DONT",
"+",
"opt",
")",
"except",
"EOFError",
":",
"# raised by self.rawq_getchar()",
"self",
".",
"iacseq",
"=",
"''",
"# Reset on EOF",
"self",
".",
"sb",
"=",
"0",
"pass",
"self",
".",
"cookedq",
"=",
"self",
".",
"cookedq",
"+",
"buf",
"[",
"0",
"]",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"buf",
"[",
"1",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/telnetlib.py#L471-L541 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/scipy/linalg.py | python | eigh | (a, b=None, lower=True, eigvals_only=False, overwrite_a=False,
overwrite_b=False, turbo=True, eigvals=None, _type=1,
check_finite=True) | return eigh_net(a) | Solve a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix.
Find eigenvalues Tensor `w` and optionally eigenvectors Tensor `v` of Tensor `a`,
where `b` is positive definite such that for every eigenvalue `λ` (i-th entry of w) and
its eigenvector `vi` (i-th column of `v`) satisfies::
a @ vi = λ * b @ vi
vi.conj().T @ a @ vi = λ
vi.conj().T @ b @ vi = 1
In the standard problem, `b` is assumed to be the identity matrix.
Args:
a (Tensor): A :math:`(M, M)` complex Hermitian or real symmetric matrix whose eigenvalues and
eigenvectors will be computed.
b (Tensor, optional): A :math:`(M, M)` complex Hermitian or real symmetric definite positive matrix in.
If omitted, identity matrix is assumed. Default: None.
lower (bool, optional): Whether the pertinent Tensor data is taken from the lower or upper
triangle of `a` and, if applicable, `b`. Default: True.
eigvals_only (bool, optional): Whether to calculate only eigenvalues and no eigenvectors.
Default: False.
_type (int, optional): For the generalized problems, this keyword specifies the problem type
to be solved for `w` and `v` (only takes 1, 2, 3 as possible inputs)::
1 => a @ v = w @ b @ v
2 => a @ b @ v = w @ v
3 => b @ a @ v = w @ v
This keyword is ignored for standard problems. Default: 1.
overwrite_a (bool, optional): Whether to overwrite data in `a` (may improve performance). Default: False.
overwrite_b (bool, optional): Whether to overwrite data in `b` (may improve performance). Default: False.
check_finite (bool, optional): Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems (crashes, non-termination)
if the inputs do contain infinities or NaNs. Default: True.
turbo (bool, optional): use divide and conquer algorithm (faster but expensive in memory, only
for generalized eigenvalue problem and if full set of eigenvalues are requested.).
Has no significant effect if eigenvectors are not requested. Default: True.
eigvals (tuple, optional): Indexes of the smallest and largest (in ascending order) eigenvalues
and corresponding eigenvectors to be returned: :math:`0 <= lo <= hi <= M-1`. If omitted, all eigenvalues
and eigenvectors are returned. Default: None.
Returns:
- Tensor with shape :math:`(N,)`, the :math:`N (1<=N<=M)` selected eigenvalues, in ascending order,
each repeated according to its multiplicity.
- Tensor with shape :math:`(M, N)`, (if ``eigvals_only == False``)
Raises:
LinAlgError: If eigenvalue computation does not converge, an error occurred, or b matrix is not
definite positive. Note that if input matrices are not symmetric or Hermitian, no error will
be reported but results will be wrong.
Supported Platforms:
``CPU`` ``GPU``
Examples:
>>> import mindspore.numpy as mnp
>>> from mindspore.common import Tensor
>>> from mindspore.scipy.linalg import eigh
>>> A = Tensor([[6., 3., 1., 5.], [3., 0., 5., 1.], [1., 5., 6., 2.], [5., 1., 2., 2.]])
>>> w, v = eigh(A)
>>> mnp.sum(mnp.dot(A, v) - mnp.dot(v, mnp.diag(w))) < 1e-10
Tensor(shape=[], dtype=Bool, value= True) | Solve a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix. | [
"Solve",
"a",
"standard",
"or",
"generalized",
"eigenvalue",
"problem",
"for",
"a",
"complex",
"Hermitian",
"or",
"real",
"symmetric",
"matrix",
"."
] | def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False,
overwrite_b=False, turbo=True, eigvals=None, _type=1,
check_finite=True):
"""
Solve a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix.
Find eigenvalues Tensor `w` and optionally eigenvectors Tensor `v` of Tensor `a`,
where `b` is positive definite such that for every eigenvalue `λ` (i-th entry of w) and
its eigenvector `vi` (i-th column of `v`) satisfies::
a @ vi = λ * b @ vi
vi.conj().T @ a @ vi = λ
vi.conj().T @ b @ vi = 1
In the standard problem, `b` is assumed to be the identity matrix.
Args:
a (Tensor): A :math:`(M, M)` complex Hermitian or real symmetric matrix whose eigenvalues and
eigenvectors will be computed.
b (Tensor, optional): A :math:`(M, M)` complex Hermitian or real symmetric definite positive matrix in.
If omitted, identity matrix is assumed. Default: None.
lower (bool, optional): Whether the pertinent Tensor data is taken from the lower or upper
triangle of `a` and, if applicable, `b`. Default: True.
eigvals_only (bool, optional): Whether to calculate only eigenvalues and no eigenvectors.
Default: False.
_type (int, optional): For the generalized problems, this keyword specifies the problem type
to be solved for `w` and `v` (only takes 1, 2, 3 as possible inputs)::
1 => a @ v = w @ b @ v
2 => a @ b @ v = w @ v
3 => b @ a @ v = w @ v
This keyword is ignored for standard problems. Default: 1.
overwrite_a (bool, optional): Whether to overwrite data in `a` (may improve performance). Default: False.
overwrite_b (bool, optional): Whether to overwrite data in `b` (may improve performance). Default: False.
check_finite (bool, optional): Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems (crashes, non-termination)
if the inputs do contain infinities or NaNs. Default: True.
turbo (bool, optional): use divide and conquer algorithm (faster but expensive in memory, only
for generalized eigenvalue problem and if full set of eigenvalues are requested.).
Has no significant effect if eigenvectors are not requested. Default: True.
eigvals (tuple, optional): Indexes of the smallest and largest (in ascending order) eigenvalues
and corresponding eigenvectors to be returned: :math:`0 <= lo <= hi <= M-1`. If omitted, all eigenvalues
and eigenvectors are returned. Default: None.
Returns:
- Tensor with shape :math:`(N,)`, the :math:`N (1<=N<=M)` selected eigenvalues, in ascending order,
each repeated according to its multiplicity.
- Tensor with shape :math:`(M, N)`, (if ``eigvals_only == False``)
Raises:
LinAlgError: If eigenvalue computation does not converge, an error occurred, or b matrix is not
definite positive. Note that if input matrices are not symmetric or Hermitian, no error will
be reported but results will be wrong.
Supported Platforms:
``CPU`` ``GPU``
Examples:
>>> import mindspore.numpy as mnp
>>> from mindspore.common import Tensor
>>> from mindspore.scipy.linalg import eigh
>>> A = Tensor([[6., 3., 1., 5.], [3., 0., 5., 1.], [1., 5., 6., 2.], [5., 1., 2., 2.]])
>>> w, v = eigh(A)
>>> mnp.sum(mnp.dot(A, v) - mnp.dot(v, mnp.diag(w))) < 1e-10
Tensor(shape=[], dtype=Bool, value= True)
"""
eigh_net = EighNet(not eigvals_only, lower=True)
return eigh_net(a) | [
"def",
"eigh",
"(",
"a",
",",
"b",
"=",
"None",
",",
"lower",
"=",
"True",
",",
"eigvals_only",
"=",
"False",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"turbo",
"=",
"True",
",",
"eigvals",
"=",
"None",
",",
"_type",
"=",
"1",
",",
"check_finite",
"=",
"True",
")",
":",
"eigh_net",
"=",
"EighNet",
"(",
"not",
"eigvals_only",
",",
"lower",
"=",
"True",
")",
"return",
"eigh_net",
"(",
"a",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/scipy/linalg.py#L331-L400 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ipaddress.py | python | _collapse_addresses_internal | (addresses) | Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed. | Loops through the addresses, collapsing concurrent netblocks. | [
"Loops",
"through",
"the",
"addresses",
"collapsing",
"concurrent",
"netblocks",
"."
] | def _collapse_addresses_internal(addresses):
"""Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed.
"""
# First merge
to_merge = list(addresses)
subnets = {}
while to_merge:
net = to_merge.pop()
supernet = net.supernet()
existing = subnets.get(supernet)
if existing is None:
subnets[supernet] = net
elif existing != net:
# Merge consecutive subnets
del subnets[supernet]
to_merge.append(supernet)
# Then iterate over resulting networks, skipping subsumed subnets
last = None
for net in sorted(subnets.values()):
if last is not None:
# Since they are sorted, last.network_address <= net.network_address
# is a given.
if last.broadcast_address >= net.broadcast_address:
continue
yield net
last = net | [
"def",
"_collapse_addresses_internal",
"(",
"addresses",
")",
":",
"# First merge",
"to_merge",
"=",
"list",
"(",
"addresses",
")",
"subnets",
"=",
"{",
"}",
"while",
"to_merge",
":",
"net",
"=",
"to_merge",
".",
"pop",
"(",
")",
"supernet",
"=",
"net",
".",
"supernet",
"(",
")",
"existing",
"=",
"subnets",
".",
"get",
"(",
"supernet",
")",
"if",
"existing",
"is",
"None",
":",
"subnets",
"[",
"supernet",
"]",
"=",
"net",
"elif",
"existing",
"!=",
"net",
":",
"# Merge consecutive subnets",
"del",
"subnets",
"[",
"supernet",
"]",
"to_merge",
".",
"append",
"(",
"supernet",
")",
"# Then iterate over resulting networks, skipping subsumed subnets",
"last",
"=",
"None",
"for",
"net",
"in",
"sorted",
"(",
"subnets",
".",
"values",
"(",
")",
")",
":",
"if",
"last",
"is",
"not",
"None",
":",
"# Since they are sorted, last.network_address <= net.network_address",
"# is a given.",
"if",
"last",
".",
"broadcast_address",
">=",
"net",
".",
"broadcast_address",
":",
"continue",
"yield",
"net",
"last",
"=",
"net"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L257-L303 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | libcxx/utils/google-benchmark/tools/gbench/util.py | python | remove_benchmark_flags | (prefix, benchmark_flags) | return [f for f in benchmark_flags if not f.startswith(prefix)] | Return a new list containing the specified benchmark_flags except those
with the specified prefix. | Return a new list containing the specified benchmark_flags except those
with the specified prefix. | [
"Return",
"a",
"new",
"list",
"containing",
"the",
"specified",
"benchmark_flags",
"except",
"those",
"with",
"the",
"specified",
"prefix",
"."
] | def remove_benchmark_flags(prefix, benchmark_flags):
"""
Return a new list containing the specified benchmark_flags except those
with the specified prefix.
"""
assert prefix.startswith('--') and prefix.endswith('=')
return [f for f in benchmark_flags if not f.startswith(prefix)] | [
"def",
"remove_benchmark_flags",
"(",
"prefix",
",",
"benchmark_flags",
")",
":",
"assert",
"prefix",
".",
"startswith",
"(",
"'--'",
")",
"and",
"prefix",
".",
"endswith",
"(",
"'='",
")",
"return",
"[",
"f",
"for",
"f",
"in",
"benchmark_flags",
"if",
"not",
"f",
".",
"startswith",
"(",
"prefix",
")",
"]"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/libcxx/utils/google-benchmark/tools/gbench/util.py#L104-L110 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py | python | TCPROSTransport.receive_loop | (self, msgs_callback) | Receive messages until shutdown
@param msgs_callback: callback to invoke for new messages received
@type msgs_callback: fn([msg]) | Receive messages until shutdown | [
"Receive",
"messages",
"until",
"shutdown"
] | def receive_loop(self, msgs_callback):
"""
Receive messages until shutdown
@param msgs_callback: callback to invoke for new messages received
@type msgs_callback: fn([msg])
"""
# - use assert here as this would be an internal error, aka bug
logger.debug("receive_loop for [%s]", self.name)
try:
while not self.done and not is_shutdown():
try:
if self.socket is not None:
msgs = self.receive_once()
if not self.done and not is_shutdown():
msgs_callback(msgs, self)
else:
self._reconnect()
except TransportException as e:
# set socket to None so we reconnect
try:
if self.socket is not None:
try:
self.socket.shutdown()
except:
pass
finally:
self.socket.close()
except:
pass
self.socket = None
except DeserializationError as e:
#TODO: how should we handle reconnect in this case?
logerr("[%s] error deserializing incoming request: %s"%self.name, str(e))
rospyerr("[%s] error deserializing incoming request: %s"%self.name, traceback.format_exc())
except:
# in many cases this will be a normal hangup, but log internally
try:
#1467 sometimes we get exceptions due to
#interpreter shutdown, so blanket ignore those if
#the reporting fails
rospydebug("exception in receive loop for [%s], may be normal. Exception is %s",self.name, traceback.format_exc())
except: pass
rospydebug("receive_loop[%s]: done condition met, exited loop"%self.name)
finally:
if not self.done:
self.close() | [
"def",
"receive_loop",
"(",
"self",
",",
"msgs_callback",
")",
":",
"# - use assert here as this would be an internal error, aka bug",
"logger",
".",
"debug",
"(",
"\"receive_loop for [%s]\"",
",",
"self",
".",
"name",
")",
"try",
":",
"while",
"not",
"self",
".",
"done",
"and",
"not",
"is_shutdown",
"(",
")",
":",
"try",
":",
"if",
"self",
".",
"socket",
"is",
"not",
"None",
":",
"msgs",
"=",
"self",
".",
"receive_once",
"(",
")",
"if",
"not",
"self",
".",
"done",
"and",
"not",
"is_shutdown",
"(",
")",
":",
"msgs_callback",
"(",
"msgs",
",",
"self",
")",
"else",
":",
"self",
".",
"_reconnect",
"(",
")",
"except",
"TransportException",
"as",
"e",
":",
"# set socket to None so we reconnect",
"try",
":",
"if",
"self",
".",
"socket",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"socket",
".",
"shutdown",
"(",
")",
"except",
":",
"pass",
"finally",
":",
"self",
".",
"socket",
".",
"close",
"(",
")",
"except",
":",
"pass",
"self",
".",
"socket",
"=",
"None",
"except",
"DeserializationError",
"as",
"e",
":",
"#TODO: how should we handle reconnect in this case?",
"logerr",
"(",
"\"[%s] error deserializing incoming request: %s\"",
"%",
"self",
".",
"name",
",",
"str",
"(",
"e",
")",
")",
"rospyerr",
"(",
"\"[%s] error deserializing incoming request: %s\"",
"%",
"self",
".",
"name",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"except",
":",
"# in many cases this will be a normal hangup, but log internally",
"try",
":",
"#1467 sometimes we get exceptions due to",
"#interpreter shutdown, so blanket ignore those if",
"#the reporting fails",
"rospydebug",
"(",
"\"exception in receive loop for [%s], may be normal. Exception is %s\"",
",",
"self",
".",
"name",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"except",
":",
"pass",
"rospydebug",
"(",
"\"receive_loop[%s]: done condition met, exited loop\"",
"%",
"self",
".",
"name",
")",
"finally",
":",
"if",
"not",
"self",
".",
"done",
":",
"self",
".",
"close",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py#L751-L800 | ||
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/selectionDataModel.py | python | SelectionDataModel._ensureValidPrimPath | (self, path) | return sdfPath | Validate an input path. If it is a string path, convert it to an
Sdf.Path object. | Validate an input path. If it is a string path, convert it to an
Sdf.Path object. | [
"Validate",
"an",
"input",
"path",
".",
"If",
"it",
"is",
"a",
"string",
"path",
"convert",
"it",
"to",
"an",
"Sdf",
".",
"Path",
"object",
"."
] | def _ensureValidPrimPath(self, path):
"""Validate an input path. If it is a string path, convert it to an
Sdf.Path object.
"""
sdfPath = Sdf.Path(str(path))
if not sdfPath.IsAbsoluteRootOrPrimPath():
raise ValueError("Path must be a prim path, got: {}".format(
repr(sdfPath)))
return sdfPath | [
"def",
"_ensureValidPrimPath",
"(",
"self",
",",
"path",
")",
":",
"sdfPath",
"=",
"Sdf",
".",
"Path",
"(",
"str",
"(",
"path",
")",
")",
"if",
"not",
"sdfPath",
".",
"IsAbsoluteRootOrPrimPath",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Path must be a prim path, got: {}\"",
".",
"format",
"(",
"repr",
"(",
"sdfPath",
")",
")",
")",
"return",
"sdfPath"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L427-L436 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/EditorLib/RectangleEffect.py | python | RectangleEffectTool.cleanup | (self) | call superclass to clean up actor | call superclass to clean up actor | [
"call",
"superclass",
"to",
"clean",
"up",
"actor"
] | def cleanup(self):
"""
call superclass to clean up actor
"""
super(RectangleEffectTool,self).cleanup() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"super",
"(",
"RectangleEffectTool",
",",
"self",
")",
".",
"cleanup",
"(",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/RectangleEffect.py#L120-L124 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | libcxx/utils/gdb/libcxx/printers.py | python | StdDequePrinter._list_it | (self) | Primary iteration worker. | Primary iteration worker. | [
"Primary",
"iteration",
"worker",
"."
] | def _list_it(self):
"""Primary iteration worker."""
num_emitted = 0
current_addr = self.start_ptr
start_index = self.first_block_start_index
while num_emitted < self.size:
end_index = min(start_index + self.size -
num_emitted, self.block_size)
for _, elem in self._bucket_it(current_addr, start_index, end_index):
yield "", elem
num_emitted += end_index - start_index
current_addr = gdb.Value(addr_as_long(current_addr) + _pointer_size) \
.cast(self.node_type)
start_index = 0 | [
"def",
"_list_it",
"(",
"self",
")",
":",
"num_emitted",
"=",
"0",
"current_addr",
"=",
"self",
".",
"start_ptr",
"start_index",
"=",
"self",
".",
"first_block_start_index",
"while",
"num_emitted",
"<",
"self",
".",
"size",
":",
"end_index",
"=",
"min",
"(",
"start_index",
"+",
"self",
".",
"size",
"-",
"num_emitted",
",",
"self",
".",
"block_size",
")",
"for",
"_",
",",
"elem",
"in",
"self",
".",
"_bucket_it",
"(",
"current_addr",
",",
"start_index",
",",
"end_index",
")",
":",
"yield",
"\"\"",
",",
"elem",
"num_emitted",
"+=",
"end_index",
"-",
"start_index",
"current_addr",
"=",
"gdb",
".",
"Value",
"(",
"addr_as_long",
"(",
"current_addr",
")",
"+",
"_pointer_size",
")",
".",
"cast",
"(",
"self",
".",
"node_type",
")",
"start_index",
"=",
"0"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/libcxx/utils/gdb/libcxx/printers.py#L463-L476 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/estimators/linear.py | python | LinearClassifier.predict_proba | (self, x=None, input_fn=None, batch_size=None, outputs=None,
as_iterable=False) | return preds[_PROBABILITIES] | Runs inference to determine the class probability predictions. | Runs inference to determine the class probability predictions. | [
"Runs",
"inference",
"to",
"determine",
"the",
"class",
"probability",
"predictions",
"."
] | def predict_proba(self, x=None, input_fn=None, batch_size=None, outputs=None,
as_iterable=False):
"""Runs inference to determine the class probability predictions."""
preds = self._estimator.predict(x=x, input_fn=input_fn,
batch_size=batch_size,
outputs=[_PROBABILITIES],
as_iterable=as_iterable)
if as_iterable:
return _as_iterable(preds, output=_PROBABILITIES)
return preds[_PROBABILITIES] | [
"def",
"predict_proba",
"(",
"self",
",",
"x",
"=",
"None",
",",
"input_fn",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"as_iterable",
"=",
"False",
")",
":",
"preds",
"=",
"self",
".",
"_estimator",
".",
"predict",
"(",
"x",
"=",
"x",
",",
"input_fn",
"=",
"input_fn",
",",
"batch_size",
"=",
"batch_size",
",",
"outputs",
"=",
"[",
"_PROBABILITIES",
"]",
",",
"as_iterable",
"=",
"as_iterable",
")",
"if",
"as_iterable",
":",
"return",
"_as_iterable",
"(",
"preds",
",",
"output",
"=",
"_PROBABILITIES",
")",
"return",
"preds",
"[",
"_PROBABILITIES",
"]"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/estimators/linear.py#L546-L555 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py | python | _addHandlerRef | (handler) | Add a handler to the internal cleanup list using a weak reference. | Add a handler to the internal cleanup list using a weak reference. | [
"Add",
"a",
"handler",
"to",
"the",
"internal",
"cleanup",
"list",
"using",
"a",
"weak",
"reference",
"."
] | def _addHandlerRef(handler):
"""
Add a handler to the internal cleanup list using a weak reference.
"""
_acquireLock()
try:
_handlerList.append(weakref.ref(handler, _removeHandlerRef))
finally:
_releaseLock() | [
"def",
"_addHandlerRef",
"(",
"handler",
")",
":",
"_acquireLock",
"(",
")",
"try",
":",
"_handlerList",
".",
"append",
"(",
"weakref",
".",
"ref",
"(",
"handler",
",",
"_removeHandlerRef",
")",
")",
"finally",
":",
"_releaseLock",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py#L783-L791 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/dgreduce.py | python | runs_are_equal | (ws1,ws2) | return run_num1==run_num2 | Compare two run numbers, provided either as run numbers,
or as workspaces or as ws names | Compare two run numbers, provided either as run numbers,
or as workspaces or as ws names | [
"Compare",
"two",
"run",
"numbers",
"provided",
"either",
"as",
"run",
"numbers",
"or",
"as",
"workspaces",
"or",
"as",
"ws",
"names"
] | def runs_are_equal(ws1,ws2):
"""Compare two run numbers, provided either as run numbers,
or as workspaces or as ws names"""
if ws1 == ws2:
return True
#-----------------------------------------------
def get_run_num(name_or_ws):
err = None
if isinstance(name_or_ws,api.MatrixWorkspace):
run_num = name_or_ws.getRunNumber()
elif name_or_ws in mtd: # this is also throw Boost.Python.ArgumentError error if mtd not accepts it
ws = mtd[name_or_ws]
run_num = ws.getRunNumber()
else:
raise AttributeError
if err is not None:
raise AttributeError("Input parameter is neither workspace nor ws name")
return run_num
#-----------------------------------------------
try:
run_num1 = get_run_num(ws1)
except AttributeError:
return False
try:
run_num2 = get_run_num(ws2)
except AttributeError:
return False
return run_num1==run_num2 | [
"def",
"runs_are_equal",
"(",
"ws1",
",",
"ws2",
")",
":",
"if",
"ws1",
"==",
"ws2",
":",
"return",
"True",
"#-----------------------------------------------",
"def",
"get_run_num",
"(",
"name_or_ws",
")",
":",
"err",
"=",
"None",
"if",
"isinstance",
"(",
"name_or_ws",
",",
"api",
".",
"MatrixWorkspace",
")",
":",
"run_num",
"=",
"name_or_ws",
".",
"getRunNumber",
"(",
")",
"elif",
"name_or_ws",
"in",
"mtd",
":",
"# this is also throw Boost.Python.ArgumentError error if mtd not accepts it",
"ws",
"=",
"mtd",
"[",
"name_or_ws",
"]",
"run_num",
"=",
"ws",
".",
"getRunNumber",
"(",
")",
"else",
":",
"raise",
"AttributeError",
"if",
"err",
"is",
"not",
"None",
":",
"raise",
"AttributeError",
"(",
"\"Input parameter is neither workspace nor ws name\"",
")",
"return",
"run_num",
"#-----------------------------------------------",
"try",
":",
"run_num1",
"=",
"get_run_num",
"(",
"ws1",
")",
"except",
"AttributeError",
":",
"return",
"False",
"try",
":",
"run_num2",
"=",
"get_run_num",
"(",
"ws2",
")",
"except",
"AttributeError",
":",
"return",
"False",
"return",
"run_num1",
"==",
"run_num2"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/dgreduce.py#L161-L190 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/cli/command_parser.py | python | _parse_interval | (interval_str) | return Interval(start=start_item,
start_included=(interval_str[0] == "["),
end=end_item,
end_included=(interval_str[-1] == "]")) | Convert a human-readable interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[1M, 2M]", "<100k", ">100ms"). The items following the ">", "<",
">=" and "<=" signs have to start with a number (e.g., 3.0, -2, .98).
The same requirement applies to the items in the parentheses or brackets.
Returns:
Interval object where start or end can be None
if the range is specified as "<N" or ">N" respectively.
Raises:
ValueError: if the input is not valid. | Convert a human-readable interval to a tuple of start and end value. | [
"Convert",
"a",
"human",
"-",
"readable",
"interval",
"to",
"a",
"tuple",
"of",
"start",
"and",
"end",
"value",
"."
] | def _parse_interval(interval_str):
"""Convert a human-readable interval to a tuple of start and end value.
Args:
interval_str: (`str`) A human-readable str representing an interval
(e.g., "[1M, 2M]", "<100k", ">100ms"). The items following the ">", "<",
">=" and "<=" signs have to start with a number (e.g., 3.0, -2, .98).
The same requirement applies to the items in the parentheses or brackets.
Returns:
Interval object where start or end can be None
if the range is specified as "<N" or ">N" respectively.
Raises:
ValueError: if the input is not valid.
"""
interval_str = interval_str.strip()
if interval_str.startswith("<="):
if _NUMBER_PATTERN.match(interval_str[2:].strip()):
return Interval(start=None, start_included=False,
end=interval_str[2:].strip(), end_included=True)
else:
raise ValueError("Invalid value string after <= in '%s'" % interval_str)
if interval_str.startswith("<"):
if _NUMBER_PATTERN.match(interval_str[1:].strip()):
return Interval(start=None, start_included=False,
end=interval_str[1:].strip(), end_included=False)
else:
raise ValueError("Invalid value string after < in '%s'" % interval_str)
if interval_str.startswith(">="):
if _NUMBER_PATTERN.match(interval_str[2:].strip()):
return Interval(start=interval_str[2:].strip(), start_included=True,
end=None, end_included=False)
else:
raise ValueError("Invalid value string after >= in '%s'" % interval_str)
if interval_str.startswith(">"):
if _NUMBER_PATTERN.match(interval_str[1:].strip()):
return Interval(start=interval_str[1:].strip(), start_included=False,
end=None, end_included=False)
else:
raise ValueError("Invalid value string after > in '%s'" % interval_str)
if (not interval_str.startswith(("[", "("))
or not interval_str.endswith(("]", ")"))):
raise ValueError(
"Invalid interval format: %s. Valid formats are: [min, max], "
"(min, max), <max, >min" % interval_str)
interval = interval_str[1:-1].split(",")
if len(interval) != 2:
raise ValueError(
"Incorrect interval format: %s. Interval should specify two values: "
"[min, max] or (min, max)." % interval_str)
start_item = interval[0].strip()
if not _NUMBER_PATTERN.match(start_item):
raise ValueError("Invalid first item in interval: '%s'" % start_item)
end_item = interval[1].strip()
if not _NUMBER_PATTERN.match(end_item):
raise ValueError("Invalid second item in interval: '%s'" % end_item)
return Interval(start=start_item,
start_included=(interval_str[0] == "["),
end=end_item,
end_included=(interval_str[-1] == "]")) | [
"def",
"_parse_interval",
"(",
"interval_str",
")",
":",
"interval_str",
"=",
"interval_str",
".",
"strip",
"(",
")",
"if",
"interval_str",
".",
"startswith",
"(",
"\"<=\"",
")",
":",
"if",
"_NUMBER_PATTERN",
".",
"match",
"(",
"interval_str",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
")",
":",
"return",
"Interval",
"(",
"start",
"=",
"None",
",",
"start_included",
"=",
"False",
",",
"end",
"=",
"interval_str",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
",",
"end_included",
"=",
"True",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid value string after <= in '%s'\"",
"%",
"interval_str",
")",
"if",
"interval_str",
".",
"startswith",
"(",
"\"<\"",
")",
":",
"if",
"_NUMBER_PATTERN",
".",
"match",
"(",
"interval_str",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
")",
":",
"return",
"Interval",
"(",
"start",
"=",
"None",
",",
"start_included",
"=",
"False",
",",
"end",
"=",
"interval_str",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
",",
"end_included",
"=",
"False",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid value string after < in '%s'\"",
"%",
"interval_str",
")",
"if",
"interval_str",
".",
"startswith",
"(",
"\">=\"",
")",
":",
"if",
"_NUMBER_PATTERN",
".",
"match",
"(",
"interval_str",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
")",
":",
"return",
"Interval",
"(",
"start",
"=",
"interval_str",
"[",
"2",
":",
"]",
".",
"strip",
"(",
")",
",",
"start_included",
"=",
"True",
",",
"end",
"=",
"None",
",",
"end_included",
"=",
"False",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid value string after >= in '%s'\"",
"%",
"interval_str",
")",
"if",
"interval_str",
".",
"startswith",
"(",
"\">\"",
")",
":",
"if",
"_NUMBER_PATTERN",
".",
"match",
"(",
"interval_str",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
")",
":",
"return",
"Interval",
"(",
"start",
"=",
"interval_str",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
",",
"start_included",
"=",
"False",
",",
"end",
"=",
"None",
",",
"end_included",
"=",
"False",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid value string after > in '%s'\"",
"%",
"interval_str",
")",
"if",
"(",
"not",
"interval_str",
".",
"startswith",
"(",
"(",
"\"[\"",
",",
"\"(\"",
")",
")",
"or",
"not",
"interval_str",
".",
"endswith",
"(",
"(",
"\"]\"",
",",
"\")\"",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid interval format: %s. Valid formats are: [min, max], \"",
"\"(min, max), <max, >min\"",
"%",
"interval_str",
")",
"interval",
"=",
"interval_str",
"[",
"1",
":",
"-",
"1",
"]",
".",
"split",
"(",
"\",\"",
")",
"if",
"len",
"(",
"interval",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"Incorrect interval format: %s. Interval should specify two values: \"",
"\"[min, max] or (min, max).\"",
"%",
"interval_str",
")",
"start_item",
"=",
"interval",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"_NUMBER_PATTERN",
".",
"match",
"(",
"start_item",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid first item in interval: '%s'\"",
"%",
"start_item",
")",
"end_item",
"=",
"interval",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"_NUMBER_PATTERN",
".",
"match",
"(",
"end_item",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid second item in interval: '%s'\"",
"%",
"end_item",
")",
"return",
"Interval",
"(",
"start",
"=",
"start_item",
",",
"start_included",
"=",
"(",
"interval_str",
"[",
"0",
"]",
"==",
"\"[\"",
")",
",",
"end",
"=",
"end_item",
",",
"end_included",
"=",
"(",
"interval_str",
"[",
"-",
"1",
"]",
"==",
"\"]\"",
")",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/command_parser.py#L342-L405 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/NTableWidget.py | python | NTableWidget.select_row | (self, row_index, status=True) | return | Select a row
:param row_index:
:param status:
:return: | Select a row
:param row_index:
:param status:
:return: | [
"Select",
"a",
"row",
":",
"param",
"row_index",
":",
":",
"param",
"status",
":",
":",
"return",
":"
] | def select_row(self, row_index, status=True):
"""
Select a row
:param row_index:
:param status:
:return:
"""
# get column index
try:
status_col_index = self._myColumnNameList.index(self._statusColName)
except ValueError as e:
# status column name is not properly set up
return False, str(e)
# Loop over all rows. If any row's status is not same as target status, then set it
num_rows = self.rowCount()
assert isinstance(row_index, int) and 0 <= row_index < num_rows, 'Row number %s of type %s is not right.' \
'' % (str(row_index), type(row_index))
if self.get_cell_value(row_index, status_col_index) != status:
self.update_cell_value(row_index, status_col_index, status)
return | [
"def",
"select_row",
"(",
"self",
",",
"row_index",
",",
"status",
"=",
"True",
")",
":",
"# get column index",
"try",
":",
"status_col_index",
"=",
"self",
".",
"_myColumnNameList",
".",
"index",
"(",
"self",
".",
"_statusColName",
")",
"except",
"ValueError",
"as",
"e",
":",
"# status column name is not properly set up",
"return",
"False",
",",
"str",
"(",
"e",
")",
"# Loop over all rows. If any row's status is not same as target status, then set it",
"num_rows",
"=",
"self",
".",
"rowCount",
"(",
")",
"assert",
"isinstance",
"(",
"row_index",
",",
"int",
")",
"and",
"0",
"<=",
"row_index",
"<",
"num_rows",
",",
"'Row number %s of type %s is not right.'",
"''",
"%",
"(",
"str",
"(",
"row_index",
")",
",",
"type",
"(",
"row_index",
")",
")",
"if",
"self",
".",
"get_cell_value",
"(",
"row_index",
",",
"status_col_index",
")",
"!=",
"status",
":",
"self",
".",
"update_cell_value",
"(",
"row_index",
",",
"status_col_index",
",",
"status",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/NTableWidget.py#L398-L420 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py | python | SdcaModel.approximate_duality_gap | (self) | Add operations to compute the approximate duality gap.
Returns:
An Operation that computes the approximate duality gap over all
examples. | Add operations to compute the approximate duality gap. | [
"Add",
"operations",
"to",
"compute",
"the",
"approximate",
"duality",
"gap",
"."
] | def approximate_duality_gap(self):
"""Add operations to compute the approximate duality gap.
Returns:
An Operation that computes the approximate duality gap over all
examples.
"""
with name_scope('sdca/approximate_duality_gap'):
_, values_list = self._hashtable.export_sharded()
shard_sums = []
for values in values_list:
with ops.device(values.device):
# For large tables to_double() below allocates a large temporary
# tensor that is freed once the sum operation completes. To reduce
# peak memory usage in cases where we have multiple large tables on a
# single device, we serialize these operations.
# Note that we need double precision to get accurate results.
with ops.control_dependencies(shard_sums):
shard_sums.append(
math_ops.reduce_sum(math_ops.to_double(values), 0))
summed_values = math_ops.add_n(shard_sums)
primal_loss = summed_values[1]
dual_loss = summed_values[2]
example_weights = summed_values[3]
# Note: we return NaN if there are no weights or all weights are 0, e.g.
# if no examples have been processed
return (primal_loss + dual_loss + self._l1_loss() +
(2.0 * self._l2_loss(self._symmetric_l2_regularization()))
) / example_weights | [
"def",
"approximate_duality_gap",
"(",
"self",
")",
":",
"with",
"name_scope",
"(",
"'sdca/approximate_duality_gap'",
")",
":",
"_",
",",
"values_list",
"=",
"self",
".",
"_hashtable",
".",
"export_sharded",
"(",
")",
"shard_sums",
"=",
"[",
"]",
"for",
"values",
"in",
"values_list",
":",
"with",
"ops",
".",
"device",
"(",
"values",
".",
"device",
")",
":",
"# For large tables to_double() below allocates a large temporary",
"# tensor that is freed once the sum operation completes. To reduce",
"# peak memory usage in cases where we have multiple large tables on a",
"# single device, we serialize these operations.",
"# Note that we need double precision to get accurate results.",
"with",
"ops",
".",
"control_dependencies",
"(",
"shard_sums",
")",
":",
"shard_sums",
".",
"append",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"to_double",
"(",
"values",
")",
",",
"0",
")",
")",
"summed_values",
"=",
"math_ops",
".",
"add_n",
"(",
"shard_sums",
")",
"primal_loss",
"=",
"summed_values",
"[",
"1",
"]",
"dual_loss",
"=",
"summed_values",
"[",
"2",
"]",
"example_weights",
"=",
"summed_values",
"[",
"3",
"]",
"# Note: we return NaN if there are no weights or all weights are 0, e.g.",
"# if no examples have been processed",
"return",
"(",
"primal_loss",
"+",
"dual_loss",
"+",
"self",
".",
"_l1_loss",
"(",
")",
"+",
"(",
"2.0",
"*",
"self",
".",
"_l2_loss",
"(",
"self",
".",
"_symmetric_l2_regularization",
"(",
")",
")",
")",
")",
"/",
"example_weights"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py#L400-L429 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/platform.py | python | popen | (cmd, mode='r', bufsize=None) | Portable popen() interface. | Portable popen() interface. | [
"Portable",
"popen",
"()",
"interface",
"."
] | def popen(cmd, mode='r', bufsize=None):
""" Portable popen() interface.
"""
# Find a working popen implementation preferring win32pipe.popen
# over os.popen over _popen
popen = None
if os.environ.get('OS','') == 'Windows_NT':
# On NT win32pipe should work; on Win9x it hangs due to bugs
# in the MS C lib (see MS KnowledgeBase article Q150956)
try:
import win32pipe
except ImportError:
pass
else:
popen = win32pipe.popen
if popen is None:
if hasattr(os,'popen'):
popen = os.popen
# Check whether it works... it doesn't in GUI programs
# on Windows platforms
if sys.platform == 'win32': # XXX Others too ?
try:
popen('')
except os.error:
popen = _popen
else:
popen = _popen
if bufsize is None:
return popen(cmd,mode)
else:
return popen(cmd,mode,bufsize) | [
"def",
"popen",
"(",
"cmd",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"None",
")",
":",
"# Find a working popen implementation preferring win32pipe.popen",
"# over os.popen over _popen",
"popen",
"=",
"None",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'OS'",
",",
"''",
")",
"==",
"'Windows_NT'",
":",
"# On NT win32pipe should work; on Win9x it hangs due to bugs",
"# in the MS C lib (see MS KnowledgeBase article Q150956)",
"try",
":",
"import",
"win32pipe",
"except",
"ImportError",
":",
"pass",
"else",
":",
"popen",
"=",
"win32pipe",
".",
"popen",
"if",
"popen",
"is",
"None",
":",
"if",
"hasattr",
"(",
"os",
",",
"'popen'",
")",
":",
"popen",
"=",
"os",
".",
"popen",
"# Check whether it works... it doesn't in GUI programs",
"# on Windows platforms",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"# XXX Others too ?",
"try",
":",
"popen",
"(",
"''",
")",
"except",
"os",
".",
"error",
":",
"popen",
"=",
"_popen",
"else",
":",
"popen",
"=",
"_popen",
"if",
"bufsize",
"is",
"None",
":",
"return",
"popen",
"(",
"cmd",
",",
"mode",
")",
"else",
":",
"return",
"popen",
"(",
"cmd",
",",
"mode",
",",
"bufsize",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/platform.py#L421-L452 | ||
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Type.is_restrict_qualified | (self) | return conf.lib.clang_isRestrictQualifiedType(self) | Determine whether a Type has the "restrict" qualifier set.
This does not look through typedefs that may have added "restrict" at
a different level. | Determine whether a Type has the "restrict" qualifier set. | [
"Determine",
"whether",
"a",
"Type",
"has",
"the",
"restrict",
"qualifier",
"set",
"."
] | def is_restrict_qualified(self):
"""Determine whether a Type has the "restrict" qualifier set.
This does not look through typedefs that may have added "restrict" at
a different level.
"""
return conf.lib.clang_isRestrictQualifiedType(self) | [
"def",
"is_restrict_qualified",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isRestrictQualifiedType",
"(",
"self",
")"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1756-L1762 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/_stream_hixie75.py | python | StreamHixie75.receive_message | (self) | Receive a WebSocket frame and return its payload an unicode string.
Returns:
payload unicode string in a WebSocket frame.
Raises:
ConnectionTerminatedException: when read returns empty
string.
BadOperationException: when called on a client-terminated
connection. | Receive a WebSocket frame and return its payload an unicode string. | [
"Receive",
"a",
"WebSocket",
"frame",
"and",
"return",
"its",
"payload",
"an",
"unicode",
"string",
"."
] | def receive_message(self):
"""Receive a WebSocket frame and return its payload an unicode string.
Returns:
payload unicode string in a WebSocket frame.
Raises:
ConnectionTerminatedException: when read returns empty
string.
BadOperationException: when called on a client-terminated
connection.
"""
if self._request.client_terminated:
raise BadOperationException(
'Requested receive_message after receiving a closing '
'handshake')
while True:
# Read 1 byte.
# mp_conn.read will block if no bytes are available.
# Timeout is controlled by TimeOut directive of Apache.
frame_type_str = self.receive_bytes(1)
frame_type = ord(frame_type_str)
if (frame_type & 0x80) == 0x80:
# The payload length is specified in the frame.
# Read and discard.
length = self._read_payload_length_hixie75()
if length > 0:
_ = self.receive_bytes(length)
# 5.3 3. 12. if /type/ is 0xFF and /length/ is 0, then set the
# /client terminated/ flag and abort these steps.
if not self._enable_closing_handshake:
continue
if frame_type == 0xFF and length == 0:
self._request.client_terminated = True
if self._request.server_terminated:
self._logger.debug(
'Received ack for server-initiated closing '
'handshake')
return None
self._logger.debug(
'Received client-initiated closing handshake')
self._send_closing_handshake()
self._logger.debug(
'Sent ack for client-initiated closing handshake')
return None
else:
# The payload is delimited with \xff.
bytes = self._read_until('\xff')
# The WebSocket protocol section 4.4 specifies that invalid
# characters must be replaced with U+fffd REPLACEMENT
# CHARACTER.
message = bytes.decode('utf-8', 'replace')
if frame_type == 0x00:
return message | [
"def",
"receive_message",
"(",
"self",
")",
":",
"if",
"self",
".",
"_request",
".",
"client_terminated",
":",
"raise",
"BadOperationException",
"(",
"'Requested receive_message after receiving a closing '",
"'handshake'",
")",
"while",
"True",
":",
"# Read 1 byte.",
"# mp_conn.read will block if no bytes are available.",
"# Timeout is controlled by TimeOut directive of Apache.",
"frame_type_str",
"=",
"self",
".",
"receive_bytes",
"(",
"1",
")",
"frame_type",
"=",
"ord",
"(",
"frame_type_str",
")",
"if",
"(",
"frame_type",
"&",
"0x80",
")",
"==",
"0x80",
":",
"# The payload length is specified in the frame.",
"# Read and discard.",
"length",
"=",
"self",
".",
"_read_payload_length_hixie75",
"(",
")",
"if",
"length",
">",
"0",
":",
"_",
"=",
"self",
".",
"receive_bytes",
"(",
"length",
")",
"# 5.3 3. 12. if /type/ is 0xFF and /length/ is 0, then set the",
"# /client terminated/ flag and abort these steps.",
"if",
"not",
"self",
".",
"_enable_closing_handshake",
":",
"continue",
"if",
"frame_type",
"==",
"0xFF",
"and",
"length",
"==",
"0",
":",
"self",
".",
"_request",
".",
"client_terminated",
"=",
"True",
"if",
"self",
".",
"_request",
".",
"server_terminated",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Received ack for server-initiated closing '",
"'handshake'",
")",
"return",
"None",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Received client-initiated closing handshake'",
")",
"self",
".",
"_send_closing_handshake",
"(",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Sent ack for client-initiated closing handshake'",
")",
"return",
"None",
"else",
":",
"# The payload is delimited with \\xff.",
"bytes",
"=",
"self",
".",
"_read_until",
"(",
"'\\xff'",
")",
"# The WebSocket protocol section 4.4 specifies that invalid",
"# characters must be replaced with U+fffd REPLACEMENT",
"# CHARACTER.",
"message",
"=",
"bytes",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
"if",
"frame_type",
"==",
"0x00",
":",
"return",
"message"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/_stream_hixie75.py#L115-L174 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/utils/registry.py | python | Registry.__init__ | (self, name) | Creates a new registry. | Creates a new registry. | [
"Creates",
"a",
"new",
"registry",
"."
] | def __init__(self, name):
"""Creates a new registry."""
self._name = name
self._registry = {} | [
"def",
"__init__",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_registry",
"=",
"{",
"}"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/utils/registry.py#L31-L34 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/model.py | python | ResourceModel.get_attributes | (self, shape) | return attributes | Get a dictionary of attribute names to original name and shape
models that represent the attributes of this resource. Looks
like the following:
{
'some_name': ('SomeName', <Shape...>)
}
:type shape: botocore.model.Shape
:param shape: The underlying shape for this resource.
:rtype: dict
:return: Mapping of resource attributes. | Get a dictionary of attribute names to original name and shape
models that represent the attributes of this resource. Looks
like the following: | [
"Get",
"a",
"dictionary",
"of",
"attribute",
"names",
"to",
"original",
"name",
"and",
"shape",
"models",
"that",
"represent",
"the",
"attributes",
"of",
"this",
"resource",
".",
"Looks",
"like",
"the",
"following",
":"
] | def get_attributes(self, shape):
"""
Get a dictionary of attribute names to original name and shape
models that represent the attributes of this resource. Looks
like the following:
{
'some_name': ('SomeName', <Shape...>)
}
:type shape: botocore.model.Shape
:param shape: The underlying shape for this resource.
:rtype: dict
:return: Mapping of resource attributes.
"""
attributes = {}
identifier_names = [i.name for i in self.identifiers]
for name, member in shape.members.items():
snake_cased = xform_name(name)
if snake_cased in identifier_names:
# Skip identifiers, these are set through other means
continue
snake_cased = self._get_name('attribute', snake_cased,
snake_case=False)
attributes[snake_cased] = (name, member)
return attributes | [
"def",
"get_attributes",
"(",
"self",
",",
"shape",
")",
":",
"attributes",
"=",
"{",
"}",
"identifier_names",
"=",
"[",
"i",
".",
"name",
"for",
"i",
"in",
"self",
".",
"identifiers",
"]",
"for",
"name",
",",
"member",
"in",
"shape",
".",
"members",
".",
"items",
"(",
")",
":",
"snake_cased",
"=",
"xform_name",
"(",
"name",
")",
"if",
"snake_cased",
"in",
"identifier_names",
":",
"# Skip identifiers, these are set through other means",
"continue",
"snake_cased",
"=",
"self",
".",
"_get_name",
"(",
"'attribute'",
",",
"snake_cased",
",",
"snake_case",
"=",
"False",
")",
"attributes",
"[",
"snake_cased",
"]",
"=",
"(",
"name",
",",
"member",
")",
"return",
"attributes"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/model.py#L391-L418 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/memory_inspector/memory_inspector/core/backends.py | python | Device.ListProcesses | (self) | Returns a sequence of |Process|. | Returns a sequence of |Process|. | [
"Returns",
"a",
"sequence",
"of",
"|Process|",
"."
] | def ListProcesses(self):
"""Returns a sequence of |Process|."""
raise NotImplementedError() | [
"def",
"ListProcesses",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/core/backends.py#L96-L98 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/sigparse.py | python | parse_signature | (sig) | return inputs, outputs | Parse generalized ufunc signature.
NOTE: ',' (COMMA) is a delimiter; not separator.
This means trailing comma is legal. | Parse generalized ufunc signature. | [
"Parse",
"generalized",
"ufunc",
"signature",
"."
] | def parse_signature(sig):
'''Parse generalized ufunc signature.
NOTE: ',' (COMMA) is a delimiter; not separator.
This means trailing comma is legal.
'''
def stripws(s):
return ''.join(c for c in s if c not in string.whitespace)
def tokenizer(src):
def readline():
yield src
gen = readline()
return tokenize.generate_tokens(lambda: next(gen))
def parse(src):
tokgen = tokenizer(src)
while True:
tok = next(tokgen)
if tok[1] == '(':
symbols = []
while True:
tok = next(tokgen)
if tok[1] == ')':
break
elif tok[0] == tokenize.NAME:
symbols.append(tok[1])
elif tok[1] == ',':
continue
else:
raise ValueError('bad token in signature "%s"' % tok[1])
yield tuple(symbols)
tok = next(tokgen)
if tok[1] == ',':
continue
elif tokenize.ISEOF(tok[0]):
break
elif tokenize.ISEOF(tok[0]):
break
else:
raise ValueError('bad token in signature "%s"' % tok[1])
ins, _, outs = stripws(sig).partition('->')
inputs = list(parse(ins))
outputs = list(parse(outs))
# check that all output symbols are defined in the inputs
isym = set()
osym = set()
for grp in inputs:
isym |= set(grp)
for grp in outputs:
osym |= set(grp)
diff = osym.difference(isym)
if diff:
raise NameError('undefined output symbols: %s' % ','.join(sorted(diff)))
return inputs, outputs | [
"def",
"parse_signature",
"(",
"sig",
")",
":",
"def",
"stripws",
"(",
"s",
")",
":",
"return",
"''",
".",
"join",
"(",
"c",
"for",
"c",
"in",
"s",
"if",
"c",
"not",
"in",
"string",
".",
"whitespace",
")",
"def",
"tokenizer",
"(",
"src",
")",
":",
"def",
"readline",
"(",
")",
":",
"yield",
"src",
"gen",
"=",
"readline",
"(",
")",
"return",
"tokenize",
".",
"generate_tokens",
"(",
"lambda",
":",
"next",
"(",
"gen",
")",
")",
"def",
"parse",
"(",
"src",
")",
":",
"tokgen",
"=",
"tokenizer",
"(",
"src",
")",
"while",
"True",
":",
"tok",
"=",
"next",
"(",
"tokgen",
")",
"if",
"tok",
"[",
"1",
"]",
"==",
"'('",
":",
"symbols",
"=",
"[",
"]",
"while",
"True",
":",
"tok",
"=",
"next",
"(",
"tokgen",
")",
"if",
"tok",
"[",
"1",
"]",
"==",
"')'",
":",
"break",
"elif",
"tok",
"[",
"0",
"]",
"==",
"tokenize",
".",
"NAME",
":",
"symbols",
".",
"append",
"(",
"tok",
"[",
"1",
"]",
")",
"elif",
"tok",
"[",
"1",
"]",
"==",
"','",
":",
"continue",
"else",
":",
"raise",
"ValueError",
"(",
"'bad token in signature \"%s\"'",
"%",
"tok",
"[",
"1",
"]",
")",
"yield",
"tuple",
"(",
"symbols",
")",
"tok",
"=",
"next",
"(",
"tokgen",
")",
"if",
"tok",
"[",
"1",
"]",
"==",
"','",
":",
"continue",
"elif",
"tokenize",
".",
"ISEOF",
"(",
"tok",
"[",
"0",
"]",
")",
":",
"break",
"elif",
"tokenize",
".",
"ISEOF",
"(",
"tok",
"[",
"0",
"]",
")",
":",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"'bad token in signature \"%s\"'",
"%",
"tok",
"[",
"1",
"]",
")",
"ins",
",",
"_",
",",
"outs",
"=",
"stripws",
"(",
"sig",
")",
".",
"partition",
"(",
"'->'",
")",
"inputs",
"=",
"list",
"(",
"parse",
"(",
"ins",
")",
")",
"outputs",
"=",
"list",
"(",
"parse",
"(",
"outs",
")",
")",
"# check that all output symbols are defined in the inputs",
"isym",
"=",
"set",
"(",
")",
"osym",
"=",
"set",
"(",
")",
"for",
"grp",
"in",
"inputs",
":",
"isym",
"|=",
"set",
"(",
"grp",
")",
"for",
"grp",
"in",
"outputs",
":",
"osym",
"|=",
"set",
"(",
"grp",
")",
"diff",
"=",
"osym",
".",
"difference",
"(",
"isym",
")",
"if",
"diff",
":",
"raise",
"NameError",
"(",
"'undefined output symbols: %s'",
"%",
"','",
".",
"join",
"(",
"sorted",
"(",
"diff",
")",
")",
")",
"return",
"inputs",
",",
"outputs"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/sigparse.py#L7-L65 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/spectral.py | python | csd | (x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,
detrend='constant', return_onesided=True, scaling='density',
axis=-1, average='mean') | return freqs, Pxy | r"""
Estimate the cross power spectral density, Pxy, using Welch's
method.
Parameters
----------
x : array_like
Time series of measurement values
y : array_like
Time series of measurement values
fs : float, optional
Sampling frequency of the `x` and `y` time series. Defaults
to 1.0.
window : str or tuple or array_like, optional
Desired window to use. If `window` is a string or tuple, it is
passed to `get_window` to generate the window values, which are
DFT-even by default. See `get_window` for a list of windows and
required parameters. If `window` is array_like it will be used
directly as the window and its length must be nperseg. Defaults
to a Hann window.
nperseg : int, optional
Length of each segment. Defaults to None, but if window is str or
tuple, is set to 256, and if window is array_like, is set to the
length of the window.
noverlap: int, optional
Number of points to overlap between segments. If `None`,
``noverlap = nperseg // 2``. Defaults to `None`.
nfft : int, optional
Length of the FFT used, if a zero padded FFT is desired. If
`None`, the FFT length is `nperseg`. Defaults to `None`.
detrend : str or function or `False`, optional
Specifies how to detrend each segment. If `detrend` is a
string, it is passed as the `type` argument to the `detrend`
function. If it is a function, it takes a segment and returns a
detrended segment. If `detrend` is `False`, no detrending is
done. Defaults to 'constant'.
return_onesided : bool, optional
If `True`, return a one-sided spectrum for real data. If
`False` return a two-sided spectrum. Note that for complex
data, a two-sided spectrum is always returned.
scaling : { 'density', 'spectrum' }, optional
Selects between computing the cross spectral density ('density')
where `Pxy` has units of V**2/Hz and computing the cross spectrum
('spectrum') where `Pxy` has units of V**2, if `x` and `y` are
measured in V and `fs` is measured in Hz. Defaults to 'density'
axis : int, optional
Axis along which the CSD is computed for both inputs; the
default is over the last axis (i.e. ``axis=-1``).
average : { 'mean', 'median' }, optional
Method to use when averaging periodograms. Defaults to 'mean'.
.. versionadded:: 1.2.0
Returns
-------
f : ndarray
Array of sample frequencies.
Pxy : ndarray
Cross spectral density or cross power spectrum of x,y.
See Also
--------
periodogram: Simple, optionally modified periodogram
lombscargle: Lomb-Scargle periodogram for unevenly sampled data
welch: Power spectral density by Welch's method. [Equivalent to
csd(x,x)]
coherence: Magnitude squared coherence by Welch's method.
Notes
--------
By convention, Pxy is computed with the conjugate FFT of X
multiplied by the FFT of Y.
If the input series differ in length, the shorter series will be
zero-padded to match.
An appropriate amount of overlap will depend on the choice of window
and on your requirements. For the default Hann window an overlap of
50% is a reasonable trade off between accurately estimating the
signal power, while not over counting any of the data. Narrower
windows may require a larger overlap.
.. versionadded:: 0.16.0
References
----------
.. [1] P. Welch, "The use of the fast Fourier transform for the
estimation of power spectra: A method based on time averaging
over short, modified periodograms", IEEE Trans. Audio
Electroacoust. vol. 15, pp. 70-73, 1967.
.. [2] Rabiner, Lawrence R., and B. Gold. "Theory and Application of
Digital Signal Processing" Prentice-Hall, pp. 414-419, 1975
Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
Generate two test signals with some common features.
>>> fs = 10e3
>>> N = 1e5
>>> amp = 20
>>> freq = 1234.0
>>> noise_power = 0.001 * fs / 2
>>> time = np.arange(N) / fs
>>> b, a = signal.butter(2, 0.25, 'low')
>>> x = np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
>>> y = signal.lfilter(b, a, x)
>>> x += amp*np.sin(2*np.pi*freq*time)
>>> y += np.random.normal(scale=0.1*np.sqrt(noise_power), size=time.shape)
Compute and plot the magnitude of the cross spectral density.
>>> f, Pxy = signal.csd(x, y, fs, nperseg=1024)
>>> plt.semilogy(f, np.abs(Pxy))
>>> plt.xlabel('frequency [Hz]')
>>> plt.ylabel('CSD [V**2/Hz]')
>>> plt.show() | r"""
Estimate the cross power spectral density, Pxy, using Welch's
method. | [
"r",
"Estimate",
"the",
"cross",
"power",
"spectral",
"density",
"Pxy",
"using",
"Welch",
"s",
"method",
"."
] | def csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,
detrend='constant', return_onesided=True, scaling='density',
axis=-1, average='mean'):
r"""
Estimate the cross power spectral density, Pxy, using Welch's
method.
Parameters
----------
x : array_like
Time series of measurement values
y : array_like
Time series of measurement values
fs : float, optional
Sampling frequency of the `x` and `y` time series. Defaults
to 1.0.
window : str or tuple or array_like, optional
Desired window to use. If `window` is a string or tuple, it is
passed to `get_window` to generate the window values, which are
DFT-even by default. See `get_window` for a list of windows and
required parameters. If `window` is array_like it will be used
directly as the window and its length must be nperseg. Defaults
to a Hann window.
nperseg : int, optional
Length of each segment. Defaults to None, but if window is str or
tuple, is set to 256, and if window is array_like, is set to the
length of the window.
noverlap: int, optional
Number of points to overlap between segments. If `None`,
``noverlap = nperseg // 2``. Defaults to `None`.
nfft : int, optional
Length of the FFT used, if a zero padded FFT is desired. If
`None`, the FFT length is `nperseg`. Defaults to `None`.
detrend : str or function or `False`, optional
Specifies how to detrend each segment. If `detrend` is a
string, it is passed as the `type` argument to the `detrend`
function. If it is a function, it takes a segment and returns a
detrended segment. If `detrend` is `False`, no detrending is
done. Defaults to 'constant'.
return_onesided : bool, optional
If `True`, return a one-sided spectrum for real data. If
`False` return a two-sided spectrum. Note that for complex
data, a two-sided spectrum is always returned.
scaling : { 'density', 'spectrum' }, optional
Selects between computing the cross spectral density ('density')
where `Pxy` has units of V**2/Hz and computing the cross spectrum
('spectrum') where `Pxy` has units of V**2, if `x` and `y` are
measured in V and `fs` is measured in Hz. Defaults to 'density'
axis : int, optional
Axis along which the CSD is computed for both inputs; the
default is over the last axis (i.e. ``axis=-1``).
average : { 'mean', 'median' }, optional
Method to use when averaging periodograms. Defaults to 'mean'.
.. versionadded:: 1.2.0
Returns
-------
f : ndarray
Array of sample frequencies.
Pxy : ndarray
Cross spectral density or cross power spectrum of x,y.
See Also
--------
periodogram: Simple, optionally modified periodogram
lombscargle: Lomb-Scargle periodogram for unevenly sampled data
welch: Power spectral density by Welch's method. [Equivalent to
csd(x,x)]
coherence: Magnitude squared coherence by Welch's method.
Notes
--------
By convention, Pxy is computed with the conjugate FFT of X
multiplied by the FFT of Y.
If the input series differ in length, the shorter series will be
zero-padded to match.
An appropriate amount of overlap will depend on the choice of window
and on your requirements. For the default Hann window an overlap of
50% is a reasonable trade off between accurately estimating the
signal power, while not over counting any of the data. Narrower
windows may require a larger overlap.
.. versionadded:: 0.16.0
References
----------
.. [1] P. Welch, "The use of the fast Fourier transform for the
estimation of power spectra: A method based on time averaging
over short, modified periodograms", IEEE Trans. Audio
Electroacoust. vol. 15, pp. 70-73, 1967.
.. [2] Rabiner, Lawrence R., and B. Gold. "Theory and Application of
Digital Signal Processing" Prentice-Hall, pp. 414-419, 1975
Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
Generate two test signals with some common features.
>>> fs = 10e3
>>> N = 1e5
>>> amp = 20
>>> freq = 1234.0
>>> noise_power = 0.001 * fs / 2
>>> time = np.arange(N) / fs
>>> b, a = signal.butter(2, 0.25, 'low')
>>> x = np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
>>> y = signal.lfilter(b, a, x)
>>> x += amp*np.sin(2*np.pi*freq*time)
>>> y += np.random.normal(scale=0.1*np.sqrt(noise_power), size=time.shape)
Compute and plot the magnitude of the cross spectral density.
>>> f, Pxy = signal.csd(x, y, fs, nperseg=1024)
>>> plt.semilogy(f, np.abs(Pxy))
>>> plt.xlabel('frequency [Hz]')
>>> plt.ylabel('CSD [V**2/Hz]')
>>> plt.show()
"""
freqs, _, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, nfft,
detrend, return_onesided, scaling, axis,
mode='psd')
# Average over windows.
if len(Pxy.shape) >= 2 and Pxy.size > 0:
if Pxy.shape[-1] > 1:
if average == 'median':
Pxy = np.median(Pxy, axis=-1) / _median_bias(Pxy.shape[-1])
elif average == 'mean':
Pxy = Pxy.mean(axis=-1)
else:
raise ValueError('average must be "median" or "mean", got %s'
% (average,))
else:
Pxy = np.reshape(Pxy, Pxy.shape[:-1])
return freqs, Pxy | [
"def",
"csd",
"(",
"x",
",",
"y",
",",
"fs",
"=",
"1.0",
",",
"window",
"=",
"'hann'",
",",
"nperseg",
"=",
"None",
",",
"noverlap",
"=",
"None",
",",
"nfft",
"=",
"None",
",",
"detrend",
"=",
"'constant'",
",",
"return_onesided",
"=",
"True",
",",
"scaling",
"=",
"'density'",
",",
"axis",
"=",
"-",
"1",
",",
"average",
"=",
"'mean'",
")",
":",
"freqs",
",",
"_",
",",
"Pxy",
"=",
"_spectral_helper",
"(",
"x",
",",
"y",
",",
"fs",
",",
"window",
",",
"nperseg",
",",
"noverlap",
",",
"nfft",
",",
"detrend",
",",
"return_onesided",
",",
"scaling",
",",
"axis",
",",
"mode",
"=",
"'psd'",
")",
"# Average over windows.",
"if",
"len",
"(",
"Pxy",
".",
"shape",
")",
">=",
"2",
"and",
"Pxy",
".",
"size",
">",
"0",
":",
"if",
"Pxy",
".",
"shape",
"[",
"-",
"1",
"]",
">",
"1",
":",
"if",
"average",
"==",
"'median'",
":",
"Pxy",
"=",
"np",
".",
"median",
"(",
"Pxy",
",",
"axis",
"=",
"-",
"1",
")",
"/",
"_median_bias",
"(",
"Pxy",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"elif",
"average",
"==",
"'mean'",
":",
"Pxy",
"=",
"Pxy",
".",
"mean",
"(",
"axis",
"=",
"-",
"1",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'average must be \"median\" or \"mean\", got %s'",
"%",
"(",
"average",
",",
")",
")",
"else",
":",
"Pxy",
"=",
"np",
".",
"reshape",
"(",
"Pxy",
",",
"Pxy",
".",
"shape",
"[",
":",
"-",
"1",
"]",
")",
"return",
"freqs",
",",
"Pxy"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/spectral.py#L460-L601 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_cocoa/gizmos.py | python | TreeListCtrl.SetStateImageList | (*args, **kwargs) | return _gizmos.TreeListCtrl_SetStateImageList(*args, **kwargs) | SetStateImageList(self, ImageList imageList) | SetStateImageList(self, ImageList imageList) | [
"SetStateImageList",
"(",
"self",
"ImageList",
"imageList",
")"
] | def SetStateImageList(*args, **kwargs):
"""SetStateImageList(self, ImageList imageList)"""
return _gizmos.TreeListCtrl_SetStateImageList(*args, **kwargs) | [
"def",
"SetStateImageList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_SetStateImageList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L535-L537 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewCtrl.GetIndent | (*args, **kwargs) | return _dataview.DataViewCtrl_GetIndent(*args, **kwargs) | GetIndent(self) -> int | GetIndent(self) -> int | [
"GetIndent",
"(",
"self",
")",
"-",
">",
"int"
] | def GetIndent(*args, **kwargs):
"""GetIndent(self) -> int"""
return _dataview.DataViewCtrl_GetIndent(*args, **kwargs) | [
"def",
"GetIndent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewCtrl_GetIndent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1740-L1742 | |
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | bin/single_node_perf_run.py | python | run_workload | (base_dir, workloads, options) | Runs workload with the given options.
Returns the git hash of the current revision to identify the output file. | Runs workload with the given options. | [
"Runs",
"workload",
"with",
"the",
"given",
"options",
"."
] | def run_workload(base_dir, workloads, options):
"""Runs workload with the given options.
Returns the git hash of the current revision to identify the output file.
"""
git_hash = get_git_hash_for_name("HEAD")
run_workload = ["{0}/bin/run-workload.py".format(IMPALA_HOME)]
impalads = ",".join(["localhost:{0}".format(21000 + i)
for i in range(0, int(options.num_impalads))])
run_workload += ["--workloads={0}".format(workloads),
"--impalads={0}".format(impalads),
"--results_json_file={0}/{1}.json".format(base_dir, git_hash),
"--query_iterations={0}".format(options.iterations),
"--table_formats={0}".format(options.table_formats),
"--plan_first"]
if options.query_names:
run_workload += ["--query_names={0}".format(options.query_names)]
configured_call(run_workload) | [
"def",
"run_workload",
"(",
"base_dir",
",",
"workloads",
",",
"options",
")",
":",
"git_hash",
"=",
"get_git_hash_for_name",
"(",
"\"HEAD\"",
")",
"run_workload",
"=",
"[",
"\"{0}/bin/run-workload.py\"",
".",
"format",
"(",
"IMPALA_HOME",
")",
"]",
"impalads",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"localhost:{0}\"",
".",
"format",
"(",
"21000",
"+",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"int",
"(",
"options",
".",
"num_impalads",
")",
")",
"]",
")",
"run_workload",
"+=",
"[",
"\"--workloads={0}\"",
".",
"format",
"(",
"workloads",
")",
",",
"\"--impalads={0}\"",
".",
"format",
"(",
"impalads",
")",
",",
"\"--results_json_file={0}/{1}.json\"",
".",
"format",
"(",
"base_dir",
",",
"git_hash",
")",
",",
"\"--query_iterations={0}\"",
".",
"format",
"(",
"options",
".",
"iterations",
")",
",",
"\"--table_formats={0}\"",
".",
"format",
"(",
"options",
".",
"table_formats",
")",
",",
"\"--plan_first\"",
"]",
"if",
"options",
".",
"query_names",
":",
"run_workload",
"+=",
"[",
"\"--query_names={0}\"",
".",
"format",
"(",
"options",
".",
"query_names",
")",
"]",
"configured_call",
"(",
"run_workload",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/single_node_perf_run.py#L132-L154 | ||
bundy-dns/bundy | 3d41934996b82b0cd2fe22dd74d2abc1daba835d | src/lib/python/bundy/config/ccsession.py | python | ModuleCCSession.send_stopping | (self) | Sends a 'stopping' message to the configuration manager. This
message is just an FYI, and no response is expected. Any errors
when sending this message (for instance if the msgq session has
previously been closed) are logged, but ignored. | Sends a 'stopping' message to the configuration manager. This
message is just an FYI, and no response is expected. Any errors
when sending this message (for instance if the msgq session has
previously been closed) are logged, but ignored. | [
"Sends",
"a",
"stopping",
"message",
"to",
"the",
"configuration",
"manager",
".",
"This",
"message",
"is",
"just",
"an",
"FYI",
"and",
"no",
"response",
"is",
"expected",
".",
"Any",
"errors",
"when",
"sending",
"this",
"message",
"(",
"for",
"instance",
"if",
"the",
"msgq",
"session",
"has",
"previously",
"been",
"closed",
")",
"are",
"logged",
"but",
"ignored",
"."
] | def send_stopping(self):
"""Sends a 'stopping' message to the configuration manager. This
message is just an FYI, and no response is expected. Any errors
when sending this message (for instance if the msgq session has
previously been closed) are logged, but ignored."""
# create_command could raise an exception as well, but except for
# out of memory related errors, these should all be programming
# failures and are not caught
msg = create_command(COMMAND_MODULE_STOPPING,
self.get_module_spec().get_full_spec())
try:
self._session.group_sendmsg(msg, "ConfigManager")
except Exception as se:
# If the session was previously closed, obvously trying to send
# a message fails. (TODO: check if session is open so we can
# error on real problems?)
logger.error(CONFIG_SESSION_STOPPING_FAILED, se) | [
"def",
"send_stopping",
"(",
"self",
")",
":",
"# create_command could raise an exception as well, but except for",
"# out of memory related errors, these should all be programming",
"# failures and are not caught",
"msg",
"=",
"create_command",
"(",
"COMMAND_MODULE_STOPPING",
",",
"self",
".",
"get_module_spec",
"(",
")",
".",
"get_full_spec",
"(",
")",
")",
"try",
":",
"self",
".",
"_session",
".",
"group_sendmsg",
"(",
"msg",
",",
"\"ConfigManager\"",
")",
"except",
"Exception",
"as",
"se",
":",
"# If the session was previously closed, obvously trying to send",
"# a message fails. (TODO: check if session is open so we can",
"# error on real problems?)",
"logger",
".",
"error",
"(",
"CONFIG_SESSION_STOPPING_FAILED",
",",
"se",
")"
] | https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/config/ccsession.py#L246-L262 | ||
unicode-org/icu | 2f8749a026f3ddc8cf54d4622480b7c543bb7fc0 | icu4c/source/python/icutools/databuilder/filtration.py | python | apply_filters | (requests, config, io) | return requests | Runs the filters and returns a new list of requests. | Runs the filters and returns a new list of requests. | [
"Runs",
"the",
"filters",
"and",
"returns",
"a",
"new",
"list",
"of",
"requests",
"."
] | def apply_filters(requests, config, io):
"""Runs the filters and returns a new list of requests."""
requests = _apply_file_filters(requests, config, io)
requests = _apply_resource_filters(requests, config, io)
return requests | [
"def",
"apply_filters",
"(",
"requests",
",",
"config",
",",
"io",
")",
":",
"requests",
"=",
"_apply_file_filters",
"(",
"requests",
",",
"config",
",",
"io",
")",
"requests",
"=",
"_apply_resource_filters",
"(",
"requests",
",",
"config",
",",
"io",
")",
"return",
"requests"
] | https://github.com/unicode-org/icu/blob/2f8749a026f3ddc8cf54d4622480b7c543bb7fc0/icu4c/source/python/icutools/databuilder/filtration.py#L244-L248 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/load_v1_in_v2.py | python | load | (export_dir, tags) | return result | Load a v1-style SavedModel as an object. | Load a v1-style SavedModel as an object. | [
"Load",
"a",
"v1",
"-",
"style",
"SavedModel",
"as",
"an",
"object",
"."
] | def load(export_dir, tags):
"""Load a v1-style SavedModel as an object."""
metrics.IncrementReadApi(_LOAD_V1_V2_LABEL)
loader = _EagerSavedModelLoader(export_dir)
result = loader.load(tags=tags)
metrics.IncrementRead(write_version="1")
return result | [
"def",
"load",
"(",
"export_dir",
",",
"tags",
")",
":",
"metrics",
".",
"IncrementReadApi",
"(",
"_LOAD_V1_V2_LABEL",
")",
"loader",
"=",
"_EagerSavedModelLoader",
"(",
"export_dir",
")",
"result",
"=",
"loader",
".",
"load",
"(",
"tags",
"=",
"tags",
")",
"metrics",
".",
"IncrementRead",
"(",
"write_version",
"=",
"\"1\"",
")",
"return",
"result"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/load_v1_in_v2.py#L278-L284 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/_shard/sharded_tensor/api.py | python | ShardedTensor.is_pinned | (self) | return self._metadata.tensor_properties.pin_memory | Returns True if the sharded tensor (each local shard) resides in pinned memory. | Returns True if the sharded tensor (each local shard) resides in pinned memory. | [
"Returns",
"True",
"if",
"the",
"sharded",
"tensor",
"(",
"each",
"local",
"shard",
")",
"resides",
"in",
"pinned",
"memory",
"."
] | def is_pinned(self) -> bool:
"""
Returns True if the sharded tensor (each local shard) resides in pinned memory.
"""
return self._metadata.tensor_properties.pin_memory | [
"def",
"is_pinned",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_metadata",
".",
"tensor_properties",
".",
"pin_memory"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/_shard/sharded_tensor/api.py#L703-L707 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py | python | stratified_sample | (tensors, labels, target_probs, batch_size,
init_probs=None, enqueue_many=False, queue_capacity=16,
threads_per_queue=1, name=None) | Stochastically creates batches based on per-class probabilities.
This method discards examples. Internally, it creates one queue to amortize
the cost of disk reads, and one queue to hold the properly-proportioned
batch. See `stratified_sample_unknown_dist` for a function that performs
stratified sampling with one queue per class and doesn't require knowing the
class data-distribution ahead of time.
Args:
tensors: List of tensors for data. All tensors are either one item or a
batch, according to enqueue_many.
labels: Tensor for label of data. Label is a single integer or a batch,
depending on enqueue_many. It is not a one-hot vector.
target_probs: Target class proportions in batch. An object whose type has a
registered Tensor conversion function.
batch_size: Size of batch to be returned.
init_probs: Class proportions in the data. An object whose type has a
registered Tensor conversion function, or `None` for estimating the
initial distribution.
enqueue_many: Bool. If true, interpret input tensors as having a batch
dimension.
queue_capacity: Capacity of the large queue that holds input examples.
threads_per_queue: Number of threads for the large queue that holds input
examples and for the final queue with the proper class proportions.
name: Optional prefix for ops created by this function.
Raises:
ValueError: enqueue_many is True and labels doesn't have a batch
dimension, or if enqueue_many is False and labels isn't a scalar.
ValueError: enqueue_many is True, and batch dimension on data and labels
don't match.
ValueError: if probs don't sum to one.
ValueError: if a zero initial probability class has a nonzero target
probability.
TFAssertion: if labels aren't integers in [0, num classes).
Returns:
(data_batch, label_batch), where data_batch is a list of tensors of the same
length as `tensors`
Example:
# Get tensor for a single data and label example.
data, label = data_provider.Get(['data', 'label'])
# Get stratified batch according to per-class probabilities.
target_probs = [...distribution you want...]
[data_batch], labels = tf.contrib.framework.sampling_ops.stratified_sample(
[data], label, target_probs)
# Run batch through network.
... | Stochastically creates batches based on per-class probabilities. | [
"Stochastically",
"creates",
"batches",
"based",
"on",
"per",
"-",
"class",
"probabilities",
"."
] | def stratified_sample(tensors, labels, target_probs, batch_size,
init_probs=None, enqueue_many=False, queue_capacity=16,
threads_per_queue=1, name=None):
"""Stochastically creates batches based on per-class probabilities.
This method discards examples. Internally, it creates one queue to amortize
the cost of disk reads, and one queue to hold the properly-proportioned
batch. See `stratified_sample_unknown_dist` for a function that performs
stratified sampling with one queue per class and doesn't require knowing the
class data-distribution ahead of time.
Args:
tensors: List of tensors for data. All tensors are either one item or a
batch, according to enqueue_many.
labels: Tensor for label of data. Label is a single integer or a batch,
depending on enqueue_many. It is not a one-hot vector.
target_probs: Target class proportions in batch. An object whose type has a
registered Tensor conversion function.
batch_size: Size of batch to be returned.
init_probs: Class proportions in the data. An object whose type has a
registered Tensor conversion function, or `None` for estimating the
initial distribution.
enqueue_many: Bool. If true, interpret input tensors as having a batch
dimension.
queue_capacity: Capacity of the large queue that holds input examples.
threads_per_queue: Number of threads for the large queue that holds input
examples and for the final queue with the proper class proportions.
name: Optional prefix for ops created by this function.
Raises:
ValueError: enqueue_many is True and labels doesn't have a batch
dimension, or if enqueue_many is False and labels isn't a scalar.
ValueError: enqueue_many is True, and batch dimension on data and labels
don't match.
ValueError: if probs don't sum to one.
ValueError: if a zero initial probability class has a nonzero target
probability.
TFAssertion: if labels aren't integers in [0, num classes).
Returns:
(data_batch, label_batch), where data_batch is a list of tensors of the same
length as `tensors`
Example:
# Get tensor for a single data and label example.
data, label = data_provider.Get(['data', 'label'])
# Get stratified batch according to per-class probabilities.
target_probs = [...distribution you want...]
[data_batch], labels = tf.contrib.framework.sampling_ops.stratified_sample(
[data], label, target_probs)
# Run batch through network.
...
"""
with ops.op_scope(tensors + [labels], name, 'stratified_sample'):
tensor_list = ops.convert_n_to_tensor_or_indexed_slices(tensors)
labels = ops.convert_to_tensor(labels)
target_probs = ops.convert_to_tensor(target_probs, dtype=dtypes.float32)
# Reduce the case of a single example to that of a batch of size 1.
if not enqueue_many:
tensor_list = [array_ops.expand_dims(tensor, 0) for tensor in tensor_list]
labels = array_ops.expand_dims(labels, 0)
# If `init_probs` is `None`, set up online estimation of data distribution.
if init_probs is None:
# We use `target_probs` to get the number of classes, so its shape must be
# fully defined at graph construction time.
target_probs.get_shape().assert_is_fully_defined()
init_probs = _estimate_data_distribution(
labels, target_probs.get_shape().num_elements())
else:
init_probs = ops.convert_to_tensor(init_probs, dtype=dtypes.float32)
# Validate that input is consistent.
tensor_list, labels, [init_probs, target_probs] = _verify_input(
tensor_list, labels, [init_probs, target_probs])
# Check that all zero initial probabilities also have zero target
# probabilities.
assert_op = logging_ops.Assert(
math_ops.reduce_all(math_ops.logical_or(
math_ops.not_equal(init_probs, 0),
math_ops.equal(target_probs, 0))),
['All classes with zero initial probability must also have zero target '
'probability: ', init_probs, target_probs])
init_probs = control_flow_ops.with_dependencies([assert_op], init_probs)
# Calculate acceptance sampling probabilities.
accept_probs = _calculate_acceptance_probabilities(init_probs, target_probs)
proportion_rejected = math_ops.reduce_sum((1 - accept_probs) * init_probs)
accept_probs = control_flow_ops.cond(
math_ops.less(proportion_rejected, .5),
lambda: accept_probs,
lambda: logging_ops.Print( # pylint: disable=g-long-lambda
accept_probs, [accept_probs],
message='Proportion of examples rejected by sampler is high.',
first_n=10))
# Make a single queue to hold input examples. Reshape output so examples
# don't have singleton batch dimension.
batched = input_ops.batch(tensor_list + [labels],
batch_size=1,
num_threads=threads_per_queue,
capacity=queue_capacity,
enqueue_many=True)
val_list = [array_ops.squeeze(x, [0]) for x in batched[:-1]]
label = array_ops.squeeze(batched[-1], [0])
# Set up second queue containing batches that have the desired class
# proportions.
batched = _get_stratified_batch_from_tensors(
val_list, label, accept_probs, batch_size, threads_per_queue)
return batched[:-1], batched[-1] | [
"def",
"stratified_sample",
"(",
"tensors",
",",
"labels",
",",
"target_probs",
",",
"batch_size",
",",
"init_probs",
"=",
"None",
",",
"enqueue_many",
"=",
"False",
",",
"queue_capacity",
"=",
"16",
",",
"threads_per_queue",
"=",
"1",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"tensors",
"+",
"[",
"labels",
"]",
",",
"name",
",",
"'stratified_sample'",
")",
":",
"tensor_list",
"=",
"ops",
".",
"convert_n_to_tensor_or_indexed_slices",
"(",
"tensors",
")",
"labels",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"labels",
")",
"target_probs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"target_probs",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
"# Reduce the case of a single example to that of a batch of size 1.",
"if",
"not",
"enqueue_many",
":",
"tensor_list",
"=",
"[",
"array_ops",
".",
"expand_dims",
"(",
"tensor",
",",
"0",
")",
"for",
"tensor",
"in",
"tensor_list",
"]",
"labels",
"=",
"array_ops",
".",
"expand_dims",
"(",
"labels",
",",
"0",
")",
"# If `init_probs` is `None`, set up online estimation of data distribution.",
"if",
"init_probs",
"is",
"None",
":",
"# We use `target_probs` to get the number of classes, so its shape must be",
"# fully defined at graph construction time.",
"target_probs",
".",
"get_shape",
"(",
")",
".",
"assert_is_fully_defined",
"(",
")",
"init_probs",
"=",
"_estimate_data_distribution",
"(",
"labels",
",",
"target_probs",
".",
"get_shape",
"(",
")",
".",
"num_elements",
"(",
")",
")",
"else",
":",
"init_probs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"init_probs",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
"# Validate that input is consistent.",
"tensor_list",
",",
"labels",
",",
"[",
"init_probs",
",",
"target_probs",
"]",
"=",
"_verify_input",
"(",
"tensor_list",
",",
"labels",
",",
"[",
"init_probs",
",",
"target_probs",
"]",
")",
"# Check that all zero initial probabilities also have zero target",
"# probabilities.",
"assert_op",
"=",
"logging_ops",
".",
"Assert",
"(",
"math_ops",
".",
"reduce_all",
"(",
"math_ops",
".",
"logical_or",
"(",
"math_ops",
".",
"not_equal",
"(",
"init_probs",
",",
"0",
")",
",",
"math_ops",
".",
"equal",
"(",
"target_probs",
",",
"0",
")",
")",
")",
",",
"[",
"'All classes with zero initial probability must also have zero target '",
"'probability: '",
",",
"init_probs",
",",
"target_probs",
"]",
")",
"init_probs",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"assert_op",
"]",
",",
"init_probs",
")",
"# Calculate acceptance sampling probabilities.",
"accept_probs",
"=",
"_calculate_acceptance_probabilities",
"(",
"init_probs",
",",
"target_probs",
")",
"proportion_rejected",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"(",
"1",
"-",
"accept_probs",
")",
"*",
"init_probs",
")",
"accept_probs",
"=",
"control_flow_ops",
".",
"cond",
"(",
"math_ops",
".",
"less",
"(",
"proportion_rejected",
",",
".5",
")",
",",
"lambda",
":",
"accept_probs",
",",
"lambda",
":",
"logging_ops",
".",
"Print",
"(",
"# pylint: disable=g-long-lambda",
"accept_probs",
",",
"[",
"accept_probs",
"]",
",",
"message",
"=",
"'Proportion of examples rejected by sampler is high.'",
",",
"first_n",
"=",
"10",
")",
")",
"# Make a single queue to hold input examples. Reshape output so examples",
"# don't have singleton batch dimension.",
"batched",
"=",
"input_ops",
".",
"batch",
"(",
"tensor_list",
"+",
"[",
"labels",
"]",
",",
"batch_size",
"=",
"1",
",",
"num_threads",
"=",
"threads_per_queue",
",",
"capacity",
"=",
"queue_capacity",
",",
"enqueue_many",
"=",
"True",
")",
"val_list",
"=",
"[",
"array_ops",
".",
"squeeze",
"(",
"x",
",",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"batched",
"[",
":",
"-",
"1",
"]",
"]",
"label",
"=",
"array_ops",
".",
"squeeze",
"(",
"batched",
"[",
"-",
"1",
"]",
",",
"[",
"0",
"]",
")",
"# Set up second queue containing batches that have the desired class",
"# proportions.",
"batched",
"=",
"_get_stratified_batch_from_tensors",
"(",
"val_list",
",",
"label",
",",
"accept_probs",
",",
"batch_size",
",",
"threads_per_queue",
")",
"return",
"batched",
"[",
":",
"-",
"1",
"]",
",",
"batched",
"[",
"-",
"1",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py#L38-L149 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/managers.py | python | Server.get_methods | (self, c, token) | return tuple(self.id_to_obj[token.id][1]) | Return the methods of the shared object indicated by token | Return the methods of the shared object indicated by token | [
"Return",
"the",
"methods",
"of",
"the",
"shared",
"object",
"indicated",
"by",
"token"
] | def get_methods(self, c, token):
'''
Return the methods of the shared object indicated by token
'''
return tuple(self.id_to_obj[token.id][1]) | [
"def",
"get_methods",
"(",
"self",
",",
"c",
",",
"token",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"id_to_obj",
"[",
"token",
".",
"id",
"]",
"[",
"1",
"]",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/managers.py#L411-L415 | |
rizinorg/cutter | 1b271a0ae8799f99c84c336a88d8c24729e4de63 | docs/apidoc.py | python | create_modules_toc_file | (key, value, destdir) | Create the module's index. | Create the module's index. | [
"Create",
"the",
"module",
"s",
"index",
"."
] | def create_modules_toc_file(key, value, destdir):
"""Create the module's index."""
text = format_heading(1, '%s' % value)
text += '.. toctree::\n'
text += ' :glob:\n\n'
text += ' %s/*\n' % key
write_file('%slist' % key, text, destdir) | [
"def",
"create_modules_toc_file",
"(",
"key",
",",
"value",
",",
"destdir",
")",
":",
"text",
"=",
"format_heading",
"(",
"1",
",",
"'%s'",
"%",
"value",
")",
"text",
"+=",
"'.. toctree::\\n'",
"text",
"+=",
"' :glob:\\n\\n'",
"text",
"+=",
"' %s/*\\n'",
"%",
"key",
"write_file",
"(",
"'%slist'",
"%",
"key",
",",
"text",
",",
"destdir",
")"
] | https://github.com/rizinorg/cutter/blob/1b271a0ae8799f99c84c336a88d8c24729e4de63/docs/apidoc.py#L59-L66 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/bayesflow/python/ops/stochastic_tensor.py | python | SampleAndReshapeValue.__init__ | (self, n=1, stop_gradient=False) | Sample `n` times and reshape the outer 2 axes so rank does not change.
Args:
n: A python integer or int32 tensor. The number of samples to take.
stop_gradient: If `True`, StochasticTensors' values are wrapped in
`stop_gradient`, to avoid backpropagation through. | Sample `n` times and reshape the outer 2 axes so rank does not change. | [
"Sample",
"n",
"times",
"and",
"reshape",
"the",
"outer",
"2",
"axes",
"so",
"rank",
"does",
"not",
"change",
"."
] | def __init__(self, n=1, stop_gradient=False):
"""Sample `n` times and reshape the outer 2 axes so rank does not change.
Args:
n: A python integer or int32 tensor. The number of samples to take.
stop_gradient: If `True`, StochasticTensors' values are wrapped in
`stop_gradient`, to avoid backpropagation through.
"""
self._n = n
self._stop_gradient = stop_gradient | [
"def",
"__init__",
"(",
"self",
",",
"n",
"=",
"1",
",",
"stop_gradient",
"=",
"False",
")",
":",
"self",
".",
"_n",
"=",
"n",
"self",
".",
"_stop_gradient",
"=",
"stop_gradient"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/bayesflow/python/ops/stochastic_tensor.py#L231-L240 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/api_key.py | python | APIKey.name | (self) | return self._name | Gets the name of this APIKey. # noqa: E501
:return: The name of this APIKey. # noqa: E501
:rtype: str | Gets the name of this APIKey. # noqa: E501 | [
"Gets",
"the",
"name",
"of",
"this",
"APIKey",
".",
"#",
"noqa",
":",
"E501"
] | def name(self):
"""Gets the name of this APIKey. # noqa: E501
:return: The name of this APIKey. # noqa: E501
:rtype: str
"""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/api_key.py#L136-L143 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py | python | ParserElement.transformString | ( self, instring ) | Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. | Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. | [
"Extension",
"to",
"C",
"{",
"L",
"{",
"scanString",
"}}",
"to",
"modify",
"matching",
"text",
"with",
"modified",
"tokens",
"that",
"may",
"be",
"returned",
"from",
"a",
"parse",
"action",
".",
"To",
"use",
"C",
"{",
"transformString",
"}",
"define",
"a",
"grammar",
"and",
"attach",
"a",
"parse",
"action",
"to",
"it",
"that",
"modifies",
"the",
"returned",
"token",
"list",
".",
"Invoking",
"C",
"{",
"transformString",
"()",
"}",
"on",
"a",
"target",
"string",
"will",
"then",
"scan",
"for",
"matches",
"and",
"replace",
"the",
"matched",
"text",
"patterns",
"according",
"to",
"the",
"logic",
"in",
"the",
"parse",
"action",
".",
"C",
"{",
"transformString",
"()",
"}",
"returns",
"the",
"resulting",
"transformed",
"string",
".",
"Example",
"::",
"wd",
"=",
"Word",
"(",
"alphas",
")",
"wd",
".",
"setParseAction",
"(",
"lambda",
"toks",
":",
"toks",
"[",
"0",
"]",
".",
"title",
"()",
")",
"print",
"(",
"wd",
".",
"transformString",
"(",
"now",
"is",
"the",
"winter",
"of",
"our",
"discontent",
"made",
"glorious",
"summer",
"by",
"this",
"sun",
"of",
"york",
".",
"))",
"Prints",
"::",
"Now",
"Is",
"The",
"Winter",
"Of",
"Our",
"Discontent",
"Made",
"Glorious",
"Summer",
"By",
"This",
"Sun",
"Of",
"York",
"."
] | def transformString( self, instring ):
"""
Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
"""
out = []
lastE = 0
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to
# keep string locs straight between transformString and scanString
self.keepTabs = True
try:
for t,s,e in self.scanString( instring ):
out.append( instring[lastE:s] )
if t:
if isinstance(t,ParseResults):
out += t.asList()
elif isinstance(t,list):
out += t
else:
out.append(t)
lastE = e
out.append(instring[lastE:])
out = [o for o in out if o]
return "".join(map(_ustr,_flatten(out)))
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc | [
"def",
"transformString",
"(",
"self",
",",
"instring",
")",
":",
"out",
"=",
"[",
"]",
"lastE",
"=",
"0",
"# force preservation of <TAB>s, to minimize unwanted transformation of string, and to",
"# keep string locs straight between transformString and scanString",
"self",
".",
"keepTabs",
"=",
"True",
"try",
":",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
")",
":",
"out",
".",
"append",
"(",
"instring",
"[",
"lastE",
":",
"s",
"]",
")",
"if",
"t",
":",
"if",
"isinstance",
"(",
"t",
",",
"ParseResults",
")",
":",
"out",
"+=",
"t",
".",
"asList",
"(",
")",
"elif",
"isinstance",
"(",
"t",
",",
"list",
")",
":",
"out",
"+=",
"t",
"else",
":",
"out",
".",
"append",
"(",
"t",
")",
"lastE",
"=",
"e",
"out",
".",
"append",
"(",
"instring",
"[",
"lastE",
":",
"]",
")",
"out",
"=",
"[",
"o",
"for",
"o",
"in",
"out",
"if",
"o",
"]",
"return",
"\"\"",
".",
"join",
"(",
"map",
"(",
"_ustr",
",",
"_flatten",
"(",
"out",
")",
")",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clears out pyparsing internal stack trace",
"raise",
"exc"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py#L1729-L1770 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py | python | Telnet.read_sb_data | (self) | return buf | Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block. | Return any data available in the SB ... SE queue. | [
"Return",
"any",
"data",
"available",
"in",
"the",
"SB",
"...",
"SE",
"queue",
"."
] | def read_sb_data(self):
"""Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block.
"""
buf = self.sbdataq
self.sbdataq = ''
return buf | [
"def",
"read_sb_data",
"(",
"self",
")",
":",
"buf",
"=",
"self",
".",
"sbdataq",
"self",
".",
"sbdataq",
"=",
"''",
"return",
"buf"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py#L455-L465 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/tools/common.py | python | check_tool_aux | (command) | Checks if 'command' can be found either in path
or is a full name to an existing file. | Checks if 'command' can be found either in path
or is a full name to an existing file. | [
"Checks",
"if",
"command",
"can",
"be",
"found",
"either",
"in",
"path",
"or",
"is",
"a",
"full",
"name",
"to",
"an",
"existing",
"file",
"."
] | def check_tool_aux(command):
""" Checks if 'command' can be found either in path
or is a full name to an existing file.
"""
assert isinstance(command, basestring)
dirname = os.path.dirname(command)
if dirname:
if os.path.exists(command):
return command
# Both NT and Cygwin will run .exe files by their unqualified names.
elif on_windows() and os.path.exists(command + '.exe'):
return command
# Only NT will run .bat files by their unqualified names.
elif os_name() == 'NT' and os.path.exists(command + '.bat'):
return command
else:
paths = path.programs_path()
if path.glob(paths, [command]):
return command | [
"def",
"check_tool_aux",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"basestring",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"command",
")",
"if",
"dirname",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"command",
")",
":",
"return",
"command",
"# Both NT and Cygwin will run .exe files by their unqualified names.",
"elif",
"on_windows",
"(",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"command",
"+",
"'.exe'",
")",
":",
"return",
"command",
"# Only NT will run .bat files by their unqualified names.",
"elif",
"os_name",
"(",
")",
"==",
"'NT'",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"command",
"+",
"'.bat'",
")",
":",
"return",
"command",
"else",
":",
"paths",
"=",
"path",
".",
"programs_path",
"(",
")",
"if",
"path",
".",
"glob",
"(",
"paths",
",",
"[",
"command",
"]",
")",
":",
"return",
"command"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/tools/common.py#L404-L422 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/client/timeline.py | python | _ChromeTraceFormatter.emit_tid | (self, name, pid, tid) | Adds a thread metadata event to the trace.
Args:
name: The thread name as a string.
pid: Identifier of the process as an integer.
tid: Identifier of the thread as an integer. | Adds a thread metadata event to the trace. | [
"Adds",
"a",
"thread",
"metadata",
"event",
"to",
"the",
"trace",
"."
] | def emit_tid(self, name, pid, tid):
"""Adds a thread metadata event to the trace.
Args:
name: The thread name as a string.
pid: Identifier of the process as an integer.
tid: Identifier of the thread as an integer.
"""
event = {}
event['name'] = 'thread_name'
event['ph'] = 'M'
event['pid'] = pid
event['tid'] = tid
event['args'] = {'name': name}
self._metadata.append(event) | [
"def",
"emit_tid",
"(",
"self",
",",
"name",
",",
"pid",
",",
"tid",
")",
":",
"event",
"=",
"{",
"}",
"event",
"[",
"'name'",
"]",
"=",
"'thread_name'",
"event",
"[",
"'ph'",
"]",
"=",
"'M'",
"event",
"[",
"'pid'",
"]",
"=",
"pid",
"event",
"[",
"'tid'",
"]",
"=",
"tid",
"event",
"[",
"'args'",
"]",
"=",
"{",
"'name'",
":",
"name",
"}",
"self",
".",
"_metadata",
".",
"append",
"(",
"event",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/timeline.py#L105-L119 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/config.py | python | ConfigContext.load_json | (self, path, default=None) | return util.load_json(path, obj) | Reads JSON format data from a file on disk and returns it as dictionary. | Reads JSON format data from a file on disk and returns it as dictionary. | [
"Reads",
"JSON",
"format",
"data",
"from",
"a",
"file",
"on",
"disk",
"and",
"returns",
"it",
"as",
"dictionary",
"."
] | def load_json(self, path, default=None):
"""Reads JSON format data from a file on disk and returns it as dictionary."""
self.context.view.loading_file(path)
obj = default
if not obj:
obj = {}
return util.load_json(path, obj) | [
"def",
"load_json",
"(",
"self",
",",
"path",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"context",
".",
"view",
".",
"loading_file",
"(",
"path",
")",
"obj",
"=",
"default",
"if",
"not",
"obj",
":",
"obj",
"=",
"{",
"}",
"return",
"util",
".",
"load_json",
"(",
"path",
",",
"obj",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/config.py#L159-L165 | |
fenderglass/Flye | 2013acc650356cc934a2a9b82eb90af260c8b52b | flye/repeat_graph/graph_alignment.py | python | iter_alignments | (filename) | Returns alignment generator | Returns alignment generator | [
"Returns",
"alignment",
"generator"
] | def iter_alignments(filename):
"""
Returns alignment generator
"""
#alignments = []
current_chain = []
with open(filename, "r") as f:
for line in f:
if not line: continue
tokens = line.strip().split()
if tokens[0] == "Chain":
if current_chain:
yield current_chain
#alignments.append(current_chain)
current_chain = []
elif tokens[0] == "Aln":
(edge_id, cur_id, cur_start, cur_end, cur_len,
ext_id, ext_start, ext_end, ext_len, left_shift,
right_shift, score, divergence) = tokens[1:]
ovlp = OverlapRange(cur_id, int(cur_len), int(cur_start), int(cur_end),
ext_id, int(ext_len), int(ext_start), int(ext_end),
int(left_shift), int(right_shift), int(score),
float(divergence))
current_chain.append(GraphAlignment(_to_signed_id(int(edge_id)), ovlp))
else:
raise Exception("Error parsing " + filename)
if current_chain:
yield current_chain | [
"def",
"iter_alignments",
"(",
"filename",
")",
":",
"#alignments = []",
"current_chain",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"not",
"line",
":",
"continue",
"tokens",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"if",
"tokens",
"[",
"0",
"]",
"==",
"\"Chain\"",
":",
"if",
"current_chain",
":",
"yield",
"current_chain",
"#alignments.append(current_chain)",
"current_chain",
"=",
"[",
"]",
"elif",
"tokens",
"[",
"0",
"]",
"==",
"\"Aln\"",
":",
"(",
"edge_id",
",",
"cur_id",
",",
"cur_start",
",",
"cur_end",
",",
"cur_len",
",",
"ext_id",
",",
"ext_start",
",",
"ext_end",
",",
"ext_len",
",",
"left_shift",
",",
"right_shift",
",",
"score",
",",
"divergence",
")",
"=",
"tokens",
"[",
"1",
":",
"]",
"ovlp",
"=",
"OverlapRange",
"(",
"cur_id",
",",
"int",
"(",
"cur_len",
")",
",",
"int",
"(",
"cur_start",
")",
",",
"int",
"(",
"cur_end",
")",
",",
"ext_id",
",",
"int",
"(",
"ext_len",
")",
",",
"int",
"(",
"ext_start",
")",
",",
"int",
"(",
"ext_end",
")",
",",
"int",
"(",
"left_shift",
")",
",",
"int",
"(",
"right_shift",
")",
",",
"int",
"(",
"score",
")",
",",
"float",
"(",
"divergence",
")",
")",
"current_chain",
".",
"append",
"(",
"GraphAlignment",
"(",
"_to_signed_id",
"(",
"int",
"(",
"edge_id",
")",
")",
",",
"ovlp",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Error parsing \"",
"+",
"filename",
")",
"if",
"current_chain",
":",
"yield",
"current_chain"
] | https://github.com/fenderglass/Flye/blob/2013acc650356cc934a2a9b82eb90af260c8b52b/flye/repeat_graph/graph_alignment.py#L42-L74 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/examples/tutorials/word2vec/word2vec_basic.py | python | maybe_download | (filename, expected_bytes) | return filename | Download a file if not present, and make sure it's the right size. | Download a file if not present, and make sure it's the right size. | [
"Download",
"a",
"file",
"if",
"not",
"present",
"and",
"make",
"sure",
"it",
"s",
"the",
"right",
"size",
"."
] | def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
if not os.path.exists(filename):
filename, _ = urllib.request.urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified', filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with a browser?')
return filename | [
"def",
"maybe_download",
"(",
"filename",
",",
"expected_bytes",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"filename",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"url",
"+",
"filename",
",",
"filename",
")",
"statinfo",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
"if",
"statinfo",
".",
"st_size",
"==",
"expected_bytes",
":",
"print",
"(",
"'Found and verified'",
",",
"filename",
")",
"else",
":",
"print",
"(",
"statinfo",
".",
"st_size",
")",
"raise",
"Exception",
"(",
"'Failed to verify '",
"+",
"filename",
"+",
"'. Can you get to it with a browser?'",
")",
"return",
"filename"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/examples/tutorials/word2vec/word2vec_basic.py#L36-L47 | |
libretro/beetle-psx-libretro | 05f55acf4ea315bcc16a1cbe0b624696ec6fee35 | intl/core_option_translation.py | python | create_non_dupe | (base_name: str, opt_num: int, comparison) | return h | Makes sure base_name is not in comparison, and if it is it's renamed.
:param base_name: Name to check/make unique.
:param opt_num: Number of the option base_name belongs to, used in making it unique.
:param comparison: Dictionary or set to search for base_name in.
:return: Unique name. | Makes sure base_name is not in comparison, and if it is it's renamed. | [
"Makes",
"sure",
"base_name",
"is",
"not",
"in",
"comparison",
"and",
"if",
"it",
"is",
"it",
"s",
"renamed",
"."
] | def create_non_dupe(base_name: str, opt_num: int, comparison) -> str:
"""Makes sure base_name is not in comparison, and if it is it's renamed.
:param base_name: Name to check/make unique.
:param opt_num: Number of the option base_name belongs to, used in making it unique.
:param comparison: Dictionary or set to search for base_name in.
:return: Unique name.
"""
h = base_name
if h in comparison:
n = 0
h = h + '_O' + str(opt_num)
h_end = len(h)
while h in comparison:
h = h[:h_end] + '_' + str(n)
n += 1
return h | [
"def",
"create_non_dupe",
"(",
"base_name",
":",
"str",
",",
"opt_num",
":",
"int",
",",
"comparison",
")",
"->",
"str",
":",
"h",
"=",
"base_name",
"if",
"h",
"in",
"comparison",
":",
"n",
"=",
"0",
"h",
"=",
"h",
"+",
"'_O'",
"+",
"str",
"(",
"opt_num",
")",
"h_end",
"=",
"len",
"(",
"h",
")",
"while",
"h",
"in",
"comparison",
":",
"h",
"=",
"h",
"[",
":",
"h_end",
"]",
"+",
"'_'",
"+",
"str",
"(",
"n",
")",
"n",
"+=",
"1",
"return",
"h"
] | https://github.com/libretro/beetle-psx-libretro/blob/05f55acf4ea315bcc16a1cbe0b624696ec6fee35/intl/core_option_translation.py#L146-L162 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/engine/training.py | python | _standardize_input_data | (data,
names,
shapes=None,
check_batch_axis=True,
exception_prefix='') | return arrays | Normalizes inputs and targets provided by users.
Users may pass data as a list of arrays, dictionary of arrays,
or as a single array. We normalize this to an ordered list of
arrays (same order as `names`), while checking that the provided
arrays have shapes that match the network's expectations.
Arguments:
data: User-provided input data (polymorphic).
names: List of expected array names.
shapes: Optional list of expected array shapes.
check_batch_axis: Boolean; whether to check that
the batch axis of the arrays matches the expected
value found in `shapes`.
exception_prefix: String prefix used for exception formatting.
Returns:
List of standardized input arrays (one array per model input).
Raises:
ValueError: in case of improperly formatted user-provided data. | Normalizes inputs and targets provided by users. | [
"Normalizes",
"inputs",
"and",
"targets",
"provided",
"by",
"users",
"."
] | def _standardize_input_data(data,
names,
shapes=None,
check_batch_axis=True,
exception_prefix=''):
"""Normalizes inputs and targets provided by users.
Users may pass data as a list of arrays, dictionary of arrays,
or as a single array. We normalize this to an ordered list of
arrays (same order as `names`), while checking that the provided
arrays have shapes that match the network's expectations.
Arguments:
data: User-provided input data (polymorphic).
names: List of expected array names.
shapes: Optional list of expected array shapes.
check_batch_axis: Boolean; whether to check that
the batch axis of the arrays matches the expected
value found in `shapes`.
exception_prefix: String prefix used for exception formatting.
Returns:
List of standardized input arrays (one array per model input).
Raises:
ValueError: in case of improperly formatted user-provided data.
"""
if not names:
return []
if data is None:
return [None for _ in range(len(names))]
if isinstance(data, dict):
arrays = []
for name in names:
if name not in data:
raise ValueError('No data provided for "' + name +
'". Need data for each key in: ' + str(names))
arrays.append(data[name])
elif isinstance(data, list):
if len(data) != len(names):
if data and hasattr(data[0], 'shape'):
raise ValueError(
'Error when checking model ' + exception_prefix +
': the list of Numpy arrays '
'that you are passing to your model '
'is not the size the model expected. '
'Expected to see ' + str(len(names)) + ' arrays but instead got '
'the following list of ' + str(len(data)) + ' arrays: ' +
str(data)[:200] + '...')
else:
if len(names) == 1:
data = [np.asarray(data)]
else:
raise ValueError('Error when checking model ' + exception_prefix +
': you are passing a list as '
'input to your model, '
'but the model expects '
'a list of ' + str(len(names)) +
' Numpy arrays instead. '
'The list you passed was: ' + str(data)[:200])
arrays = data
else:
if not hasattr(data, 'shape'):
raise TypeError('Error when checking model ' + exception_prefix +
': data should be a Numpy array, '
'or list/dict of Numpy arrays. '
'Found: ' + str(data)[:200] + '...')
if len(names) > 1:
# Case: model expects multiple inputs but only received
# a single Numpy array.
raise ValueError('The model expects ' + str(len(names)) + ' ' +
exception_prefix +
' arrays, but only received one array. '
'Found: array with shape ' + str(data.shape))
arrays = [data]
# Make arrays at least 2D.
for i in range(len(names)):
array = arrays[i]
if len(array.shape) == 1:
array = np.expand_dims(array, 1)
arrays[i] = array
# Check shapes compatibility.
if shapes:
for i in range(len(names)):
if shapes[i] is None:
continue
array = arrays[i]
if len(array.shape) != len(shapes[i]):
raise ValueError(
'Error when checking ' + exception_prefix + ': expected ' + names[i]
+ ' to have ' + str(len(shapes[i])) +
' dimensions, but got array with shape ' + str(array.shape))
for j, (dim, ref_dim) in enumerate(zip(array.shape, shapes[i])):
if not j and not check_batch_axis:
# skip the first axis
continue
if ref_dim:
if ref_dim != dim:
raise ValueError('Error when checking ' + exception_prefix +
': expected ' + names[i] + ' to have shape ' +
str(shapes[i]) + ' but got array with shape ' +
str(array.shape))
return arrays | [
"def",
"_standardize_input_data",
"(",
"data",
",",
"names",
",",
"shapes",
"=",
"None",
",",
"check_batch_axis",
"=",
"True",
",",
"exception_prefix",
"=",
"''",
")",
":",
"if",
"not",
"names",
":",
"return",
"[",
"]",
"if",
"data",
"is",
"None",
":",
"return",
"[",
"None",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"names",
")",
")",
"]",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"arrays",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"not",
"in",
"data",
":",
"raise",
"ValueError",
"(",
"'No data provided for \"'",
"+",
"name",
"+",
"'\". Need data for each key in: '",
"+",
"str",
"(",
"names",
")",
")",
"arrays",
".",
"append",
"(",
"data",
"[",
"name",
"]",
")",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"if",
"len",
"(",
"data",
")",
"!=",
"len",
"(",
"names",
")",
":",
"if",
"data",
"and",
"hasattr",
"(",
"data",
"[",
"0",
"]",
",",
"'shape'",
")",
":",
"raise",
"ValueError",
"(",
"'Error when checking model '",
"+",
"exception_prefix",
"+",
"': the list of Numpy arrays '",
"'that you are passing to your model '",
"'is not the size the model expected. '",
"'Expected to see '",
"+",
"str",
"(",
"len",
"(",
"names",
")",
")",
"+",
"' arrays but instead got '",
"'the following list of '",
"+",
"str",
"(",
"len",
"(",
"data",
")",
")",
"+",
"' arrays: '",
"+",
"str",
"(",
"data",
")",
"[",
":",
"200",
"]",
"+",
"'...'",
")",
"else",
":",
"if",
"len",
"(",
"names",
")",
"==",
"1",
":",
"data",
"=",
"[",
"np",
".",
"asarray",
"(",
"data",
")",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Error when checking model '",
"+",
"exception_prefix",
"+",
"': you are passing a list as '",
"'input to your model, '",
"'but the model expects '",
"'a list of '",
"+",
"str",
"(",
"len",
"(",
"names",
")",
")",
"+",
"' Numpy arrays instead. '",
"'The list you passed was: '",
"+",
"str",
"(",
"data",
")",
"[",
":",
"200",
"]",
")",
"arrays",
"=",
"data",
"else",
":",
"if",
"not",
"hasattr",
"(",
"data",
",",
"'shape'",
")",
":",
"raise",
"TypeError",
"(",
"'Error when checking model '",
"+",
"exception_prefix",
"+",
"': data should be a Numpy array, '",
"'or list/dict of Numpy arrays. '",
"'Found: '",
"+",
"str",
"(",
"data",
")",
"[",
":",
"200",
"]",
"+",
"'...'",
")",
"if",
"len",
"(",
"names",
")",
">",
"1",
":",
"# Case: model expects multiple inputs but only received",
"# a single Numpy array.",
"raise",
"ValueError",
"(",
"'The model expects '",
"+",
"str",
"(",
"len",
"(",
"names",
")",
")",
"+",
"' '",
"+",
"exception_prefix",
"+",
"' arrays, but only received one array. '",
"'Found: array with shape '",
"+",
"str",
"(",
"data",
".",
"shape",
")",
")",
"arrays",
"=",
"[",
"data",
"]",
"# Make arrays at least 2D.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"names",
")",
")",
":",
"array",
"=",
"arrays",
"[",
"i",
"]",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"==",
"1",
":",
"array",
"=",
"np",
".",
"expand_dims",
"(",
"array",
",",
"1",
")",
"arrays",
"[",
"i",
"]",
"=",
"array",
"# Check shapes compatibility.",
"if",
"shapes",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"names",
")",
")",
":",
"if",
"shapes",
"[",
"i",
"]",
"is",
"None",
":",
"continue",
"array",
"=",
"arrays",
"[",
"i",
"]",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"!=",
"len",
"(",
"shapes",
"[",
"i",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Error when checking '",
"+",
"exception_prefix",
"+",
"': expected '",
"+",
"names",
"[",
"i",
"]",
"+",
"' to have '",
"+",
"str",
"(",
"len",
"(",
"shapes",
"[",
"i",
"]",
")",
")",
"+",
"' dimensions, but got array with shape '",
"+",
"str",
"(",
"array",
".",
"shape",
")",
")",
"for",
"j",
",",
"(",
"dim",
",",
"ref_dim",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"array",
".",
"shape",
",",
"shapes",
"[",
"i",
"]",
")",
")",
":",
"if",
"not",
"j",
"and",
"not",
"check_batch_axis",
":",
"# skip the first axis",
"continue",
"if",
"ref_dim",
":",
"if",
"ref_dim",
"!=",
"dim",
":",
"raise",
"ValueError",
"(",
"'Error when checking '",
"+",
"exception_prefix",
"+",
"': expected '",
"+",
"names",
"[",
"i",
"]",
"+",
"' to have shape '",
"+",
"str",
"(",
"shapes",
"[",
"i",
"]",
")",
"+",
"' but got array with shape '",
"+",
"str",
"(",
"array",
".",
"shape",
")",
")",
"return",
"arrays"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/training.py#L40-L144 | |
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/json_format.py | python | _Printer._MessageToJsonObject | (self, message) | return self._RegularMessageToJsonObject(message, js) | Converts message to an object according to Proto3 JSON Specification. | Converts message to an object according to Proto3 JSON Specification. | [
"Converts",
"message",
"to",
"an",
"object",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | def _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification."""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return self._WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
js = {}
return self._RegularMessageToJsonObject(message, js) | [
"def",
"_MessageToJsonObject",
"(",
"self",
",",
"message",
")",
":",
"message_descriptor",
"=",
"message",
".",
"DESCRIPTOR",
"full_name",
"=",
"message_descriptor",
".",
"full_name",
"if",
"_IsWrapperMessage",
"(",
"message_descriptor",
")",
":",
"return",
"self",
".",
"_WrapperMessageToJsonObject",
"(",
"message",
")",
"if",
"full_name",
"in",
"_WKTJSONMETHODS",
":",
"return",
"methodcaller",
"(",
"_WKTJSONMETHODS",
"[",
"full_name",
"]",
"[",
"0",
"]",
",",
"message",
")",
"(",
"self",
")",
"js",
"=",
"{",
"}",
"return",
"self",
".",
"_RegularMessageToJsonObject",
"(",
"message",
",",
"js",
")"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/json_format.py#L123-L132 | |
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | python/ola/ClientWrapper.py | python | SelectServer._CheckTimeouts | (self, now) | Execute any expired timeouts. | Execute any expired timeouts. | [
"Execute",
"any",
"expired",
"timeouts",
"."
] | def _CheckTimeouts(self, now):
"""Execute any expired timeouts."""
while len(self._events):
event = self._events[0]
if event.HasExpired(now):
event.Run()
else:
break
heapq.heappop(self._events) | [
"def",
"_CheckTimeouts",
"(",
"self",
",",
"now",
")",
":",
"while",
"len",
"(",
"self",
".",
"_events",
")",
":",
"event",
"=",
"self",
".",
"_events",
"[",
"0",
"]",
"if",
"event",
".",
"HasExpired",
"(",
"now",
")",
":",
"event",
".",
"Run",
"(",
")",
"else",
":",
"break",
"heapq",
".",
"heappop",
"(",
"self",
".",
"_events",
")"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/ClientWrapper.py#L251-L259 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/decomposition/_pca.py | python | _assess_dimension_ | (spectrum, rank, n_samples, n_features) | return ll | Compute the likelihood of a rank ``rank`` dataset.
The dataset is assumed to be embedded in gaussian noise of shape(n,
dimf) having spectrum ``spectrum``.
Parameters
----------
spectrum : array of shape (n)
Data spectrum.
rank : int
Tested rank value.
n_samples : int
Number of samples.
n_features : int
Number of features.
Returns
-------
ll : float,
The log-likelihood
Notes
-----
This implements the method of `Thomas P. Minka:
Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604` | Compute the likelihood of a rank ``rank`` dataset. | [
"Compute",
"the",
"likelihood",
"of",
"a",
"rank",
"rank",
"dataset",
"."
] | def _assess_dimension_(spectrum, rank, n_samples, n_features):
"""Compute the likelihood of a rank ``rank`` dataset.
The dataset is assumed to be embedded in gaussian noise of shape(n,
dimf) having spectrum ``spectrum``.
Parameters
----------
spectrum : array of shape (n)
Data spectrum.
rank : int
Tested rank value.
n_samples : int
Number of samples.
n_features : int
Number of features.
Returns
-------
ll : float,
The log-likelihood
Notes
-----
This implements the method of `Thomas P. Minka:
Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604`
"""
if rank > len(spectrum):
raise ValueError("The tested rank cannot exceed the rank of the"
" dataset")
pu = -rank * log(2.)
for i in range(rank):
pu += (gammaln((n_features - i) / 2.) -
log(np.pi) * (n_features - i) / 2.)
pl = np.sum(np.log(spectrum[:rank]))
pl = -pl * n_samples / 2.
if rank == n_features:
pv = 0
v = 1
else:
v = np.sum(spectrum[rank:]) / (n_features - rank)
pv = -np.log(v) * n_samples * (n_features - rank) / 2.
m = n_features * rank - rank * (rank + 1.) / 2.
pp = log(2. * np.pi) * (m + rank + 1.) / 2.
pa = 0.
spectrum_ = spectrum.copy()
spectrum_[rank:n_features] = v
for i in range(rank):
for j in range(i + 1, len(spectrum)):
pa += log((spectrum[i] - spectrum[j]) *
(1. / spectrum_[j] - 1. / spectrum_[i])) + log(n_samples)
ll = pu + pl + pv + pp - pa / 2. - rank * log(n_samples) / 2.
return ll | [
"def",
"_assess_dimension_",
"(",
"spectrum",
",",
"rank",
",",
"n_samples",
",",
"n_features",
")",
":",
"if",
"rank",
">",
"len",
"(",
"spectrum",
")",
":",
"raise",
"ValueError",
"(",
"\"The tested rank cannot exceed the rank of the\"",
"\" dataset\"",
")",
"pu",
"=",
"-",
"rank",
"*",
"log",
"(",
"2.",
")",
"for",
"i",
"in",
"range",
"(",
"rank",
")",
":",
"pu",
"+=",
"(",
"gammaln",
"(",
"(",
"n_features",
"-",
"i",
")",
"/",
"2.",
")",
"-",
"log",
"(",
"np",
".",
"pi",
")",
"*",
"(",
"n_features",
"-",
"i",
")",
"/",
"2.",
")",
"pl",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"spectrum",
"[",
":",
"rank",
"]",
")",
")",
"pl",
"=",
"-",
"pl",
"*",
"n_samples",
"/",
"2.",
"if",
"rank",
"==",
"n_features",
":",
"pv",
"=",
"0",
"v",
"=",
"1",
"else",
":",
"v",
"=",
"np",
".",
"sum",
"(",
"spectrum",
"[",
"rank",
":",
"]",
")",
"/",
"(",
"n_features",
"-",
"rank",
")",
"pv",
"=",
"-",
"np",
".",
"log",
"(",
"v",
")",
"*",
"n_samples",
"*",
"(",
"n_features",
"-",
"rank",
")",
"/",
"2.",
"m",
"=",
"n_features",
"*",
"rank",
"-",
"rank",
"*",
"(",
"rank",
"+",
"1.",
")",
"/",
"2.",
"pp",
"=",
"log",
"(",
"2.",
"*",
"np",
".",
"pi",
")",
"*",
"(",
"m",
"+",
"rank",
"+",
"1.",
")",
"/",
"2.",
"pa",
"=",
"0.",
"spectrum_",
"=",
"spectrum",
".",
"copy",
"(",
")",
"spectrum_",
"[",
"rank",
":",
"n_features",
"]",
"=",
"v",
"for",
"i",
"in",
"range",
"(",
"rank",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"spectrum",
")",
")",
":",
"pa",
"+=",
"log",
"(",
"(",
"spectrum",
"[",
"i",
"]",
"-",
"spectrum",
"[",
"j",
"]",
")",
"*",
"(",
"1.",
"/",
"spectrum_",
"[",
"j",
"]",
"-",
"1.",
"/",
"spectrum_",
"[",
"i",
"]",
")",
")",
"+",
"log",
"(",
"n_samples",
")",
"ll",
"=",
"pu",
"+",
"pl",
"+",
"pv",
"+",
"pp",
"-",
"pa",
"/",
"2.",
"-",
"rank",
"*",
"log",
"(",
"n_samples",
")",
"/",
"2.",
"return",
"ll"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/decomposition/_pca.py#L30-L89 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/p4util/procutil.py | python | plump_qcvar | (val: Union[float, str, List], shape_clue: str, ret: str = 'np') | Prepare serialized QCVariable for set_variable by convert flat arrays into shaped ones and floating strings.
Parameters
----------
val :
flat (?, ) list or scalar or string, probably from JSON storage.
shape_clue
Label that includes (case insensitive) one of the following as
a clue to the array's natural dimensions: 'gradient', 'hessian'
ret
{'np', 'psi4'}
Whether to return `np.ndarray` or `psi4.core.Matrix`.
Returns
-------
float or numpy.ndarray or Matrix
Reshaped array of type `ret` with natural dimensions of `shape_clue`. | Prepare serialized QCVariable for set_variable by convert flat arrays into shaped ones and floating strings. | [
"Prepare",
"serialized",
"QCVariable",
"for",
"set_variable",
"by",
"convert",
"flat",
"arrays",
"into",
"shaped",
"ones",
"and",
"floating",
"strings",
"."
] | def plump_qcvar(val: Union[float, str, List], shape_clue: str, ret: str = 'np') -> Union[float, np.ndarray, core.Matrix]:
"""Prepare serialized QCVariable for set_variable by convert flat arrays into shaped ones and floating strings.
Parameters
----------
val :
flat (?, ) list or scalar or string, probably from JSON storage.
shape_clue
Label that includes (case insensitive) one of the following as
a clue to the array's natural dimensions: 'gradient', 'hessian'
ret
{'np', 'psi4'}
Whether to return `np.ndarray` or `psi4.core.Matrix`.
Returns
-------
float or numpy.ndarray or Matrix
Reshaped array of type `ret` with natural dimensions of `shape_clue`.
"""
if isinstance(val, (np.ndarray, core.Matrix)):
raise TypeError
elif isinstance(val, list):
tgt = np.asarray(val)
else:
# presumably scalar. may be string
return float(val)
# TODO choose float vs Decimal for return if string?
if 'gradient' in shape_clue.lower():
reshaper = (-1, 3)
elif 'hessian' in shape_clue.lower():
ndof = int(math.sqrt(len(tgt)))
reshaper = (ndof, ndof)
else:
raise ValidationError(f'Uncertain how to reshape array: {shape_clue}')
if ret == 'np':
return tgt.reshape(reshaper)
elif ret == 'psi4':
return core.Matrix.from_array(tgt.reshape(reshaper))
else:
raise ValidationError(f'Return type not among [np, psi4]: {ret}') | [
"def",
"plump_qcvar",
"(",
"val",
":",
"Union",
"[",
"float",
",",
"str",
",",
"List",
"]",
",",
"shape_clue",
":",
"str",
",",
"ret",
":",
"str",
"=",
"'np'",
")",
"->",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
",",
"core",
".",
"Matrix",
"]",
":",
"if",
"isinstance",
"(",
"val",
",",
"(",
"np",
".",
"ndarray",
",",
"core",
".",
"Matrix",
")",
")",
":",
"raise",
"TypeError",
"elif",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"tgt",
"=",
"np",
".",
"asarray",
"(",
"val",
")",
"else",
":",
"# presumably scalar. may be string",
"return",
"float",
"(",
"val",
")",
"# TODO choose float vs Decimal for return if string?",
"if",
"'gradient'",
"in",
"shape_clue",
".",
"lower",
"(",
")",
":",
"reshaper",
"=",
"(",
"-",
"1",
",",
"3",
")",
"elif",
"'hessian'",
"in",
"shape_clue",
".",
"lower",
"(",
")",
":",
"ndof",
"=",
"int",
"(",
"math",
".",
"sqrt",
"(",
"len",
"(",
"tgt",
")",
")",
")",
"reshaper",
"=",
"(",
"ndof",
",",
"ndof",
")",
"else",
":",
"raise",
"ValidationError",
"(",
"f'Uncertain how to reshape array: {shape_clue}'",
")",
"if",
"ret",
"==",
"'np'",
":",
"return",
"tgt",
".",
"reshape",
"(",
"reshaper",
")",
"elif",
"ret",
"==",
"'psi4'",
":",
"return",
"core",
".",
"Matrix",
".",
"from_array",
"(",
"tgt",
".",
"reshape",
"(",
"reshaper",
")",
")",
"else",
":",
"raise",
"ValidationError",
"(",
"f'Return type not among [np, psi4]: {ret}'",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/procutil.py#L592-L634 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | EntryPoint.resolve | (self) | Resolve the entry point from its module and attrs. | [] | def resolve(self):
"""
Resolve the entry point from its module and attrs.
"""
module = __import__(self.module_name, fromlist=['__name__'], level=0)
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc)) | [
"def",
"resolve",
"(",
"self",
")",
":",
"module",
"=",
"__import__",
"(",
"self",
".",
"module_name",
",",
"fromlist",
"=",
"[",
"'__name__'",
"]",
",",
"level",
"=",
"0",
")",
"try",
":",
"return",
"functools",
".",
"reduce",
"(",
"getattr",
",",
"self",
".",
"attrs",
",",
"module",
")",
"except",
"AttributeError",
"as",
"exc",
":",
"raise",
"ImportError",
"(",
"str",
"(",
"exc",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L4889-L4905 | |||
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | scribus/plugins/scriptplugin_py2x/scripts/FontSample.py | python | Application.__testUpDownState | (self) | Only enable the up and down buttons when just a single item is selected.
Enable should be applied to up, down or both depending on its
position in the listbox. At all other times disable both. | Only enable the up and down buttons when just a single item is selected. | [
"Only",
"enable",
"the",
"up",
"and",
"down",
"buttons",
"when",
"just",
"a",
"single",
"item",
"is",
"selected",
"."
] | def __testUpDownState(self):
"""Only enable the up and down buttons when just a single item is selected.
Enable should be applied to up, down or both depending on its
position in the listbox. At all other times disable both.
"""
# Get a count of how many items are currently selected...
selection = list(self.listbox2.curselection())
tcount = 0
for sel in selection:
tcount = tcount + 1
position = 0
if tcount == 1:
position = IntType(selection[0])
# If one selected and there is more than one item in the listbox then ok...
if tcount == 1 and self.listbox2.size() > 1:
# Now test the position of the selected line...
if position > 0 and position < self.listbox2.size() - 1: # Both
self.__setUpDownActive(1, 1)
# If not one less or lesser from the bottom (listbox.count-1?) then gray the down button.
elif position == self.listbox2.size() - 1: # Up only
self.__setUpDownActive(1, 0)
# If not one or more from the top then gray up button.
elif position == 0: # Down only
self.__setUpDownActive(0, 1)
else:
self.__setUpDownActive(0, 0) | [
"def",
"__testUpDownState",
"(",
"self",
")",
":",
"# Get a count of how many items are currently selected...",
"selection",
"=",
"list",
"(",
"self",
".",
"listbox2",
".",
"curselection",
"(",
")",
")",
"tcount",
"=",
"0",
"for",
"sel",
"in",
"selection",
":",
"tcount",
"=",
"tcount",
"+",
"1",
"position",
"=",
"0",
"if",
"tcount",
"==",
"1",
":",
"position",
"=",
"IntType",
"(",
"selection",
"[",
"0",
"]",
")",
"# If one selected and there is more than one item in the listbox then ok...",
"if",
"tcount",
"==",
"1",
"and",
"self",
".",
"listbox2",
".",
"size",
"(",
")",
">",
"1",
":",
"# Now test the position of the selected line...",
"if",
"position",
">",
"0",
"and",
"position",
"<",
"self",
".",
"listbox2",
".",
"size",
"(",
")",
"-",
"1",
":",
"# Both",
"self",
".",
"__setUpDownActive",
"(",
"1",
",",
"1",
")",
"# If not one less or lesser from the bottom (listbox.count-1?) then gray the down button.",
"elif",
"position",
"==",
"self",
".",
"listbox2",
".",
"size",
"(",
")",
"-",
"1",
":",
"# Up only",
"self",
".",
"__setUpDownActive",
"(",
"1",
",",
"0",
")",
"# If not one or more from the top then gray up button.",
"elif",
"position",
"==",
"0",
":",
"# Down only",
"self",
".",
"__setUpDownActive",
"(",
"0",
",",
"1",
")",
"else",
":",
"self",
".",
"__setUpDownActive",
"(",
"0",
",",
"0",
")"
] | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin_py2x/scripts/FontSample.py#L1379-L1407 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | _DropCommonSuffixes | (filename) | return os.path.splitext(filename)[0] | Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed. | Drops common suffixes like _test.cc or -inl.h from filename. | [
"Drops",
"common",
"suffixes",
"like",
"_test",
".",
"cc",
"or",
"-",
"inl",
".",
"h",
"from",
"filename",
"."
] | def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed.
"""
for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
'inl.h', 'impl.h', 'internal.h'):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.path.splitext(filename)[0] | [
"def",
"_DropCommonSuffixes",
"(",
"filename",
")",
":",
"for",
"suffix",
"in",
"(",
"'test.cc'",
",",
"'regtest.cc'",
",",
"'unittest.cc'",
",",
"'inl.h'",
",",
"'impl.h'",
",",
"'internal.h'",
")",
":",
"if",
"(",
"filename",
".",
"endswith",
"(",
"suffix",
")",
"and",
"len",
"(",
"filename",
")",
">",
"len",
"(",
"suffix",
")",
"and",
"filename",
"[",
"-",
"len",
"(",
"suffix",
")",
"-",
"1",
"]",
"in",
"(",
"'-'",
",",
"'_'",
")",
")",
":",
"return",
"filename",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"-",
"1",
"]",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L2913-L2937 | |
kevin-ssy/Optical-Flow-Guided-Feature | 07d4501a29002ee7821c38c1820e4a64c1acf6e8 | lib/caffe-action/scripts/cpp_lint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style.",
"args",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?%s\\s*\\(([^,()]+)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"(",
"args",
"and",
"args",
".",
"group",
"(",
"1",
")",
"!=",
"'void'",
"and",
"not",
"Match",
"(",
"r'(const\\s+)?%s(\\s+const)?\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"args",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-argument constructors should be marked explicit.'",
")"
] | https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/scripts/cpp_lint.py#L2194-L2298 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py | python | CalculateGeneratorInputInfo | (params) | Calculate the generator specific info that gets fed to input (called by
gyp). | Calculate the generator specific info that gets fed to input (called by
gyp). | [
"Calculate",
"the",
"generator",
"specific",
"info",
"that",
"gets",
"fed",
"to",
"input",
"(",
"called",
"by",
"gyp",
")",
"."
] | def CalculateGeneratorInputInfo(params):
"""Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get("generator_flags", {})
if generator_flags.get("adjust_static_libraries", False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted = True | [
"def",
"CalculateGeneratorInputInfo",
"(",
"params",
")",
":",
"generator_flags",
"=",
"params",
".",
"get",
"(",
"\"generator_flags\"",
",",
"{",
"}",
")",
"if",
"generator_flags",
".",
"get",
"(",
"\"adjust_static_libraries\"",
",",
"False",
")",
":",
"global",
"generator_wants_static_library_dependencies_adjusted",
"generator_wants_static_library_dependencies_adjusted",
"=",
"True"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L69-L75 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/display.py | python | display_svg | (*objs, **kwargs) | Display the SVG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw svg data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
metadata : dict (optional)
Metadata to be associated with the specific mimetype output. | Display the SVG representation of an object. | [
"Display",
"the",
"SVG",
"representation",
"of",
"an",
"object",
"."
] | def display_svg(*objs, **kwargs):
"""Display the SVG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw svg data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
metadata : dict (optional)
Metadata to be associated with the specific mimetype output.
"""
_display_mimetype('image/svg+xml', objs, **kwargs) | [
"def",
"display_svg",
"(",
"*",
"objs",
",",
"*",
"*",
"kwargs",
")",
":",
"_display_mimetype",
"(",
"'image/svg+xml'",
",",
"objs",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/display.py#L453-L467 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/versionpredicate.py | python | VersionPredicate.satisfied_by | (self, version) | return True | True if version is compatible with all the predicates in self.
The parameter version must be acceptable to the StrictVersion
constructor. It may be either a string or StrictVersion. | True if version is compatible with all the predicates in self.
The parameter version must be acceptable to the StrictVersion
constructor. It may be either a string or StrictVersion. | [
"True",
"if",
"version",
"is",
"compatible",
"with",
"all",
"the",
"predicates",
"in",
"self",
".",
"The",
"parameter",
"version",
"must",
"be",
"acceptable",
"to",
"the",
"StrictVersion",
"constructor",
".",
"It",
"may",
"be",
"either",
"a",
"string",
"or",
"StrictVersion",
"."
] | def satisfied_by(self, version):
"""True if version is compatible with all the predicates in self.
The parameter version must be acceptable to the StrictVersion
constructor. It may be either a string or StrictVersion.
"""
for cond, ver in self.pred:
if not compmap[cond](version, ver):
return False
return True | [
"def",
"satisfied_by",
"(",
"self",
",",
"version",
")",
":",
"for",
"cond",
",",
"ver",
"in",
"self",
".",
"pred",
":",
"if",
"not",
"compmap",
"[",
"cond",
"]",
"(",
"version",
",",
"ver",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/versionpredicate.py#L132-L140 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_dummy_thread.py | python | RLock.acquire | (self, waitflag=None, timeout=-1) | return locked | Aquire the lock, can be called multiple times in succession. | Aquire the lock, can be called multiple times in succession. | [
"Aquire",
"the",
"lock",
"can",
"be",
"called",
"multiple",
"times",
"in",
"succession",
"."
] | def acquire(self, waitflag=None, timeout=-1):
"""Aquire the lock, can be called multiple times in succession.
"""
locked = super().acquire(waitflag, timeout)
if locked:
self._levels += 1
return locked | [
"def",
"acquire",
"(",
"self",
",",
"waitflag",
"=",
"None",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"locked",
"=",
"super",
"(",
")",
".",
"acquire",
"(",
"waitflag",
",",
"timeout",
")",
"if",
"locked",
":",
"self",
".",
"_levels",
"+=",
"1",
"return",
"locked"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_dummy_thread.py#L164-L170 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py | python | rehash | (path, blocksize=1 << 20) | return (digest, str(length)) | Return (encoded_digest, length) for path using hashlib.sha256() | Return (encoded_digest, length) for path using hashlib.sha256() | [
"Return",
"(",
"encoded_digest",
"length",
")",
"for",
"path",
"using",
"hashlib",
".",
"sha256",
"()"
] | def rehash(path, blocksize=1 << 20):
# type: (str, int) -> Tuple[str, str]
"""Return (encoded_digest, length) for path using hashlib.sha256()"""
h, length = hash_file(path, blocksize)
digest = 'sha256=' + urlsafe_b64encode(
h.digest()
).decode('latin1').rstrip('=')
return (digest, str(length)) | [
"def",
"rehash",
"(",
"path",
",",
"blocksize",
"=",
"1",
"<<",
"20",
")",
":",
"# type: (str, int) -> Tuple[str, str]",
"h",
",",
"length",
"=",
"hash_file",
"(",
"path",
",",
"blocksize",
")",
"digest",
"=",
"'sha256='",
"+",
"urlsafe_b64encode",
"(",
"h",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"'latin1'",
")",
".",
"rstrip",
"(",
"'='",
")",
"return",
"(",
"digest",
",",
"str",
"(",
"length",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py#L171-L185 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/series.py | python | Series.round | (self, decimals=0, *args, **kwargs) | return result | Round each value in a Series to the given number of decimals.
Parameters
----------
decimals : int, default 0
Number of decimal places to round to. If decimals is negative,
it specifies the number of positions to the left of the decimal point.
*args, **kwargs
Additional arguments and keywords have no effect but might be
accepted for compatibility with NumPy.
Returns
-------
Series
Rounded values of the Series.
See Also
--------
numpy.around : Round values of an np.array.
DataFrame.round : Round values of a DataFrame.
Examples
--------
>>> s = pd.Series([0.1, 1.3, 2.7])
>>> s.round()
0 0.0
1 1.0
2 3.0
dtype: float64 | Round each value in a Series to the given number of decimals. | [
"Round",
"each",
"value",
"in",
"a",
"Series",
"to",
"the",
"given",
"number",
"of",
"decimals",
"."
] | def round(self, decimals=0, *args, **kwargs) -> Series:
"""
Round each value in a Series to the given number of decimals.
Parameters
----------
decimals : int, default 0
Number of decimal places to round to. If decimals is negative,
it specifies the number of positions to the left of the decimal point.
*args, **kwargs
Additional arguments and keywords have no effect but might be
accepted for compatibility with NumPy.
Returns
-------
Series
Rounded values of the Series.
See Also
--------
numpy.around : Round values of an np.array.
DataFrame.round : Round values of a DataFrame.
Examples
--------
>>> s = pd.Series([0.1, 1.3, 2.7])
>>> s.round()
0 0.0
1 1.0
2 3.0
dtype: float64
"""
nv.validate_round(args, kwargs)
result = self._values.round(decimals)
result = self._constructor(result, index=self.index).__finalize__(
self, method="round"
)
return result | [
"def",
"round",
"(",
"self",
",",
"decimals",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Series",
":",
"nv",
".",
"validate_round",
"(",
"args",
",",
"kwargs",
")",
"result",
"=",
"self",
".",
"_values",
".",
"round",
"(",
"decimals",
")",
"result",
"=",
"self",
".",
"_constructor",
"(",
"result",
",",
"index",
"=",
"self",
".",
"index",
")",
".",
"__finalize__",
"(",
"self",
",",
"method",
"=",
"\"round\"",
")",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/series.py#L2360-L2398 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/android/pylib/utils/reraiser_thread.py | python | ReraiserThreadGroup.JoinAll | (self, watcher=watchdog_timer.WatchdogTimer(None)) | Join all threads.
Reraises exceptions raised by the child threads and supports breaking
immediately on exceptions raised on the main thread. Unfinished threads'
stacks will be logged on watchdog timeout.
Args:
watcher: Watchdog object providing timeout, by default waits forever. | Join all threads. | [
"Join",
"all",
"threads",
"."
] | def JoinAll(self, watcher=watchdog_timer.WatchdogTimer(None)):
"""Join all threads.
Reraises exceptions raised by the child threads and supports breaking
immediately on exceptions raised on the main thread. Unfinished threads'
stacks will be logged on watchdog timeout.
Args:
watcher: Watchdog object providing timeout, by default waits forever.
"""
try:
self._JoinAll(watcher)
except TimeoutError:
for thread in (t for t in self._threads if t.isAlive()):
LogThreadStack(thread)
raise | [
"def",
"JoinAll",
"(",
"self",
",",
"watcher",
"=",
"watchdog_timer",
".",
"WatchdogTimer",
"(",
"None",
")",
")",
":",
"try",
":",
"self",
".",
"_JoinAll",
"(",
"watcher",
")",
"except",
"TimeoutError",
":",
"for",
"thread",
"in",
"(",
"t",
"for",
"t",
"in",
"self",
".",
"_threads",
"if",
"t",
".",
"isAlive",
"(",
")",
")",
":",
"LogThreadStack",
"(",
"thread",
")",
"raise"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/utils/reraiser_thread.py#L119-L134 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarIter.__next__ | (self) | return tarinfo | Return the next item using TarFile's next() method.
When all members have been read, set TarFile as _loaded. | Return the next item using TarFile's next() method.
When all members have been read, set TarFile as _loaded. | [
"Return",
"the",
"next",
"item",
"using",
"TarFile",
"s",
"next",
"()",
"method",
".",
"When",
"all",
"members",
"have",
"been",
"read",
"set",
"TarFile",
"as",
"_loaded",
"."
] | def __next__(self):
"""Return the next item using TarFile's next() method.
When all members have been read, set TarFile as _loaded.
"""
# Fix for SF #1100429: Under rare circumstances it can
# happen that getmembers() is called during iteration,
# which will cause TarIter to stop prematurely.
if not self.tarfile._loaded:
tarinfo = self.tarfile.next()
if not tarinfo:
self.tarfile._loaded = True
raise StopIteration
else:
try:
tarinfo = self.tarfile.members[self.index]
except IndexError:
raise StopIteration
self.index += 1
return tarinfo | [
"def",
"__next__",
"(",
"self",
")",
":",
"# Fix for SF #1100429: Under rare circumstances it can",
"# happen that getmembers() is called during iteration,",
"# which will cause TarIter to stop prematurely.",
"if",
"not",
"self",
".",
"tarfile",
".",
"_loaded",
":",
"tarinfo",
"=",
"self",
".",
"tarfile",
".",
"next",
"(",
")",
"if",
"not",
"tarinfo",
":",
"self",
".",
"tarfile",
".",
"_loaded",
"=",
"True",
"raise",
"StopIteration",
"else",
":",
"try",
":",
"tarinfo",
"=",
"self",
".",
"tarfile",
".",
"members",
"[",
"self",
".",
"index",
"]",
"except",
"IndexError",
":",
"raise",
"StopIteration",
"self",
".",
"index",
"+=",
"1",
"return",
"tarinfo"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2570-L2588 | |
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | python/caffe/detector.py | python | Detector.detect_windows | (self, images_windows) | return detections | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts. | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net. | [
"Do",
"windowed",
"detection",
"over",
"given",
"images",
"and",
"windows",
".",
"Windows",
"are",
"extracted",
"then",
"warped",
"to",
"the",
"input",
"dimensions",
"of",
"the",
"net",
"."
] | def detect_windows(self, images_windows):
"""
Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
# Extract windows.
window_inputs = []
for image_fname, windows in images_windows:
image = caffe.io.load_image(image_fname).astype(np.float32)
for window in windows:
window_inputs.append(self.crop(image, window))
# Run through the net (warping windows to input dimensions).
in_ = self.inputs[0]
caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2])
+ self.blobs[in_].data.shape[2:],
dtype=np.float32)
for ix, window_in in enumerate(window_inputs):
caffe_in[ix] = self.transformer.preprocess(in_, window_in)
out = self.forward_all(**{in_: caffe_in})
predictions = out[self.outputs[0]].squeeze(axis=(2, 3))
# Package predictions with images and windows.
detections = []
ix = 0
for image_fname, windows in images_windows:
for window in windows:
detections.append({
'window': window,
'prediction': predictions[ix],
'filename': image_fname
})
ix += 1
return detections | [
"def",
"detect_windows",
"(",
"self",
",",
"images_windows",
")",
":",
"# Extract windows.",
"window_inputs",
"=",
"[",
"]",
"for",
"image_fname",
",",
"windows",
"in",
"images_windows",
":",
"image",
"=",
"caffe",
".",
"io",
".",
"load_image",
"(",
"image_fname",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"for",
"window",
"in",
"windows",
":",
"window_inputs",
".",
"append",
"(",
"self",
".",
"crop",
"(",
"image",
",",
"window",
")",
")",
"# Run through the net (warping windows to input dimensions).",
"in_",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
"caffe_in",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"window_inputs",
")",
",",
"window_inputs",
"[",
"0",
"]",
".",
"shape",
"[",
"2",
"]",
")",
"+",
"self",
".",
"blobs",
"[",
"in_",
"]",
".",
"data",
".",
"shape",
"[",
"2",
":",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"ix",
",",
"window_in",
"in",
"enumerate",
"(",
"window_inputs",
")",
":",
"caffe_in",
"[",
"ix",
"]",
"=",
"self",
".",
"transformer",
".",
"preprocess",
"(",
"in_",
",",
"window_in",
")",
"out",
"=",
"self",
".",
"forward_all",
"(",
"*",
"*",
"{",
"in_",
":",
"caffe_in",
"}",
")",
"predictions",
"=",
"out",
"[",
"self",
".",
"outputs",
"[",
"0",
"]",
"]",
".",
"squeeze",
"(",
"axis",
"=",
"(",
"2",
",",
"3",
")",
")",
"# Package predictions with images and windows.",
"detections",
"=",
"[",
"]",
"ix",
"=",
"0",
"for",
"image_fname",
",",
"windows",
"in",
"images_windows",
":",
"for",
"window",
"in",
"windows",
":",
"detections",
".",
"append",
"(",
"{",
"'window'",
":",
"window",
",",
"'prediction'",
":",
"predictions",
"[",
"ix",
"]",
",",
"'filename'",
":",
"image_fname",
"}",
")",
"ix",
"+=",
"1",
"return",
"detections"
] | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/python/caffe/detector.py#L56-L99 | |
logcabin/logcabin | ee6c55ae9744b82b451becd9707d26c7c1b6bbfb | site_scons/site_tools/protoc.py | python | generate | (env) | Add Builders and construction variables for protoc to an Environment. | Add Builders and construction variables for protoc to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"protoc",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for protoc to an Environment."""
try:
bld = env['BUILDERS']['Protoc']
except KeyError:
bld = ProtocBuilder
env['BUILDERS']['Protoc'] = bld
env['PROTOC'] = env.Detect(protocs) or 'protoc'
env['PROTOCFLAGS'] = SCons.Util.CLVar('')
env['PROTOCPROTOPATH'] = SCons.Util.CLVar('')
env['PROTOCCOM'] = '$PROTOC ${["-I%s"%x for x in PROTOCPROTOPATH]} $PROTOCFLAGS --cpp_out=$PROTOCCPPOUTFLAGS$PROTOCOUTDIR ${PROTOCPYTHONOUTDIR and ("--python_out="+PROTOCPYTHONOUTDIR) or ""} ${PROTOCFDSOUT and ("-o"+PROTOCFDSOUT) or ""} ${SOURCES}'
env['PROTOCOUTDIR'] = '${SOURCE.dir}'
env['PROTOCPYTHONOUTDIR'] = "python"
env['PROTOCSRCSUFFIX'] = '.proto' | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Protoc'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"ProtocBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Protoc'",
"]",
"=",
"bld",
"env",
"[",
"'PROTOC'",
"]",
"=",
"env",
".",
"Detect",
"(",
"protocs",
")",
"or",
"'protoc'",
"env",
"[",
"'PROTOCFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env",
"[",
"'PROTOCPROTOPATH'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env",
"[",
"'PROTOCCOM'",
"]",
"=",
"'$PROTOC ${[\"-I%s\"%x for x in PROTOCPROTOPATH]} $PROTOCFLAGS --cpp_out=$PROTOCCPPOUTFLAGS$PROTOCOUTDIR ${PROTOCPYTHONOUTDIR and (\"--python_out=\"+PROTOCPYTHONOUTDIR) or \"\"} ${PROTOCFDSOUT and (\"-o\"+PROTOCFDSOUT) or \"\"} ${SOURCES}'",
"env",
"[",
"'PROTOCOUTDIR'",
"]",
"=",
"'${SOURCE.dir}'",
"env",
"[",
"'PROTOCPYTHONOUTDIR'",
"]",
"=",
"\"python\"",
"env",
"[",
"'PROTOCSRCSUFFIX'",
"]",
"=",
"'.proto'"
] | https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/site_scons/site_tools/protoc.py#L89-L103 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/util/strings.py | python | decode_until_null | (data, encoding='utf-8') | return data.decode(encoding) | decodes a bytes object, aborting at the first \\0 character.
>>> decode_until_null(b"foo\\0bar")
'foo' | decodes a bytes object, aborting at the first \\0 character. | [
"decodes",
"a",
"bytes",
"object",
"aborting",
"at",
"the",
"first",
"\\\\",
"0",
"character",
"."
] | def decode_until_null(data, encoding='utf-8'):
"""
decodes a bytes object, aborting at the first \\0 character.
>>> decode_until_null(b"foo\\0bar")
'foo'
"""
end = data.find(0)
if end != -1:
data = data[:end]
return data.decode(encoding) | [
"def",
"decode_until_null",
"(",
"data",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"end",
"=",
"data",
".",
"find",
"(",
"0",
")",
"if",
"end",
"!=",
"-",
"1",
":",
"data",
"=",
"data",
"[",
":",
"end",
"]",
"return",
"data",
".",
"decode",
"(",
"encoding",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/strings.py#L8-L19 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/adapters.py | python | HTTPAdapter.get_connection | (self, url, proxies=None) | return conn | Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request. | Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. | [
"Returns",
"a",
"urllib3",
"connection",
"for",
"the",
"given",
"URL",
".",
"This",
"should",
"not",
"be",
"called",
"from",
"user",
"code",
"and",
"is",
"only",
"exposed",
"for",
"use",
"when",
"subclassing",
"the",
":",
"class",
":",
"HTTPAdapter",
"<requests",
".",
"adapters",
".",
"HTTPAdapter",
">",
"."
] | def get_connection(self, url, proxies=None):
"""Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.
"""
proxies = proxies or {}
proxy = proxies.get(urlparse(url.lower()).scheme)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
# Only scheme should be lower case
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.connection_from_url(url)
return conn | [
"def",
"get_connection",
"(",
"self",
",",
"url",
",",
"proxies",
"=",
"None",
")",
":",
"proxies",
"=",
"proxies",
"or",
"{",
"}",
"proxy",
"=",
"proxies",
".",
"get",
"(",
"urlparse",
"(",
"url",
".",
"lower",
"(",
")",
")",
".",
"scheme",
")",
"if",
"proxy",
":",
"proxy",
"=",
"prepend_scheme_if_needed",
"(",
"proxy",
",",
"'http'",
")",
"proxy_manager",
"=",
"self",
".",
"proxy_manager_for",
"(",
"proxy",
")",
"conn",
"=",
"proxy_manager",
".",
"connection_from_url",
"(",
"url",
")",
"else",
":",
"# Only scheme should be lower case",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"url",
"=",
"parsed",
".",
"geturl",
"(",
")",
"conn",
"=",
"self",
".",
"poolmanager",
".",
"connection_from_url",
"(",
"url",
")",
"return",
"conn"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/adapters.py#L232-L253 | |
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | pymnn/pip_package/MNN/expr/__init__.py | python | reduce_all | (x, axis=[], keepdims=False) | return _F.reduce_all(x, axis, keepdims) | reduce_all(x, axis=[], keepdims=False)
Return the all of nonzero of all/axis.
Parameters
----------
x : var_like, input value, dtype just support int32.
axis : axis_like, input value, just support int32. Default is [], reduce all.
keepdims: bool, input value. Default is False.
Returns
-------
z : Var. The all of `x` along the `axis`.
Example:
-------
>>> expr.reduce_all([[0,1],[0,3]])
var(0)
>>> expr.reduce_all([[0,1],[0,3]], 0)
var([0, 1]) | reduce_all(x, axis=[], keepdims=False)
Return the all of nonzero of all/axis. | [
"reduce_all",
"(",
"x",
"axis",
"=",
"[]",
"keepdims",
"=",
"False",
")",
"Return",
"the",
"all",
"of",
"nonzero",
"of",
"all",
"/",
"axis",
"."
] | def reduce_all(x, axis=[], keepdims=False):
'''
reduce_all(x, axis=[], keepdims=False)
Return the all of nonzero of all/axis.
Parameters
----------
x : var_like, input value, dtype just support int32.
axis : axis_like, input value, just support int32. Default is [], reduce all.
keepdims: bool, input value. Default is False.
Returns
-------
z : Var. The all of `x` along the `axis`.
Example:
-------
>>> expr.reduce_all([[0,1],[0,3]])
var(0)
>>> expr.reduce_all([[0,1],[0,3]], 0)
var([0, 1])
'''
x = _to_var(x)
if x.dtype != _F.int:
raise ValueError('MNN.expr.reduce_all just support int32')
axis = _to_axis(axis)
return _F.reduce_all(x, axis, keepdims) | [
"def",
"reduce_all",
"(",
"x",
",",
"axis",
"=",
"[",
"]",
",",
"keepdims",
"=",
"False",
")",
":",
"x",
"=",
"_to_var",
"(",
"x",
")",
"if",
"x",
".",
"dtype",
"!=",
"_F",
".",
"int",
":",
"raise",
"ValueError",
"(",
"'MNN.expr.reduce_all just support int32'",
")",
"axis",
"=",
"_to_axis",
"(",
"axis",
")",
"return",
"_F",
".",
"reduce_all",
"(",
"x",
",",
"axis",
",",
"keepdims",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L1410-L1436 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | _is_egg_path | (path) | return path.lower().endswith('.egg') | Determine if given path appears to be an egg. | Determine if given path appears to be an egg. | [
"Determine",
"if",
"given",
"path",
"appears",
"to",
"be",
"an",
"egg",
"."
] | def _is_egg_path(path):
"""
Determine if given path appears to be an egg.
"""
return path.lower().endswith('.egg') | [
"def",
"_is_egg_path",
"(",
"path",
")",
":",
"return",
"path",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.egg'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2360-L2364 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/function.py | python | _DefinedFunction.stateful_ops | (self) | return self._stateful_ops | Returns the list of stateful ops in function definition.
Returns:
A list of (op.name, op.type) pairs. | Returns the list of stateful ops in function definition. | [
"Returns",
"the",
"list",
"of",
"stateful",
"ops",
"in",
"function",
"definition",
"."
] | def stateful_ops(self):
"""Returns the list of stateful ops in function definition.
Returns:
A list of (op.name, op.type) pairs.
"""
self._create_definition_if_needed()
return self._stateful_ops | [
"def",
"stateful_ops",
"(",
"self",
")",
":",
"self",
".",
"_create_definition_if_needed",
"(",
")",
"return",
"self",
".",
"_stateful_ops"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/function.py#L364-L371 | |
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | _VerboseLevel | () | return _cpplint_state.verbose_level | Returns the module's verbosity setting. | Returns the module's verbosity setting. | [
"Returns",
"the",
"module",
"s",
"verbosity",
"setting",
"."
] | def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level | [
"def",
"_VerboseLevel",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"verbose_level"
] | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L777-L779 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ToggleButton_GetClassDefaultAttributes | (*args, **kwargs) | return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs) | ToggleButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | ToggleButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"ToggleButton_GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def ToggleButton_GetClassDefaultAttributes(*args, **kwargs):
"""
ToggleButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"ToggleButton_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToggleButton_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3050-L3065 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/symbol/random.py | python | gamma | (alpha=1, beta=1, shape=_Null, dtype=_Null, **kwargs) | return _random_helper(_internal._random_gamma, _internal._sample_gamma,
[alpha, beta], shape, dtype, kwargs) | Draw random samples from a gamma distribution.
Samples are distributed according to a gamma distribution parametrized
by *alpha* (shape) and *beta* (scale).
Parameters
----------
alpha : float or Symbol
The shape of the gamma distribution. Should be greater than zero.
beta : float or Symbol
The scale of the gamma distribution. Should be greater than zero.
Default is equal to 1.
shape : int or tuple of ints
The number of samples to draw. If shape is, e.g., `(m, n)` and `alpha` and
`beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta`
are Symbols with shape, e.g., `(x, y)`, then output will have shape
`(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair.
dtype : {'float16','float32', 'float64'}
Data type of output samples. Default is 'float32' | Draw random samples from a gamma distribution. | [
"Draw",
"random",
"samples",
"from",
"a",
"gamma",
"distribution",
"."
] | def gamma(alpha=1, beta=1, shape=_Null, dtype=_Null, **kwargs):
"""Draw random samples from a gamma distribution.
Samples are distributed according to a gamma distribution parametrized
by *alpha* (shape) and *beta* (scale).
Parameters
----------
alpha : float or Symbol
The shape of the gamma distribution. Should be greater than zero.
beta : float or Symbol
The scale of the gamma distribution. Should be greater than zero.
Default is equal to 1.
shape : int or tuple of ints
The number of samples to draw. If shape is, e.g., `(m, n)` and `alpha` and
`beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta`
are Symbols with shape, e.g., `(x, y)`, then output will have shape
`(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair.
dtype : {'float16','float32', 'float64'}
Data type of output samples. Default is 'float32'
"""
return _random_helper(_internal._random_gamma, _internal._sample_gamma,
[alpha, beta], shape, dtype, kwargs) | [
"def",
"gamma",
"(",
"alpha",
"=",
"1",
",",
"beta",
"=",
"1",
",",
"shape",
"=",
"_Null",
",",
"dtype",
"=",
"_Null",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_random_helper",
"(",
"_internal",
".",
"_random_gamma",
",",
"_internal",
".",
"_sample_gamma",
",",
"[",
"alpha",
",",
"beta",
"]",
",",
"shape",
",",
"dtype",
",",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/random.py#L147-L169 | |
PJunhyuk/people-counting-pose | 8cdaab5281847c296b305643842053d496e2e4e8 | lib/coco/PythonAPI/pycocotools/coco.py | python | COCO.getCatIds | (self, catNms=[], supNms=[], catIds=[]) | return ids | filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids | filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids | [
"filtering",
"parameters",
".",
"default",
"skips",
"that",
"filter",
".",
":",
"param",
"catNms",
"(",
"str",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"cat",
"names",
":",
"param",
"supNms",
"(",
"str",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"supercategory",
"names",
":",
"param",
"catIds",
"(",
"int",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"cat",
"ids",
":",
"return",
":",
"ids",
"(",
"int",
"array",
")",
":",
"integer",
"array",
"of",
"cat",
"ids"
] | def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""
filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids
"""
catNms = catNms if type(catNms) == list else [catNms]
supNms = supNms if type(supNms) == list else [supNms]
catIds = catIds if type(catIds) == list else [catIds]
if len(catNms) == len(supNms) == len(catIds) == 0:
cats = self.dataset['categories']
else:
cats = self.dataset['categories']
cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms]
cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds]
ids = [cat['id'] for cat in cats]
return ids | [
"def",
"getCatIds",
"(",
"self",
",",
"catNms",
"=",
"[",
"]",
",",
"supNms",
"=",
"[",
"]",
",",
"catIds",
"=",
"[",
"]",
")",
":",
"catNms",
"=",
"catNms",
"if",
"type",
"(",
"catNms",
")",
"==",
"list",
"else",
"[",
"catNms",
"]",
"supNms",
"=",
"supNms",
"if",
"type",
"(",
"supNms",
")",
"==",
"list",
"else",
"[",
"supNms",
"]",
"catIds",
"=",
"catIds",
"if",
"type",
"(",
"catIds",
")",
"==",
"list",
"else",
"[",
"catIds",
"]",
"if",
"len",
"(",
"catNms",
")",
"==",
"len",
"(",
"supNms",
")",
"==",
"len",
"(",
"catIds",
")",
"==",
"0",
":",
"cats",
"=",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
"else",
":",
"cats",
"=",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"catNms",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'name'",
"]",
"in",
"catNms",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"supNms",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'supercategory'",
"]",
"in",
"supNms",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"catIds",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'id'",
"]",
"in",
"catIds",
"]",
"ids",
"=",
"[",
"cat",
"[",
"'id'",
"]",
"for",
"cat",
"in",
"cats",
"]",
"return",
"ids"
] | https://github.com/PJunhyuk/people-counting-pose/blob/8cdaab5281847c296b305643842053d496e2e4e8/lib/coco/PythonAPI/pycocotools/coco.py#L152-L172 | |
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/jsontemplate/jsontemplate.py | python | _AbstractSection.Append | (self, statement) | Append a statement to this block. | Append a statement to this block. | [
"Append",
"a",
"statement",
"to",
"this",
"block",
"."
] | def Append(self, statement):
"""Append a statement to this block."""
self.current_clause.append(statement) | [
"def",
"Append",
"(",
"self",
",",
"statement",
")",
":",
"self",
".",
"current_clause",
".",
"append",
"(",
"statement",
")"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/jsontemplate/jsontemplate.py#L362-L364 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/common.py | python | delayedInterrupts | () | Block SIGINT and SIGTERM temporarily. | Block SIGINT and SIGTERM temporarily. | [
"Block",
"SIGINT",
"and",
"SIGTERM",
"temporarily",
"."
] | def delayedInterrupts():
"""Block SIGINT and SIGTERM temporarily."""
quit = []
def delay(sig, frame):
if quit:
print ('Ctrl-C: Quitting during delayed interrupts section ' +
'because user insisted')
raise KeyboardInterrupt
else:
quit.append((sig, frame))
sigs = [signal.SIGINT, signal.SIGTERM]
prevHandlers = [signal.signal(sig, delay)
for sig in sigs]
try:
yield None
finally:
for sig, handler in zip(sigs, prevHandlers):
signal.signal(sig, handler)
if quit:
raise KeyboardInterrupt(
'Signal received while in delayed interrupts section') | [
"def",
"delayedInterrupts",
"(",
")",
":",
"quit",
"=",
"[",
"]",
"def",
"delay",
"(",
"sig",
",",
"frame",
")",
":",
"if",
"quit",
":",
"print",
"(",
"'Ctrl-C: Quitting during delayed interrupts section '",
"+",
"'because user insisted'",
")",
"raise",
"KeyboardInterrupt",
"else",
":",
"quit",
".",
"append",
"(",
"(",
"sig",
",",
"frame",
")",
")",
"sigs",
"=",
"[",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIGTERM",
"]",
"prevHandlers",
"=",
"[",
"signal",
".",
"signal",
"(",
"sig",
",",
"delay",
")",
"for",
"sig",
"in",
"sigs",
"]",
"try",
":",
"yield",
"None",
"finally",
":",
"for",
"sig",
",",
"handler",
"in",
"zip",
"(",
"sigs",
",",
"prevHandlers",
")",
":",
"signal",
".",
"signal",
"(",
"sig",
",",
"handler",
")",
"if",
"quit",
":",
"raise",
"KeyboardInterrupt",
"(",
"'Signal received while in delayed interrupts section'",
")"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/common.py#L236-L256 | ||
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/fem/forms.py | python | FormMetaClass.ufcx_form | (self) | return self._ufcx_form | The compiled ufcx_form object | The compiled ufcx_form object | [
"The",
"compiled",
"ufcx_form",
"object"
] | def ufcx_form(self):
"""The compiled ufcx_form object"""
return self._ufcx_form | [
"def",
"ufcx_form",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ufcx_form"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/forms.py#L53-L55 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/DirectEnergyConversion.py | python | DirectEnergyConversion.spectra_masks | (self,value) | return | set up spectra masks | set up spectra masks | [
"set",
"up",
"spectra",
"masks"
] | def spectra_masks(self,value):
""" set up spectra masks """
if value is None:
if hasattr(self,'_spectra_masks') and self._spectra_masks is not None:
if self._spectra_masks in mtd:
DeleteWorkspace(self._spectra_masks)
self._spectra_masks=None
elif isinstance(value,api.Workspace):
self._spectra_masks = value.name()
elif isinstance(value, str):
if value in mtd:
self._spectra_masks = value
else:
self._spectra_masks = None
else:
#pylint: disable=W0201
self._spectra_masks = None
return | [
"def",
"spectra_masks",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_spectra_masks'",
")",
"and",
"self",
".",
"_spectra_masks",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_spectra_masks",
"in",
"mtd",
":",
"DeleteWorkspace",
"(",
"self",
".",
"_spectra_masks",
")",
"self",
".",
"_spectra_masks",
"=",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"api",
".",
"Workspace",
")",
":",
"self",
".",
"_spectra_masks",
"=",
"value",
".",
"name",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"if",
"value",
"in",
"mtd",
":",
"self",
".",
"_spectra_masks",
"=",
"value",
"else",
":",
"self",
".",
"_spectra_masks",
"=",
"None",
"else",
":",
"#pylint: disable=W0201",
"self",
".",
"_spectra_masks",
"=",
"None",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/DirectEnergyConversion.py#L1361-L1378 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | SignResponse.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
signatureSigAlg = buf.readShort()
self.signature = UnionFactory.create('TPMU_SIGNATURE', signatureSigAlg)
self.signature.initFromTpm(buf) | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"signatureSigAlg",
"=",
"buf",
".",
"readShort",
"(",
")",
"self",
".",
"signature",
"=",
"UnionFactory",
".",
"create",
"(",
"'TPMU_SIGNATURE'",
",",
"signatureSigAlg",
")",
"self",
".",
"signature",
".",
"initFromTpm",
"(",
"buf",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L13616-L13620 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/superplot/model.py | python | SuperplotModel.get_workspace_color | (self, ws_name) | return None | Get the color of a workspace.
Args:
ws_name (str): workspace name
Returns:
(str): color or None | Get the color of a workspace. | [
"Get",
"the",
"color",
"of",
"a",
"workspace",
"."
] | def get_workspace_color(self, ws_name):
"""
Get the color of a workspace.
Args:
ws_name (str): workspace name
Returns:
(str): color or None
"""
if ws_name in self._ws_colors:
return self._ws_colors[ws_name]
return None | [
"def",
"get_workspace_color",
"(",
"self",
",",
"ws_name",
")",
":",
"if",
"ws_name",
"in",
"self",
".",
"_ws_colors",
":",
"return",
"self",
".",
"_ws_colors",
"[",
"ws_name",
"]",
"return",
"None"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/superplot/model.py#L145-L157 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/pylib/results/flakiness_dashboard/json_results_generator.py | python | JSONResultsGeneratorBase._GetSVNRevision | (self, in_directory) | Returns the svn revision for the given directory.
Args:
in_directory: The directory where svn is to be run. | Returns the svn revision for the given directory. | [
"Returns",
"the",
"svn",
"revision",
"for",
"the",
"given",
"directory",
"."
] | def _GetSVNRevision(self, in_directory):
"""Returns the svn revision for the given directory.
Args:
in_directory: The directory where svn is to be run.
"""
# This is overridden in flakiness_dashboard_results_uploader.py.
raise NotImplementedError() | [
"def",
"_GetSVNRevision",
"(",
"self",
",",
"in_directory",
")",
":",
"# This is overridden in flakiness_dashboard_results_uploader.py.",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/results/flakiness_dashboard/json_results_generator.py#L358-L365 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/config.py | python | ConfigOptionsHandler._parse_packages | (self, value) | return find_packages(**find_kwargs) | Parses `packages` option value.
:param value:
:rtype: list | Parses `packages` option value. | [
"Parses",
"packages",
"option",
"value",
"."
] | def _parse_packages(self, value):
"""Parses `packages` option value.
:param value:
:rtype: list
"""
find_directives = ['find:', 'find_namespace:']
trimmed_value = value.strip()
if trimmed_value not in find_directives:
return self._parse_list(value)
findns = trimmed_value == find_directives[1]
# Read function arguments from a dedicated section.
find_kwargs = self.parse_section_packages__find(
self.sections.get('packages.find', {})
)
if findns:
from setuptools import find_namespace_packages as find_packages
else:
from setuptools import find_packages
return find_packages(**find_kwargs) | [
"def",
"_parse_packages",
"(",
"self",
",",
"value",
")",
":",
"find_directives",
"=",
"[",
"'find:'",
",",
"'find_namespace:'",
"]",
"trimmed_value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"trimmed_value",
"not",
"in",
"find_directives",
":",
"return",
"self",
".",
"_parse_list",
"(",
"value",
")",
"findns",
"=",
"trimmed_value",
"==",
"find_directives",
"[",
"1",
"]",
"# Read function arguments from a dedicated section.",
"find_kwargs",
"=",
"self",
".",
"parse_section_packages__find",
"(",
"self",
".",
"sections",
".",
"get",
"(",
"'packages.find'",
",",
"{",
"}",
")",
")",
"if",
"findns",
":",
"from",
"setuptools",
"import",
"find_namespace_packages",
"as",
"find_packages",
"else",
":",
"from",
"setuptools",
"import",
"find_packages",
"return",
"find_packages",
"(",
"*",
"*",
"find_kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/config.py#L656-L680 | |
OpenGenus/cosmos | 1a94e8880068e51d571543be179c323936bd0936 | code/data_structures/src/list/singly_linked_list/operations/insertion/insertion_at_front.py | python | SinglyLinkedList.insert_in_front | (self, data) | Inserts New data at the beginning of the Linked List
Takes O(1) time | Inserts New data at the beginning of the Linked List
Takes O(1) time | [
"Inserts",
"New",
"data",
"at",
"the",
"beginning",
"of",
"the",
"Linked",
"List",
"Takes",
"O",
"(",
"1",
")",
"time"
] | def insert_in_front(self, data):
"""
Inserts New data at the beginning of the Linked List
Takes O(1) time
"""
self.head = Node(self, data=data, next=self.head) | [
"def",
"insert_in_front",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"head",
"=",
"Node",
"(",
"self",
",",
"data",
"=",
"data",
",",
"next",
"=",
"self",
".",
"head",
")"
] | https://github.com/OpenGenus/cosmos/blob/1a94e8880068e51d571543be179c323936bd0936/code/data_structures/src/list/singly_linked_list/operations/insertion/insertion_at_front.py#L38-L43 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/syndata.py | python | SyntaxDataBase.SetLexer | (self, lex) | Set the lexer object for this data object | Set the lexer object for this data object | [
"Set",
"the",
"lexer",
"object",
"for",
"this",
"data",
"object"
] | def SetLexer(self, lex):
"""Set the lexer object for this data object"""
self._lexer = lex | [
"def",
"SetLexer",
"(",
"self",
",",
"lex",
")",
":",
"self",
".",
"_lexer",
"=",
"lex"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/syndata.py#L130-L132 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/gaussian_process/_gpc.py | python | _BinaryGaussianProcessClassifierLaplace.log_marginal_likelihood | (self, theta=None, eval_gradient=False,
clone_kernel=True) | return Z, d_Z | Returns log-marginal likelihood of theta for training data.
Parameters
----------
theta : array-like of shape (n_kernel_params,) or None
Kernel hyperparameters for which the log-marginal likelihood is
evaluated. If None, the precomputed log_marginal_likelihood
of ``self.kernel_.theta`` is returned.
eval_gradient : bool, default: False
If True, the gradient of the log-marginal likelihood with respect
to the kernel hyperparameters at position theta is returned
additionally. If True, theta must not be None.
clone_kernel : bool, default=True
If True, the kernel attribute is copied. If False, the kernel
attribute is modified, but may result in a performance improvement.
Returns
-------
log_likelihood : float
Log-marginal likelihood of theta for training data.
log_likelihood_gradient : array, shape = (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel
hyperparameters at position theta.
Only returned when eval_gradient is True. | Returns log-marginal likelihood of theta for training data. | [
"Returns",
"log",
"-",
"marginal",
"likelihood",
"of",
"theta",
"for",
"training",
"data",
"."
] | def log_marginal_likelihood(self, theta=None, eval_gradient=False,
clone_kernel=True):
"""Returns log-marginal likelihood of theta for training data.
Parameters
----------
theta : array-like of shape (n_kernel_params,) or None
Kernel hyperparameters for which the log-marginal likelihood is
evaluated. If None, the precomputed log_marginal_likelihood
of ``self.kernel_.theta`` is returned.
eval_gradient : bool, default: False
If True, the gradient of the log-marginal likelihood with respect
to the kernel hyperparameters at position theta is returned
additionally. If True, theta must not be None.
clone_kernel : bool, default=True
If True, the kernel attribute is copied. If False, the kernel
attribute is modified, but may result in a performance improvement.
Returns
-------
log_likelihood : float
Log-marginal likelihood of theta for training data.
log_likelihood_gradient : array, shape = (n_kernel_params,), optional
Gradient of the log-marginal likelihood with respect to the kernel
hyperparameters at position theta.
Only returned when eval_gradient is True.
"""
if theta is None:
if eval_gradient:
raise ValueError(
"Gradient can only be evaluated for theta!=None")
return self.log_marginal_likelihood_value_
if clone_kernel:
kernel = self.kernel_.clone_with_theta(theta)
else:
kernel = self.kernel_
kernel.theta = theta
if eval_gradient:
K, K_gradient = kernel(self.X_train_, eval_gradient=True)
else:
K = kernel(self.X_train_)
# Compute log-marginal-likelihood Z and also store some temporaries
# which can be reused for computing Z's gradient
Z, (pi, W_sr, L, b, a) = \
self._posterior_mode(K, return_temporaries=True)
if not eval_gradient:
return Z
# Compute gradient based on Algorithm 5.1 of GPML
d_Z = np.empty(theta.shape[0])
# XXX: Get rid of the np.diag() in the next line
R = W_sr[:, np.newaxis] * cho_solve((L, True), np.diag(W_sr)) # Line 7
C = solve(L, W_sr[:, np.newaxis] * K) # Line 8
# Line 9: (use einsum to compute np.diag(C.T.dot(C))))
s_2 = -0.5 * (np.diag(K) - np.einsum('ij, ij -> j', C, C)) \
* (pi * (1 - pi) * (1 - 2 * pi)) # third derivative
for j in range(d_Z.shape[0]):
C = K_gradient[:, :, j] # Line 11
# Line 12: (R.T.ravel().dot(C.ravel()) = np.trace(R.dot(C)))
s_1 = .5 * a.T.dot(C).dot(a) - .5 * R.T.ravel().dot(C.ravel())
b = C.dot(self.y_train_ - pi) # Line 13
s_3 = b - K.dot(R.dot(b)) # Line 14
d_Z[j] = s_1 + s_2.T.dot(s_3) # Line 15
return Z, d_Z | [
"def",
"log_marginal_likelihood",
"(",
"self",
",",
"theta",
"=",
"None",
",",
"eval_gradient",
"=",
"False",
",",
"clone_kernel",
"=",
"True",
")",
":",
"if",
"theta",
"is",
"None",
":",
"if",
"eval_gradient",
":",
"raise",
"ValueError",
"(",
"\"Gradient can only be evaluated for theta!=None\"",
")",
"return",
"self",
".",
"log_marginal_likelihood_value_",
"if",
"clone_kernel",
":",
"kernel",
"=",
"self",
".",
"kernel_",
".",
"clone_with_theta",
"(",
"theta",
")",
"else",
":",
"kernel",
"=",
"self",
".",
"kernel_",
"kernel",
".",
"theta",
"=",
"theta",
"if",
"eval_gradient",
":",
"K",
",",
"K_gradient",
"=",
"kernel",
"(",
"self",
".",
"X_train_",
",",
"eval_gradient",
"=",
"True",
")",
"else",
":",
"K",
"=",
"kernel",
"(",
"self",
".",
"X_train_",
")",
"# Compute log-marginal-likelihood Z and also store some temporaries",
"# which can be reused for computing Z's gradient",
"Z",
",",
"(",
"pi",
",",
"W_sr",
",",
"L",
",",
"b",
",",
"a",
")",
"=",
"self",
".",
"_posterior_mode",
"(",
"K",
",",
"return_temporaries",
"=",
"True",
")",
"if",
"not",
"eval_gradient",
":",
"return",
"Z",
"# Compute gradient based on Algorithm 5.1 of GPML",
"d_Z",
"=",
"np",
".",
"empty",
"(",
"theta",
".",
"shape",
"[",
"0",
"]",
")",
"# XXX: Get rid of the np.diag() in the next line",
"R",
"=",
"W_sr",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"*",
"cho_solve",
"(",
"(",
"L",
",",
"True",
")",
",",
"np",
".",
"diag",
"(",
"W_sr",
")",
")",
"# Line 7",
"C",
"=",
"solve",
"(",
"L",
",",
"W_sr",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"*",
"K",
")",
"# Line 8",
"# Line 9: (use einsum to compute np.diag(C.T.dot(C))))",
"s_2",
"=",
"-",
"0.5",
"*",
"(",
"np",
".",
"diag",
"(",
"K",
")",
"-",
"np",
".",
"einsum",
"(",
"'ij, ij -> j'",
",",
"C",
",",
"C",
")",
")",
"*",
"(",
"pi",
"*",
"(",
"1",
"-",
"pi",
")",
"*",
"(",
"1",
"-",
"2",
"*",
"pi",
")",
")",
"# third derivative",
"for",
"j",
"in",
"range",
"(",
"d_Z",
".",
"shape",
"[",
"0",
"]",
")",
":",
"C",
"=",
"K_gradient",
"[",
":",
",",
":",
",",
"j",
"]",
"# Line 11",
"# Line 12: (R.T.ravel().dot(C.ravel()) = np.trace(R.dot(C)))",
"s_1",
"=",
".5",
"*",
"a",
".",
"T",
".",
"dot",
"(",
"C",
")",
".",
"dot",
"(",
"a",
")",
"-",
".5",
"*",
"R",
".",
"T",
".",
"ravel",
"(",
")",
".",
"dot",
"(",
"C",
".",
"ravel",
"(",
")",
")",
"b",
"=",
"C",
".",
"dot",
"(",
"self",
".",
"y_train_",
"-",
"pi",
")",
"# Line 13",
"s_3",
"=",
"b",
"-",
"K",
".",
"dot",
"(",
"R",
".",
"dot",
"(",
"b",
")",
")",
"# Line 14",
"d_Z",
"[",
"j",
"]",
"=",
"s_1",
"+",
"s_2",
".",
"T",
".",
"dot",
"(",
"s_3",
")",
"# Line 15",
"return",
"Z",
",",
"d_Z"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/gaussian_process/_gpc.py#L317-L391 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/utils.py | python | read_compile_settings_file | (settings_file, configuration) | return result | Read in a compile settings file and extract the dictionary of known values
:param settings_file:
:param configuration:
:return: | Read in a compile settings file and extract the dictionary of known values
:param settings_file:
:param configuration:
:return: | [
"Read",
"in",
"a",
"compile",
"settings",
"file",
"and",
"extract",
"the",
"dictionary",
"of",
"known",
"values",
":",
"param",
"settings_file",
":",
":",
"param",
"configuration",
":",
":",
"return",
":"
] | def read_compile_settings_file(settings_file, configuration):
"""
Read in a compile settings file and extract the dictionary of known values
:param settings_file:
:param configuration:
:return:
"""
def _read_config_item(config_settings, key, evaluated_keys={}, pending_keys=[]):
if key in evaluated_keys:
return evaluated_keys[key]
read_values = config_settings[key]
evaluated_values = []
for read_value in read_values:
if read_value.startswith('@'):
alias_key = read_value[1:]
if alias_key not in config_settings:
raise ValueError("Invalid alias key '{}' in section '{}'".format(read_value, key))
if alias_key in pending_keys:
raise ValueError("Invalid alias key '{}' in section '{}' creates a circular reference.".format(read_value, key))
elif alias_key not in evaluated_keys:
pending_keys.append(key)
evaluated_values += _read_config_item(config_settings, alias_key, evaluated_keys, pending_keys)
pending_keys.remove(key)
else:
evaluated_values += evaluated_keys[alias_key]
else:
evaluated_values.append(read_value)
evaluated_keys[key] = evaluated_values
return evaluated_values
def _merge_config(left_config, right_config):
if right_config:
merged_config = {}
for left_key, left_values in list(left_config.items()):
merged_config[left_key] = left_values[:]
for right_key, right_values in list(right_config.items()):
if right_key in merged_config:
merged_config[right_key] += [merge_item for merge_item in right_values if merge_item not in merged_config[right_key]]
else:
merged_config[right_key] = right_values[:]
return merged_config
else:
return left_config
def _read_config_section(settings, section_name, default_section_name):
if default_section_name:
default_dict = _read_config_section(settings, default_section_name, None)
else:
default_dict = None
if section_name not in settings:
return default_dict
section_settings = settings.get(section_name)
result = {}
for key in list(section_settings.keys()):
result[key] = _read_config_item(section_settings, key)
merged_result = _merge_config(result, default_dict)
return merged_result
settings_json = parse_json_file(settings_file, allow_non_standard_comments=True)
result = _read_config_section(settings_json, configuration, 'common')
return result | [
"def",
"read_compile_settings_file",
"(",
"settings_file",
",",
"configuration",
")",
":",
"def",
"_read_config_item",
"(",
"config_settings",
",",
"key",
",",
"evaluated_keys",
"=",
"{",
"}",
",",
"pending_keys",
"=",
"[",
"]",
")",
":",
"if",
"key",
"in",
"evaluated_keys",
":",
"return",
"evaluated_keys",
"[",
"key",
"]",
"read_values",
"=",
"config_settings",
"[",
"key",
"]",
"evaluated_values",
"=",
"[",
"]",
"for",
"read_value",
"in",
"read_values",
":",
"if",
"read_value",
".",
"startswith",
"(",
"'@'",
")",
":",
"alias_key",
"=",
"read_value",
"[",
"1",
":",
"]",
"if",
"alias_key",
"not",
"in",
"config_settings",
":",
"raise",
"ValueError",
"(",
"\"Invalid alias key '{}' in section '{}'\"",
".",
"format",
"(",
"read_value",
",",
"key",
")",
")",
"if",
"alias_key",
"in",
"pending_keys",
":",
"raise",
"ValueError",
"(",
"\"Invalid alias key '{}' in section '{}' creates a circular reference.\"",
".",
"format",
"(",
"read_value",
",",
"key",
")",
")",
"elif",
"alias_key",
"not",
"in",
"evaluated_keys",
":",
"pending_keys",
".",
"append",
"(",
"key",
")",
"evaluated_values",
"+=",
"_read_config_item",
"(",
"config_settings",
",",
"alias_key",
",",
"evaluated_keys",
",",
"pending_keys",
")",
"pending_keys",
".",
"remove",
"(",
"key",
")",
"else",
":",
"evaluated_values",
"+=",
"evaluated_keys",
"[",
"alias_key",
"]",
"else",
":",
"evaluated_values",
".",
"append",
"(",
"read_value",
")",
"evaluated_keys",
"[",
"key",
"]",
"=",
"evaluated_values",
"return",
"evaluated_values",
"def",
"_merge_config",
"(",
"left_config",
",",
"right_config",
")",
":",
"if",
"right_config",
":",
"merged_config",
"=",
"{",
"}",
"for",
"left_key",
",",
"left_values",
"in",
"list",
"(",
"left_config",
".",
"items",
"(",
")",
")",
":",
"merged_config",
"[",
"left_key",
"]",
"=",
"left_values",
"[",
":",
"]",
"for",
"right_key",
",",
"right_values",
"in",
"list",
"(",
"right_config",
".",
"items",
"(",
")",
")",
":",
"if",
"right_key",
"in",
"merged_config",
":",
"merged_config",
"[",
"right_key",
"]",
"+=",
"[",
"merge_item",
"for",
"merge_item",
"in",
"right_values",
"if",
"merge_item",
"not",
"in",
"merged_config",
"[",
"right_key",
"]",
"]",
"else",
":",
"merged_config",
"[",
"right_key",
"]",
"=",
"right_values",
"[",
":",
"]",
"return",
"merged_config",
"else",
":",
"return",
"left_config",
"def",
"_read_config_section",
"(",
"settings",
",",
"section_name",
",",
"default_section_name",
")",
":",
"if",
"default_section_name",
":",
"default_dict",
"=",
"_read_config_section",
"(",
"settings",
",",
"default_section_name",
",",
"None",
")",
"else",
":",
"default_dict",
"=",
"None",
"if",
"section_name",
"not",
"in",
"settings",
":",
"return",
"default_dict",
"section_settings",
"=",
"settings",
".",
"get",
"(",
"section_name",
")",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"list",
"(",
"section_settings",
".",
"keys",
"(",
")",
")",
":",
"result",
"[",
"key",
"]",
"=",
"_read_config_item",
"(",
"section_settings",
",",
"key",
")",
"merged_result",
"=",
"_merge_config",
"(",
"result",
",",
"default_dict",
")",
"return",
"merged_result",
"settings_json",
"=",
"parse_json_file",
"(",
"settings_file",
",",
"allow_non_standard_comments",
"=",
"True",
")",
"result",
"=",
"_read_config_section",
"(",
"settings_json",
",",
"configuration",
",",
"'common'",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/utils.py#L536-L604 | |
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/python/flatbuffers/flexbuffers.py | python | TypedVector.Value | (self) | Returns underlying data as list object. | Returns underlying data as list object. | [
"Returns",
"underlying",
"data",
"as",
"list",
"object",
"."
] | def Value(self):
"""Returns underlying data as list object."""
if not self:
return []
if self._element_type is Type.BOOL:
return [bool(e) for e in _UnpackVector(U, self.Bytes, len(self))]
elif self._element_type is Type.INT:
return list(_UnpackVector(I, self.Bytes, len(self)))
elif self._element_type is Type.UINT:
return list(_UnpackVector(U, self.Bytes, len(self)))
elif self._element_type is Type.FLOAT:
return list(_UnpackVector(F, self.Bytes, len(self)))
elif self._element_type is Type.KEY:
return [e.AsKey for e in self]
elif self._element_type is Type.STRING:
return [e.AsString for e in self]
else:
raise TypeError('unsupported element_type: %s' % self._element_type) | [
"def",
"Value",
"(",
"self",
")",
":",
"if",
"not",
"self",
":",
"return",
"[",
"]",
"if",
"self",
".",
"_element_type",
"is",
"Type",
".",
"BOOL",
":",
"return",
"[",
"bool",
"(",
"e",
")",
"for",
"e",
"in",
"_UnpackVector",
"(",
"U",
",",
"self",
".",
"Bytes",
",",
"len",
"(",
"self",
")",
")",
"]",
"elif",
"self",
".",
"_element_type",
"is",
"Type",
".",
"INT",
":",
"return",
"list",
"(",
"_UnpackVector",
"(",
"I",
",",
"self",
".",
"Bytes",
",",
"len",
"(",
"self",
")",
")",
")",
"elif",
"self",
".",
"_element_type",
"is",
"Type",
".",
"UINT",
":",
"return",
"list",
"(",
"_UnpackVector",
"(",
"U",
",",
"self",
".",
"Bytes",
",",
"len",
"(",
"self",
")",
")",
")",
"elif",
"self",
".",
"_element_type",
"is",
"Type",
".",
"FLOAT",
":",
"return",
"list",
"(",
"_UnpackVector",
"(",
"F",
",",
"self",
".",
"Bytes",
",",
"len",
"(",
"self",
")",
")",
")",
"elif",
"self",
".",
"_element_type",
"is",
"Type",
".",
"KEY",
":",
"return",
"[",
"e",
".",
"AsKey",
"for",
"e",
"in",
"self",
"]",
"elif",
"self",
".",
"_element_type",
"is",
"Type",
".",
"STRING",
":",
"return",
"[",
"e",
".",
"AsString",
"for",
"e",
"in",
"self",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"'unsupported element_type: %s'",
"%",
"self",
".",
"_element_type",
")"
] | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/flexbuffers.py#L479-L497 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/xml/sax/handler.py | python | ContentHandler.characters | (self, content) | Receive notification of character data.
The Parser will call this method to report each chunk of
character data. SAX parsers may return all contiguous
character data in a single chunk, or they may split it into
several chunks; however, all of the characters in any single
event must come from the same external entity so that the
Locator provides useful information. | Receive notification of character data. | [
"Receive",
"notification",
"of",
"character",
"data",
"."
] | def characters(self, content):
"""Receive notification of character data.
The Parser will call this method to report each chunk of
character data. SAX parsers may return all contiguous
character data in a single chunk, or they may split it into
several chunks; however, all of the characters in any single
event must come from the same external entity so that the
Locator provides useful information.""" | [
"def",
"characters",
"(",
"self",
",",
"content",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/handler.py#L158-L166 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/cookies.py | python | RequestsCookieJar.iterkeys | (self) | Dict-like iterkeys() that returns an iterator of names of cookies from the jar.
See itervalues() and iteritems(). | Dict-like iterkeys() that returns an iterator of names of cookies from the jar.
See itervalues() and iteritems(). | [
"Dict",
"-",
"like",
"iterkeys",
"()",
"that",
"returns",
"an",
"iterator",
"of",
"names",
"of",
"cookies",
"from",
"the",
"jar",
".",
"See",
"itervalues",
"()",
"and",
"iteritems",
"()",
"."
] | def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies from the jar.
See itervalues() and iteritems()."""
for cookie in iter(self):
yield cookie.name | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"name"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/cookies.py#L201-L205 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/ObjectsFem.py | python | makeConstraintSelfWeight | (
doc,
name="ConstraintSelfWeight"
) | return obj | makeConstraintSelfWeight(document, [name]):
creates a self weight object to define a gravity load | makeConstraintSelfWeight(document, [name]):
creates a self weight object to define a gravity load | [
"makeConstraintSelfWeight",
"(",
"document",
"[",
"name",
"]",
")",
":",
"creates",
"a",
"self",
"weight",
"object",
"to",
"define",
"a",
"gravity",
"load"
] | def makeConstraintSelfWeight(
doc,
name="ConstraintSelfWeight"
):
"""makeConstraintSelfWeight(document, [name]):
creates a self weight object to define a gravity load"""
obj = doc.addObject("Fem::ConstraintPython", name)
from femobjects import constraint_selfweight
constraint_selfweight.ConstraintSelfWeight(obj)
if FreeCAD.GuiUp:
from femviewprovider import view_constraint_selfweight
view_constraint_selfweight.VPConstraintSelfWeight(
obj.ViewObject
)
return obj | [
"def",
"makeConstraintSelfWeight",
"(",
"doc",
",",
"name",
"=",
"\"ConstraintSelfWeight\"",
")",
":",
"obj",
"=",
"doc",
".",
"addObject",
"(",
"\"Fem::ConstraintPython\"",
",",
"name",
")",
"from",
"femobjects",
"import",
"constraint_selfweight",
"constraint_selfweight",
".",
"ConstraintSelfWeight",
"(",
"obj",
")",
"if",
"FreeCAD",
".",
"GuiUp",
":",
"from",
"femviewprovider",
"import",
"view_constraint_selfweight",
"view_constraint_selfweight",
".",
"VPConstraintSelfWeight",
"(",
"obj",
".",
"ViewObject",
")",
"return",
"obj"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L271-L285 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/data_flow_ops.py | python | ConditionalAccumulator.apply_grad | (self, grad, local_step=0, name=None) | return gen_data_flow_ops.accumulator_apply_gradient(
self._accumulator_ref, local_step=local_step, gradient=grad, name=name) | Attempts to apply a gradient to the accumulator.
The attempt is silently dropped if the gradient is stale, i.e., local_step
is less than the accumulator's global time step.
Args:
grad: The gradient tensor to be applied.
local_step: Time step at which the gradient was computed.
name: Optional name for the operation.
Returns:
The operation that (conditionally) applies a gradient to the accumulator.
Raises:
ValueError: If grad is of the wrong shape | Attempts to apply a gradient to the accumulator. | [
"Attempts",
"to",
"apply",
"a",
"gradient",
"to",
"the",
"accumulator",
"."
] | def apply_grad(self, grad, local_step=0, name=None):
"""Attempts to apply a gradient to the accumulator.
The attempt is silently dropped if the gradient is stale, i.e., local_step
is less than the accumulator's global time step.
Args:
grad: The gradient tensor to be applied.
local_step: Time step at which the gradient was computed.
name: Optional name for the operation.
Returns:
The operation that (conditionally) applies a gradient to the accumulator.
Raises:
ValueError: If grad is of the wrong shape
"""
grad = ops.convert_to_tensor(grad, self._dtype)
grad.get_shape().assert_is_compatible_with(self._shape)
local_step = math_ops.to_int64(ops.convert_to_tensor(local_step))
return gen_data_flow_ops.accumulator_apply_gradient(
self._accumulator_ref, local_step=local_step, gradient=grad, name=name) | [
"def",
"apply_grad",
"(",
"self",
",",
"grad",
",",
"local_step",
"=",
"0",
",",
"name",
"=",
"None",
")",
":",
"grad",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"grad",
",",
"self",
".",
"_dtype",
")",
"grad",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"self",
".",
"_shape",
")",
"local_step",
"=",
"math_ops",
".",
"to_int64",
"(",
"ops",
".",
"convert_to_tensor",
"(",
"local_step",
")",
")",
"return",
"gen_data_flow_ops",
".",
"accumulator_apply_gradient",
"(",
"self",
".",
"_accumulator_ref",
",",
"local_step",
"=",
"local_step",
",",
"gradient",
"=",
"grad",
",",
"name",
"=",
"name",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L1161-L1182 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/control_flow_ops.py | python | exit | (data, name=None) | Exits the current frame to its parent frame.
Exit makes its input `data` available to the parent frame.
Args:
data: The tensor to be made available to the parent frame.
name: A name for this operation (optional).
Returns:
The same tensor as `data`. | Exits the current frame to its parent frame. | [
"Exits",
"the",
"current",
"frame",
"to",
"its",
"parent",
"frame",
"."
] | def exit(data, name=None):
"""Exits the current frame to its parent frame.
Exit makes its input `data` available to the parent frame.
Args:
data: The tensor to be made available to the parent frame.
name: A name for this operation (optional).
Returns:
The same tensor as `data`.
"""
data = ops.convert_to_tensor_or_indexed_slices(data, as_ref=True)
if isinstance(data, ops.Tensor):
if data.dtype.is_ref_dtype:
return gen_control_flow_ops._ref_exit(data, name)
else:
return gen_control_flow_ops._exit(data, name)
else:
if not isinstance(data, (ops.IndexedSlices, ops.SparseTensor)):
raise TypeError("Type %s not supported" % type(data))
values = exit(data.values, name=name)
indices = gen_control_flow_ops._exit(data.indices, name="indices")
if isinstance(data, ops.IndexedSlices):
dense_shape = data.dense_shape
if dense_shape is not None:
dense_shape = gen_control_flow_ops._exit(dense_shape, name)
return ops.IndexedSlices(values, indices, dense_shape)
else:
dense_shape = gen_control_flow_ops._exit(data.shape, name)
return ops.SparseTensor(indices, values, dense_shape) | [
"def",
"exit",
"(",
"data",
",",
"name",
"=",
"None",
")",
":",
"data",
"=",
"ops",
".",
"convert_to_tensor_or_indexed_slices",
"(",
"data",
",",
"as_ref",
"=",
"True",
")",
"if",
"isinstance",
"(",
"data",
",",
"ops",
".",
"Tensor",
")",
":",
"if",
"data",
".",
"dtype",
".",
"is_ref_dtype",
":",
"return",
"gen_control_flow_ops",
".",
"_ref_exit",
"(",
"data",
",",
"name",
")",
"else",
":",
"return",
"gen_control_flow_ops",
".",
"_exit",
"(",
"data",
",",
"name",
")",
"else",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"ops",
".",
"IndexedSlices",
",",
"ops",
".",
"SparseTensor",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Type %s not supported\"",
"%",
"type",
"(",
"data",
")",
")",
"values",
"=",
"exit",
"(",
"data",
".",
"values",
",",
"name",
"=",
"name",
")",
"indices",
"=",
"gen_control_flow_ops",
".",
"_exit",
"(",
"data",
".",
"indices",
",",
"name",
"=",
"\"indices\"",
")",
"if",
"isinstance",
"(",
"data",
",",
"ops",
".",
"IndexedSlices",
")",
":",
"dense_shape",
"=",
"data",
".",
"dense_shape",
"if",
"dense_shape",
"is",
"not",
"None",
":",
"dense_shape",
"=",
"gen_control_flow_ops",
".",
"_exit",
"(",
"dense_shape",
",",
"name",
")",
"return",
"ops",
".",
"IndexedSlices",
"(",
"values",
",",
"indices",
",",
"dense_shape",
")",
"else",
":",
"dense_shape",
"=",
"gen_control_flow_ops",
".",
"_exit",
"(",
"data",
".",
"shape",
",",
"name",
")",
"return",
"ops",
".",
"SparseTensor",
"(",
"indices",
",",
"values",
",",
"dense_shape",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/control_flow_ops.py#L254-L284 | ||
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/prediction/multiple_gpu_estimator/mlp_data.py | python | MlpDataSet.parser | (self, serialized_example) | return image, label | Parses a single tf.Example into image and label tensors. | Parses a single tf.Example into image and label tensors. | [
"Parses",
"a",
"single",
"tf",
".",
"Example",
"into",
"image",
"and",
"label",
"tensors",
"."
] | def parser(self, serialized_example):
"""Parses a single tf.Example into image and label tensors."""
# Dimensions of the images in the CIFAR-10 dataset.
features = tf.parse_single_example(
serialized_example,
features={
'data': tf.FixedLenFeature([62], tf.float32),
'label': tf.FixedLenFeature([1], tf.float32),
})
image = features['data']
label = tf.cast(features['label'], tf.int32)+1
return image, label | [
"def",
"parser",
"(",
"self",
",",
"serialized_example",
")",
":",
"# Dimensions of the images in the CIFAR-10 dataset.",
"features",
"=",
"tf",
".",
"parse_single_example",
"(",
"serialized_example",
",",
"features",
"=",
"{",
"'data'",
":",
"tf",
".",
"FixedLenFeature",
"(",
"[",
"62",
"]",
",",
"tf",
".",
"float32",
")",
",",
"'label'",
":",
"tf",
".",
"FixedLenFeature",
"(",
"[",
"1",
"]",
",",
"tf",
".",
"float32",
")",
",",
"}",
")",
"image",
"=",
"features",
"[",
"'data'",
"]",
"label",
"=",
"tf",
".",
"cast",
"(",
"features",
"[",
"'label'",
"]",
",",
"tf",
".",
"int32",
")",
"+",
"1",
"return",
"image",
",",
"label"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/prediction/multiple_gpu_estimator/mlp_data.py#L59-L72 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py | python | search_annotations | (query='', limit=None, offset=None, strict=False, **fields) | return _do_mb_search('annotation', query, fields, limit, offset, strict) | Search for annotations and return a dict with an 'annotation-list' key.
*Available search fields*: {fields} | Search for annotations and return a dict with an 'annotation-list' key. | [
"Search",
"for",
"annotations",
"and",
"return",
"a",
"dict",
"with",
"an",
"annotation",
"-",
"list",
"key",
"."
] | def search_annotations(query='', limit=None, offset=None, strict=False, **fields):
"""Search for annotations and return a dict with an 'annotation-list' key.
*Available search fields*: {fields}"""
return _do_mb_search('annotation', query, fields, limit, offset, strict) | [
"def",
"search_annotations",
"(",
"query",
"=",
"''",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"*",
"*",
"fields",
")",
":",
"return",
"_do_mb_search",
"(",
"'annotation'",
",",
"query",
",",
"fields",
",",
"limit",
",",
"offset",
",",
"strict",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py#L897-L901 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/training/saver.py | python | Saver.as_saver_def | (self) | return self.saver_def | Generates a `SaverDef` representation of this saver.
Returns:
A `SaverDef` proto. | Generates a `SaverDef` representation of this saver. | [
"Generates",
"a",
"SaverDef",
"representation",
"of",
"this",
"saver",
"."
] | def as_saver_def(self):
"""Generates a `SaverDef` representation of this saver.
Returns:
A `SaverDef` proto.
"""
return self.saver_def | [
"def",
"as_saver_def",
"(",
"self",
")",
":",
"return",
"self",
".",
"saver_def"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/saver.py#L1284-L1290 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/boto3/__init__.py | python | setup_default_session | (**kwargs) | Set up a default session, passing through any parameters to the session
constructor. There is no need to call this unless you wish to pass custom
parameters, because a default session will be created for you. | Set up a default session, passing through any parameters to the session
constructor. There is no need to call this unless you wish to pass custom
parameters, because a default session will be created for you. | [
"Set",
"up",
"a",
"default",
"session",
"passing",
"through",
"any",
"parameters",
"to",
"the",
"session",
"constructor",
".",
"There",
"is",
"no",
"need",
"to",
"call",
"this",
"unless",
"you",
"wish",
"to",
"pass",
"custom",
"parameters",
"because",
"a",
"default",
"session",
"will",
"be",
"created",
"for",
"you",
"."
] | def setup_default_session(**kwargs):
"""
Set up a default session, passing through any parameters to the session
constructor. There is no need to call this unless you wish to pass custom
parameters, because a default session will be created for you.
"""
global DEFAULT_SESSION
DEFAULT_SESSION = Session(**kwargs) | [
"def",
"setup_default_session",
"(",
"*",
"*",
"kwargs",
")",
":",
"global",
"DEFAULT_SESSION",
"DEFAULT_SESSION",
"=",
"Session",
"(",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/__init__.py#L27-L34 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/pytables.py | python | Table.write_metadata | (self, key: str, values: np.ndarray) | Write out a metadata array to the key as a fixed-format Series.
Parameters
----------
key : str
values : ndarray | Write out a metadata array to the key as a fixed-format Series. | [
"Write",
"out",
"a",
"metadata",
"array",
"to",
"the",
"key",
"as",
"a",
"fixed",
"-",
"format",
"Series",
"."
] | def write_metadata(self, key: str, values: np.ndarray):
"""
Write out a metadata array to the key as a fixed-format Series.
Parameters
----------
key : str
values : ndarray
"""
# error: Incompatible types in assignment (expression has type
# "Series", variable has type "ndarray")
values = Series(values) # type: ignore[assignment]
# error: Value of type variable "FrameOrSeries" of "put" of "HDFStore"
# cannot be "ndarray"
self.parent.put( # type: ignore[type-var]
self._get_metadata_path(key),
values,
format="table",
encoding=self.encoding,
errors=self.errors,
nan_rep=self.nan_rep,
) | [
"def",
"write_metadata",
"(",
"self",
",",
"key",
":",
"str",
",",
"values",
":",
"np",
".",
"ndarray",
")",
":",
"# error: Incompatible types in assignment (expression has type",
"# \"Series\", variable has type \"ndarray\")",
"values",
"=",
"Series",
"(",
"values",
")",
"# type: ignore[assignment]",
"# error: Value of type variable \"FrameOrSeries\" of \"put\" of \"HDFStore\"",
"# cannot be \"ndarray\"",
"self",
".",
"parent",
".",
"put",
"(",
"# type: ignore[type-var]",
"self",
".",
"_get_metadata_path",
"(",
"key",
")",
",",
"values",
",",
"format",
"=",
"\"table\"",
",",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
",",
"nan_rep",
"=",
"self",
".",
"nan_rep",
",",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L3464-L3485 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | Choice.GetCurrentSelection | (*args, **kwargs) | return _controls_.Choice_GetCurrentSelection(*args, **kwargs) | GetCurrentSelection(self) -> int
Unlike `GetSelection` which only returns the accepted selection value,
i.e. the selection in the control once the user closes the dropdown
list, this function returns the current selection. That is, while the
dropdown list is shown, it returns the currently selected item in
it. When it is not shown, its result is the same as for the other
function. | GetCurrentSelection(self) -> int | [
"GetCurrentSelection",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCurrentSelection(*args, **kwargs):
"""
GetCurrentSelection(self) -> int
Unlike `GetSelection` which only returns the accepted selection value,
i.e. the selection in the control once the user closes the dropdown
list, this function returns the current selection. That is, while the
dropdown list is shown, it returns the currently selected item in
it. When it is not shown, its result is the same as for the other
function.
"""
return _controls_.Choice_GetCurrentSelection(*args, **kwargs) | [
"def",
"GetCurrentSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Choice_GetCurrentSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L514-L525 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xmlrpc/server.py | python | ServerHTMLDoc.docroutine | (self, object, name, mod=None,
funcs={}, classes={}, methods={}, cl=None) | return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) | Produce HTML documentation for a function or method object. | Produce HTML documentation for a function or method object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"function",
"or",
"method",
"object",
"."
] | def docroutine(self, object, name, mod=None,
funcs={}, classes={}, methods={}, cl=None):
"""Produce HTML documentation for a function or method object."""
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
title = '<a name="%s"><strong>%s</strong></a>' % (
self.escape(anchor), self.escape(name))
if callable(object):
argspec = str(signature(object))
else:
argspec = '(...)'
if isinstance(object, tuple):
argspec = object[0] or argspec
docstring = object[1] or ""
else:
docstring = pydoc.getdoc(object)
decl = title + argspec + (note and self.grey(
'<font face="helvetica, arial">%s</font>' % note))
doc = self.markup(
docstring, self.preformat, funcs, classes, methods)
doc = doc and '<dd><tt>%s</tt></dd>' % doc
return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) | [
"def",
"docroutine",
"(",
"self",
",",
"object",
",",
"name",
",",
"mod",
"=",
"None",
",",
"funcs",
"=",
"{",
"}",
",",
"classes",
"=",
"{",
"}",
",",
"methods",
"=",
"{",
"}",
",",
"cl",
"=",
"None",
")",
":",
"anchor",
"=",
"(",
"cl",
"and",
"cl",
".",
"__name__",
"or",
"''",
")",
"+",
"'-'",
"+",
"name",
"note",
"=",
"''",
"title",
"=",
"'<a name=\"%s\"><strong>%s</strong></a>'",
"%",
"(",
"self",
".",
"escape",
"(",
"anchor",
")",
",",
"self",
".",
"escape",
"(",
"name",
")",
")",
"if",
"callable",
"(",
"object",
")",
":",
"argspec",
"=",
"str",
"(",
"signature",
"(",
"object",
")",
")",
"else",
":",
"argspec",
"=",
"'(...)'",
"if",
"isinstance",
"(",
"object",
",",
"tuple",
")",
":",
"argspec",
"=",
"object",
"[",
"0",
"]",
"or",
"argspec",
"docstring",
"=",
"object",
"[",
"1",
"]",
"or",
"\"\"",
"else",
":",
"docstring",
"=",
"pydoc",
".",
"getdoc",
"(",
"object",
")",
"decl",
"=",
"title",
"+",
"argspec",
"+",
"(",
"note",
"and",
"self",
".",
"grey",
"(",
"'<font face=\"helvetica, arial\">%s</font>'",
"%",
"note",
")",
")",
"doc",
"=",
"self",
".",
"markup",
"(",
"docstring",
",",
"self",
".",
"preformat",
",",
"funcs",
",",
"classes",
",",
"methods",
")",
"doc",
"=",
"doc",
"and",
"'<dd><tt>%s</tt></dd>'",
"%",
"doc",
"return",
"'<dl><dt>%s</dt>%s</dl>\\n'",
"%",
"(",
"decl",
",",
"doc",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xmlrpc/server.py#L765-L792 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | HtmlWinParser.GetCharWidth | (*args, **kwargs) | return _html.HtmlWinParser_GetCharWidth(*args, **kwargs) | GetCharWidth(self) -> int | GetCharWidth(self) -> int | [
"GetCharWidth",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCharWidth(*args, **kwargs):
"""GetCharWidth(self) -> int"""
return _html.HtmlWinParser_GetCharWidth(*args, **kwargs) | [
"def",
"GetCharWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlWinParser_GetCharWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L256-L258 | |
xieyufei1993/FOTS | 9881966697fd5e2936d2cca8aa04309e4b64f77c | utils/bbox.py | python | Toolbox.resize_image | (im, max_side_len = 2400) | return im, (ratio_h, ratio_w) | resize image to a size multiple of 32 which is required by the network
:param im: the resized image
:param max_side_len: limit of max image size to avoid out of memory in gpu
:return: the resized image and the resize ratio | resize image to a size multiple of 32 which is required by the network
:param im: the resized image
:param max_side_len: limit of max image size to avoid out of memory in gpu
:return: the resized image and the resize ratio | [
"resize",
"image",
"to",
"a",
"size",
"multiple",
"of",
"32",
"which",
"is",
"required",
"by",
"the",
"network",
":",
"param",
"im",
":",
"the",
"resized",
"image",
":",
"param",
"max_side_len",
":",
"limit",
"of",
"max",
"image",
"size",
"to",
"avoid",
"out",
"of",
"memory",
"in",
"gpu",
":",
"return",
":",
"the",
"resized",
"image",
"and",
"the",
"resize",
"ratio"
] | def resize_image(im, max_side_len = 2400):
'''
resize image to a size multiple of 32 which is required by the network
:param im: the resized image
:param max_side_len: limit of max image size to avoid out of memory in gpu
:return: the resized image and the resize ratio
'''
h, w, _ = im.shape
resize_w = w
resize_h = h
# limit the max side
if max(resize_h, resize_w) > max_side_len:
ratio = float(max_side_len) / resize_h if resize_h > resize_w else float(max_side_len) / resize_w
else:
ratio = 1.
resize_h = int(resize_h * ratio)
resize_w = int(resize_w * ratio)
resize_h = resize_h if resize_h % 32 == 0 else (resize_h // 32 - 1) * 32
resize_w = resize_w if resize_w % 32 == 0 else (resize_w // 32 - 1) * 32
im = cv2.resize(im, (int(resize_w), int(resize_h)))
ratio_h = resize_h / float(h)
ratio_w = resize_w / float(w)
return im, (ratio_h, ratio_w) | [
"def",
"resize_image",
"(",
"im",
",",
"max_side_len",
"=",
"2400",
")",
":",
"h",
",",
"w",
",",
"_",
"=",
"im",
".",
"shape",
"resize_w",
"=",
"w",
"resize_h",
"=",
"h",
"# limit the max side",
"if",
"max",
"(",
"resize_h",
",",
"resize_w",
")",
">",
"max_side_len",
":",
"ratio",
"=",
"float",
"(",
"max_side_len",
")",
"/",
"resize_h",
"if",
"resize_h",
">",
"resize_w",
"else",
"float",
"(",
"max_side_len",
")",
"/",
"resize_w",
"else",
":",
"ratio",
"=",
"1.",
"resize_h",
"=",
"int",
"(",
"resize_h",
"*",
"ratio",
")",
"resize_w",
"=",
"int",
"(",
"resize_w",
"*",
"ratio",
")",
"resize_h",
"=",
"resize_h",
"if",
"resize_h",
"%",
"32",
"==",
"0",
"else",
"(",
"resize_h",
"//",
"32",
"-",
"1",
")",
"*",
"32",
"resize_w",
"=",
"resize_w",
"if",
"resize_w",
"%",
"32",
"==",
"0",
"else",
"(",
"resize_w",
"//",
"32",
"-",
"1",
")",
"*",
"32",
"im",
"=",
"cv2",
".",
"resize",
"(",
"im",
",",
"(",
"int",
"(",
"resize_w",
")",
",",
"int",
"(",
"resize_h",
")",
")",
")",
"ratio_h",
"=",
"resize_h",
"/",
"float",
"(",
"h",
")",
"ratio_w",
"=",
"resize_w",
"/",
"float",
"(",
"w",
")",
"return",
"im",
",",
"(",
"ratio_h",
",",
"ratio_w",
")"
] | https://github.com/xieyufei1993/FOTS/blob/9881966697fd5e2936d2cca8aa04309e4b64f77c/utils/bbox.py#L136-L163 | |
LisaAnne/lisa-caffe-public | 49b8643ddef23a4f6120017968de30c45e693f59 | scripts/cpp_lint.py | python | CheckCaffeDataLayerSetUp | (filename, clean_lines, linenum, error) | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | [
"Except",
"the",
"base",
"classes",
"Caffe",
"DataLayer",
"should",
"define",
"DataLayerSetUp",
"instead",
"of",
"LayerSetUp",
".",
"The",
"base",
"DataLayers",
"define",
"common",
"SetUp",
"steps",
"the",
"subclasses",
"should",
"not",
"override",
"them",
".",
"Args",
":",
"filename",
":",
"The",
"name",
"of",
"the",
"current",
"file",
".",
"clean_lines",
":",
"A",
"CleansedLines",
"instance",
"containing",
"the",
"file",
".",
"linenum",
":",
"The",
"number",
"of",
"the",
"line",
"to",
"check",
".",
"error",
":",
"The",
"function",
"to",
"call",
"with",
"any",
"errors",
"found",
"."
] | def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error):
"""Except the base classes, Caffe DataLayer should define DataLayerSetUp
instead of LayerSetUp.
The base DataLayers define common SetUp steps, the subclasses should
not override them.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
ix = line.find('DataLayer<Dtype>::LayerSetUp')
if ix >= 0 and (
line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or
line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.')
ix = line.find('DataLayer<Dtype>::DataLayerSetUp')
if ix >= 0 and (
line.find('void Base') == -1 and
line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and
line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1):
error(filename, linenum, 'caffe/data_layer_setup', 2,
'Except the base classes, Caffe DataLayer should define'
+ ' DataLayerSetUp instead of LayerSetUp. The base DataLayers'
+ ' define common SetUp steps, the subclasses should'
+ ' not override them.') | [
"def",
"CheckCaffeDataLayerSetUp",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"ix",
"=",
"line",
".",
"find",
"(",
"'DataLayer<Dtype>::LayerSetUp'",
")",
"if",
"ix",
">=",
"0",
"and",
"(",
"line",
".",
"find",
"(",
"'void DataLayer<Dtype>::LayerSetUp'",
")",
"!=",
"-",
"1",
"or",
"line",
".",
"find",
"(",
"'void ImageDataLayer<Dtype>::LayerSetUp'",
")",
"!=",
"-",
"1",
"or",
"line",
".",
"find",
"(",
"'void MemoryDataLayer<Dtype>::LayerSetUp'",
")",
"!=",
"-",
"1",
"or",
"line",
".",
"find",
"(",
"'void WindowDataLayer<Dtype>::LayerSetUp'",
")",
"!=",
"-",
"1",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'caffe/data_layer_setup'",
",",
"2",
",",
"'Except the base classes, Caffe DataLayer should define'",
"+",
"' DataLayerSetUp instead of LayerSetUp. The base DataLayers'",
"+",
"' define common SetUp steps, the subclasses should'",
"+",
"' not override them.'",
")",
"ix",
"=",
"line",
".",
"find",
"(",
"'DataLayer<Dtype>::DataLayerSetUp'",
")",
"if",
"ix",
">=",
"0",
"and",
"(",
"line",
".",
"find",
"(",
"'void Base'",
")",
"==",
"-",
"1",
"and",
"line",
".",
"find",
"(",
"'void DataLayer<Dtype>::DataLayerSetUp'",
")",
"==",
"-",
"1",
"and",
"line",
".",
"find",
"(",
"'void ImageDataLayer<Dtype>::DataLayerSetUp'",
")",
"==",
"-",
"1",
"and",
"line",
".",
"find",
"(",
"'void MemoryDataLayer<Dtype>::DataLayerSetUp'",
")",
"==",
"-",
"1",
"and",
"line",
".",
"find",
"(",
"'void WindowDataLayer<Dtype>::DataLayerSetUp'",
")",
"==",
"-",
"1",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'caffe/data_layer_setup'",
",",
"2",
",",
"'Except the base classes, Caffe DataLayer should define'",
"+",
"' DataLayerSetUp instead of LayerSetUp. The base DataLayers'",
"+",
"' define common SetUp steps, the subclasses should'",
"+",
"' not override them.'",
")"
] | https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/scripts/cpp_lint.py#L1595-L1631 | ||
uncrustify/uncrustify | 719cf9d153a9ec14be8d5f01536121ced71d8bc9 | scripts/option_reducer.py | python | same_expected_generated | (formatted_path, unc_bin_path, cfg_file_path,
input_path, lang=None) | return True if formatted_string == expected_string else False | Calls uncrustify and compares its generated output with the content of a
file
Parameters
----------------------------------------------------------------------------
:param formatted_path: str
path to a file containing the expected content
:params unc_bin_path, cfg_file_path, input_path, lang: str, str, str,
str / None
see uncrustify()
:return: bool
----------------------------------------------------------------------------
True if the strings match, False otherwise | Calls uncrustify and compares its generated output with the content of a
file | [
"Calls",
"uncrustify",
"and",
"compares",
"its",
"generated",
"output",
"with",
"the",
"content",
"of",
"a",
"file"
] | def same_expected_generated(formatted_path, unc_bin_path, cfg_file_path,
input_path, lang=None):
"""
Calls uncrustify and compares its generated output with the content of a
file
Parameters
----------------------------------------------------------------------------
:param formatted_path: str
path to a file containing the expected content
:params unc_bin_path, cfg_file_path, input_path, lang: str, str, str,
str / None
see uncrustify()
:return: bool
----------------------------------------------------------------------------
True if the strings match, False otherwise
"""
expected_string = ''
with open(formatted_path, 'rb') as f:
expected_string = f.read()
formatted_string = uncrustify(unc_bin_path, cfg_file_path, input_path, lang)
return True if formatted_string == expected_string else False | [
"def",
"same_expected_generated",
"(",
"formatted_path",
",",
"unc_bin_path",
",",
"cfg_file_path",
",",
"input_path",
",",
"lang",
"=",
"None",
")",
":",
"expected_string",
"=",
"''",
"with",
"open",
"(",
"formatted_path",
",",
"'rb'",
")",
"as",
"f",
":",
"expected_string",
"=",
"f",
".",
"read",
"(",
")",
"formatted_string",
"=",
"uncrustify",
"(",
"unc_bin_path",
",",
"cfg_file_path",
",",
"input_path",
",",
"lang",
")",
"return",
"True",
"if",
"formatted_string",
"==",
"expected_string",
"else",
"False"
] | https://github.com/uncrustify/uncrustify/blob/719cf9d153a9ec14be8d5f01536121ced71d8bc9/scripts/option_reducer.py#L194-L222 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/rcnn/rcnn/dataset/imdb.py | python | IMDB.rpn_roidb | (self, gt_roidb, append_gt=False) | return roidb | get rpn roidb and ground truth roidb
:param gt_roidb: ground truth roidb
:param append_gt: append ground truth
:return: roidb of rpn | get rpn roidb and ground truth roidb
:param gt_roidb: ground truth roidb
:param append_gt: append ground truth
:return: roidb of rpn | [
"get",
"rpn",
"roidb",
"and",
"ground",
"truth",
"roidb",
":",
"param",
"gt_roidb",
":",
"ground",
"truth",
"roidb",
":",
"param",
"append_gt",
":",
"append",
"ground",
"truth",
":",
"return",
":",
"roidb",
"of",
"rpn"
] | def rpn_roidb(self, gt_roidb, append_gt=False):
"""
get rpn roidb and ground truth roidb
:param gt_roidb: ground truth roidb
:param append_gt: append ground truth
:return: roidb of rpn
"""
if append_gt:
logger.info('%s appending ground truth annotations' % self.name)
rpn_roidb = self.load_rpn_roidb(gt_roidb)
roidb = IMDB.merge_roidbs(gt_roidb, rpn_roidb)
else:
roidb = self.load_rpn_roidb(gt_roidb)
return roidb | [
"def",
"rpn_roidb",
"(",
"self",
",",
"gt_roidb",
",",
"append_gt",
"=",
"False",
")",
":",
"if",
"append_gt",
":",
"logger",
".",
"info",
"(",
"'%s appending ground truth annotations'",
"%",
"self",
".",
"name",
")",
"rpn_roidb",
"=",
"self",
".",
"load_rpn_roidb",
"(",
"gt_roidb",
")",
"roidb",
"=",
"IMDB",
".",
"merge_roidbs",
"(",
"gt_roidb",
",",
"rpn_roidb",
")",
"else",
":",
"roidb",
"=",
"self",
".",
"load_rpn_roidb",
"(",
"gt_roidb",
")",
"return",
"roidb"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/rcnn/rcnn/dataset/imdb.py#L105-L118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.