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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/sparse_ops.py | python | sparse_split | (split_dim, num_split, sp_input, name=None) | return sparse_tensors | Split a `SparseTensor` into `num_split` tensors along `split_dim`.
If the `sp_input.shape[split_dim]` is not an integer multiple of `num_split`
each slice starting from 0:`shape[split_dim] % num_split` gets extra one
dimension. For example, if `split_dim = 1` and `num_split = 2` and the
input is:
input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are:
output_tensor[0] =
[ a ]
[b c ]
output_tensor[1] =
[ d e ]
[ ]
Args:
split_dim: A 0-D `int32` `Tensor`. The dimension along which to split.
num_split: A Python integer. The number of ways to split.
sp_input: The `SparseTensor` to split.
name: A name for the operation (optional).
Returns:
`num_split` `SparseTensor` objects resulting from splitting `value`.
Raises:
TypeError: If `sp_input` is not a `SparseTensor`. | Split a `SparseTensor` into `num_split` tensors along `split_dim`. | [
"Split",
"a",
"SparseTensor",
"into",
"num_split",
"tensors",
"along",
"split_dim",
"."
] | def sparse_split(split_dim, num_split, sp_input, name=None):
"""Split a `SparseTensor` into `num_split` tensors along `split_dim`.
If the `sp_input.shape[split_dim]` is not an integer multiple of `num_split`
each slice starting from 0:`shape[split_dim] % num_split` gets extra one
dimension. For example, if `split_dim = 1` and `num_split = 2` and the
input is:
input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are:
output_tensor[0] =
[ a ]
[b c ]
output_tensor[1] =
[ d e ]
[ ]
Args:
split_dim: A 0-D `int32` `Tensor`. The dimension along which to split.
num_split: A Python integer. The number of ways to split.
sp_input: The `SparseTensor` to split.
name: A name for the operation (optional).
Returns:
`num_split` `SparseTensor` objects resulting from splitting `value`.
Raises:
TypeError: If `sp_input` is not a `SparseTensor`.
"""
sp_input = _convert_to_sparse_tensor(sp_input)
output_inds, output_vals, output_shapes = (gen_sparse_ops._sparse_split(
split_dim,
sp_input.indices,
sp_input.values,
sp_input.shape,
num_split,
name=name))
sparse_tensors = []
for i in range(0, num_split):
sparse_tensors.append(
ops.SparseTensor(output_inds[i], output_vals[i], output_shapes[i]))
return sparse_tensors | [
"def",
"sparse_split",
"(",
"split_dim",
",",
"num_split",
",",
"sp_input",
",",
"name",
"=",
"None",
")",
":",
"sp_input",
"=",
"_convert_to_sparse_tensor",
"(",
"sp_input",
")",
"output_inds",
",",
"output_vals",
",",
"output_shapes",
"=",
"(",
"gen_sparse_ops... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/sparse_ops.py#L445-L492 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/_multivariate.py | python | wishart_gen.mode | (self, df, scale) | return _squeeze_output(out) if out is not None else out | Mode of the Wishart distribution
Only valid if the degrees of freedom are greater than the dimension of
the scale matrix.
Parameters
----------
%(_doc_default_callparams)s
Returns
-------
mode : float or None
The Mode of the distribution | Mode of the Wishart distribution | [
"Mode",
"of",
"the",
"Wishart",
"distribution"
] | def mode(self, df, scale):
"""
Mode of the Wishart distribution
Only valid if the degrees of freedom are greater than the dimension of
the scale matrix.
Parameters
----------
%(_doc_default_callparams)s
Returns
-------
mode : float or None
The Mode of the distribution
"""
dim, df, scale = self._process_parameters(df, scale)
out = self._mode(dim, df, scale)
return _squeeze_output(out) if out is not None else out | [
"def",
"mode",
"(",
"self",
",",
"df",
",",
"scale",
")",
":",
"dim",
",",
"df",
",",
"scale",
"=",
"self",
".",
"_process_parameters",
"(",
"df",
",",
"scale",
")",
"out",
"=",
"self",
".",
"_mode",
"(",
"dim",
",",
"df",
",",
"scale",
")",
"r... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L1768-L1786 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | mlir/python/mlir/dialects/_arith_ops_ext.py | python | ConstantOp.create_index | (cls, value: int, *, loc=None, ip=None) | return cls(
IndexType.get(context=_get_default_loc_context(loc)),
value,
loc=loc,
ip=ip) | Create an index-typed constant. | Create an index-typed constant. | [
"Create",
"an",
"index",
"-",
"typed",
"constant",
"."
] | def create_index(cls, value: int, *, loc=None, ip=None):
"""Create an index-typed constant."""
return cls(
IndexType.get(context=_get_default_loc_context(loc)),
value,
loc=loc,
ip=ip) | [
"def",
"create_index",
"(",
"cls",
",",
"value",
":",
"int",
",",
"*",
",",
"loc",
"=",
"None",
",",
"ip",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"IndexType",
".",
"get",
"(",
"context",
"=",
"_get_default_loc_context",
"(",
"loc",
")",
")",
... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/_arith_ops_ext.py#L51-L57 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xpathParserContext.xpathCompareValues | (self, inf, strict) | return ret | Implement the compare operation on XPath objects: @arg1 <
@arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 >
@arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When
neither object to be compared is a node-set and the
operator is <=, <, >=, >, then the objects are compared by
converted both objects to numbers and comparing the numbers
according to IEEE 754. The < comparison will be true if and
only if the first number is less than the second number.
The <= comparison will be true if and only if the first
number is less than or equal to the second number. The >
comparison will be true if and only if the first number is
greater than the second number. The >= comparison will be
true if and only if the first number is greater than or
equal to the second number. | Implement the compare operation on XPath objects: | [
"Implement",
"the",
"compare",
"operation",
"on",
"XPath",
"objects",
":"
] | def xpathCompareValues(self, inf, strict):
"""Implement the compare operation on XPath objects: @arg1 <
@arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 >
@arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When
neither object to be compared is a node-set and the
operator is <=, <, >=, >, then the objects are compared by
converted both objects to numbers and comparing the numbers
according to IEEE 754. The < comparison will be true if and
only if the first number is less than the second number.
The <= comparison will be true if and only if the first
number is less than or equal to the second number. The >
comparison will be true if and only if the first number is
greater than the second number. The >= comparison will be
true if and only if the first number is greater than or
equal to the second number. """
ret = libxml2mod.xmlXPathCompareValues(self._o, inf, strict)
return ret | [
"def",
"xpathCompareValues",
"(",
"self",
",",
"inf",
",",
"strict",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathCompareValues",
"(",
"self",
".",
"_o",
",",
"inf",
",",
"strict",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7399-L7415 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_5_2.py | python | MiroInterpreter.do_download | (self, line) | download <name> -- Downloads an item by name in the feed/playlist selected. | download <name> -- Downloads an item by name in the feed/playlist selected. | [
"download",
"<name",
">",
"--",
"Downloads",
"an",
"item",
"by",
"name",
"in",
"the",
"feed",
"/",
"playlist",
"selected",
"."
] | def do_download(self, line):
"""download <name> -- Downloads an item by name in the feed/playlist selected."""
if self.selection_type is None:
print "Error: No feed/playlist selected"
return
item = self._find_item(line)
if item is None:
print "No item named %r" % line
return
if item.get_state() == 'downloading':
print '%s is currently being downloaded' % item.get_title()
elif item.is_downloaded():
print '%s is already downloaded' % item.get_title()
else:
item.download() | [
"def",
"do_download",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"selection_type",
"is",
"None",
":",
"print",
"\"Error: No feed/playlist selected\"",
"return",
"item",
"=",
"self",
".",
"_find_item",
"(",
"line",
")",
"if",
"item",
"is",
"None",... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_2_5_2.py#L616-L630 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlSelection.Set | (*args, **kwargs) | return _html.HtmlSelection_Set(*args, **kwargs) | Set(self, Point fromPos, HtmlCell fromCell, Point toPos, HtmlCell toCell) | Set(self, Point fromPos, HtmlCell fromCell, Point toPos, HtmlCell toCell) | [
"Set",
"(",
"self",
"Point",
"fromPos",
"HtmlCell",
"fromCell",
"Point",
"toPos",
"HtmlCell",
"toCell",
")"
] | def Set(*args, **kwargs):
"""Set(self, Point fromPos, HtmlCell fromCell, Point toPos, HtmlCell toCell)"""
return _html.HtmlSelection_Set(*args, **kwargs) | [
"def",
"Set",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlSelection_Set",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L463-L465 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/random_ops.py | python | uniform | (shape, minval, maxval, seed=None, dtype=mstype.float32) | return value | Generates random numbers according to the Uniform random number distribution.
Note:
The number in tensor minval should be strictly less than maxval at any position after broadcasting.
Args:
shape (tuple): The shape of random tensor to be generated.
The format is :math:`(N,*)` where :math:`*` means, any number of additional dimensions
and the length of :math:`(N,*)` should be less than 8 in broadcast operation.
minval (Tensor): The distribution parameter `a`.
It defines the minimum possible generated value, with int32 or float32 data type.
If dtype is int32, only one number is allowed.
maxval (Tensor): The distribution parameter `b`.
It defines the maximum possible generated value, with int32 or float32 data type.
If dtype is int32, only one number is allowed.
seed (int): Seed is used as entropy source for the random number engines to generate pseudo-random numbers,
must be non-negative. Default: None, which will be treated as 0.
dtype (mindspore.dtype): Type of the Uniform distribution. If it is int32, it generates numbers from discrete
uniform distribution; if it is float32, it generates numbers from continuous uniform distribution. It only
supports these two data types. Default: mindspore.float32.
Returns:
Tensor. The shape should be equal to the broadcasted shape between the input `shape` and shapes
of `minval` and `maxval`.
The dtype is designated as the input `dtype`.
Raises:
TypeError: If `shape` is not tuple.
TypeError: If 'minval' or 'maxval' is neither int32 nor float32
and dtype of 'minval' is not the same as 'maxval'.
TypeError: If `seed` is not an int.
TypeError: If 'dtype' is neither int32 nor float32.
Supported Platforms:
``Ascend`` ``GPU``
Examples:
>>> from mindspore import Tensor, ops
>>> import mindspore
>>> import numpy as np
>>> # For discrete uniform distribution, only one number is allowed for both minval and maxval:
>>> shape = (4, 2)
>>> minval = Tensor(1, mindspore.int32)
>>> maxval = Tensor(2, mindspore.int32)
>>> output = ops.uniform(shape, minval, maxval, seed=5, dtype=mindspore.int32)
>>>
>>> # For continuous uniform distribution, minval and maxval can be multi-dimentional:
>>> shape = (3, 1, 2)
>>> minval = Tensor(np.array([[3, 4], [5, 6]]), mindspore.float32)
>>> maxval = Tensor([8.0, 10.0], mindspore.float32)
>>> output = ops.uniform(shape, minval, maxval, seed=5)
>>> result = output.shape
>>> print(result)
(3, 2, 2) | Generates random numbers according to the Uniform random number distribution. | [
"Generates",
"random",
"numbers",
"according",
"to",
"the",
"Uniform",
"random",
"number",
"distribution",
"."
] | def uniform(shape, minval, maxval, seed=None, dtype=mstype.float32):
"""
Generates random numbers according to the Uniform random number distribution.
Note:
The number in tensor minval should be strictly less than maxval at any position after broadcasting.
Args:
shape (tuple): The shape of random tensor to be generated.
The format is :math:`(N,*)` where :math:`*` means, any number of additional dimensions
and the length of :math:`(N,*)` should be less than 8 in broadcast operation.
minval (Tensor): The distribution parameter `a`.
It defines the minimum possible generated value, with int32 or float32 data type.
If dtype is int32, only one number is allowed.
maxval (Tensor): The distribution parameter `b`.
It defines the maximum possible generated value, with int32 or float32 data type.
If dtype is int32, only one number is allowed.
seed (int): Seed is used as entropy source for the random number engines to generate pseudo-random numbers,
must be non-negative. Default: None, which will be treated as 0.
dtype (mindspore.dtype): Type of the Uniform distribution. If it is int32, it generates numbers from discrete
uniform distribution; if it is float32, it generates numbers from continuous uniform distribution. It only
supports these two data types. Default: mindspore.float32.
Returns:
Tensor. The shape should be equal to the broadcasted shape between the input `shape` and shapes
of `minval` and `maxval`.
The dtype is designated as the input `dtype`.
Raises:
TypeError: If `shape` is not tuple.
TypeError: If 'minval' or 'maxval' is neither int32 nor float32
and dtype of 'minval' is not the same as 'maxval'.
TypeError: If `seed` is not an int.
TypeError: If 'dtype' is neither int32 nor float32.
Supported Platforms:
``Ascend`` ``GPU``
Examples:
>>> from mindspore import Tensor, ops
>>> import mindspore
>>> import numpy as np
>>> # For discrete uniform distribution, only one number is allowed for both minval and maxval:
>>> shape = (4, 2)
>>> minval = Tensor(1, mindspore.int32)
>>> maxval = Tensor(2, mindspore.int32)
>>> output = ops.uniform(shape, minval, maxval, seed=5, dtype=mindspore.int32)
>>>
>>> # For continuous uniform distribution, minval and maxval can be multi-dimentional:
>>> shape = (3, 1, 2)
>>> minval = Tensor(np.array([[3, 4], [5, 6]]), mindspore.float32)
>>> maxval = Tensor([8.0, 10.0], mindspore.float32)
>>> output = ops.uniform(shape, minval, maxval, seed=5)
>>> result = output.shape
>>> print(result)
(3, 2, 2)
"""
minval_dtype = F.dtype(minval)
maxval_dtype = F.dtype(maxval)
const_utils.check_type_valid(dtype, [mstype.int32, mstype.float32], 'uniform')
const_utils.check_tensors_dtype_same(minval_dtype, dtype, "uniform")
const_utils.check_tensors_dtype_same(maxval_dtype, dtype, "uniform")
seed1, seed2 = _get_seed(seed, "uniform")
if const_utils.is_same_type(dtype, mstype.int32):
random_uniform = P.UniformInt(seed1, seed2)
value = random_uniform(shape, minval, maxval)
else:
uniform_real = P.UniformReal(seed1, seed2)
random_uniform = uniform_real(shape)
value = random_uniform * (maxval - minval) + minval
return value | [
"def",
"uniform",
"(",
"shape",
",",
"minval",
",",
"maxval",
",",
"seed",
"=",
"None",
",",
"dtype",
"=",
"mstype",
".",
"float32",
")",
":",
"minval_dtype",
"=",
"F",
".",
"dtype",
"(",
"minval",
")",
"maxval_dtype",
"=",
"F",
".",
"dtype",
"(",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/random_ops.py#L135-L205 | |
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/fast_rcnn/bbox_transform.py | python | clip_boxes | (boxes, im_shape) | return boxes | Clip boxes to image boundaries. | Clip boxes to image boundaries. | [
"Clip",
"boxes",
"to",
"image",
"boundaries",
"."
] | def clip_boxes(boxes, im_shape):
"""
Clip boxes to image boundaries.
"""
# x1 >= 0
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
# y1 >= 0
boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)
# x2 < im_shape[1]
boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)
# y2 < im_shape[0]
boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0)
return boxes | [
"def",
"clip_boxes",
"(",
"boxes",
",",
"im_shape",
")",
":",
"# x1 >= 0",
"boxes",
"[",
":",
",",
"0",
":",
":",
"4",
"]",
"=",
"np",
".",
"maximum",
"(",
"np",
".",
"minimum",
"(",
"boxes",
"[",
":",
",",
"0",
":",
":",
"4",
"]",
",",
"im_s... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/fast_rcnn/bbox_transform.py#L62-L75 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/commands/kvstore.py | python | KvStoreCmdBase.get_node_ip | (self, prefix_db: openr_types.PrefixDatabase) | return None | get routable IP address of node from it's prefix database | get routable IP address of node from it's prefix database | [
"get",
"routable",
"IP",
"address",
"of",
"node",
"from",
"it",
"s",
"prefix",
"database"
] | def get_node_ip(self, prefix_db: openr_types.PrefixDatabase) -> Any:
"""get routable IP address of node from it's prefix database"""
# First look for LOOPBACK prefix
for prefix_entry in prefix_db.prefixEntries:
if prefix_entry.type == network_types.PrefixType.LOOPBACK:
return ipnetwork.sprint_addr(prefix_entry.prefix.prefixAddress.addr)
# Next look for PREFIX_ALLOCATOR prefix if any
for prefix_entry in prefix_db.prefixEntries:
if prefix_entry.type == network_types.PrefixType.PREFIX_ALLOCATOR:
return utils.alloc_prefix_to_loopback_ip_str(prefix_entry.prefix)
# Else return None
return None | [
"def",
"get_node_ip",
"(",
"self",
",",
"prefix_db",
":",
"openr_types",
".",
"PrefixDatabase",
")",
"->",
"Any",
":",
"# First look for LOOPBACK prefix",
"for",
"prefix_entry",
"in",
"prefix_db",
".",
"prefixEntries",
":",
"if",
"prefix_entry",
".",
"type",
"==",... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/kvstore.py#L142-L156 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/gen_rule_target.py | python | GenRuleTarget.__init__ | (self,
name,
srcs,
deps,
outs,
cmd,
blade,
kwargs) | Init method.
Init the gen rule target. | Init method. | [
"Init",
"method",
"."
] | def __init__(self,
name,
srcs,
deps,
outs,
cmd,
blade,
kwargs):
"""Init method.
Init the gen rule target.
"""
srcs = var_to_list(srcs)
deps = var_to_list(deps)
outs = var_to_list(outs)
Target.__init__(self,
name,
'gen_rule',
srcs,
deps,
blade,
kwargs)
self.data['outs'] = outs
self.data['cmd'] = cmd | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"srcs",
",",
"deps",
",",
"outs",
",",
"cmd",
",",
"blade",
",",
"kwargs",
")",
":",
"srcs",
"=",
"var_to_list",
"(",
"srcs",
")",
"deps",
"=",
"var_to_list",
"(",
"deps",
")",
"outs",
"=",
"var_to_... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/gen_rule_target.py#L23-L49 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/android/pylib/android_commands.py | python | AndroidCommands.GetBuildId | (self) | return build_id | Returns the build ID of the system (e.g. JRM79C). | Returns the build ID of the system (e.g. JRM79C). | [
"Returns",
"the",
"build",
"ID",
"of",
"the",
"system",
"(",
"e",
".",
"g",
".",
"JRM79C",
")",
"."
] | def GetBuildId(self):
"""Returns the build ID of the system (e.g. JRM79C)."""
build_id = self.RunShellCommand('getprop ro.build.id')[0]
assert build_id
return build_id | [
"def",
"GetBuildId",
"(",
"self",
")",
":",
"build_id",
"=",
"self",
".",
"RunShellCommand",
"(",
"'getprop ro.build.id'",
")",
"[",
"0",
"]",
"assert",
"build_id",
"return",
"build_id"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/pylib/android_commands.py#L697-L701 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/serialcli.py | python | Serial._update_rts_state | (self) | Set terminal status line: Request To Send | Set terminal status line: Request To Send | [
"Set",
"terminal",
"status",
"line",
":",
"Request",
"To",
"Send"
] | def _update_rts_state(self):
"""Set terminal status line: Request To Send"""
if not self.is_open:
raise portNotOpenError
self._port_handle.RtsEnable = bool(self._rts_state) | [
"def",
"_update_rts_state",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"portNotOpenError",
"self",
".",
"_port_handle",
".",
"RtsEnable",
"=",
"bool",
"(",
"self",
".",
"_rts_state",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/serialcli.py#L209-L213 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/plan/motionplanning.py | python | destroy | () | return _motionplanning.destroy() | destroys internal data structures | destroys internal data structures | [
"destroys",
"internal",
"data",
"structures"
] | def destroy():
"""
destroys internal data structures
"""
return _motionplanning.destroy() | [
"def",
"destroy",
"(",
")",
":",
"return",
"_motionplanning",
".",
"destroy",
"(",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/motionplanning.py#L260-L265 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DateTime.Today | (*args, **kwargs) | return _misc_.DateTime_Today(*args, **kwargs) | Today() -> DateTime | Today() -> DateTime | [
"Today",
"()",
"-",
">",
"DateTime"
] | def Today(*args, **kwargs):
"""Today() -> DateTime"""
return _misc_.DateTime_Today(*args, **kwargs) | [
"def",
"Today",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_Today",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3776-L3778 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/ensdf.py | python | _parse_gamma_continuation_record | (g, inten, tti) | return conversions | This parses an ENSDF gamma continuation record | This parses an ENSDF gamma continuation record | [
"This",
"parses",
"an",
"ENSDF",
"gamma",
"continuation",
"record"
] | def _parse_gamma_continuation_record(g, inten, tti):
"""
This parses an ENSDF gamma continuation record
"""
conversions = {}
entries = g.group(2).split('$')
for entry in entries:
entry = entry.replace('AP', '=')
entry = entry.replace('EL1C+EL2C', 'LC')
if '+=' in entry or 'EAV' in entry:
continue
if 'C=' in entry:
tsplit = entry.split('C')
else:
tsplit = entry.split('=')
tsplit[0] = tsplit[0].lstrip('C')
greff = inten
if '/T' in entry:
tsplit = entry.split('/T')
greff = tti
if greff is None:
greff = inten
if greff is None:
greff = 1.0
if len(tsplit) == 2:
conv = None
err = None
contype = tsplit[0].lstrip('E')
eff = tsplit[1].lstrip('= ').split()
if len(eff) == 2:
conv, err = _get_val_err(eff[0], eff[1])
elif len(eff) == 1:
conv = _getvalue(eff[0])
if conv is None and contype not in conversions:
conversions[contype] = (None, None)
elif contype not in conversions:
conversions[contype] = (conv * greff, err)
return conversions | [
"def",
"_parse_gamma_continuation_record",
"(",
"g",
",",
"inten",
",",
"tti",
")",
":",
"conversions",
"=",
"{",
"}",
"entries",
"=",
"g",
".",
"group",
"(",
"2",
")",
".",
"split",
"(",
"'$'",
")",
"for",
"entry",
"in",
"entries",
":",
"entry",
"="... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/ensdf.py#L297-L335 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/shape.py | python | _ShapeUtil.get_dims | (self, x, sample=True, batch=True, event=True) | return sample_shape + batch_shape + event_shape | Returns subset of tensor's dimension indexes (indexes into shape).
Args:
x: `Tensor`.
sample: `Boolean`. Include sample dimensions or not.
batch: `Boolean`. Include batch dimensions or not.
event: `Boolean`. Include event dimensions or not.
Raises:
ValueError: if `x.get_shape().ndims` is `None`
Returns:
List enumerating requested dimensions. | Returns subset of tensor's dimension indexes (indexes into shape). | [
"Returns",
"subset",
"of",
"tensor",
"s",
"dimension",
"indexes",
"(",
"indexes",
"into",
"shape",
")",
"."
] | def get_dims(self, x, sample=True, batch=True, event=True):
"""Returns subset of tensor's dimension indexes (indexes into shape).
Args:
x: `Tensor`.
sample: `Boolean`. Include sample dimensions or not.
batch: `Boolean`. Include batch dimensions or not.
event: `Boolean`. Include event dimensions or not.
Raises:
ValueError: if `x.get_shape().ndims` is `None`
Returns:
List enumerating requested dimensions.
"""
ndims = self.get_ndims(x)
if sample and batch and event:
return list(range(ndims))
sample_start = 0
batch_start = self.get_sample_ndims(x)
event_start = batch_start + self.batch_ndims
sample_shape = list(range(sample_start, batch_start)) if sample else []
batch_shape = list(range(batch_start, event_start)) if batch else []
event_shape = list(range(event_start, ndims)) if event else []
return sample_shape + batch_shape + event_shape | [
"def",
"get_dims",
"(",
"self",
",",
"x",
",",
"sample",
"=",
"True",
",",
"batch",
"=",
"True",
",",
"event",
"=",
"True",
")",
":",
"ndims",
"=",
"self",
".",
"get_ndims",
"(",
"x",
")",
"if",
"sample",
"and",
"batch",
"and",
"event",
":",
"ret... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/shape.py#L209-L237 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tensor_tracer_report.py | python | TTReportHandle._write_op_list_section | (self, graph_order) | Writes the Op-list section of the report. | Writes the Op-list section of the report. | [
"Writes",
"the",
"Op",
"-",
"list",
"section",
"of",
"the",
"report",
"."
] | def _write_op_list_section(self, graph_order):
"""Writes the Op-list section of the report."""
self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_OP_LIST))
self._write_report('%s %d\n'%(_FIELD_NAME_NUM_OPS,
len(graph_order.operations)))
for i in range(0, len(graph_order.operations)):
op = graph_order.operations[i]
line = '%d "%s" %s'%(i, op.name, op.type)
for out_tensor in op.outputs:
if out_tensor.name not in graph_order.tensor_to_idx:
raise ValueError(
'out_tensor %s is not in tensor_to_idx'%out_tensor.name)
line += ' %d'%graph_order.tensor_to_idx[out_tensor.name]
line += '\n'
self._write_report(line)
self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_OP_LIST)) | [
"def",
"_write_op_list_section",
"(",
"self",
",",
"graph_order",
")",
":",
"self",
".",
"_write_report",
"(",
"'%s %s\\n'",
"%",
"(",
"_MARKER_SECTION_BEGIN",
",",
"_SECTION_NAME_OP_LIST",
")",
")",
"self",
".",
"_write_report",
"(",
"'%s %d\\n'",
"%",
"(",
"_F... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tensor_tracer_report.py#L345-L361 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/rangeobj.py | python | range_iter_len | (typingctx, val) | An implementation of len(range_iter) for internal use. | An implementation of len(range_iter) for internal use. | [
"An",
"implementation",
"of",
"len",
"(",
"range_iter",
")",
"for",
"internal",
"use",
"."
] | def range_iter_len(typingctx, val):
"""
An implementation of len(range_iter) for internal use.
"""
if isinstance(val, types.RangeIteratorType):
val_type = val.yield_type
def codegen(context, builder, sig, args):
(value,) = args
iter_type = range_impl_map[val_type][1]
iterobj = cgutils.create_struct_proxy(iter_type)(context, builder, value)
int_type = iterobj.count.type
return impl_ret_untracked(context, builder, int_type, builder.load(iterobj.count))
return signature(val_type, val), codegen
elif isinstance(val, types.ListIter):
def codegen(context, builder, sig, args):
(value,) = args
intp_t = context.get_value_type(types.intp)
iterobj = ListIterInstance(context, builder, sig.args[0], value)
return impl_ret_untracked(context, builder, intp_t, iterobj.size)
return signature(types.intp, val), codegen
elif isinstance(val, types.ArrayIterator):
def codegen(context, builder, sig, args):
(iterty,) = sig.args
(value,) = args
intp_t = context.get_value_type(types.intp)
iterobj = context.make_helper(builder, iterty, value=value)
arrayty = iterty.array_type
ary = make_array(arrayty)(context, builder, value=iterobj.array)
shape = cgutils.unpack_tuple(builder, ary.shape)
# array iterates along the outer dimension
return impl_ret_untracked(context, builder, intp_t, shape[0])
return signature(types.intp, val), codegen | [
"def",
"range_iter_len",
"(",
"typingctx",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"types",
".",
"RangeIteratorType",
")",
":",
"val_type",
"=",
"val",
".",
"yield_type",
"def",
"codegen",
"(",
"context",
",",
"builder",
",",
"sig",
",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/rangeobj.py#L183-L214 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/initfini.py | python | initialize_native_asmprinter | () | Initialize the native ASM printer. | Initialize the native ASM printer. | [
"Initialize",
"the",
"native",
"ASM",
"printer",
"."
] | def initialize_native_asmprinter():
"""
Initialize the native ASM printer.
"""
ffi.lib.LLVMPY_InitializeNativeAsmPrinter() | [
"def",
"initialize_native_asmprinter",
"(",
")",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_InitializeNativeAsmPrinter",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/initfini.py#L39-L43 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/mixture/gaussian_mixture.py | python | _check_precisions | (precisions, covariance_type, n_components, n_features) | return precisions | Validate user provided precisions.
Parameters
----------
precisions : array-like,
'full' : shape of (n_components, n_features, n_features)
'tied' : shape of (n_features, n_features)
'diag' : shape of (n_components, n_features)
'spherical' : shape of (n_components,)
covariance_type : string
n_components : int
Number of components.
n_features : int
Number of features.
Returns
-------
precisions : array | Validate user provided precisions. | [
"Validate",
"user",
"provided",
"precisions",
"."
] | def _check_precisions(precisions, covariance_type, n_components, n_features):
"""Validate user provided precisions.
Parameters
----------
precisions : array-like,
'full' : shape of (n_components, n_features, n_features)
'tied' : shape of (n_features, n_features)
'diag' : shape of (n_components, n_features)
'spherical' : shape of (n_components,)
covariance_type : string
n_components : int
Number of components.
n_features : int
Number of features.
Returns
-------
precisions : array
"""
precisions = check_array(precisions, dtype=[np.float64, np.float32],
ensure_2d=False,
allow_nd=covariance_type == 'full')
precisions_shape = {'full': (n_components, n_features, n_features),
'tied': (n_features, n_features),
'diag': (n_components, n_features),
'spherical': (n_components,)}
_check_shape(precisions, precisions_shape[covariance_type],
'%s precision' % covariance_type)
_check_precisions = {'full': _check_precisions_full,
'tied': _check_precision_matrix,
'diag': _check_precision_positivity,
'spherical': _check_precision_positivity}
_check_precisions[covariance_type](precisions, covariance_type)
return precisions | [
"def",
"_check_precisions",
"(",
"precisions",
",",
"covariance_type",
",",
"n_components",
",",
"n_features",
")",
":",
"precisions",
"=",
"check_array",
"(",
"precisions",
",",
"dtype",
"=",
"[",
"np",
".",
"float64",
",",
"np",
".",
"float32",
"]",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/gaussian_mixture.py#L98-L137 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/module/executor_group.py | python | DataParallelExecutorGroup.forward | (self, data_batch, is_train=None) | Split `data_batch` according to workload and run forward on each devices.
Parameters
----------
data_batch : DataBatch
Or could be any object implementing similar interface.
is_train : bool
The hint for the backend, indicating whether we are during training phase.
Default is `None`, then the value `self.for_training` will be used.
Returns
------- | Split `data_batch` according to workload and run forward on each devices. | [
"Split",
"data_batch",
"according",
"to",
"workload",
"and",
"run",
"forward",
"on",
"each",
"devices",
"."
] | def forward(self, data_batch, is_train=None):
"""Split `data_batch` according to workload and run forward on each devices.
Parameters
----------
data_batch : DataBatch
Or could be any object implementing similar interface.
is_train : bool
The hint for the backend, indicating whether we are during training phase.
Default is `None`, then the value `self.for_training` will be used.
Returns
-------
"""
_load_data(data_batch, self.data_arrays, self.data_layouts)
if is_train is None:
is_train = self.for_training
if isinstance(data_batch, list):
if self.label_arrays is not None and data_batch is not None and data_batch[0].label:
_load_label(data_batch, self.label_arrays, self.label_layouts)
else:
if self.label_arrays is not None and data_batch.label:
_load_label(data_batch, self.label_arrays, self.label_layouts)
for exec_ in self.execs:
exec_.forward(is_train=is_train) | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
")",
":",
"_load_data",
"(",
"data_batch",
",",
"self",
".",
"data_arrays",
",",
"self",
".",
"data_layouts",
")",
"if",
"is_train",
"is",
"None",
":",
"is_train",
"=",
"self... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/module/executor_group.py#L436-L462 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir.py | python | Scope.get | (self, name) | return self.get_exact(name) | Refer to a variable. Returns the latest version. | Refer to a variable. Returns the latest version. | [
"Refer",
"to",
"a",
"variable",
".",
"Returns",
"the",
"latest",
"version",
"."
] | def get(self, name):
"""
Refer to a variable. Returns the latest version.
"""
if name in self.redefined:
name = "%s.%d" % (name, self.redefined[name])
return self.get_exact(name) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"redefined",
":",
"name",
"=",
"\"%s.%d\"",
"%",
"(",
"name",
",",
"self",
".",
"redefined",
"[",
"name",
"]",
")",
"return",
"self",
".",
"get_exact",
"(",
"name",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir.py#L1051-L1057 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/cookielib.py | python | CookieJar.make_cookies | (self, response, request) | return cookies | Return sequence of Cookie objects extracted from response object. | Return sequence of Cookie objects extracted from response object. | [
"Return",
"sequence",
"of",
"Cookie",
"objects",
"extracted",
"from",
"response",
"object",
"."
] | def make_cookies(self, response, request):
"""Return sequence of Cookie objects extracted from response object."""
# get cookie-attributes for RFC 2965 and Netscape protocols
headers = response.info()
rfc2965_hdrs = headers.getheaders("Set-Cookie2")
ns_hdrs = headers.getheaders("Set-Cookie")
rfc2965 = self._policy.rfc2965
netscape = self._policy.netscape
if ((not rfc2965_hdrs and not ns_hdrs) or
(not ns_hdrs and not rfc2965) or
(not rfc2965_hdrs and not netscape) or
(not netscape and not rfc2965)):
return [] # no relevant cookie headers: quick exit
try:
cookies = self._cookies_from_attrs_set(
split_header_words(rfc2965_hdrs), request)
except Exception:
_warn_unhandled_exception()
cookies = []
if ns_hdrs and netscape:
try:
# RFC 2109 and Netscape cookies
ns_cookies = self._cookies_from_attrs_set(
parse_ns_headers(ns_hdrs), request)
except Exception:
_warn_unhandled_exception()
ns_cookies = []
self._process_rfc2109_cookies(ns_cookies)
# Look for Netscape cookies (from Set-Cookie headers) that match
# corresponding RFC 2965 cookies (from Set-Cookie2 headers).
# For each match, keep the RFC 2965 cookie and ignore the Netscape
# cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are
# bundled in with the Netscape cookies for this purpose, which is
# reasonable behaviour.
if rfc2965:
lookup = {}
for cookie in cookies:
lookup[(cookie.domain, cookie.path, cookie.name)] = None
def no_matching_rfc2965(ns_cookie, lookup=lookup):
key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
return key not in lookup
ns_cookies = filter(no_matching_rfc2965, ns_cookies)
if ns_cookies:
cookies.extend(ns_cookies)
return cookies | [
"def",
"make_cookies",
"(",
"self",
",",
"response",
",",
"request",
")",
":",
"# get cookie-attributes for RFC 2965 and Netscape protocols",
"headers",
"=",
"response",
".",
"info",
"(",
")",
"rfc2965_hdrs",
"=",
"headers",
".",
"getheaders",
"(",
"\"Set-Cookie2\"",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cookielib.py#L1571-L1623 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/symsrc/pefile.py | python | PE.set_bytes_at_rva | (self, rva, data) | return self.set_bytes_at_offset(offset, data) | Overwrite, with the given string, the bytes at the file offset corresponding to the given RVA.
Return True if successful, False otherwise. It can fail if the
offset is outside the file's boundaries. | Overwrite, with the given string, the bytes at the file offset corresponding to the given RVA.
Return True if successful, False otherwise. It can fail if the
offset is outside the file's boundaries. | [
"Overwrite",
"with",
"the",
"given",
"string",
"the",
"bytes",
"at",
"the",
"file",
"offset",
"corresponding",
"to",
"the",
"given",
"RVA",
".",
"Return",
"True",
"if",
"successful",
"False",
"otherwise",
".",
"It",
"can",
"fail",
"if",
"the",
"offset",
"i... | def set_bytes_at_rva(self, rva, data):
"""Overwrite, with the given string, the bytes at the file offset corresponding to the given RVA.
Return True if successful, False otherwise. It can fail if the
offset is outside the file's boundaries.
"""
offset = self.get_physical_by_rva(rva)
if not offset:
raise False
return self.set_bytes_at_offset(offset, data) | [
"def",
"set_bytes_at_rva",
"(",
"self",
",",
"rva",
",",
"data",
")",
":",
"offset",
"=",
"self",
".",
"get_physical_by_rva",
"(",
"rva",
")",
"if",
"not",
"offset",
":",
"raise",
"False",
"return",
"self",
".",
"set_bytes_at_offset",
"(",
"offset",
",",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/symsrc/pefile.py#L3564-L3575 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | Context.Etiny | (self) | return int(self.Emin - self.prec + 1) | Returns Etiny (= Emin - prec + 1) | Returns Etiny (= Emin - prec + 1) | [
"Returns",
"Etiny",
"(",
"=",
"Emin",
"-",
"prec",
"+",
"1",
")"
] | def Etiny(self):
"""Returns Etiny (= Emin - prec + 1)"""
return int(self.Emin - self.prec + 1) | [
"def",
"Etiny",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"Emin",
"-",
"self",
".",
"prec",
"+",
"1",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L4067-L4069 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ToolBarBase.AddStretchableSpace | (*args, **kwargs) | return _controls_.ToolBarBase_AddStretchableSpace(*args, **kwargs) | AddStretchableSpace(self) -> ToolBarToolBase | AddStretchableSpace(self) -> ToolBarToolBase | [
"AddStretchableSpace",
"(",
"self",
")",
"-",
">",
"ToolBarToolBase"
] | def AddStretchableSpace(*args, **kwargs):
"""AddStretchableSpace(self) -> ToolBarToolBase"""
return _controls_.ToolBarBase_AddStretchableSpace(*args, **kwargs) | [
"def",
"AddStretchableSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarBase_AddStretchableSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3763-L3765 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/fractions.py | python | Fraction.__rfloordiv__ | (b, a) | a // b | a // b | [
"a",
"//",
"b"
] | def __rfloordiv__(b, a):
"""a // b"""
# Will be math.floor(a / b) in 3.0.
div = a / b
if isinstance(div, Rational):
# trunc(math.floor(div)) doesn't work if the rational is
# more precise than a float because the intermediate
# rounding may cross an integer boundary.
return div.numerator // div.denominator
else:
return math.floor(div) | [
"def",
"__rfloordiv__",
"(",
"b",
",",
"a",
")",
":",
"# Will be math.floor(a / b) in 3.0.",
"div",
"=",
"a",
"/",
"b",
"if",
"isinstance",
"(",
"div",
",",
"Rational",
")",
":",
"# trunc(math.floor(div)) doesn't work if the rational is",
"# more precise than a float be... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/fractions.py#L429-L439 | ||
INK-USC/USC-DS-RelationExtraction | eebcfa7fd2eda5bba92f3ef8158797cdf91e6981 | code/Model/baselines/sentence-level-models/vocab.py | python | Vocab.unmap | (self, idx_list) | return [self.id2word[idx] for idx in idx_list] | Unmap ids back to tokens. | Unmap ids back to tokens. | [
"Unmap",
"ids",
"back",
"to",
"tokens",
"."
] | def unmap(self, idx_list):
"""
Unmap ids back to tokens.
"""
return [self.id2word[idx] for idx in idx_list] | [
"def",
"unmap",
"(",
"self",
",",
"idx_list",
")",
":",
"return",
"[",
"self",
".",
"id2word",
"[",
"idx",
"]",
"for",
"idx",
"in",
"idx_list",
"]"
] | https://github.com/INK-USC/USC-DS-RelationExtraction/blob/eebcfa7fd2eda5bba92f3ef8158797cdf91e6981/code/Model/baselines/sentence-level-models/vocab.py#L93-L97 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/reshape.py | python | Reshape._maybe_check_valid_shape | (self, shape, validate_args) | return assertions | Check that a shape Tensor is int-type and otherwise sane. | Check that a shape Tensor is int-type and otherwise sane. | [
"Check",
"that",
"a",
"shape",
"Tensor",
"is",
"int",
"-",
"type",
"and",
"otherwise",
"sane",
"."
] | def _maybe_check_valid_shape(self, shape, validate_args):
"""Check that a shape Tensor is int-type and otherwise sane."""
if not shape.dtype.is_integer:
raise TypeError("{} dtype ({}) should be `int`-like.".format(
shape, shape.dtype.name))
assertions = []
ndims = array_ops.rank(shape)
ndims_ = tensor_util.constant_value(ndims)
if ndims_ is not None and ndims_ > 1:
raise ValueError("`{}` rank ({}) should be <= 1.".format(
shape, ndims_))
elif validate_args:
assertions.append(check_ops.assert_less_equal(
ndims, 1, message="`{}` rank should be <= 1.".format(shape)))
shape_ = tensor_util.constant_value_as_shape(shape)
if shape_.is_fully_defined():
es = np.int32(shape_.as_list())
if sum(es == -1) > 1:
raise ValueError(
"`{}` must have at most one `-1` (given {})"
.format(shape, es))
if np.any(es < -1):
raise ValueError(
"`{}` elements must be either positive integers or `-1`"
"(given {})."
.format(shape, es))
elif validate_args:
assertions.extend([
check_ops.assert_less_equal(
math_ops.reduce_sum(
math_ops.cast(math_ops.equal(shape, -1), dtypes.int32)),
1,
message="`{}` elements must have at most one `-1`."
.format(shape)),
check_ops.assert_greater_equal(
shape, -1,
message="`{}` elements must be either positive integers or `-1`."
.format(shape)),
])
return assertions | [
"def",
"_maybe_check_valid_shape",
"(",
"self",
",",
"shape",
",",
"validate_args",
")",
":",
"if",
"not",
"shape",
".",
"dtype",
".",
"is_integer",
":",
"raise",
"TypeError",
"(",
"\"{} dtype ({}) should be `int`-like.\"",
".",
"format",
"(",
"shape",
",",
"sha... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/reshape.py#L164-L206 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | msg/tools/px_generate_uorb_topic_files.py | python | generate_output_from_file | (format_idx, filename, outputdir, package, templatedir, includepath) | return generate_by_template(output_file, template_file, em_globals) | Converts a single .msg file to an uorb header/source file | Converts a single .msg file to an uorb header/source file | [
"Converts",
"a",
"single",
".",
"msg",
"file",
"to",
"an",
"uorb",
"header",
"/",
"source",
"file"
] | def generate_output_from_file(format_idx, filename, outputdir, package, templatedir, includepath):
"""
Converts a single .msg file to an uorb header/source file
"""
msg_context = genmsg.msg_loader.MsgContext.create_default()
full_type_name = genmsg.gentools.compute_full_type_name(
package, os.path.basename(filename))
spec = genmsg.msg_loader.load_msg_from_file(
msg_context, filename, full_type_name)
field_name_and_type = {}
for field in spec.parsed_fields():
field_name_and_type.update({field.name: field.type})
# assert if the timestamp field exists
try:
assert 'timestamp' in field_name_and_type
except AssertionError:
print("[ERROR] uORB topic files generator:\n\tgenerate_output_from_file:\tNo 'timestamp' field found in " +
spec.short_name + " msg definition!")
exit(1)
# assert if the timestamp field is of type uint64
try:
assert field_name_and_type.get('timestamp') == 'uint64'
except AssertionError:
print("[ERROR] uORB topic files generator:\n\tgenerate_output_from_file:\t'timestamp' field in " + spec.short_name +
" msg definition is not of type uint64 but rather of type " + field_name_and_type.get('timestamp') + "!")
exit(1)
topics = get_multi_topics(filename)
if includepath:
search_path = genmsg.command_line.includepath_to_dict(includepath)
else:
search_path = {}
genmsg.msg_loader.load_depends(msg_context, spec, search_path)
md5sum = genmsg.gentools.compute_md5(msg_context, spec)
if len(topics) == 0:
topics.append(spec.short_name)
em_globals = {
"file_name_in": filename,
"md5sum": md5sum,
"search_path": search_path,
"msg_context": msg_context,
"spec": spec,
"topics": topics,
"constrained_flash": CONSTRAINED_FLASH
}
# Make sure output directory exists:
if not os.path.isdir(outputdir):
os.makedirs(outputdir)
template_file = os.path.join(templatedir, TEMPLATE_FILE[format_idx])
output_file = os.path.join(outputdir, spec.short_name +
OUTPUT_FILE_EXT[format_idx])
return generate_by_template(output_file, template_file, em_globals) | [
"def",
"generate_output_from_file",
"(",
"format_idx",
",",
"filename",
",",
"outputdir",
",",
"package",
",",
"templatedir",
",",
"includepath",
")",
":",
"msg_context",
"=",
"genmsg",
".",
"msg_loader",
".",
"MsgContext",
".",
"create_default",
"(",
")",
"full... | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/msg/tools/px_generate_uorb_topic_files.py#L124-L177 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/tensorboard/backend/handler.py | python | TensorboardHandler._serve_audio | (self, query_params) | Given a tag and list of runs, serve a list of audio.
Note that the audio clips themselves are not sent; instead, we respond with
URLs to the audio. The frontend should treat these URLs as opaque and should
not try to parse information about them or generate them itself, as the
format may change.
Args:
query_params: The query parameters as a dict. | Given a tag and list of runs, serve a list of audio. | [
"Given",
"a",
"tag",
"and",
"list",
"of",
"runs",
"serve",
"a",
"list",
"of",
"audio",
"."
] | def _serve_audio(self, query_params):
"""Given a tag and list of runs, serve a list of audio.
Note that the audio clips themselves are not sent; instead, we respond with
URLs to the audio. The frontend should treat these URLs as opaque and should
not try to parse information about them or generate them itself, as the
format may change.
Args:
query_params: The query parameters as a dict.
"""
tag = query_params.get('tag')
run = query_params.get('run')
audio_list = self._multiplexer.Audio(run, tag)
response = self._audio_response_for_run(audio_list, run, tag)
self._send_json_response(response) | [
"def",
"_serve_audio",
"(",
"self",
",",
"query_params",
")",
":",
"tag",
"=",
"query_params",
".",
"get",
"(",
"'tag'",
")",
"run",
"=",
"query_params",
".",
"get",
"(",
"'run'",
")",
"audio_list",
"=",
"self",
".",
"_multiplexer",
".",
"Audio",
"(",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/tensorboard/backend/handler.py#L429-L446 | ||
BitcoinUnlimited/BitcoinUnlimited | 05de381c02eb4bfca94957733acadfa217527f25 | contrib/devtools/benchmark_diff.py | python | BenchmarkFileComparator._common_benches | (self) | return list(self.after_benchmark_names & self.before_benchmark_names) | Returns a list of benchmarks in both files. | Returns a list of benchmarks in both files. | [
"Returns",
"a",
"list",
"of",
"benchmarks",
"in",
"both",
"files",
"."
] | def _common_benches(self):
"""Returns a list of benchmarks in both files."""
return list(self.after_benchmark_names & self.before_benchmark_names) | [
"def",
"_common_benches",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"after_benchmark_names",
"&",
"self",
".",
"before_benchmark_names",
")"
] | https://github.com/BitcoinUnlimited/BitcoinUnlimited/blob/05de381c02eb4bfca94957733acadfa217527f25/contrib/devtools/benchmark_diff.py#L163-L165 | |
Illumina/hap.py | 84011695b2ff2406c16a335106db6831fb67fdfe | src/python/Tools/vcfextract.py | python | field | (val) | return val | extract field into result, guess type | extract field into result, guess type | [
"extract",
"field",
"into",
"result",
"guess",
"type"
] | def field(val):
""" extract field into result, guess type """
if "," in val:
val = map(field, val.split(","))
else:
done = False
try:
val = int(val)
done = True
except:
pass
if done:
return val
try:
val = float(val)
except:
pass
return val | [
"def",
"field",
"(",
"val",
")",
":",
"if",
"\",\"",
"in",
"val",
":",
"val",
"=",
"map",
"(",
"field",
",",
"val",
".",
"split",
"(",
"\",\"",
")",
")",
"else",
":",
"done",
"=",
"False",
"try",
":",
"val",
"=",
"int",
"(",
"val",
")",
"done... | https://github.com/Illumina/hap.py/blob/84011695b2ff2406c16a335106db6831fb67fdfe/src/python/Tools/vcfextract.py#L22-L40 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | MaskedArray._get_imaginary | (self) | Get the imaginary part of a complex array. | Get the imaginary part of a complex array. | [
"Get",
"the",
"imaginary",
"part",
"of",
"a",
"complex",
"array",
"."
] | def _get_imaginary(self):
"Get the imaginary part of a complex array."
if self._mask is nomask:
return masked_array(self._data.imag, mask=nomask,
fill_value = self.fill_value())
else:
return masked_array(self._data.imag, mask=self._mask,
fill_value = self.fill_value()) | [
"def",
"_get_imaginary",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mask",
"is",
"nomask",
":",
"return",
"masked_array",
"(",
"self",
".",
"_data",
".",
"imag",
",",
"mask",
"=",
"nomask",
",",
"fill_value",
"=",
"self",
".",
"fill_value",
"(",
")",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L714-L721 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/config.py | python | get_memory_info | (device) | return context.context().get_memory_info(device) | Get memory info for the chosen device, as a dict.
This function returns a dict containing information about the device's memory
usage. For example:
>>> if tf.config.list_physical_devices('GPU'):
... # Returns a dict in the form {'current': <current mem usage>,
... # 'peak': <peak mem usage>}
... tf.config.experimental.get_memory_info('GPU:0')
Currently returns the following keys:
- `'current'`: The current memory used by the device, in bytes.
- `'peak'`: The peak memory used by the device across the run of the
program, in bytes. Can be reset with
`tf.config.experimental.reset_memory_stats`.
More keys may be added in the future, including device-specific keys.
Currently only supports GPU and TPU. If called on a CPU device, an exception
will be raised.
For GPUs, TensorFlow will allocate all the memory by default, unless changed
with `tf.config.experimental.set_memory_growth`. The dict specifies only the
current and peak memory that TensorFlow is actually using, not the memory that
TensorFlow has allocated on the GPU.
Args:
device: Device string to get the memory information for, e.g. `"GPU:0"`,
`"TPU:0"`. See https://www.tensorflow.org/api_docs/python/tf/device for
specifying device strings.
Returns:
A dict with keys `'current'` and `'peak'`, specifying the current and peak
memory usage respectively.
Raises:
ValueError: No device found with the device name, like '"nonexistent"'.
ValueError: Invalid device name, like '"GPU"', '"CPU:GPU"', '"CPU:"'.
ValueError: Multiple devices matched with the device name.
ValueError: Memory statistics not tracked, like '"CPU:0"'. | Get memory info for the chosen device, as a dict. | [
"Get",
"memory",
"info",
"for",
"the",
"chosen",
"device",
"as",
"a",
"dict",
"."
] | def get_memory_info(device):
"""Get memory info for the chosen device, as a dict.
This function returns a dict containing information about the device's memory
usage. For example:
>>> if tf.config.list_physical_devices('GPU'):
... # Returns a dict in the form {'current': <current mem usage>,
... # 'peak': <peak mem usage>}
... tf.config.experimental.get_memory_info('GPU:0')
Currently returns the following keys:
- `'current'`: The current memory used by the device, in bytes.
- `'peak'`: The peak memory used by the device across the run of the
program, in bytes. Can be reset with
`tf.config.experimental.reset_memory_stats`.
More keys may be added in the future, including device-specific keys.
Currently only supports GPU and TPU. If called on a CPU device, an exception
will be raised.
For GPUs, TensorFlow will allocate all the memory by default, unless changed
with `tf.config.experimental.set_memory_growth`. The dict specifies only the
current and peak memory that TensorFlow is actually using, not the memory that
TensorFlow has allocated on the GPU.
Args:
device: Device string to get the memory information for, e.g. `"GPU:0"`,
`"TPU:0"`. See https://www.tensorflow.org/api_docs/python/tf/device for
specifying device strings.
Returns:
A dict with keys `'current'` and `'peak'`, specifying the current and peak
memory usage respectively.
Raises:
ValueError: No device found with the device name, like '"nonexistent"'.
ValueError: Invalid device name, like '"GPU"', '"CPU:GPU"', '"CPU:"'.
ValueError: Multiple devices matched with the device name.
ValueError: Memory statistics not tracked, like '"CPU:0"'.
"""
return context.context().get_memory_info(device) | [
"def",
"get_memory_info",
"(",
"device",
")",
":",
"return",
"context",
".",
"context",
"(",
")",
".",
"get_memory_info",
"(",
"device",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/config.py#L531-L573 | |
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/python/flatbuffers/builder.py | python | Builder.assertNested | (self) | Check that we are in the process of building an object. | Check that we are in the process of building an object. | [
"Check",
"that",
"we",
"are",
"in",
"the",
"process",
"of",
"building",
"an",
"object",
"."
] | def assertNested(self):
"""
Check that we are in the process of building an object.
"""
if not self.nested:
raise IsNotNestedError() | [
"def",
"assertNested",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"nested",
":",
"raise",
"IsNotNestedError",
"(",
")"
] | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/builder.py#L478-L484 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/colourutils.py | python | BestLabelColour | (color, bw=False) | return txt_color | Get the best color to use for the label that will be drawn on
top of the given color.
:param Colour `color`: background color that text will be drawn on
:keyword `bw`: If True, only return black or white | Get the best color to use for the label that will be drawn on
top of the given color.
:param Colour `color`: background color that text will be drawn on
:keyword `bw`: If True, only return black or white | [
"Get",
"the",
"best",
"color",
"to",
"use",
"for",
"the",
"label",
"that",
"will",
"be",
"drawn",
"on",
"top",
"of",
"the",
"given",
"color",
".",
":",
"param",
"Colour",
"color",
":",
"background",
"color",
"that",
"text",
"will",
"be",
"drawn",
"on",... | def BestLabelColour(color, bw=False):
"""
Get the best color to use for the label that will be drawn on
top of the given color.
:param Colour `color`: background color that text will be drawn on
:keyword `bw`: If True, only return black or white
"""
avg = sum(color.Get()) / 3
if avg > 192:
txt_color = wx.BLACK
elif avg > 128:
if bw: txt_color = wx.BLACK
else: txt_color = AdjustColour(color, -95)
elif avg < 64:
txt_color = wx.WHITE
else:
if bw: txt_color = wx.WHITE
else: txt_color = AdjustColour(color, 95)
return txt_color | [
"def",
"BestLabelColour",
"(",
"color",
",",
"bw",
"=",
"False",
")",
":",
"avg",
"=",
"sum",
"(",
"color",
".",
"Get",
"(",
")",
")",
"/",
"3",
"if",
"avg",
">",
"192",
":",
"txt_color",
"=",
"wx",
".",
"BLACK",
"elif",
"avg",
">",
"128",
":",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/colourutils.py#L52-L72 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py | python | MainWindow.update_peak_added_info | (self, int_msg, int_msg2) | Update the peak-being-added information
:param int_msg:
:param int_msg2:
:return: | Update the peak-being-added information
:param int_msg:
:param int_msg2:
:return: | [
"Update",
"the",
"peak",
"-",
"being",
"-",
"added",
"information",
":",
"param",
"int_msg",
":",
":",
"param",
"int_msg2",
":",
":",
"return",
":"
] | def update_peak_added_info(self, int_msg, int_msg2):
"""
Update the peak-being-added information
:param int_msg:
:param int_msg2:
:return:
"""
# get parameters passed
exp_number = int_msg
scan_number = int_msg2
# get PeakInfo
peak_info = self._myControl.get_peak_info(exp_number, scan_number)
assert isinstance(peak_info, r4c.PeakProcessRecord)
# add to table
self.set_ub_peak_table(peak_info) | [
"def",
"update_peak_added_info",
"(",
"self",
",",
"int_msg",
",",
"int_msg2",
")",
":",
"# get parameters passed",
"exp_number",
"=",
"int_msg",
"scan_number",
"=",
"int_msg2",
"# get PeakInfo",
"peak_info",
"=",
"self",
".",
"_myControl",
".",
"get_peak_info",
"("... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L4164-L4180 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridInterface_InitAllTypeHandlers | (*args) | return _propgrid.PropertyGridInterface_InitAllTypeHandlers(*args) | PropertyGridInterface_InitAllTypeHandlers() | PropertyGridInterface_InitAllTypeHandlers() | [
"PropertyGridInterface_InitAllTypeHandlers",
"()"
] | def PropertyGridInterface_InitAllTypeHandlers(*args):
"""PropertyGridInterface_InitAllTypeHandlers()"""
return _propgrid.PropertyGridInterface_InitAllTypeHandlers(*args) | [
"def",
"PropertyGridInterface_InitAllTypeHandlers",
"(",
"*",
"args",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_InitAllTypeHandlers",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1803-L1805 | |
Caffe-MPI/Caffe-MPI.github.io | df5992af571a2a19981b69635115c393f18d1c76 | python/caffe/io.py | python | array_to_blobproto | (arr, diff=None) | return blob | Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | [
"Converts",
"a",
"N",
"-",
"dimensional",
"array",
"to",
"blob",
"proto",
".",
"If",
"diff",
"is",
"given",
"also",
"convert",
"the",
"diff",
".",
"You",
"need",
"to",
"make",
"sure",
"that",
"arr",
"and",
"diff",
"have",
"the",
"same",
"shape",
"and",... | def array_to_blobproto(arr, diff=None):
"""Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
"""
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob | [
"def",
"array_to_blobproto",
"(",
"arr",
",",
"diff",
"=",
"None",
")",
":",
"blob",
"=",
"caffe_pb2",
".",
"BlobProto",
"(",
")",
"blob",
".",
"shape",
".",
"dim",
".",
"extend",
"(",
"arr",
".",
"shape",
")",
"blob",
".",
"data",
".",
"extend",
"... | https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/python/caffe/io.py#L36-L46 | |
potassco/clingo | e0c91d8f95cc28de1c480a871f9c97c30de83d40 | libpyclingo/clingo/solving.py | python | SolveControl.symbolic_atoms | (self) | return SymbolicAtoms(atoms) | `clingo.symbolic_atoms.SymbolicAtoms` object to inspect the symbolic atoms. | `clingo.symbolic_atoms.SymbolicAtoms` object to inspect the symbolic atoms. | [
"clingo",
".",
"symbolic_atoms",
".",
"SymbolicAtoms",
"object",
"to",
"inspect",
"the",
"symbolic",
"atoms",
"."
] | def symbolic_atoms(self) -> SymbolicAtoms:
'''
`clingo.symbolic_atoms.SymbolicAtoms` object to inspect the symbolic atoms.
'''
atoms = _c_call('clingo_symbolic_atoms_t*', _lib.clingo_solve_control_symbolic_atoms, self._rep)
return SymbolicAtoms(atoms) | [
"def",
"symbolic_atoms",
"(",
"self",
")",
"->",
"SymbolicAtoms",
":",
"atoms",
"=",
"_c_call",
"(",
"'clingo_symbolic_atoms_t*'",
",",
"_lib",
".",
"clingo_solve_control_symbolic_atoms",
",",
"self",
".",
"_rep",
")",
"return",
"SymbolicAtoms",
"(",
"atoms",
")"
... | https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/solving.py#L199-L204 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/dep_util.py | python | newer_pairwise | (sources, targets) | return n_sources, n_targets | Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'. | Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'. | [
"Walk",
"two",
"filename",
"lists",
"in",
"parallel",
"testing",
"if",
"each",
"source",
"is",
"newer",
"than",
"its",
"corresponding",
"target",
".",
"Return",
"a",
"pair",
"of",
"lists",
"(",
"sources",
"targets",
")",
"where",
"source",
"is",
"newer",
"... | def newer_pairwise(sources, targets):
"""Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'.
"""
if len(sources) != len(targets):
raise ValueError, "'sources' and 'targets' must be same length"
# build a pair of lists (sources, targets) where source is newer
n_sources = []
n_targets = []
for source, target in zip(sources, targets):
if newer(source, target):
n_sources.append(source)
n_targets.append(target)
return n_sources, n_targets | [
"def",
"newer_pairwise",
"(",
"sources",
",",
"targets",
")",
":",
"if",
"len",
"(",
"sources",
")",
"!=",
"len",
"(",
"targets",
")",
":",
"raise",
"ValueError",
",",
"\"'sources' and 'targets' must be same length\"",
"# build a pair of lists (sources, targets) where ... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/dep_util.py#L33-L50 | |
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | examples/python/keras/candle_uno/default_utils.py | python | Benchmark.set_locals | (self) | Functionality to set variables specific for the benchmark
- required: set of required parameters for the benchmark.
- additional_definitions: list of dictionaries describing \
the additional parameters for the benchmark. | Functionality to set variables specific for the benchmark
- required: set of required parameters for the benchmark.
- additional_definitions: list of dictionaries describing \
the additional parameters for the benchmark. | [
"Functionality",
"to",
"set",
"variables",
"specific",
"for",
"the",
"benchmark",
"-",
"required",
":",
"set",
"of",
"required",
"parameters",
"for",
"the",
"benchmark",
".",
"-",
"additional_definitions",
":",
"list",
"of",
"dictionaries",
"describing",
"\\",
"... | def set_locals(self):
""" Functionality to set variables specific for the benchmark
- required: set of required parameters for the benchmark.
- additional_definitions: list of dictionaries describing \
the additional parameters for the benchmark.
"""
pass | [
"def",
"set_locals",
"(",
"self",
")",
":",
"pass"
] | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/examples/python/keras/candle_uno/default_utils.py#L962-L969 | ||
glinscott/leela-chess | 481f1de6c0d2ad7f4e27df551ac5fc754e684f69 | scripts/stats/netstats.py | python | plot_stats | (stats, name, cfg) | Plots various chess statistics | Plots various chess statistics | [
"Plots",
"various",
"chess",
"statistics"
] | def plot_stats(stats, name, cfg):
"""
Plots various chess statistics
"""
types = ['o', '.', '^', 'v', '+', 'x']
colors = ['w', 'k', 'b', 'g', 'm', 'r']
edges = ['k', 'k', 'b', 'g', 'm', 'r']
w = np.sum(stats['white'])
b = np.sum(stats['black'])
d = np.sum(stats['draw'])
t = w + b + d
w = int(np.round(w / float(t) * 100))
b = int(np.round(b / float(t) * 100))
d = int(np.round(d / float(t) * 100))
max_plies = stats['white'].size
fig=plt.figure(figsize=(12, 5), dpi=80)
plt.xlim(0, max_plies)
plt.xlabel('ply (half-move)')
plt.ylabel('games')
games = int(np.sum(stats['plycount']))
cutoff = (stats['plycount'][max_plies-1][0] / float(games)) * 100
plt.title('{} games, (w {}%, b {}%, d {}%) - {:.2f}% cutoff [{}]'.format(games, w, b, d, cutoff, name))
for i, k in enumerate(['white', 'black', 'nomaterial', 'stalemate', '3-fold', '50-move']):
stats[k][stats[k] == 0] = np.nan
plt.plot(range(1, max_plies), stats[k][:max_plies-1], "{}".format(types[i]+colors[i]), label=k, markeredgecolor=edges[i])
plt.legend()
filename = os.path.join(cfg.output, '{}.png'.format(name))
fig.savefig(filename, bbox_inches='tight')
print("Saved as `{}'".format(filename)) | [
"def",
"plot_stats",
"(",
"stats",
",",
"name",
",",
"cfg",
")",
":",
"types",
"=",
"[",
"'o'",
",",
"'.'",
",",
"'^'",
",",
"'v'",
",",
"'+'",
",",
"'x'",
"]",
"colors",
"=",
"[",
"'w'",
",",
"'k'",
",",
"'b'",
",",
"'g'",
",",
"'m'",
",",
... | https://github.com/glinscott/leela-chess/blob/481f1de6c0d2ad7f4e27df551ac5fc754e684f69/scripts/stats/netstats.py#L47-L77 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.erase_up | (self) | Erases the screen from the current line up to the top of the
screen. | Erases the screen from the current line up to the top of the
screen. | [
"Erases",
"the",
"screen",
"from",
"the",
"current",
"line",
"up",
"to",
"the",
"top",
"of",
"the",
"screen",
"."
] | def erase_up (self): # <ESC>[1J
'''Erases the screen from the current line up to the top of the
screen.'''
self.erase_start_of_line ()
self.fill_region (self.cur_r-1, 1, 1, self.cols) | [
"def",
"erase_up",
"(",
"self",
")",
":",
"# <ESC>[1J",
"self",
".",
"erase_start_of_line",
"(",
")",
"self",
".",
"fill_region",
"(",
"self",
".",
"cur_r",
"-",
"1",
",",
"1",
",",
"1",
",",
"self",
".",
"cols",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L400-L405 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Image.configure | (self, **kw) | Configure the image. | Configure the image. | [
"Configure",
"the",
"image",
"."
] | def configure(self, **kw):
"""Configure the image."""
res = ()
for k, v in _cnfmerge(kw).items():
if v is not None:
if k[-1] == '_': k = k[:-1]
if hasattr(v, '__call__'):
v = self._register(v)
res = res + ('-'+k, v)
self.tk.call((self.name, 'config') + res) | [
"def",
"configure",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"res",
"=",
"(",
")",
"for",
"k",
",",
"v",
"in",
"_cnfmerge",
"(",
"kw",
")",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"if",
"k",
"[",
"-",
"1",
"]"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3276-L3285 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailcap.py | python | findmatch | (caps, MIMEtype, key='view', filename="/dev/null", plist=[]) | return None, None | Find a match for a mailcap entry.
Return a tuple containing the command line, and the mailcap entry
used; (None, None) if no match is found. This may invoke the
'test' command of several matching entries before deciding which
entry to use. | Find a match for a mailcap entry. | [
"Find",
"a",
"match",
"for",
"a",
"mailcap",
"entry",
"."
] | def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
"""Find a match for a mailcap entry.
Return a tuple containing the command line, and the mailcap entry
used; (None, None) if no match is found. This may invoke the
'test' command of several matching entries before deciding which
entry to use.
"""
entries = lookup(caps, MIMEtype, key)
# XXX This code should somehow check for the needsterminal flag.
for e in entries:
if 'test' in e:
test = subst(e['test'], filename, plist)
if test and os.system(test) != 0:
continue
command = subst(e[key], MIMEtype, filename, plist)
return command, e
return None, None | [
"def",
"findmatch",
"(",
"caps",
",",
"MIMEtype",
",",
"key",
"=",
"'view'",
",",
"filename",
"=",
"\"/dev/null\"",
",",
"plist",
"=",
"[",
"]",
")",
":",
"entries",
"=",
"lookup",
"(",
"caps",
",",
"MIMEtype",
",",
"key",
")",
"# XXX This code should so... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailcap.py#L138-L156 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.WriteAndroidNdkModuleRule | (self, module_name, all_sources, link_deps) | Write a set of LOCAL_XXX definitions for Android NDK.
These variable definitions will be used by Android NDK but do nothing for
non-Android applications.
Arguments:
module_name: Android NDK module name, which must be unique among all
module names.
all_sources: A list of source files (will be filtered by Compilable).
link_deps: A list of link dependencies, which must be sorted in
the order from dependencies to dependents. | Write a set of LOCAL_XXX definitions for Android NDK. | [
"Write",
"a",
"set",
"of",
"LOCAL_XXX",
"definitions",
"for",
"Android",
"NDK",
"."
] | def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps):
"""Write a set of LOCAL_XXX definitions for Android NDK.
These variable definitions will be used by Android NDK but do nothing for
non-Android applications.
Arguments:
module_name: Android NDK module name, which must be unique among all
module names.
all_sources: A list of source files (will be filtered by Compilable).
link_deps: A list of link dependencies, which must be sorted in
the order from dependencies to dependents.
"""
if self.type not in ('executable', 'shared_library', 'static_library'):
return
self.WriteLn('# Variable definitions for Android applications')
self.WriteLn('include $(CLEAR_VARS)')
self.WriteLn('LOCAL_MODULE := ' + module_name)
self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) '
'$(DEFS_$(BUILDTYPE)) '
# LOCAL_CFLAGS is applied to both of C and C++. There is
# no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C
# sources.
'$(CFLAGS_C_$(BUILDTYPE)) '
# $(INCS_$(BUILDTYPE)) includes the prefix '-I' while
# LOCAL_C_INCLUDES does not expect it. So put it in
# LOCAL_CFLAGS.
'$(INCS_$(BUILDTYPE))')
# LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred.
self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))')
self.WriteLn('LOCAL_C_INCLUDES :=')
self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)')
# Detect the C++ extension.
cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0}
default_cpp_ext = '.cpp'
for filename in all_sources:
ext = os.path.splitext(filename)[1]
if ext in cpp_ext:
cpp_ext[ext] += 1
if cpp_ext[ext] > cpp_ext[default_cpp_ext]:
default_cpp_ext = ext
self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext)
self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)),
'LOCAL_SRC_FILES')
# Filter out those which do not match prefix and suffix and produce
# the resulting list without prefix and suffix.
def DepsToModules(deps, prefix, suffix):
modules = []
for filepath in deps:
filename = os.path.basename(filepath)
if filename.startswith(prefix) and filename.endswith(suffix):
modules.append(filename[len(prefix):-len(suffix)])
return modules
# Retrieve the default value of 'SHARED_LIB_SUFFIX'
params = {'flavor': 'linux'}
default_variables = {}
CalculateVariables(default_variables, params)
self.WriteList(
DepsToModules(link_deps,
generator_default_variables['SHARED_LIB_PREFIX'],
default_variables['SHARED_LIB_SUFFIX']),
'LOCAL_SHARED_LIBRARIES')
self.WriteList(
DepsToModules(link_deps,
generator_default_variables['STATIC_LIB_PREFIX'],
generator_default_variables['STATIC_LIB_SUFFIX']),
'LOCAL_STATIC_LIBRARIES')
if self.type == 'executable':
self.WriteLn('include $(BUILD_EXECUTABLE)')
elif self.type == 'shared_library':
self.WriteLn('include $(BUILD_SHARED_LIBRARY)')
elif self.type == 'static_library':
self.WriteLn('include $(BUILD_STATIC_LIBRARY)')
self.WriteLn() | [
"def",
"WriteAndroidNdkModuleRule",
"(",
"self",
",",
"module_name",
",",
"all_sources",
",",
"link_deps",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"(",
"'executable'",
",",
"'shared_library'",
",",
"'static_library'",
")",
":",
"return",
"self",
".",... | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/make.py#L1760-L1840 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/ndarray/ndarray.py | python | NDArray._set_nd_advanced_indexing | (self, key, value) | This function is called by __setitem__ when key is an advanced index. | This function is called by __setitem__ when key is an advanced index. | [
"This",
"function",
"is",
"called",
"by",
"__setitem__",
"when",
"key",
"is",
"an",
"advanced",
"index",
"."
] | def _set_nd_advanced_indexing(self, key, value):
"""This function is called by __setitem__ when key is an advanced index."""
indices = self._get_index_nd(key)
vshape = _get_oshape_of_gather_nd_op(self.shape, indices.shape)
value_nd = self._prepare_value_nd(value, vshape)
_internal._scatter_set_nd(lhs=self, rhs=value_nd, indices=indices,
shape=self.shape, out=self) | [
"def",
"_set_nd_advanced_indexing",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"indices",
"=",
"self",
".",
"_get_index_nd",
"(",
"key",
")",
"vshape",
"=",
"_get_oshape_of_gather_nd_op",
"(",
"self",
".",
"shape",
",",
"indices",
".",
"shape",
")",
... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L768-L774 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/utils/chemdraw.py | python | OptimizeSDFile | (inFileName, outFileName, problemFileName='problems.sdf', restartEvery=20) | optimizes the structure of every molecule in the input SD file
**Arguments**
- inFileName: name of the input SD file
- outFileName: name of the output SD file
- problemFileName: (optional) name of the SD file used to store molecules which
fail during the optimization process
- restartEvery: (optional) Chem3D will be shut down and restarted
every _restartEvery_ molecules to try and keep core leaks under control | optimizes the structure of every molecule in the input SD file | [
"optimizes",
"the",
"structure",
"of",
"every",
"molecule",
"in",
"the",
"input",
"SD",
"file"
] | def OptimizeSDFile(inFileName, outFileName, problemFileName='problems.sdf', restartEvery=20):
""" optimizes the structure of every molecule in the input SD file
**Arguments**
- inFileName: name of the input SD file
- outFileName: name of the output SD file
- problemFileName: (optional) name of the SD file used to store molecules which
fail during the optimization process
- restartEvery: (optional) Chem3D will be shut down and restarted
every _restartEvery_ molecules to try and keep core leaks under control
"""
inFile = open(inFileName, 'r')
outFile = open(outFileName, 'w+')
problemFile = None
props = {}
lines = []
nextLine = inFile.readline()
skip = 0
nDone = 0
t1 = time.time()
while nextLine != '':
if nextLine.find('M END') != -1:
lines.append(nextLine)
molBlock = ''.join(lines)
try:
newMolBlock = Add3DCoordsToMol(molBlock, 'chemical/mdl-molfile', props=props)
except Exception:
badBlock = molBlock
skip = 1
lines = []
else:
skip = 0
lines = [newMolBlock]
elif nextLine.find('$$$$') != -1:
t2 = time.time()
nDone += 1
print('finished molecule %d in %f seconds' % (nDone, time.time() - t1))
t1 = time.time()
if nDone % restartEvery == 0:
CloseChem3D()
StartChem3D()
outFile.close()
outFile = open(outFileName, 'a')
if not skip:
for prop in props.keys():
lines.append('> <%s>\n%f\n\n' % (prop, props[prop]))
lines.append(nextLine)
outFile.write(''.join(lines))
lines = []
else:
skip = 0
lines.append(nextLine)
if problemFile is None:
problemFile = open(problemFileName, 'w+')
problemFile.write(badBlock)
problemFile.write(''.join(lines))
lines = []
else:
lines.append(nextLine)
nextLine = inFile.readline()
outFile.close()
if problemFile is not None:
problemFile.close() | [
"def",
"OptimizeSDFile",
"(",
"inFileName",
",",
"outFileName",
",",
"problemFileName",
"=",
"'problems.sdf'",
",",
"restartEvery",
"=",
"20",
")",
":",
"inFile",
"=",
"open",
"(",
"inFileName",
",",
"'r'",
")",
"outFile",
"=",
"open",
"(",
"outFileName",
",... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/utils/chemdraw.py#L360-L428 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/aoc/upgrade_ability_subprocessor.py | python | AoCUpgradeAbilitySubprocessor.turn_ability | (converter_group, line, container_obj_ref, diff=None) | return patches | Creates a patch for the Turn ability of a line.
:param converter_group: Group that gets the patch.
:type converter_group: ...dataformat.converter_object.ConverterObjectGroup
:param line: Unit/Building line that has the ability.
:type line: ...dataformat.converter_object.ConverterObjectGroup
:param container_obj_ref: Reference of the raw API object the patch is nested in.
:type container_obj_ref: str
:param diff: A diff between two ConvertObject instances.
:type diff: ...dataformat.converter_object.ConverterObject
:returns: The forward references for the generated patches.
:rtype: list | Creates a patch for the Turn ability of a line. | [
"Creates",
"a",
"patch",
"for",
"the",
"Turn",
"ability",
"of",
"a",
"line",
"."
] | def turn_ability(converter_group, line, container_obj_ref, diff=None):
"""
Creates a patch for the Turn ability of a line.
:param converter_group: Group that gets the patch.
:type converter_group: ...dataformat.converter_object.ConverterObjectGroup
:param line: Unit/Building line that has the ability.
:type line: ...dataformat.converter_object.ConverterObjectGroup
:param container_obj_ref: Reference of the raw API object the patch is nested in.
:type container_obj_ref: str
:param diff: A diff between two ConvertObject instances.
:type diff: ...dataformat.converter_object.ConverterObject
:returns: The forward references for the generated patches.
:rtype: list
"""
head_unit_id = line.get_head_unit_id()
tech_id = converter_group.get_id()
dataset = line.data
patches = []
name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version)
tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version)
game_entity_name = name_lookup_dict[head_unit_id][0]
if diff:
diff_turn_speed = diff["turn_speed"]
if isinstance(diff_turn_speed, NoDiffMember):
return patches
diff_turn_speed_value = diff_turn_speed.get_value()
else:
return patches
patch_target_ref = f"{game_entity_name}.Turn"
patch_target_forward_ref = ForwardRef(line, patch_target_ref)
# Wrapper
wrapper_name = f"Change{game_entity_name}TurnWrapper"
wrapper_ref = f"{container_obj_ref}.{wrapper_name}"
wrapper_raw_api_object = RawAPIObject(wrapper_ref,
wrapper_name,
dataset.nyan_api_objects)
wrapper_raw_api_object.add_raw_parent("engine.util.patch.Patch")
if isinstance(line, GenieBuildingLineGroup):
# Store building upgrades next to their game entity definition,
# not in the Age up techs.
wrapper_raw_api_object.set_location("data/game_entity/generic/%s/"
% (name_lookup_dict[head_unit_id][1]))
wrapper_raw_api_object.set_filename(f"{tech_lookup_dict[tech_id][1]}_upgrade")
else:
wrapper_raw_api_object.set_location(ForwardRef(converter_group, container_obj_ref))
# Nyan patch
nyan_patch_name = f"Change{game_entity_name}Turn"
nyan_patch_ref = f"{container_obj_ref}.{wrapper_name}.{nyan_patch_name}"
nyan_patch_location = ForwardRef(converter_group, wrapper_ref)
nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref,
nyan_patch_name,
dataset.nyan_api_objects,
nyan_patch_location)
nyan_patch_raw_api_object.add_raw_parent("engine.util.patch.NyanPatch")
nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref)
# Speed
turn_speed_unmodified = diff_turn_speed_value
turn_speed = MemberSpecialValue.NYAN_INF
# Ships/Trebuchets turn slower
if turn_speed_unmodified > 0:
turn_yaw = diff["max_yaw_per_sec_moving"].get_value()
turn_speed = degrees(turn_yaw)
nyan_patch_raw_api_object.add_raw_patch_member("turn_speed",
turn_speed,
"engine.ability.type.Turn",
MemberOperator.ASSIGN)
patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref)
wrapper_raw_api_object.add_raw_member("patch",
patch_forward_ref,
"engine.util.patch.Patch")
converter_group.add_raw_api_object(wrapper_raw_api_object)
converter_group.add_raw_api_object(nyan_patch_raw_api_object)
wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref)
patches.append(wrapper_forward_ref)
return patches | [
"def",
"turn_ability",
"(",
"converter_group",
",",
"line",
",",
"container_obj_ref",
",",
"diff",
"=",
"None",
")",
":",
"head_unit_id",
"=",
"line",
".",
"get_head_unit_id",
"(",
")",
"tech_id",
"=",
"converter_group",
".",
"get_id",
"(",
")",
"dataset",
"... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/aoc/upgrade_ability_subprocessor.py#L1682-L1774 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/array_ops.py | python | matrix_diag | (diagonal,
name="diag",
k=0,
num_rows=-1,
num_cols=-1,
padding_value=0) | return gen_array_ops.matrix_diag(diagonal=diagonal, name=name) | Returns a batched diagonal tensor with given batched diagonal values.
Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th
diagonals of a matrix, with everything else padded with `padding`. `num_rows`
and `num_cols` specify the dimension of the innermost matrix of the output. If
both are not specified, the op assumes the innermost matrix is square and
infers its size from `k` and the innermost dimension of `diagonal`. If only
one of them is specified, the op assumes the unspecified value is the smallest
possible based on other criteria.
Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor
has rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only
one diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has
rank `r` with shape `[I, J, ..., L, num_rows, num_cols]`.
The second innermost dimension of `diagonal` has double meaning. When `k` is
scalar or `k[0] == k[1]`, `M` is part of the batch size [I, J, ..., M], and
the output tensor is:
```
output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper
output[i, j, ..., l, m, n] ; otherwise
```
Otherwise, `M` is treated as the number of diagonals for the matrix in the
same batch (`M = k[1]-k[0]+1`), and the output tensor is:
```
output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, k[1]-d, n-max(d, 0)] ; if d_lower <= d <= d_upper
input[i, j, ..., l, m, n] ; otherwise
```
where `d = n - m`
For example:
```
# The main diagonal.
diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)
[5, 6, 7, 8]])
tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]],
[[5, 0, 0, 0],
[0, 6, 0, 0],
[0, 0, 7, 0],
[0, 0, 0, 8]]]
# A superdiagonal (per batch).
diagonal = np.array([[1, 2, 3], # Input shape: (2, 3)
[4, 5, 6]])
tf.matrix_diag(diagonal, k = 1)
==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)
[0, 0, 2, 0],
[0, 0, 0, 3],
[0, 0, 0, 0]],
[[0, 4, 0, 0],
[0, 0, 5, 0],
[0, 0, 0, 6],
[0, 0, 0, 0]]]
# A band of diagonals.
diagonals = np.array([[[1, 2, 3], # Input shape: (2, 2, 3)
[4, 5, 0]],
[[6, 7, 9],
[9, 1, 0]]])
tf.matrix_diag(diagonals, k = (-1, 0))
==> [[[1, 0, 0], # Output shape: (2, 3, 3)
[4, 2, 0],
[0, 5, 3]],
[[6, 0, 0],
[9, 7, 0],
[0, 1, 9]]]
# Rectangular matrix.
diagonal = np.array([1, 2]) # Input shape: (2)
tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)
==> [[0, 0, 0, 0], # Output shape: (3, 4)
[1, 0, 0, 0],
[0, 2, 0, 0]]
# Rectangular matrix with inferred num_cols and padding = 9.
tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding = 9)
==> [[9, 9], # Output shape: (3, 2)
[1, 9],
[9, 2]]
```
Args:
diagonal: A `Tensor` with `rank k >= 1`.
name: A name for the operation (optional).
k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the
main diagonal, and negative value means subdiagonals. `k` can be a single
integer (for a single diagonal) or a pair of integers specifying the low
and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.
num_rows: The number of rows of the output matrix. If it is not provided,
the op assumes the output matrix is a square matrix and infers the matrix
size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.
num_cols: The number of columns of the output matrix. If it is not provided,
the op assumes the output matrix is a square matrix and infers the matrix
size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.
padding_value: The value to fill the area outside the specified diagonal
band with. Default is 0.
Returns:
A Tensor. Has the same type as `diagonal`. | Returns a batched diagonal tensor with given batched diagonal values. | [
"Returns",
"a",
"batched",
"diagonal",
"tensor",
"with",
"given",
"batched",
"diagonal",
"values",
"."
] | def matrix_diag(diagonal,
name="diag",
k=0,
num_rows=-1,
num_cols=-1,
padding_value=0):
"""Returns a batched diagonal tensor with given batched diagonal values.
Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th
diagonals of a matrix, with everything else padded with `padding`. `num_rows`
and `num_cols` specify the dimension of the innermost matrix of the output. If
both are not specified, the op assumes the innermost matrix is square and
infers its size from `k` and the innermost dimension of `diagonal`. If only
one of them is specified, the op assumes the unspecified value is the smallest
possible based on other criteria.
Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor
has rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only
one diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has
rank `r` with shape `[I, J, ..., L, num_rows, num_cols]`.
The second innermost dimension of `diagonal` has double meaning. When `k` is
scalar or `k[0] == k[1]`, `M` is part of the batch size [I, J, ..., M], and
the output tensor is:
```
output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper
output[i, j, ..., l, m, n] ; otherwise
```
Otherwise, `M` is treated as the number of diagonals for the matrix in the
same batch (`M = k[1]-k[0]+1`), and the output tensor is:
```
output[i, j, ..., l, m, n]
= diagonal[i, j, ..., l, k[1]-d, n-max(d, 0)] ; if d_lower <= d <= d_upper
input[i, j, ..., l, m, n] ; otherwise
```
where `d = n - m`
For example:
```
# The main diagonal.
diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)
[5, 6, 7, 8]])
tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]],
[[5, 0, 0, 0],
[0, 6, 0, 0],
[0, 0, 7, 0],
[0, 0, 0, 8]]]
# A superdiagonal (per batch).
diagonal = np.array([[1, 2, 3], # Input shape: (2, 3)
[4, 5, 6]])
tf.matrix_diag(diagonal, k = 1)
==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)
[0, 0, 2, 0],
[0, 0, 0, 3],
[0, 0, 0, 0]],
[[0, 4, 0, 0],
[0, 0, 5, 0],
[0, 0, 0, 6],
[0, 0, 0, 0]]]
# A band of diagonals.
diagonals = np.array([[[1, 2, 3], # Input shape: (2, 2, 3)
[4, 5, 0]],
[[6, 7, 9],
[9, 1, 0]]])
tf.matrix_diag(diagonals, k = (-1, 0))
==> [[[1, 0, 0], # Output shape: (2, 3, 3)
[4, 2, 0],
[0, 5, 3]],
[[6, 0, 0],
[9, 7, 0],
[0, 1, 9]]]
# Rectangular matrix.
diagonal = np.array([1, 2]) # Input shape: (2)
tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)
==> [[0, 0, 0, 0], # Output shape: (3, 4)
[1, 0, 0, 0],
[0, 2, 0, 0]]
# Rectangular matrix with inferred num_cols and padding = 9.
tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding = 9)
==> [[9, 9], # Output shape: (3, 2)
[1, 9],
[9, 2]]
```
Args:
diagonal: A `Tensor` with `rank k >= 1`.
name: A name for the operation (optional).
k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the
main diagonal, and negative value means subdiagonals. `k` can be a single
integer (for a single diagonal) or a pair of integers specifying the low
and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.
num_rows: The number of rows of the output matrix. If it is not provided,
the op assumes the output matrix is a square matrix and infers the matrix
size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.
num_cols: The number of columns of the output matrix. If it is not provided,
the op assumes the output matrix is a square matrix and infers the matrix
size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.
padding_value: The value to fill the area outside the specified diagonal
band with. Default is 0.
Returns:
A Tensor. Has the same type as `diagonal`.
"""
# LINT.IfChange
if compat.forward_compatible(2019, 8, 31):
# LINT.ThenChange(//tensorflow/python/kernel_tests/diag_op_test.py)
# Special case to sidestep the tf.constant conversion error:
# TypeError: Expected bool, got 0 of type 'int' instead.
if hasattr(diagonal, "dtype") and diagonal.dtype == "bool":
padding_value = bool(padding_value)
return gen_array_ops.matrix_diag_v2(
diagonal=diagonal,
k=k,
num_rows=num_rows,
num_cols=num_cols,
padding_value=padding_value,
name=name)
# Call v1 to maintain forward compatibility.
return gen_array_ops.matrix_diag(diagonal=diagonal, name=name) | [
"def",
"matrix_diag",
"(",
"diagonal",
",",
"name",
"=",
"\"diag\"",
",",
"k",
"=",
"0",
",",
"num_rows",
"=",
"-",
"1",
",",
"num_cols",
"=",
"-",
"1",
",",
"padding_value",
"=",
"0",
")",
":",
"# LINT.IfChange",
"if",
"compat",
".",
"forward_compatib... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/array_ops.py#L1946-L2078 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/externals/cloudpickle/cloudpickle_fast.py | python | _class_reduce | (obj) | return NotImplemented | Select the reducer depending on the dynamic nature of the class obj | Select the reducer depending on the dynamic nature of the class obj | [
"Select",
"the",
"reducer",
"depending",
"on",
"the",
"dynamic",
"nature",
"of",
"the",
"class",
"obj"
] | def _class_reduce(obj):
"""Select the reducer depending on the dynamic nature of the class obj"""
if obj is type(None): # noqa
return type, (None,)
elif obj is type(Ellipsis):
return type, (Ellipsis,)
elif obj is type(NotImplemented):
return type, (NotImplemented,)
elif obj in _BUILTIN_TYPE_NAMES:
return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
elif not _should_pickle_by_reference(obj):
return _dynamic_class_reduce(obj)
return NotImplemented | [
"def",
"_class_reduce",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"type",
"(",
"None",
")",
":",
"# noqa",
"return",
"type",
",",
"(",
"None",
",",
")",
"elif",
"obj",
"is",
"type",
"(",
"Ellipsis",
")",
":",
"return",
"type",
",",
"(",
"Ellipsis",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/externals/cloudpickle/cloudpickle_fast.py#L407-L419 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py | python | SysLogHandler.mapPriority | (self, levelName) | return self.priority_map.get(levelName, "warning") | Map a logging level name to a key in the priority_names map.
This is useful in two scenarios: when custom levels are being
used, and in the case where you can't do a straightforward
mapping by lowercasing the logging level name because of locale-
specific issues (see SF #1524081). | Map a logging level name to a key in the priority_names map.
This is useful in two scenarios: when custom levels are being
used, and in the case where you can't do a straightforward
mapping by lowercasing the logging level name because of locale-
specific issues (see SF #1524081). | [
"Map",
"a",
"logging",
"level",
"name",
"to",
"a",
"key",
"in",
"the",
"priority_names",
"map",
".",
"This",
"is",
"useful",
"in",
"two",
"scenarios",
":",
"when",
"custom",
"levels",
"are",
"being",
"used",
"and",
"in",
"the",
"case",
"where",
"you",
... | def mapPriority(self, levelName):
"""
Map a logging level name to a key in the priority_names map.
This is useful in two scenarios: when custom levels are being
used, and in the case where you can't do a straightforward
mapping by lowercasing the logging level name because of locale-
specific issues (see SF #1524081).
"""
return self.priority_map.get(levelName, "warning") | [
"def",
"mapPriority",
"(",
"self",
",",
"levelName",
")",
":",
"return",
"self",
".",
"priority_map",
".",
"get",
"(",
"levelName",
",",
"\"warning\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py#L897-L905 | |
PlatformLab/Arachne | e67391471007174dd4002dc2c160628e19c284e8 | scripts/cpplint.py | python | NestingState.InClassDeclaration | (self) | return self.stack and isinstance(self.stack[-1], _ClassInfo) | Check if we are currently one level inside a class or struct declaration.
Returns:
True if top of the stack is a class/struct, False otherwise. | Check if we are currently one level inside a class or struct declaration. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"a",
"class",
"or",
"struct",
"declaration",
"."
] | def InClassDeclaration(self):
"""Check if we are currently one level inside a class or struct declaration.
Returns:
True if top of the stack is a class/struct, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ClassInfo) | [
"def",
"InClassDeclaration",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ClassInfo",
")"
] | https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L2320-L2326 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.BraceHighlight | (*args, **kwargs) | return _stc.StyledTextCtrl_BraceHighlight(*args, **kwargs) | BraceHighlight(self, int pos1, int pos2)
Highlight the characters at two positions. | BraceHighlight(self, int pos1, int pos2) | [
"BraceHighlight",
"(",
"self",
"int",
"pos1",
"int",
"pos2",
")"
] | def BraceHighlight(*args, **kwargs):
"""
BraceHighlight(self, int pos1, int pos2)
Highlight the characters at two positions.
"""
return _stc.StyledTextCtrl_BraceHighlight(*args, **kwargs) | [
"def",
"BraceHighlight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_BraceHighlight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L4799-L4805 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/vis/editors.py | python | VisualEditorBase.updateValueFromGui | (self) | return | Called the value is requested (from Save... and OK) | Called the value is requested (from Save... and OK) | [
"Called",
"the",
"value",
"is",
"requested",
"(",
"from",
"Save",
"...",
"and",
"OK",
")"
] | def updateValueFromGui(self):
"""Called the value is requested (from Save... and OK)"""
return | [
"def",
"updateValueFromGui",
"(",
"self",
")",
":",
"return"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/vis/editors.py#L47-L49 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PyFileDialogAdapter.__init__ | (self, *args, **kwargs) | __init__(self) -> PyFileDialogAdapter | __init__(self) -> PyFileDialogAdapter | [
"__init__",
"(",
"self",
")",
"-",
">",
"PyFileDialogAdapter"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> PyFileDialogAdapter"""
_propgrid.PyFileDialogAdapter_swiginit(self,_propgrid.new_PyFileDialogAdapter(*args, **kwargs))
self._SetSelf(self); self._RegisterMethods() | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_propgrid",
".",
"PyFileDialogAdapter_swiginit",
"(",
"self",
",",
"_propgrid",
".",
"new_PyFileDialogAdapter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"se... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3987-L3990 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py | python | _count_elements | (mapping, iterable) | Tally elements from the iterable. | Tally elements from the iterable. | [
"Tally",
"elements",
"from",
"the",
"iterable",
"."
] | def _count_elements(mapping, iterable):
'Tally elements from the iterable.'
mapping_get = mapping.get
for elem in iterable:
mapping[elem] = mapping_get(elem, 0) + 1 | [
"def",
"_count_elements",
"(",
"mapping",
",",
"iterable",
")",
":",
"mapping_get",
"=",
"mapping",
".",
"get",
"for",
"elem",
"in",
"iterable",
":",
"mapping",
"[",
"elem",
"]",
"=",
"mapping_get",
"(",
"elem",
",",
"0",
")",
"+",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py#L488-L492 | ||
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | tools/api_proto_plugin/annotations.py | python | xform_annotation | (s, annotation_xforms) | return xformed | Return transformed string with annotation transformers.
The annotation will be replaced with the new value returned by the transformer.
If the transformer returns None, then the annotation will be removed.
If the annotation presented in transformers doesn't exist in the original string,
a new annotation will be appended to the end of string.
Args:
annotation_xforms: a dict of transformers for annotations.
Returns:
transformed string. | Return transformed string with annotation transformers. | [
"Return",
"transformed",
"string",
"with",
"annotation",
"transformers",
"."
] | def xform_annotation(s, annotation_xforms):
"""Return transformed string with annotation transformers.
The annotation will be replaced with the new value returned by the transformer.
If the transformer returns None, then the annotation will be removed.
If the annotation presented in transformers doesn't exist in the original string,
a new annotation will be appended to the end of string.
Args:
annotation_xforms: a dict of transformers for annotations.
Returns:
transformed string.
"""
present_annotations = set()
def xform(match):
annotation, content, trailing = match.groups()
present_annotations.add(annotation)
annotation_xform = annotation_xforms.get(annotation)
if annotation_xform:
value = annotation_xform(annotation)
return '[#%s: %s]%s' % (annotation, value, trailing) if value is not None else ''
else:
return match.group(0)
def append(s, annotation, content):
return '%s [#%s: %s]\n' % (s, annotation, content)
xformed = re.sub(ANNOTATION_REGEX, xform, s)
for annotation, xform in sorted(annotation_xforms.items()):
if annotation not in present_annotations:
value = xform(None)
if value is not None:
xformed = append(xformed, annotation, value)
return xformed | [
"def",
"xform_annotation",
"(",
"s",
",",
"annotation_xforms",
")",
":",
"present_annotations",
"=",
"set",
"(",
")",
"def",
"xform",
"(",
"match",
")",
":",
"annotation",
",",
"content",
",",
"trailing",
"=",
"match",
".",
"groups",
"(",
")",
"present_ann... | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/tools/api_proto_plugin/annotations.py#L80-L115 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/parser/WebIDL.py | python | Parser.p_UnionMemberType | (self, p) | UnionMemberType : UnionType TypeSuffix
| UnionMemberTypeArrayOfAny TypeSuffix | UnionMemberType : UnionType TypeSuffix
| UnionMemberTypeArrayOfAny TypeSuffix | [
"UnionMemberType",
":",
"UnionType",
"TypeSuffix",
"|",
"UnionMemberTypeArrayOfAny",
"TypeSuffix"
] | def p_UnionMemberType(self, p):
"""
UnionMemberType : UnionType TypeSuffix
| UnionMemberTypeArrayOfAny TypeSuffix
"""
p[0] = self.handleModifiers(p[1], p[2]) | [
"def",
"p_UnionMemberType",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"handleModifiers",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L5191-L5196 | ||
rst-tu-dortmund/teb_local_planner | f737130fa6a9024fef9fcdca6eadacaa69bf30a4 | scripts/export_to_svg.py | python | sign | (number) | return cmp(number,0) | Signum function: get sign of a number
@param number: get sign of this number
@type number: numeric type (eg. integer)
@return: sign of number
@rtype: integer {1, -1, 0} | Signum function: get sign of a number | [
"Signum",
"function",
":",
"get",
"sign",
"of",
"a",
"number"
] | def sign(number):
"""
Signum function: get sign of a number
@param number: get sign of this number
@type number: numeric type (eg. integer)
@return: sign of number
@rtype: integer {1, -1, 0}
"""
return cmp(number,0) | [
"def",
"sign",
"(",
"number",
")",
":",
"return",
"cmp",
"(",
"number",
",",
"0",
")"
] | https://github.com/rst-tu-dortmund/teb_local_planner/blob/f737130fa6a9024fef9fcdca6eadacaa69bf30a4/scripts/export_to_svg.py#L45-L54 | |
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/ops.py | python | broadcast | (
data: NodeInput,
target_shape: NodeInput,
axes_mapping: Optional[NodeInput] = None,
broadcast_spec: str = "NUMPY",
name: Optional[str] = None,
) | return _get_node_factory().create(
"Broadcast", inputs, {"broadcast_spec": broadcast_spec.upper()}
) | Create a node which broadcasts the input node's values along specified axes to a desired shape.
:param data: The node with input tensor data.
:param target_shape: The node with a new shape we want to broadcast tensor to.
:param axes_mapping: The node with a axis positions (0-based) in the result
that are being broadcast.
:param broadcast_spec: The type of broadcasting that specifies mapping of input tensor axes
to output shape axes. Range of values: NUMPY, EXPLICIT, BIDIRECTIONAL.
:param name: Optional new name for output node.
:return: New node with broadcast shape. | Create a node which broadcasts the input node's values along specified axes to a desired shape. | [
"Create",
"a",
"node",
"which",
"broadcasts",
"the",
"input",
"node",
"s",
"values",
"along",
"specified",
"axes",
"to",
"a",
"desired",
"shape",
"."
] | def broadcast(
data: NodeInput,
target_shape: NodeInput,
axes_mapping: Optional[NodeInput] = None,
broadcast_spec: str = "NUMPY",
name: Optional[str] = None,
) -> Node:
"""Create a node which broadcasts the input node's values along specified axes to a desired shape.
:param data: The node with input tensor data.
:param target_shape: The node with a new shape we want to broadcast tensor to.
:param axes_mapping: The node with a axis positions (0-based) in the result
that are being broadcast.
:param broadcast_spec: The type of broadcasting that specifies mapping of input tensor axes
to output shape axes. Range of values: NUMPY, EXPLICIT, BIDIRECTIONAL.
:param name: Optional new name for output node.
:return: New node with broadcast shape.
"""
inputs = as_nodes(data, target_shape)
if broadcast_spec.upper() == "EXPLICIT":
inputs.append(as_node(axes_mapping))
return _get_node_factory().create(
"Broadcast", inputs, {"broadcast_spec": broadcast_spec.upper()}
) | [
"def",
"broadcast",
"(",
"data",
":",
"NodeInput",
",",
"target_shape",
":",
"NodeInput",
",",
"axes_mapping",
":",
"Optional",
"[",
"NodeInput",
"]",
"=",
"None",
",",
"broadcast_spec",
":",
"str",
"=",
"\"NUMPY\"",
",",
"name",
":",
"Optional",
"[",
"str... | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L1390-L1413 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | orttraining/orttraining/python/training/_checkpoint_storage.py | python | save | (save_obj: dict, path) | Persists the input dictionary to a file specified by path.
Saves an hdf5 representation of the save_obj dictionary to a file or a file-like object specified by path.
Values are saved in a format supported by h5py. For example, a PyTorch tensor is saved and loaded as a
numpy object. So, user types may be converted from their original types to numpy equivalent types.
Args:
save_obj: dictionary that needs to be saved.
save_obj should consist of types supported by hdf5 file format.
if hdf5 does not recognize a type, an exception is raised.
if save_obj is not a dictionary, a ValueError is raised.
path: string representation to a file path or a python file-like object.
if file already exists at path, an exception is raised. | Persists the input dictionary to a file specified by path. | [
"Persists",
"the",
"input",
"dictionary",
"to",
"a",
"file",
"specified",
"by",
"path",
"."
] | def save(save_obj: dict, path):
"""Persists the input dictionary to a file specified by path.
Saves an hdf5 representation of the save_obj dictionary to a file or a file-like object specified by path.
Values are saved in a format supported by h5py. For example, a PyTorch tensor is saved and loaded as a
numpy object. So, user types may be converted from their original types to numpy equivalent types.
Args:
save_obj: dictionary that needs to be saved.
save_obj should consist of types supported by hdf5 file format.
if hdf5 does not recognize a type, an exception is raised.
if save_obj is not a dictionary, a ValueError is raised.
path: string representation to a file path or a python file-like object.
if file already exists at path, an exception is raised.
"""
if not isinstance(save_obj, Mapping):
raise ValueError("Object to be saved must be a dictionary")
with h5py.File(path, 'w-') as f:
_dfs_save(f, save_obj) | [
"def",
"save",
"(",
"save_obj",
":",
"dict",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"save_obj",
",",
"Mapping",
")",
":",
"raise",
"ValueError",
"(",
"\"Object to be saved must be a dictionary\"",
")",
"with",
"h5py",
".",
"File",
"(",
"path"... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/_checkpoint_storage.py#L20-L39 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftfunctions/scale.py | python | scale_edge | (obj, edge_index, scale, center) | Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire). | Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire). | [
"Needed",
"for",
"SubObjects",
"modifiers",
".",
"Implemented",
"by",
"Dion",
"Moult",
"during",
"0",
".",
"19",
"dev",
"cycle",
"(",
"works",
"only",
"with",
"Draft",
"Wire",
")",
"."
] | def scale_edge(obj, edge_index, scale, center):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
scale_vertex(obj, edge_index, scale, center)
if utils.is_closed_edge(edge_index, obj):
scale_vertex(obj, 0, scale, center)
else:
scale_vertex(obj, edge_index+1, scale, center) | [
"def",
"scale_edge",
"(",
"obj",
",",
"edge_index",
",",
"scale",
",",
"center",
")",
":",
"scale_vertex",
"(",
"obj",
",",
"edge_index",
",",
"scale",
",",
"center",
")",
"if",
"utils",
".",
"is_closed_edge",
"(",
"edge_index",
",",
"obj",
")",
":",
"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftfunctions/scale.py#L171-L180 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/grid_search.py | python | ParameterGrid.__getitem__ | (self, ind) | Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of string to any
Equal to list(self)[ind] | Get the parameters that would be ``ind``th in iteration | [
"Get",
"the",
"parameters",
"that",
"would",
"be",
"ind",
"th",
"in",
"iteration"
] | def __getitem__(self, ind):
"""Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of string to any
Equal to list(self)[ind]
"""
# This is used to make discrete sampling without replacement memory
# efficient.
for sub_grid in self.param_grid:
# XXX: could memoize information used here
if not sub_grid:
if ind == 0:
return {}
else:
ind -= 1
continue
# Reverse so most frequent cycling parameter comes first
keys, values_lists = zip(*sorted(sub_grid.items())[::-1])
sizes = [len(v_list) for v_list in values_lists]
total = np.product(sizes)
if ind >= total:
# Try the next grid
ind -= total
else:
out = {}
for key, v_list, n in zip(keys, values_lists, sizes):
ind, offset = divmod(ind, n)
out[key] = v_list[offset]
return out
raise IndexError('ParameterGrid index out of range') | [
"def",
"__getitem__",
"(",
"self",
",",
"ind",
")",
":",
"# This is used to make discrete sampling without replacement memory",
"# efficient.",
"for",
"sub_grid",
"in",
"self",
".",
"param_grid",
":",
"# XXX: could memoize information used here",
"if",
"not",
"sub_grid",
":... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/grid_search.py#L127-L166 | ||
Genius-x/genius-x | 9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0 | cocos2d/tools/bindings-generator/clang/cindex.py | python | Cursor.underlying_typedef_type | (self) | return self._underlying_type | Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises. | Return the underlying type of a typedef declaration. | [
"Return",
"the",
"underlying",
"type",
"of",
"a",
"typedef",
"declaration",
"."
] | def underlying_typedef_type(self):
"""Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises.
"""
if not hasattr(self, '_underlying_type'):
assert self.kind.is_declaration()
self._underlying_type = \
conf.lib.clang_getTypedefDeclUnderlyingType(self)
return self._underlying_type | [
"def",
"underlying_typedef_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_underlying_type'",
")",
":",
"assert",
"self",
".",
"kind",
".",
"is_declaration",
"(",
")",
"self",
".",
"_underlying_type",
"=",
"conf",
".",
"lib",
"."... | https://github.com/Genius-x/genius-x/blob/9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0/cocos2d/tools/bindings-generator/clang/cindex.py#L1331-L1342 | |
HKUST-Aerial-Robotics/Fast-Planner | 2ddd7793eecd573dbb5b47e2c985aa06606df3cf | uav_simulator/Utils/multi_map_server/quadrotor_msgs/build/catkin_generated/installspace/_setup_util.py | python | _rollback_env_variable | (environ, name, subfolder) | return new_value if value_modified else None | For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder.
:param subfolder: str '' or subfoldername that may start with '/'
:returns: the updated value of the environment variable. | For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder. | [
"For",
"each",
"catkin",
"workspace",
"in",
"CMAKE_PREFIX_PATH",
"remove",
"the",
"first",
"entry",
"from",
"env",
"[",
"NAME",
"]",
"matching",
"workspace",
"+",
"subfolder",
"."
] | def _rollback_env_variable(environ, name, subfolder):
'''
For each catkin workspace in CMAKE_PREFIX_PATH remove the first entry from env[NAME] matching workspace + subfolder.
:param subfolder: str '' or subfoldername that may start with '/'
:returns: the updated value of the environment variable.
'''
value = environ[name] if name in environ else ''
env_paths = [path for path in value.split(os.pathsep) if path]
value_modified = False
if subfolder:
if subfolder.startswith(os.path.sep) or (os.path.altsep and subfolder.startswith(os.path.altsep)):
subfolder = subfolder[1:]
if subfolder.endswith(os.path.sep) or (os.path.altsep and subfolder.endswith(os.path.altsep)):
subfolder = subfolder[:-1]
for ws_path in _get_workspaces(environ, include_fuerte=True, include_non_existing=True):
path_to_find = os.path.join(ws_path, subfolder) if subfolder else ws_path
path_to_remove = None
for env_path in env_paths:
env_path_clean = env_path[:-1] if env_path and env_path[-1] in [os.path.sep, os.path.altsep] else env_path
if env_path_clean == path_to_find:
path_to_remove = env_path
break
if path_to_remove:
env_paths.remove(path_to_remove)
value_modified = True
new_value = os.pathsep.join(env_paths)
return new_value if value_modified else None | [
"def",
"_rollback_env_variable",
"(",
"environ",
",",
"name",
",",
"subfolder",
")",
":",
"value",
"=",
"environ",
"[",
"name",
"]",
"if",
"name",
"in",
"environ",
"else",
"''",
"env_paths",
"=",
"[",
"path",
"for",
"path",
"in",
"value",
".",
"split",
... | https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/quadrotor_msgs/build/catkin_generated/installspace/_setup_util.py#L84-L111 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py | python | Binomial.name | (self) | return self._name | Name to prepend to all ops. | Name to prepend to all ops. | [
"Name",
"to",
"prepend",
"to",
"all",
"ops",
"."
] | def name(self):
"""Name to prepend to all ops."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py#L153-L155 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PyTextCtrlEditor._SetSelf | (*args, **kwargs) | return _propgrid.PyTextCtrlEditor__SetSelf(*args, **kwargs) | _SetSelf(self, PyObject self) | _SetSelf(self, PyObject self) | [
"_SetSelf",
"(",
"self",
"PyObject",
"self",
")"
] | def _SetSelf(*args, **kwargs):
"""_SetSelf(self, PyObject self)"""
return _propgrid.PyTextCtrlEditor__SetSelf(*args, **kwargs) | [
"def",
"_SetSelf",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PyTextCtrlEditor__SetSelf",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L4165-L4167 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/dddoc/main.py | python | main | (argv) | return res | Program entry point. | Program entry point. | [
"Program",
"entry",
"point",
"."
] | def main(argv):
"""Program entry point."""
print '%s\n' % HEADER
start_time = datetime.datetime.now()
# Parse arguments.
parser = optparse.OptionParser()
parser.add_option('-d', '--doc-dir', dest='doc_dirs', action='append',
default=[],
help=('Read .dddoc files from this directory. '
'Can be given multiple times.'))
parser.add_option('-o', '--out-dir', dest='out_dir', default='html',
help='Name of output directory. Default: "html".')
parser.add_option('-e', '--demos-dir', dest='demos_dir',
default='../projects/library/demos',
help=('Directory to demos. Default: '
'"../projects/library/demos".'))
parser.add_option('-I', '--include-dir', dest='include_dirs',
action='append', default=[],
help='Paths to the directories for files and snippets.')
parser.add_option('-c', '--cache-only', dest='cache_only', default=False,
action='store_true',
help='Ignore files if cache file exists.')
options, args = parser.parse_args(argv)
print 'doc dirs: %s' % ', '.join(options.doc_dirs)
print
# Show help if no arguments are given.
if len(args) < 2:
print CMD_HELP % args[0]
return 1
# Create application object and run documentation generation.
app = DDDocRunner(index_only=False, doc_dirs=options.doc_dirs,
out_dir=options.out_dir,
include_dirs=options.include_dirs,
demos_dir=options.demos_dir,
cache_only=options.cache_only)
res = app.run(args)
elapsed = datetime.datetime.now() - start_time
print >>sys.stderr, 'Took %d s' % elapsed.seconds
return res | [
"def",
"main",
"(",
"argv",
")",
":",
"print",
"'%s\\n'",
"%",
"HEADER",
"start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"# Parse arguments.",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",... | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dddoc/main.py#L84-L127 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/media.py | python | MediaCtrl.GetState | (*args, **kwargs) | return _media.MediaCtrl_GetState(*args, **kwargs) | GetState(self) -> int | GetState(self) -> int | [
"GetState",
"(",
"self",
")",
"-",
">",
"int"
] | def GetState(*args, **kwargs):
"""GetState(self) -> int"""
return _media.MediaCtrl_GetState(*args, **kwargs) | [
"def",
"GetState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_media",
".",
"MediaCtrl_GetState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/media.py#L121-L123 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/platform/gfile.py | python | _GFileBase.flush | (self) | return self._fp.flush() | Flush the underlying file handle. | Flush the underlying file handle. | [
"Flush",
"the",
"underlying",
"file",
"handle",
"."
] | def flush(self):
"""Flush the underlying file handle."""
return self._fp.flush() | [
"def",
"flush",
"(",
"self",
")",
":",
"return",
"self",
".",
"_fp",
".",
"flush",
"(",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/platform/gfile.py#L81-L83 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/tensor_array_ops.py | python | _GraphTensorArrayV2.size | (self, name=None) | See TensorArray. | See TensorArray. | [
"See",
"TensorArray",
"."
] | def size(self, name=None):
"""See TensorArray."""
if not self._dynamic_size and self._size is not None:
return ops.convert_to_tensor(self._size, dtype=dtypes.int32)
else:
return list_ops.tensor_list_length(input_handle=self._flow, name=name) | [
"def",
"size",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_dynamic_size",
"and",
"self",
".",
"_size",
"is",
"not",
"None",
":",
"return",
"ops",
".",
"convert_to_tensor",
"(",
"self",
".",
"_size",
",",
"dtype",
"=",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/tensor_array_ops.py#L645-L650 | ||
yue/yue | 619d62c191b13c51c01be451dc48917c34a5aefc | building/tools/cpplint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (_global_error_suppressions.get(category, False) or
linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment or
global suppression. | Returns true if the specified error category is suppressed on this line. | [
"Returns",
"true",
"if",
"the",
"specified",
"error",
"category",
"is",
"suppressed",
"on",
"this",
"line",
"."
] | def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment or
global suppression.
"""
return (_global_error_suppressions.get(category, False) or
linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"_global_error_suppressions",
".",
"get",
"(",
"category",
",",
"False",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"... | https://github.com/yue/yue/blob/619d62c191b13c51c01be451dc48917c34a5aefc/building/tools/cpplint.py#L633-L648 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | NV_ReadResponse.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(NV_ReadResponse) | Returns new NV_ReadResponse object constructed from its marshaled
representation in the given byte buffer | Returns new NV_ReadResponse object constructed from its marshaled
representation in the given byte buffer | [
"Returns",
"new",
"NV_ReadResponse",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new NV_ReadResponse object constructed from its marshaled
representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(NV_ReadResponse) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"NV_ReadResponse",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17095-L17099 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/estimators/estimator.py | python | BaseEstimator._extract_metric_update_ops | (self, eval_dict) | return update_ops, value_ops | Separate update operations from metric value operations. | Separate update operations from metric value operations. | [
"Separate",
"update",
"operations",
"from",
"metric",
"value",
"operations",
"."
] | def _extract_metric_update_ops(self, eval_dict):
"""Separate update operations from metric value operations."""
update_ops = []
value_ops = {}
for name, metric_ops in six.iteritems(eval_dict):
if isinstance(metric_ops, (list, tuple)):
if len(metric_ops) == 2:
value_ops[name] = metric_ops[0]
update_ops.append(metric_ops[1])
else:
logging.warning(
'Ignoring metric {}. It returned a list|tuple with len {}, '
'expected 2'.format(name, len(metric_ops)))
value_ops[name] = metric_ops
else:
value_ops[name] = metric_ops
if update_ops:
update_ops = control_flow_ops.group(*update_ops)
else:
update_ops = None
return update_ops, value_ops | [
"def",
"_extract_metric_update_ops",
"(",
"self",
",",
"eval_dict",
")",
":",
"update_ops",
"=",
"[",
"]",
"value_ops",
"=",
"{",
"}",
"for",
"name",
",",
"metric_ops",
"in",
"six",
".",
"iteritems",
"(",
"eval_dict",
")",
":",
"if",
"isinstance",
"(",
"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L798-L820 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/javascripttokens.py | python | JavaScriptToken.IsAssignment | (self) | return (self.type == JavaScriptTokenType.OPERATOR and
self.string.endswith('=') and
self.string not in ('==', '!=', '>=', '<=', '===', '!==')) | Tests if this token is an assignment operator.
Returns:
True if this token is an assignment operator. | Tests if this token is an assignment operator. | [
"Tests",
"if",
"this",
"token",
"is",
"an",
"assignment",
"operator",
"."
] | def IsAssignment(self):
"""Tests if this token is an assignment operator.
Returns:
True if this token is an assignment operator.
"""
return (self.type == JavaScriptTokenType.OPERATOR and
self.string.endswith('=') and
self.string not in ('==', '!=', '>=', '<=', '===', '!==')) | [
"def",
"IsAssignment",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"type",
"==",
"JavaScriptTokenType",
".",
"OPERATOR",
"and",
"self",
".",
"string",
".",
"endswith",
"(",
"'='",
")",
"and",
"self",
".",
"string",
"not",
"in",
"(",
"'=='",
",",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/javascripttokens.py#L121-L129 | |
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | build/fbcode_builder/getdeps/fetcher.py | python | ChangeStatus.record_change | (self, file_name) | Used by the shipit fetcher to record changes as it updates
files in the destination. If the file name might be one used
in the cmake build system that we use for 1st party code, then
record that as a "make file" change. We could broaden this
to match any file used by various build systems, but it is
only really useful for our internal cmake stuff at this time.
If the file isn't a build file and is under the `fbcode_builder`
dir then we don't class that as an interesting change that we
might need to rebuild, so we ignore it.
Otherwise we record the file as a source file change. | Used by the shipit fetcher to record changes as it updates
files in the destination. If the file name might be one used
in the cmake build system that we use for 1st party code, then
record that as a "make file" change. We could broaden this
to match any file used by various build systems, but it is
only really useful for our internal cmake stuff at this time.
If the file isn't a build file and is under the `fbcode_builder`
dir then we don't class that as an interesting change that we
might need to rebuild, so we ignore it.
Otherwise we record the file as a source file change. | [
"Used",
"by",
"the",
"shipit",
"fetcher",
"to",
"record",
"changes",
"as",
"it",
"updates",
"files",
"in",
"the",
"destination",
".",
"If",
"the",
"file",
"name",
"might",
"be",
"one",
"used",
"in",
"the",
"cmake",
"build",
"system",
"that",
"we",
"use",... | def record_change(self, file_name):
"""Used by the shipit fetcher to record changes as it updates
files in the destination. If the file name might be one used
in the cmake build system that we use for 1st party code, then
record that as a "make file" change. We could broaden this
to match any file used by various build systems, but it is
only really useful for our internal cmake stuff at this time.
If the file isn't a build file and is under the `fbcode_builder`
dir then we don't class that as an interesting change that we
might need to rebuild, so we ignore it.
Otherwise we record the file as a source file change."""
file_name = file_name.lower()
if file_name_is_cmake_file(file_name):
self.make_files += 1
elif "/fbcode_builder/cmake" in file_name:
self.source_files += 1
elif "/fbcode_builder/" not in file_name:
self.source_files += 1 | [
"def",
"record_change",
"(",
"self",
",",
"file_name",
")",
":",
"file_name",
"=",
"file_name",
".",
"lower",
"(",
")",
"if",
"file_name_is_cmake_file",
"(",
"file_name",
")",
":",
"self",
".",
"make_files",
"+=",
"1",
"elif",
"\"/fbcode_builder/cmake\"",
"in"... | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/build/fbcode_builder/getdeps/fetcher.py#L72-L90 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hyperlink.py | python | HyperLinkCtrl.GetColours | (self) | return self._LinkColour, self._VisitedColour, self._LinkRolloverColour | Gets the colours for the link, the visited link and the mouse
rollover. | Gets the colours for the link, the visited link and the mouse
rollover. | [
"Gets",
"the",
"colours",
"for",
"the",
"link",
"the",
"visited",
"link",
"and",
"the",
"mouse",
"rollover",
"."
] | def GetColours(self):
"""
Gets the colours for the link, the visited link and the mouse
rollover.
"""
return self._LinkColour, self._VisitedColour, self._LinkRolloverColour | [
"def",
"GetColours",
"(",
"self",
")",
":",
"return",
"self",
".",
"_LinkColour",
",",
"self",
".",
"_VisitedColour",
",",
"self",
".",
"_LinkRolloverColour"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hyperlink.py#L466-L472 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py | python | Makefile.generate_target_clean | (self, mfile) | The default implementation of the clean target.
mfile is the file object. | The default implementation of the clean target. | [
"The",
"default",
"implementation",
"of",
"the",
"clean",
"target",
"."
] | def generate_target_clean(self, mfile):
"""The default implementation of the clean target.
mfile is the file object.
"""
mfile.write("\nclean:\n") | [
"def",
"generate_target_clean",
"(",
"self",
",",
"mfile",
")",
":",
"mfile",
".",
"write",
"(",
"\"\\nclean:\\n\"",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L1347-L1352 | ||
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/appController.py | python | AppController._refreshPrimViewSelection | (self, expandedPrims) | Refresh the selected prim view items to match the selection data
model. | Refresh the selected prim view items to match the selection data
model. | [
"Refresh",
"the",
"selected",
"prim",
"view",
"items",
"to",
"match",
"the",
"selection",
"data",
"model",
"."
] | def _refreshPrimViewSelection(self, expandedPrims):
"""Refresh the selected prim view items to match the selection data
model.
"""
self._ui.primView.clearSelection()
selectedItems = [
self._getItemAtPath(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]
if len(selectedItems) > 0:
self._ui.primView.setCurrentItem(selectedItems[0])
# unexpand items that were expanded through setting the current item
currExpandedPrims = self._getExpandedPrimViewPrims()
self._expandPrims(currExpandedPrims, expand=False)
# expand previously expanded items in primview
self._expandPrims(expandedPrims)
self._ui.primView.updateSelection(selectedItems, []) | [
"def",
"_refreshPrimViewSelection",
"(",
"self",
",",
"expandedPrims",
")",
":",
"self",
".",
"_ui",
".",
"primView",
".",
"clearSelection",
"(",
")",
"selectedItems",
"=",
"[",
"self",
".",
"_getItemAtPath",
"(",
"prim",
".",
"GetPath",
"(",
")",
")",
"fo... | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L3334-L3353 | ||
google/mozc | 7329757e1ad30e327c1ae823a8302c79482d6b9c | src/build_mozc.py | python | RunTests | (target_platform, configuration, parallel_num) | Run built tests actually.
Args:
target_platform: The build target ('Linux', 'Windows', etc.)
configuration: build configuration ('Release' or 'Debug')
parallel_num: allows specified jobs at once.
Raises:
RunOrDieError: One or more tests have failed. | Run built tests actually. | [
"Run",
"built",
"tests",
"actually",
"."
] | def RunTests(target_platform, configuration, parallel_num):
"""Run built tests actually.
Args:
target_platform: The build target ('Linux', 'Windows', etc.)
configuration: build configuration ('Release' or 'Debug')
parallel_num: allows specified jobs at once.
Raises:
RunOrDieError: One or more tests have failed.
"""
# TODO(nona): move this function to build_tools/test_tools
base_path = os.path.join(GetBuildBaseName(target_platform), configuration)
options = []
# Specify the log_dir directory.
# base_path looks like out_mac/Debug.
options.append('--log_dir=%s' % base_path)
failed_tests = []
# This is a silly algorithm: it runs *all* tests built in the target
# directory. Therefore, if you build multiple tests without
# cleaning, the second runtests runs every test.
# TODO(mukai): parses gyp files and get the target binaries, if possible.
executable_suffix = ''
test_function = RunTest
if target_platform == 'Windows':
executable_suffix = '.exe'
elif target_platform == 'iOS':
executable_suffix = '.app'
test_function = RunTestOnIos
parallel_num = 1
test_binaries = glob.glob(
os.path.join(base_path, '*_test' + executable_suffix))
# Prepare gtest_report directory.
gtest_report_dir = os.path.abspath(os.path.join(base_path, 'gtest_report'))
if os.path.exists(gtest_report_dir):
# Clear existing gtest reports.
RemoveDirectoryRecursively(gtest_report_dir)
os.makedirs(gtest_report_dir)
failed_tests = []
# Create default test reports in case any test process crashes and cannot
# leave test result as a XML report.
# TODO(yukawa): Move this template to test_tools/gtest_report.py.
xml_template = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
' <testsuite name="%s" tests="1" errors="1">\n'
' <testcase name="No reporting XML">\n'
' <error message="No reporting XML has been generated. '
'Process crash?" />\n'
' </testcase>\n'
'</testsuite>\n')
for binary in test_binaries:
binary_filename = os.path.basename(binary)
xml_path = os.path.join(gtest_report_dir, '%s.xml' % binary_filename)
with open(xml_path, 'w') as f:
f.write(xml_template % binary_filename)
if parallel_num == 1:
for binary in test_binaries:
logging.info('running %s...', binary)
try:
test_function(binary, gtest_report_dir, options)
except RunOrDieError as e:
logging.error(e)
failed_tests.append(binary)
else:
launcher = test_launcher.TestLauncher(gtest_report_dir)
for binary in test_binaries:
launcher.AddTestCommand([binary] + options)
failed_tests = launcher.Execute(parallel_num)
if failed_tests:
error_text = ColoredText('following tests failed', logging.ERROR)
raise RunOrDieError('\n'.join([error_text] + failed_tests)) | [
"def",
"RunTests",
"(",
"target_platform",
",",
"configuration",
",",
"parallel_num",
")",
":",
"# TODO(nona): move this function to build_tools/test_tools",
"base_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"GetBuildBaseName",
"(",
"target_platform",
")",
",",
"... | https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/build_mozc.py#L660-L739 | ||
tinyobjloader/tinyobjloader | 8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93 | deps/cpplint.py | python | CheckForNonConstReference | (filename, clean_lines, linenum,
nesting_state, error) | Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
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: The function to call with any errors found. | Check for non-const references. | [
"Check",
"for",
"non",
"-",
"const",
"references",
"."
] | def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
"""Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
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: The function to call with any errors found.
"""
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# If a function is inherited, current function doesn't have much of
# a choice, so any non-const references should not be blamed on
# derived function.
if IsDerivedFunction(clean_lines, linenum):
return
# Don't warn on out-of-line method definitions, as we would warn on the
# in-line declaration, if it isn't marked with 'override'.
if IsOutOfLineMethodDefinition(clean_lines, linenum):
return
# Long type names may be broken across multiple lines, usually in one
# of these forms:
# LongType
# ::LongTypeContinued &identifier
# LongType::
# LongTypeContinued &identifier
# LongType<
# ...>::LongTypeContinued &identifier
#
# If we detected a type split across two lines, join the previous
# line to current line so that we can match const references
# accordingly.
#
# Note that this only scans back one line, since scanning back
# arbitrary number of lines would be expensive. If you have a type
# that spans more than 2 lines, please use a typedef.
if linenum > 1:
previous = None
if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
# previous_line\n + ::current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
clean_lines.elided[linenum - 1])
elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
# previous_line::\n + current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
clean_lines.elided[linenum - 1])
if previous:
line = previous.group(1) + line.lstrip()
else:
# Check for templated parameter that is split across multiple lines
endpos = line.rfind('>')
if endpos > -1:
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, endpos)
if startpos > -1 and startline < linenum:
# Found the matching < on an earlier line, collect all
# pieces up to current line.
line = ''
for i in xrange(startline, linenum + 1):
line += clean_lines.elided[i].strip()
# Check for non-const references in function parameters. A single '&' may
# found in the following places:
# inside expression: binary & for bitwise AND
# inside expression: unary & for taking the address of something
# inside declarators: reference parameter
# We will exclude the first two cases by checking that we are not inside a
# function body, including one that was just introduced by a trailing '{'.
# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
if (nesting_state.previous_stack_top and
not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
# Not at toplevel, not within a class, and not within a namespace
return
# Avoid initializer lists. We only need to scan back from the
# current line for something that starts with ':'.
#
# We don't need to check the current line, since the '&' would
# appear inside the second set of parentheses on the current line as
# opposed to the first set.
if linenum > 0:
for i in xrange(linenum - 1, max(0, linenum - 10), -1):
previous_line = clean_lines.elided[i]
if not Search(r'[),]\s*$', previous_line):
break
if Match(r'^\s*:\s+\S', previous_line):
return
# Avoid preprocessors
if Search(r'\\\s*$', line):
return
# Avoid constructor initializer lists
if IsInitializerList(clean_lines, linenum):
return
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>". Do not check
# those function parameters.
#
# We also accept & in static_assert, which looks like a function but
# it's actually a declaration expression.
whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
r'operator\s*[<>][<>]|'
r'static_assert|COMPILE_ASSERT'
r')\s*\(')
if Search(whitelisted_functions, line):
return
elif not Search(r'\S+\([^)]*$', line):
# Don't see a whitelisted function on this line. Actually we
# didn't see any function name on this line, so this is likely a
# multi-line parameter list. Try a bit harder to catch this case.
for i in xrange(2):
if (linenum > i and
Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
return
decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
error(filename, linenum, 'runtime/references', 2,
'Is this a non-const reference? '
'If so, make const or use a pointer: ' +
ReplaceAll(' *<', '<', parameter)) | [
"def",
"CheckForNonConstReference",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Do nothing if there is no '&' on current line.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"'&'",
"n... | https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L5080-L5215 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/distribute/distributed_training_utils_v1.py | python | _make_replica_execution_function | (model, mode) | return func | A single step of the distributed execution on a replica. | A single step of the distributed execution on a replica. | [
"A",
"single",
"step",
"of",
"the",
"distributed",
"execution",
"on",
"a",
"replica",
"."
] | def _make_replica_execution_function(model, mode):
"""A single step of the distributed execution on a replica."""
if mode == ModeKeys.TRAIN:
func = model.train_on_batch
elif mode == ModeKeys.TEST:
func = model.test_on_batch
else:
def predict_on_batch(x, y=None, sample_weights=None):
del y, sample_weights
return model.predict_on_batch(x)
func = predict_on_batch
if mode != ModeKeys.PREDICT:
# `reset_metrics` is set to False to maintain stateful metrics across
# batch-level calls.
func = functools.partial(func, reset_metrics=False)
return func | [
"def",
"_make_replica_execution_function",
"(",
"model",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"ModeKeys",
".",
"TRAIN",
":",
"func",
"=",
"model",
".",
"train_on_batch",
"elif",
"mode",
"==",
"ModeKeys",
".",
"TEST",
":",
"func",
"=",
"model",
".",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/distribute/distributed_training_utils_v1.py#L861-L880 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_mirror.py | python | Mirror.action | (self, arg) | Handle the 3D scene events.
This is installed as an EventCallback in the Inventor view.
Parameters
----------
arg: dict
Dictionary with strings that indicates the type of event received
from the 3D view. | Handle the 3D scene events. | [
"Handle",
"the",
"3D",
"scene",
"events",
"."
] | def action(self, arg):
"""Handle the 3D scene events.
This is installed as an EventCallback in the Inventor view.
Parameters
----------
arg: dict
Dictionary with strings that indicates the type of event received
from the 3D view.
"""
if arg["Type"] == "SoKeyboardEvent":
if arg["Key"] == "ESCAPE":
self.finish()
elif arg["Type"] == "SoLocation2Event": # mouse movement detection
(self.point,
ctrlPoint, info) = gui_tool_utils.getPoint(self, arg)
if len(self.node) > 0:
last = self.node[-1]
if self.ghost:
if self.point != last:
# TODO: the following doesn't work at the moment
mu = self.point.sub(last).normalize()
# This part used to test for the GUI to obtain
# the camera view but this is unnecessary
# as this command is always launched in the GUI.
_view = Gui.ActiveDocument.ActiveView
mv = _view.getViewDirection().negative()
mw = mv.cross(mu)
_plane = WorkingPlane.plane(u=mu, v=mv, w=mw,
pos=last)
tm = _plane.getPlacement().toMatrix()
m = self.ghost.getMatrix()
m = m.multiply(tm.inverse())
m.scale(App.Vector(1, 1, -1))
m = m.multiply(tm)
m.scale(App.Vector(-1, 1, 1))
self.ghost.setMatrix(m)
if self.extendedCopy:
if not gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT):
self.finish()
gui_tool_utils.redraw3DView()
elif arg["Type"] == "SoMouseButtonEvent":
if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
if self.point:
self.ui.redraw()
if (self.node == []):
self.node.append(self.point)
self.ui.isRelative.show()
if self.ghost:
self.ghost.on()
_msg(translate("draft",
"Pick end point of mirror line"))
if self.planetrack:
self.planetrack.set(self.point)
else:
last = self.node[0]
if (self.ui.isCopy.isChecked()
or gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT)):
self.mirror(last, self.point, True)
else:
self.mirror(last, self.point)
if gui_tool_utils.hasMod(arg, gui_tool_utils.MODALT):
self.extendedCopy = True
else:
self.finish(cont=True) | [
"def",
"action",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
"[",
"\"Type\"",
"]",
"==",
"\"SoKeyboardEvent\"",
":",
"if",
"arg",
"[",
"\"Key\"",
"]",
"==",
"\"ESCAPE\"",
":",
"self",
".",
"finish",
"(",
")",
"elif",
"arg",
"[",
"\"Type\"",
"]",
... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_mirror.py#L125-L190 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/tools/scan-build-py/libscanbuild/analyze.py | python | require | (required) | return decorator | Decorator for checking the required values in state.
It checks the required attributes in the passed state and stop when
any of those is missing. | Decorator for checking the required values in state. | [
"Decorator",
"for",
"checking",
"the",
"required",
"values",
"in",
"state",
"."
] | def require(required):
""" Decorator for checking the required values in state.
It checks the required attributes in the passed state and stop when
any of those is missing. """
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
for key in required:
if key not in args[0]:
raise KeyError('{0} not passed to {1}'.format(
key, function.__name__))
return function(*args, **kwargs)
return wrapper
return decorator | [
"def",
"require",
"(",
"required",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"required",
... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/tools/scan-build-py/libscanbuild/analyze.py#L402-L420 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/profiler/parser/integrator.py | python | Integrator._aicore_detail_data_load | (self) | Load data according to the parsed AICORE operator file. | Load data according to the parsed AICORE operator file. | [
"Load",
"data",
"according",
"to",
"the",
"parsed",
"AICORE",
"operator",
"file",
"."
] | def _aicore_detail_data_load(self):
"""Load data according to the parsed AICORE operator file."""
op_detail_file_path = os.path.join(
self._profiling_dir,
self._file_name_aicore_detail_info.format(self._device_id)
)
framework_file_path = os.path.join(
self._profiling_dir,
self._file_name_framework.format(self._device_id)
)
op_detail_file_path = validate_and_normalize_path(op_detail_file_path)
framework_file_path = validate_and_normalize_path(framework_file_path)
if not os.path.isfile(op_detail_file_path):
logger.warning('The file <%s> does not exist.', op_detail_file_path)
return
if not os.path.isfile(framework_file_path):
logger.warning('The file <%s> does not exist.', framework_file_path)
return
framework_infos = dict()
with open(framework_file_path, 'r') as file:
csv_reader = csv.reader(file)
_ = next(csv_reader)
for info in csv_reader:
framework_infos[info[3]] = [
info[3], info[4], info[5], info[6], json.loads(info[7]) if info[7] else None]
with open(op_detail_file_path, 'r') as file:
csv_reader = csv.reader(file)
_ = next(csv_reader)
for info in csv_reader:
framework_info = framework_infos.get(info[0])
self._aicore_detail_data.append(
[
framework_info[1], framework_info[2], float(info[1]),
framework_info[3], framework_info[0], framework_info[4]
]
)
del framework_infos | [
"def",
"_aicore_detail_data_load",
"(",
"self",
")",
":",
"op_detail_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_profiling_dir",
",",
"self",
".",
"_file_name_aicore_detail_info",
".",
"format",
"(",
"self",
".",
"_device_id",
")",
")"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/integrator.py#L220-L258 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/connectionpool.py | python | HTTPConnectionPool._make_request | (self, conn, method, url, timeout=_Default,
**httplib_request_kw) | return httplib_response | Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts. | Perform a request on a given urllib connection object taken from our
pool. | [
"Perform",
"a",
"request",
"on",
"a",
"given",
"urllib",
"connection",
"object",
"taken",
"from",
"our",
"pool",
"."
] | def _make_request(self, conn, method, url, timeout=_Default,
**httplib_request_kw):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = timeout_obj.connect_timeout
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls httplib.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
conn.request(method, url, **httplib_request_kw)
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, 'sock', None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try: # Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError: # Python 2.6 and older
httplib_response = conn.getresponse()
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
httplib_response.status,
httplib_response.length))
return httplib_response | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",
".",
"_get_timeout",
"(",
"ti... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/connectionpool.py#L317-L384 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/stochastic_gradient.py | python | BaseSGDRegressor.fit | (self, X, y, coef_init=None, intercept_init=None,
sample_weight=None) | return self._fit(X, y, alpha=self.alpha, C=1.0,
loss=self.loss, learning_rate=self.learning_rate,
coef_init=coef_init,
intercept_init=intercept_init,
sample_weight=sample_weight) | Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : numpy array, shape (n_samples,)
Target values
coef_init : array, shape (n_features,)
The initial coefficients to warm-start the optimization.
intercept_init : array, shape (1,)
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), optional
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : returns an instance of self. | Fit linear model with Stochastic Gradient Descent. | [
"Fit",
"linear",
"model",
"with",
"Stochastic",
"Gradient",
"Descent",
"."
] | def fit(self, X, y, coef_init=None, intercept_init=None,
sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : numpy array, shape (n_samples,)
Target values
coef_init : array, shape (n_features,)
The initial coefficients to warm-start the optimization.
intercept_init : array, shape (1,)
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), optional
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : returns an instance of self.
"""
return self._fit(X, y, alpha=self.alpha, C=1.0,
loss=self.loss, learning_rate=self.learning_rate,
coef_init=coef_init,
intercept_init=intercept_init,
sample_weight=sample_weight) | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"coef_init",
"=",
"None",
",",
"intercept_init",
"=",
"None",
",",
"sample_weight",
"=",
"None",
")",
":",
"return",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
",",
"alpha",
"=",
"self",
".",
"alp... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/stochastic_gradient.py#L944-L973 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/xgettext.py | python | _POTUpdateBuilder | (env, **kw) | return _POTBuilder(**kw) | Creates `POTUpdate` builder object | Creates `POTUpdate` builder object | [
"Creates",
"POTUpdate",
"builder",
"object"
] | def _POTUpdateBuilder(env, **kw):
""" Creates `POTUpdate` builder object """
import SCons.Action
from SCons.Tool.GettextCommon import _POTargetFactory
kw['action'] = SCons.Action.Action(_update_pot_file, None)
kw['suffix'] = '$POTSUFFIX'
kw['target_factory'] = _POTargetFactory(env, alias='$POTUPDATE_ALIAS').File
kw['emitter'] = _pot_update_emitter
return _POTBuilder(**kw) | [
"def",
"_POTUpdateBuilder",
"(",
"env",
",",
"*",
"*",
"kw",
")",
":",
"import",
"SCons",
".",
"Action",
"from",
"SCons",
".",
"Tool",
".",
"GettextCommon",
"import",
"_POTargetFactory",
"kw",
"[",
"'action'",
"]",
"=",
"SCons",
".",
"Action",
".",
"Acti... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/xgettext.py#L257-L265 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/graph_editor/match.py | python | OpMatcher.control_input_ops | (self, *args) | return self | Add input matches. | Add input matches. | [
"Add",
"input",
"matches",
"."
] | def control_input_ops(self, *args):
"""Add input matches."""
if self.control_input_op_matches is not None:
raise ValueError("control_input_op_matches is already set.")
self.control_input_op_matches = []
for input_match in args:
self.control_input_op_matches.append(_make_graph_match(input_match))
return self | [
"def",
"control_input_ops",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"control_input_op_matches",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"control_input_op_matches is already set.\"",
")",
"self",
".",
"control_input_op_matches",
"=... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/match.py#L131-L138 | |
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/python/flatbuffers/flexbuffers.py | python | Builder.String | (self, value) | return loc | Encodes string value. | Encodes string value. | [
"Encodes",
"string",
"value",
"."
] | def String(self, value):
"""Encodes string value."""
reset_to = len(self._buf)
encoded = value.encode('utf-8')
loc = self._WriteBlob(encoded, append_zero=True, type_=Type.STRING)
if self._share_strings:
prev_loc = self._string_pool.FindOrInsert(encoded, loc)
if prev_loc is not None:
del self._buf[reset_to:]
self._stack[-1]._value = loc = prev_loc # pylint: disable=protected-access
return loc | [
"def",
"String",
"(",
"self",
",",
"value",
")",
":",
"reset_to",
"=",
"len",
"(",
"self",
".",
"_buf",
")",
"encoded",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"loc",
"=",
"self",
".",
"_WriteBlob",
"(",
"encoded",
",",
"append_zero",
"=",
... | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/flexbuffers.py#L1160-L1171 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py | python | backport_makefile | (
self, mode="r", buffering=None, encoding=None, errors=None, newline=None
) | return text | Backport of ``socket.makefile`` from Python 3.5. | Backport of ``socket.makefile`` from Python 3.5. | [
"Backport",
"of",
"socket",
".",
"makefile",
"from",
"Python",
"3",
".",
"5",
"."
] | def backport_makefile(
self, mode="r", buffering=None, encoding=None, errors=None, newline=None
):
"""
Backport of ``socket.makefile`` from Python 3.5.
"""
if not set(mode) <= {"r", "w", "b"}:
raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
writing = "w" in mode
reading = "r" in mode or not writing
assert reading or writing
binary = "b" in mode
rawmode = ""
if reading:
rawmode += "r"
if writing:
rawmode += "w"
raw = SocketIO(self, rawmode)
self._makefile_refs += 1
if buffering is None:
buffering = -1
if buffering < 0:
buffering = io.DEFAULT_BUFFER_SIZE
if buffering == 0:
if not binary:
raise ValueError("unbuffered streams must be binary")
return raw
if reading and writing:
buffer = io.BufferedRWPair(raw, raw, buffering)
elif reading:
buffer = io.BufferedReader(raw, buffering)
else:
assert writing
buffer = io.BufferedWriter(raw, buffering)
if binary:
return buffer
text = io.TextIOWrapper(buffer, encoding, errors, newline)
text.mode = mode
return text | [
"def",
"backport_makefile",
"(",
"self",
",",
"mode",
"=",
"\"r\"",
",",
"buffering",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"if",
"not",
"set",
"(",
"mode",
")",
"<=",
"{",
"\"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py#L13-L51 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | Distribution.get_entry_info | (self, group, name) | return self.get_entry_map(group).get(name) | Return the EntryPoint object for `group`+`name`, or ``None`` | Return the EntryPoint object for `group`+`name`, or ``None`` | [
"Return",
"the",
"EntryPoint",
"object",
"for",
"group",
"+",
"name",
"or",
"None"
] | def get_entry_info(self, group, name):
"""Return the EntryPoint object for `group`+`name`, or ``None``"""
return self.get_entry_map(group).get(name) | [
"def",
"get_entry_info",
"(",
"self",
",",
"group",
",",
"name",
")",
":",
"return",
"self",
".",
"get_entry_map",
"(",
"group",
")",
".",
"get",
"(",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2873-L2875 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PageSetupDialogData.SetPaperId | (*args, **kwargs) | return _windows_.PageSetupDialogData_SetPaperId(*args, **kwargs) | SetPaperId(self, int id) | SetPaperId(self, int id) | [
"SetPaperId",
"(",
"self",
"int",
"id",
")"
] | def SetPaperId(*args, **kwargs):
"""SetPaperId(self, int id)"""
return _windows_.PageSetupDialogData_SetPaperId(*args, **kwargs) | [
"def",
"SetPaperId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_SetPaperId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L4979-L4981 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/lang/matrix.py | python | Matrix.inverse | (self) | The inverse of a matrix.
Note:
The matrix dimension should be less than or equal to 4.
Returns:
The inverse of a matrix.
Raises:
Exception: Inversions of matrices with sizes >= 5 are not supported. | The inverse of a matrix. | [
"The",
"inverse",
"of",
"a",
"matrix",
"."
] | def inverse(self):
"""The inverse of a matrix.
Note:
The matrix dimension should be less than or equal to 4.
Returns:
The inverse of a matrix.
Raises:
Exception: Inversions of matrices with sizes >= 5 are not supported.
"""
assert self.n == self.m, 'Only square matrices are invertible'
if self.n == 1:
return Matrix([1 / self(0, 0)])
if self.n == 2:
inv_determinant = impl.expr_init(1.0 / self.determinant())
return inv_determinant * Matrix([[self(
1, 1), -self(0, 1)], [-self(1, 0), self(0, 0)]])
if self.n == 3:
n = 3
inv_determinant = impl.expr_init(1.0 / self.determinant())
entries = [[0] * n for _ in range(n)]
def E(x, y):
return self(x % n, y % n)
for i in range(n):
for j in range(n):
entries[j][i] = inv_determinant * (
E(i + 1, j + 1) * E(i + 2, j + 2) -
E(i + 2, j + 1) * E(i + 1, j + 2))
return Matrix(entries)
if self.n == 4:
n = 4
inv_determinant = impl.expr_init(1.0 / self.determinant())
entries = [[0] * n for _ in range(n)]
def E(x, y):
return self(x % n, y % n)
for i in range(n):
for j in range(n):
entries[j][i] = inv_determinant * (-1)**(i + j) * ((
E(i + 1, j + 1) *
(E(i + 2, j + 2) * E(i + 3, j + 3) -
E(i + 3, j + 2) * E(i + 2, j + 3)) - E(i + 2, j + 1) *
(E(i + 1, j + 2) * E(i + 3, j + 3) -
E(i + 3, j + 2) * E(i + 1, j + 3)) + E(i + 3, j + 1) *
(E(i + 1, j + 2) * E(i + 2, j + 3) -
E(i + 2, j + 2) * E(i + 1, j + 3))))
return Matrix(entries)
raise Exception(
"Inversions of matrices with sizes >= 5 are not supported") | [
"def",
"inverse",
"(",
"self",
")",
":",
"assert",
"self",
".",
"n",
"==",
"self",
".",
"m",
",",
"'Only square matrices are invertible'",
"if",
"self",
".",
"n",
"==",
"1",
":",
"return",
"Matrix",
"(",
"[",
"1",
"/",
"self",
"(",
"0",
",",
"0",
"... | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/matrix.py#L424-L478 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py | python | count_nonzero | (a, axis=None) | return a_bool.sum(axis=axis, dtype=np.intp) | Counts the number of non-zero values in the array ``a``.
The word "non-zero" is in reference to the Python 2.x
built-in method ``__nonzero__()`` (renamed ``__bool__()``
in Python 3.x) of Python objects that tests an object's
"truthfulness". For example, any number is considered
truthful if it is nonzero, whereas any string is considered
truthful if it is not the empty string. Thus, this function
(recursively) counts how many elements in ``a`` (and in
sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
method evaluated to ``True``.
Parameters
----------
a : array_like
The array for which to count non-zeros.
axis : int or tuple, optional
Axis or tuple of axes along which to count non-zeros.
Default is None, meaning that non-zeros will be counted
along a flattened version of ``a``.
.. versionadded:: 1.12.0
Returns
-------
count : int or array of int
Number of non-zero values in the array along a given axis.
Otherwise, the total number of non-zero values in the array
is returned.
See Also
--------
nonzero : Return the coordinates of all the non-zero values.
Examples
--------
>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=0)
array([1, 1, 1, 1, 1])
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)
array([2, 3]) | Counts the number of non-zero values in the array ``a``. | [
"Counts",
"the",
"number",
"of",
"non",
"-",
"zero",
"values",
"in",
"the",
"array",
"a",
"."
] | def count_nonzero(a, axis=None):
"""
Counts the number of non-zero values in the array ``a``.
The word "non-zero" is in reference to the Python 2.x
built-in method ``__nonzero__()`` (renamed ``__bool__()``
in Python 3.x) of Python objects that tests an object's
"truthfulness". For example, any number is considered
truthful if it is nonzero, whereas any string is considered
truthful if it is not the empty string. Thus, this function
(recursively) counts how many elements in ``a`` (and in
sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
method evaluated to ``True``.
Parameters
----------
a : array_like
The array for which to count non-zeros.
axis : int or tuple, optional
Axis or tuple of axes along which to count non-zeros.
Default is None, meaning that non-zeros will be counted
along a flattened version of ``a``.
.. versionadded:: 1.12.0
Returns
-------
count : int or array of int
Number of non-zero values in the array along a given axis.
Otherwise, the total number of non-zero values in the array
is returned.
See Also
--------
nonzero : Return the coordinates of all the non-zero values.
Examples
--------
>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=0)
array([1, 1, 1, 1, 1])
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)
array([2, 3])
"""
if axis is None:
return multiarray.count_nonzero(a)
a = asanyarray(a)
# TODO: this works around .astype(bool) not working properly (gh-9847)
if np.issubdtype(a.dtype, np.character):
a_bool = a != a.dtype.type()
else:
a_bool = a.astype(np.bool_, copy=False)
return a_bool.sum(axis=axis, dtype=np.intp) | [
"def",
"count_nonzero",
"(",
"a",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"return",
"multiarray",
".",
"count_nonzero",
"(",
"a",
")",
"a",
"=",
"asanyarray",
"(",
"a",
")",
"# TODO: this works around .astype(bool) not working prop... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py#L403-L462 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/attrs/attr/_make.py | python | _setattr | (attr_name, value_var, has_on_setattr) | return "_setattr('%s', %s)" % (attr_name, value_var) | Use the cached object.setattr to set *attr_name* to *value_var*. | Use the cached object.setattr to set *attr_name* to *value_var*. | [
"Use",
"the",
"cached",
"object",
".",
"setattr",
"to",
"set",
"*",
"attr_name",
"*",
"to",
"*",
"value_var",
"*",
"."
] | def _setattr(attr_name, value_var, has_on_setattr):
"""
Use the cached object.setattr to set *attr_name* to *value_var*.
"""
return "_setattr('%s', %s)" % (attr_name, value_var) | [
"def",
"_setattr",
"(",
"attr_name",
",",
"value_var",
",",
"has_on_setattr",
")",
":",
"return",
"\"_setattr('%s', %s)\"",
"%",
"(",
"attr_name",
",",
"value_var",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/attrs/attr/_make.py#L2074-L2078 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/metrics_impl.py | python | _num_relevant | (labels, k) | Computes number of relevant values for each row in labels.
For labels with shape [D1, ... DN, num_labels], this is the minimum of
`num_labels` and `k`.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels], where N >= 1 and num_labels is the number of
target classes for the associated prediction. Commonly, N=1 and `labels`
has shape [batch_size, num_labels].
k: Integer, k for @k metric.
Returns:
Integer `Tensor` of shape [D1, ... DN], where each value is the number of
relevant values for that row.
Raises:
ValueError: if inputs have invalid dtypes or values. | Computes number of relevant values for each row in labels. | [
"Computes",
"number",
"of",
"relevant",
"values",
"for",
"each",
"row",
"in",
"labels",
"."
] | def _num_relevant(labels, k):
"""Computes number of relevant values for each row in labels.
For labels with shape [D1, ... DN, num_labels], this is the minimum of
`num_labels` and `k`.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels], where N >= 1 and num_labels is the number of
target classes for the associated prediction. Commonly, N=1 and `labels`
has shape [batch_size, num_labels].
k: Integer, k for @k metric.
Returns:
Integer `Tensor` of shape [D1, ... DN], where each value is the number of
relevant values for that row.
Raises:
ValueError: if inputs have invalid dtypes or values.
"""
if k < 1:
raise ValueError(f'Invalid k={k}')
with ops.name_scope(None, 'num_relevant', (labels,)) as scope:
# For SparseTensor, calculate separate count for each row.
labels = sparse_tensor.convert_to_tensor_or_sparse_tensor(labels)
if isinstance(labels, sparse_tensor.SparseTensor):
return math_ops.minimum(sets.set_size(labels), k, name=scope)
# The relevant values for each (d1, ... dN) is the minimum of k and the
# number of labels along the last dimension that are non-negative.
num_labels = math_ops.reduce_sum(
array_ops.where_v2(math_ops.greater_equal(labels, 0),
array_ops.ones_like(labels),
array_ops.zeros_like(labels)),
axis=-1)
return math_ops.minimum(num_labels, k, name=scope) | [
"def",
"_num_relevant",
"(",
"labels",
",",
"k",
")",
":",
"if",
"k",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"f'Invalid k={k}'",
")",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"'num_relevant'",
",",
"(",
"labels",
",",
")",
")",
"as",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/metrics_impl.py#L3144-L3179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.