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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py | python | DirichletMultinomial.variance | (self, name="mean") | Class variances for every batch member.
The variance for each batch member is defined as the following:
```
Var(X_j) = n * alpha_j / alpha_0 * (1 - alpha_j / alpha_0) *
(n + alpha_0) / (1 + alpha_0)
```
where `alpha_0 = sum_j alpha_j`.
The covariance between elements in a batch is defined as:
```
Cov(X_i, X_j) = -n * alpha_i * alpha_j / alpha_0 ** 2 *
(n + alpha_0) / (1 + alpha_0)
```
Args:
name: The name for this op.
Returns:
A `Tensor` representing the variances for each batch member. | Class variances for every batch member. | [
"Class",
"variances",
"for",
"every",
"batch",
"member",
"."
] | def variance(self, name="mean"):
"""Class variances for every batch member.
The variance for each batch member is defined as the following:
```
Var(X_j) = n * alpha_j / alpha_0 * (1 - alpha_j / alpha_0) *
(n + alpha_0) / (1 + alpha_0)
```
where `alpha_0 = sum_j alpha_j`.
The covariance between elements in a batch is defined as:
```
Cov(X_i, X_j) = -n * alpha_i * alpha_j / alpha_0 ** 2 *
(n + alpha_0) / (1 + alpha_0)
```
Args:
name: The name for this op.
Returns:
A `Tensor` representing the variances for each batch member.
"""
alpha = self._alpha
alpha_sum = self._alpha_sum
n = self._n
with ops.name_scope(self.name):
with ops.op_scope([alpha, alpha_sum, n], name):
expanded_alpha_sum = array_ops.expand_dims(alpha_sum, -1)
shared_factor = n * (expanded_alpha_sum + n) / (
expanded_alpha_sum + 1) * array_ops.ones_like(alpha)
mean_no_n = alpha / expanded_alpha_sum
expanded_mean_no_n = array_ops.expand_dims(mean_no_n, -1)
variance = -math_ops.batch_matmul(
expanded_mean_no_n, expanded_mean_no_n, adj_y=True)
variance += array_ops.batch_matrix_diag(mean_no_n)
variance *= array_ops.expand_dims(shared_factor, -1)
return variance | [
"def",
"variance",
"(",
"self",
",",
"name",
"=",
"\"mean\"",
")",
":",
"alpha",
"=",
"self",
".",
"_alpha",
"alpha_sum",
"=",
"self",
".",
"_alpha_sum",
"n",
"=",
"self",
".",
"_n",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"alpha",
",",
"alpha_sum",
",",
"n",
"]",
",",
"name",
")",
":",
"expanded_alpha_sum",
"=",
"array_ops",
".",
"expand_dims",
"(",
"alpha_sum",
",",
"-",
"1",
")",
"shared_factor",
"=",
"n",
"*",
"(",
"expanded_alpha_sum",
"+",
"n",
")",
"/",
"(",
"expanded_alpha_sum",
"+",
"1",
")",
"*",
"array_ops",
".",
"ones_like",
"(",
"alpha",
")",
"mean_no_n",
"=",
"alpha",
"/",
"expanded_alpha_sum",
"expanded_mean_no_n",
"=",
"array_ops",
".",
"expand_dims",
"(",
"mean_no_n",
",",
"-",
"1",
")",
"variance",
"=",
"-",
"math_ops",
".",
"batch_matmul",
"(",
"expanded_mean_no_n",
",",
"expanded_mean_no_n",
",",
"adj_y",
"=",
"True",
")",
"variance",
"+=",
"array_ops",
".",
"batch_matrix_diag",
"(",
"mean_no_n",
")",
"variance",
"*=",
"array_ops",
".",
"expand_dims",
"(",
"shared_factor",
",",
"-",
"1",
")",
"return",
"variance"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py#L210-L250 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.GetRangePointer | (*args, **kwargs) | return _stc.StyledTextCtrl_GetRangePointer(*args, **kwargs) | GetRangePointer(self, int position, int rangeLength) -> char | GetRangePointer(self, int position, int rangeLength) -> char | [
"GetRangePointer",
"(",
"self",
"int",
"position",
"int",
"rangeLength",
")",
"-",
">",
"char"
] | def GetRangePointer(*args, **kwargs):
"""GetRangePointer(self, int position, int rangeLength) -> char"""
return _stc.StyledTextCtrl_GetRangePointer(*args, **kwargs) | [
"def",
"GetRangePointer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetRangePointer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L5751-L5753 | |
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/utils/check_cfc/check_cfc.py | python | get_input_file | (args) | Return the input file string if it can be found (and there is only
one). | Return the input file string if it can be found (and there is only
one). | [
"Return",
"the",
"input",
"file",
"string",
"if",
"it",
"can",
"be",
"found",
"(",
"and",
"there",
"is",
"only",
"one",
")",
"."
] | def get_input_file(args):
"""Return the input file string if it can be found (and there is only
one)."""
inputFiles = list()
for arg in args:
testarg = arg
quotes = ('"', "'")
while testarg.endswith(quotes):
testarg = testarg[:-1]
testarg = os.path.normcase(testarg)
# Test if it is a source file
if testarg.endswith(gSrcFileSuffixes):
inputFiles.append(arg)
if len(inputFiles) == 1:
return inputFiles[0]
else:
return None | [
"def",
"get_input_file",
"(",
"args",
")",
":",
"inputFiles",
"=",
"list",
"(",
")",
"for",
"arg",
"in",
"args",
":",
"testarg",
"=",
"arg",
"quotes",
"=",
"(",
"'\"'",
",",
"\"'\"",
")",
"while",
"testarg",
".",
"endswith",
"(",
"quotes",
")",
":",
"testarg",
"=",
"testarg",
"[",
":",
"-",
"1",
"]",
"testarg",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"testarg",
")",
"# Test if it is a source file",
"if",
"testarg",
".",
"endswith",
"(",
"gSrcFileSuffixes",
")",
":",
"inputFiles",
".",
"append",
"(",
"arg",
")",
"if",
"len",
"(",
"inputFiles",
")",
"==",
"1",
":",
"return",
"inputFiles",
"[",
"0",
"]",
"else",
":",
"return",
"None"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/utils/check_cfc/check_cfc.py#L187-L204 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | MaskedArray.tolist | (self, fill_value=None) | return self.filled(fill_value).tolist() | Convert to list | Convert to list | [
"Convert",
"to",
"list"
] | def tolist(self, fill_value=None):
"Convert to list"
return self.filled(fill_value).tolist() | [
"def",
"tolist",
"(",
"self",
",",
"fill_value",
"=",
"None",
")",
":",
"return",
"self",
".",
"filled",
"(",
"fill_value",
")",
".",
"tolist",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1377-L1379 | |
xlgames-inc/XLE | cdd8682367d9e9fdbdda9f79d72bb5b1499cec46 | Foreign/FreeType/src/tools/docmaker/sources.py | python | SourceBlockFormat.__init__ | ( self, id, start, column, end ) | Create a block pattern, used to recognize special documentation
blocks. | Create a block pattern, used to recognize special documentation
blocks. | [
"Create",
"a",
"block",
"pattern",
"used",
"to",
"recognize",
"special",
"documentation",
"blocks",
"."
] | def __init__( self, id, start, column, end ):
"""Create a block pattern, used to recognize special documentation
blocks."""
self.id = id
self.start = re.compile( start, re.VERBOSE )
self.column = re.compile( column, re.VERBOSE )
self.end = re.compile( end, re.VERBOSE ) | [
"def",
"__init__",
"(",
"self",
",",
"id",
",",
"start",
",",
"column",
",",
"end",
")",
":",
"self",
".",
"id",
"=",
"id",
"self",
".",
"start",
"=",
"re",
".",
"compile",
"(",
"start",
",",
"re",
".",
"VERBOSE",
")",
"self",
".",
"column",
"=",
"re",
".",
"compile",
"(",
"column",
",",
"re",
".",
"VERBOSE",
")",
"self",
".",
"end",
"=",
"re",
".",
"compile",
"(",
"end",
",",
"re",
".",
"VERBOSE",
")"
] | https://github.com/xlgames-inc/XLE/blob/cdd8682367d9e9fdbdda9f79d72bb5b1499cec46/Foreign/FreeType/src/tools/docmaker/sources.py#L50-L56 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/message.py | python | Message.replace_header | (self, _name, _value) | Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised. | Replace a header. | [
"Replace",
"a",
"header",
"."
] | def replace_header(self, _name, _value):
"""Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised.
"""
_name = _name.lower()
for i, (k, v) in zip(range(len(self._headers)), self._headers):
if k.lower() == _name:
self._headers[i] = (k, _value)
break
else:
raise KeyError(_name) | [
"def",
"replace_header",
"(",
"self",
",",
"_name",
",",
"_value",
")",
":",
"_name",
"=",
"_name",
".",
"lower",
"(",
")",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"zip",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"_headers",
")",
")",
",",
"self",
".",
"_headers",
")",
":",
"if",
"k",
".",
"lower",
"(",
")",
"==",
"_name",
":",
"self",
".",
"_headers",
"[",
"i",
"]",
"=",
"(",
"k",
",",
"_value",
")",
"break",
"else",
":",
"raise",
"KeyError",
"(",
"_name",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/message.py#L413-L426 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | libVeles/cpplint.py | python | _CppLintState.ResetErrorCounts | (self) | Sets the module's error statistic back to zero. | Sets the module's error statistic back to zero. | [
"Sets",
"the",
"module",
"s",
"error",
"statistic",
"back",
"to",
"zero",
"."
] | def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {} | [
"def",
"ResetErrorCounts",
"(",
"self",
")",
":",
"self",
".",
"error_count",
"=",
"0",
"self",
".",
"errors_by_category",
"=",
"{",
"}"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L606-L609 | ||
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmlparser3.py | python | Parser.parse | (self) | return self.root | Parse preprocessed WML into a tree of tags and attributes. | Parse preprocessed WML into a tree of tags and attributes. | [
"Parse",
"preprocessed",
"WML",
"into",
"a",
"tree",
"of",
"tags",
"and",
"attributes",
"."
] | def parse(self) -> RootNode:
"""
Parse preprocessed WML into a tree of tags and attributes.
"""
# parsing state
self.temp_string = b""
self.temp_string_node = None
self.commas = 0
self.temp_key_nodes = []
self.in_string = False
self.in_arrows = False
self.textdomain = "wesnoth"
self.translatable = False
self.root = RootNode()
self.parent_node = [self.root]
self.skip_newlines_after_plus = False
self.in_tag = b""
command_marker_byte = bytes([254])
input = self.preprocessed
if not input: input = self.path
for rawline in open(input, "rb"):
compos = rawline.find(command_marker_byte)
self.parser_line += 1
# Everything from chr(254) to newline is the command.
if compos != 0:
self.line_in_file += 1
if compos >= 0:
self.parse_line_without_commands(rawline[:compos])
self.handle_command(rawline[compos + 1:-1])
else:
self.parse_line_without_commands(rawline)
if self.keep_temp_dir is None and self.temp_dir:
if self.verbose:
print(("removing " + self.temp_dir))
shutil.rmtree(self.temp_dir, ignore_errors=True)
return self.root | [
"def",
"parse",
"(",
"self",
")",
"->",
"RootNode",
":",
"# parsing state",
"self",
".",
"temp_string",
"=",
"b\"\"",
"self",
".",
"temp_string_node",
"=",
"None",
"self",
".",
"commas",
"=",
"0",
"self",
".",
"temp_key_nodes",
"=",
"[",
"]",
"self",
".",
"in_string",
"=",
"False",
"self",
".",
"in_arrows",
"=",
"False",
"self",
".",
"textdomain",
"=",
"\"wesnoth\"",
"self",
".",
"translatable",
"=",
"False",
"self",
".",
"root",
"=",
"RootNode",
"(",
")",
"self",
".",
"parent_node",
"=",
"[",
"self",
".",
"root",
"]",
"self",
".",
"skip_newlines_after_plus",
"=",
"False",
"self",
".",
"in_tag",
"=",
"b\"\"",
"command_marker_byte",
"=",
"bytes",
"(",
"[",
"254",
"]",
")",
"input",
"=",
"self",
".",
"preprocessed",
"if",
"not",
"input",
":",
"input",
"=",
"self",
".",
"path",
"for",
"rawline",
"in",
"open",
"(",
"input",
",",
"\"rb\"",
")",
":",
"compos",
"=",
"rawline",
".",
"find",
"(",
"command_marker_byte",
")",
"self",
".",
"parser_line",
"+=",
"1",
"# Everything from chr(254) to newline is the command.",
"if",
"compos",
"!=",
"0",
":",
"self",
".",
"line_in_file",
"+=",
"1",
"if",
"compos",
">=",
"0",
":",
"self",
".",
"parse_line_without_commands",
"(",
"rawline",
"[",
":",
"compos",
"]",
")",
"self",
".",
"handle_command",
"(",
"rawline",
"[",
"compos",
"+",
"1",
":",
"-",
"1",
"]",
")",
"else",
":",
"self",
".",
"parse_line_without_commands",
"(",
"rawline",
")",
"if",
"self",
".",
"keep_temp_dir",
"is",
"None",
"and",
"self",
".",
"temp_dir",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"(",
"\"removing \"",
"+",
"self",
".",
"temp_dir",
")",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"temp_dir",
",",
"ignore_errors",
"=",
"True",
")",
"return",
"self",
".",
"root"
] | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmlparser3.py#L605-L646 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/PyShell.py | python | idle_showwarning | (
message, category, filename, lineno, file=None, line=None) | Show Idle-format warning (after replacing warnings.showwarning).
The differences are the formatter called, the file=None replacement,
which can be None, the capture of the consequence AttributeError,
and the output of a hard-coded prompt. | Show Idle-format warning (after replacing warnings.showwarning). | [
"Show",
"Idle",
"-",
"format",
"warning",
"(",
"after",
"replacing",
"warnings",
".",
"showwarning",
")",
"."
] | def idle_showwarning(
message, category, filename, lineno, file=None, line=None):
"""Show Idle-format warning (after replacing warnings.showwarning).
The differences are the formatter called, the file=None replacement,
which can be None, the capture of the consequence AttributeError,
and the output of a hard-coded prompt.
"""
if file is None:
file = warning_stream
try:
file.write(idle_formatwarning(
message, category, filename, lineno, line=line))
file.write(">>> ")
except (AttributeError, IOError):
pass | [
"def",
"idle_showwarning",
"(",
"message",
",",
"category",
",",
"filename",
",",
"lineno",
",",
"file",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"warning_stream",
"try",
":",
"file",
".",
"write",
"(",
"idle_formatwarning",
"(",
"message",
",",
"category",
",",
"filename",
",",
"lineno",
",",
"line",
"=",
"line",
")",
")",
"file",
".",
"write",
"(",
"\">>> \"",
")",
"except",
"(",
"AttributeError",
",",
"IOError",
")",
":",
"pass"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/PyShell.py#L68-L83 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Main.py | python | find_deepest_user_frame | (tb) | return tb[0] | Find the deepest stack frame that is not part of SCons.
Input is a "pre-processed" stack trace in the form
returned by traceback.extract_tb() or traceback.extract_stack() | Find the deepest stack frame that is not part of SCons. | [
"Find",
"the",
"deepest",
"stack",
"frame",
"that",
"is",
"not",
"part",
"of",
"SCons",
"."
] | def find_deepest_user_frame(tb):
"""
Find the deepest stack frame that is not part of SCons.
Input is a "pre-processed" stack trace in the form
returned by traceback.extract_tb() or traceback.extract_stack()
"""
tb.reverse()
# find the deepest traceback frame that is not part
# of SCons:
for frame in tb:
filename = frame[0]
if filename.find(os.sep+'SCons'+os.sep) == -1:
return frame
return tb[0] | [
"def",
"find_deepest_user_frame",
"(",
"tb",
")",
":",
"tb",
".",
"reverse",
"(",
")",
"# find the deepest traceback frame that is not part",
"# of SCons:",
"for",
"frame",
"in",
"tb",
":",
"filename",
"=",
"frame",
"[",
"0",
"]",
"if",
"filename",
".",
"find",
"(",
"os",
".",
"sep",
"+",
"'SCons'",
"+",
"os",
".",
"sep",
")",
"==",
"-",
"1",
":",
"return",
"frame",
"return",
"tb",
"[",
"0",
"]"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Main.py#L547-L563 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/cluster/_birch.py | python | Birch.fit | (self, X, y=None) | return self._fit(X) | Build a CF Tree for the input data.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self
Fitted estimator. | Build a CF Tree for the input data. | [
"Build",
"a",
"CF",
"Tree",
"for",
"the",
"input",
"data",
"."
] | def fit(self, X, y=None):
"""
Build a CF Tree for the input data.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self
Fitted estimator.
"""
self.fit_, self.partial_fit_ = True, False
return self._fit(X) | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"fit_",
",",
"self",
".",
"partial_fit_",
"=",
"True",
",",
"False",
"return",
"self",
".",
"_fit",
"(",
"X",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_birch.py#L441-L459 | |
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/python/semver/semver.py | python | parse | (version) | return verinfo | Parse version to major, minor, patch, pre-release, build parts. | Parse version to major, minor, patch, pre-release, build parts. | [
"Parse",
"version",
"to",
"major",
"minor",
"patch",
"pre",
"-",
"release",
"build",
"parts",
"."
] | def parse(version):
"""
Parse version to major, minor, patch, pre-release, build parts.
"""
match = _REGEX.match(version)
if match is None:
raise ValueError('%s is not valid SemVer string' % version)
verinfo = match.groupdict()
verinfo['major'] = int(verinfo['major'])
verinfo['minor'] = int(verinfo['minor'])
verinfo['patch'] = int(verinfo['patch'])
return verinfo | [
"def",
"parse",
"(",
"version",
")",
":",
"match",
"=",
"_REGEX",
".",
"match",
"(",
"version",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'%s is not valid SemVer string'",
"%",
"version",
")",
"verinfo",
"=",
"match",
".",
"groupdict",
"(",
")",
"verinfo",
"[",
"'major'",
"]",
"=",
"int",
"(",
"verinfo",
"[",
"'major'",
"]",
")",
"verinfo",
"[",
"'minor'",
"]",
"=",
"int",
"(",
"verinfo",
"[",
"'minor'",
"]",
")",
"verinfo",
"[",
"'patch'",
"]",
"=",
"int",
"(",
"verinfo",
"[",
"'patch'",
"]",
")",
"return",
"verinfo"
] | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/python/semver/semver.py#L17-L31 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/ssd/config/utils.py | python | zip_namedtuple | (nt_list) | return ret | accept list of namedtuple, return a dict of zipped fields | accept list of namedtuple, return a dict of zipped fields | [
"accept",
"list",
"of",
"namedtuple",
"return",
"a",
"dict",
"of",
"zipped",
"fields"
] | def zip_namedtuple(nt_list):
""" accept list of namedtuple, return a dict of zipped fields """
if not nt_list:
return dict()
if not isinstance(nt_list, list):
nt_list = [nt_list]
for nt in nt_list:
assert type(nt) == type(nt_list[0])
ret = {k : [v] for k, v in nt_list[0]._asdict().items()}
for nt in nt_list[1:]:
for k, v in nt._asdict().items():
ret[k].append(v)
return ret | [
"def",
"zip_namedtuple",
"(",
"nt_list",
")",
":",
"if",
"not",
"nt_list",
":",
"return",
"dict",
"(",
")",
"if",
"not",
"isinstance",
"(",
"nt_list",
",",
"list",
")",
":",
"nt_list",
"=",
"[",
"nt_list",
"]",
"for",
"nt",
"in",
"nt_list",
":",
"assert",
"type",
"(",
"nt",
")",
"==",
"type",
"(",
"nt_list",
"[",
"0",
"]",
")",
"ret",
"=",
"{",
"k",
":",
"[",
"v",
"]",
"for",
"k",
",",
"v",
"in",
"nt_list",
"[",
"0",
"]",
".",
"_asdict",
"(",
")",
".",
"items",
"(",
")",
"}",
"for",
"nt",
"in",
"nt_list",
"[",
"1",
":",
"]",
":",
"for",
"k",
",",
"v",
"in",
"nt",
".",
"_asdict",
"(",
")",
".",
"items",
"(",
")",
":",
"ret",
"[",
"k",
"]",
".",
"append",
"(",
"v",
")",
"return",
"ret"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/ssd/config/utils.py#L78-L90 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/cli/profile_analyzer_cli.py | python | ProfileDataTableView.__init__ | (self, profile_datum_list, time_unit=cli_shared.TIME_UNIT_US) | Constructor.
Args:
profile_datum_list: List of `ProfileDatum` objects.
time_unit: must be in cli_shared.TIME_UNITS. | Constructor. | [
"Constructor",
"."
] | def __init__(self, profile_datum_list, time_unit=cli_shared.TIME_UNIT_US):
"""Constructor.
Args:
profile_datum_list: List of `ProfileDatum` objects.
time_unit: must be in cli_shared.TIME_UNITS.
"""
self._profile_datum_list = profile_datum_list
self.formatted_start_time = [
datum.start_time for datum in profile_datum_list]
self.formatted_op_time = [
cli_shared.time_to_readable_str(datum.op_time,
force_time_unit=time_unit)
for datum in profile_datum_list]
self.formatted_exec_time = [
cli_shared.time_to_readable_str(
datum.node_exec_stats.all_end_rel_micros,
force_time_unit=time_unit)
for datum in profile_datum_list]
self._column_names = ["Node",
"Op Type",
"Start Time (us)",
"Op Time (%s)" % time_unit,
"Exec Time (%s)" % time_unit,
"Filename:Lineno(function)"]
self._column_sort_ids = [SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE,
SORT_OPS_BY_START_TIME, SORT_OPS_BY_OP_TIME,
SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_LINE] | [
"def",
"__init__",
"(",
"self",
",",
"profile_datum_list",
",",
"time_unit",
"=",
"cli_shared",
".",
"TIME_UNIT_US",
")",
":",
"self",
".",
"_profile_datum_list",
"=",
"profile_datum_list",
"self",
".",
"formatted_start_time",
"=",
"[",
"datum",
".",
"start_time",
"for",
"datum",
"in",
"profile_datum_list",
"]",
"self",
".",
"formatted_op_time",
"=",
"[",
"cli_shared",
".",
"time_to_readable_str",
"(",
"datum",
".",
"op_time",
",",
"force_time_unit",
"=",
"time_unit",
")",
"for",
"datum",
"in",
"profile_datum_list",
"]",
"self",
".",
"formatted_exec_time",
"=",
"[",
"cli_shared",
".",
"time_to_readable_str",
"(",
"datum",
".",
"node_exec_stats",
".",
"all_end_rel_micros",
",",
"force_time_unit",
"=",
"time_unit",
")",
"for",
"datum",
"in",
"profile_datum_list",
"]",
"self",
".",
"_column_names",
"=",
"[",
"\"Node\"",
",",
"\"Op Type\"",
",",
"\"Start Time (us)\"",
",",
"\"Op Time (%s)\"",
"%",
"time_unit",
",",
"\"Exec Time (%s)\"",
"%",
"time_unit",
",",
"\"Filename:Lineno(function)\"",
"]",
"self",
".",
"_column_sort_ids",
"=",
"[",
"SORT_OPS_BY_OP_NAME",
",",
"SORT_OPS_BY_OP_TYPE",
",",
"SORT_OPS_BY_START_TIME",
",",
"SORT_OPS_BY_OP_TIME",
",",
"SORT_OPS_BY_EXEC_TIME",
",",
"SORT_OPS_BY_LINE",
"]"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/profile_analyzer_cli.py#L51-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | TextAttrDimension.SetPosition | (*args, **kwargs) | return _richtext.TextAttrDimension_SetPosition(*args, **kwargs) | SetPosition(self, int pos) | SetPosition(self, int pos) | [
"SetPosition",
"(",
"self",
"int",
"pos",
")"
] | def SetPosition(*args, **kwargs):
"""SetPosition(self, int pos)"""
return _richtext.TextAttrDimension_SetPosition(*args, **kwargs) | [
"def",
"SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextAttrDimension_SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L180-L182 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/common/string_utils.py | python | SanitizeText | (text) | return text.strip(" \t\n\r") | Sanitizes text.
Function removes leading and trailing whitespaces.
Args:
text: input string.
Returns:
sanitized string. | Sanitizes text. | [
"Sanitizes",
"text",
"."
] | def SanitizeText(text):
"""Sanitizes text.
Function removes leading and trailing whitespaces.
Args:
text: input string.
Returns:
sanitized string.
"""
return text.strip(" \t\n\r") | [
"def",
"SanitizeText",
"(",
"text",
")",
":",
"return",
"text",
".",
"strip",
"(",
"\" \\t\\n\\r\"",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/common/string_utils.py#L28-L38 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py | python | TurtleScreenBase._listen | (self) | Set focus on canvas (in order to collect key-events) | Set focus on canvas (in order to collect key-events) | [
"Set",
"focus",
"on",
"canvas",
"(",
"in",
"order",
"to",
"collect",
"key",
"-",
"events",
")"
] | def _listen(self):
"""Set focus on canvas (in order to collect key-events)
"""
self.cv.focus_force() | [
"def",
"_listen",
"(",
"self",
")",
":",
"self",
".",
"cv",
".",
"focus_force",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L713-L716 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/summary_ops_v2.py | python | _should_record_summaries_internal | (default_state) | return math_ops.logical_and(cond_distributed, cond) | Returns boolean Tensor if summaries should/shouldn't be recorded.
Now the summary condition is decided by logical "and" of two conditions:
ctx.summary_recording and ctx.summary_recording_distribution_strategy. The
former one is usually set by user, and the latter one is controlled by
DistributionStrategy (tf.distribute.ReplicaContext).
Args:
default_state: can be True or False. The default summary behavior when user
does not specify ctx.summary_recording and
ctx.summary_recording_distribution_strategy is True. | Returns boolean Tensor if summaries should/shouldn't be recorded. | [
"Returns",
"boolean",
"Tensor",
"if",
"summaries",
"should",
"/",
"shouldn",
"t",
"be",
"recorded",
"."
] | def _should_record_summaries_internal(default_state):
"""Returns boolean Tensor if summaries should/shouldn't be recorded.
Now the summary condition is decided by logical "and" of two conditions:
ctx.summary_recording and ctx.summary_recording_distribution_strategy. The
former one is usually set by user, and the latter one is controlled by
DistributionStrategy (tf.distribute.ReplicaContext).
Args:
default_state: can be True or False. The default summary behavior when user
does not specify ctx.summary_recording and
ctx.summary_recording_distribution_strategy is True.
"""
ctx = context.context()
resolve = lambda x: x() if callable(x) else x
cond_distributed = resolve(ctx.summary_recording_distribution_strategy)
cond = resolve(ctx.summary_recording)
if cond is None:
cond = default_state
return math_ops.logical_and(cond_distributed, cond) | [
"def",
"_should_record_summaries_internal",
"(",
"default_state",
")",
":",
"ctx",
"=",
"context",
".",
"context",
"(",
")",
"resolve",
"=",
"lambda",
"x",
":",
"x",
"(",
")",
"if",
"callable",
"(",
"x",
")",
"else",
"x",
"cond_distributed",
"=",
"resolve",
"(",
"ctx",
".",
"summary_recording_distribution_strategy",
")",
"cond",
"=",
"resolve",
"(",
"ctx",
".",
"summary_recording",
")",
"if",
"cond",
"is",
"None",
":",
"cond",
"=",
"default_state",
"return",
"math_ops",
".",
"logical_and",
"(",
"cond_distributed",
",",
"cond",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/summary_ops_v2.py#L64-L83 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiToolBarEvent.SetDropDownClicked | (*args, **kwargs) | return _aui.AuiToolBarEvent_SetDropDownClicked(*args, **kwargs) | SetDropDownClicked(self, bool c) | SetDropDownClicked(self, bool c) | [
"SetDropDownClicked",
"(",
"self",
"bool",
"c",
")"
] | def SetDropDownClicked(*args, **kwargs):
"""SetDropDownClicked(self, bool c)"""
return _aui.AuiToolBarEvent_SetDropDownClicked(*args, **kwargs) | [
"def",
"SetDropDownClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBarEvent_SetDropDownClicked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1685-L1687 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/data_adapter.py | python | DataHandler._configure_dataset_and_inferred_steps | (self, strategy, x, steps_per_epoch,
class_weight, distribute) | Configure the `_dataset` and `_inferred_steps` attributes. | Configure the `_dataset` and `_inferred_steps` attributes. | [
"Configure",
"the",
"_dataset",
"and",
"_inferred_steps",
"attributes",
"."
] | def _configure_dataset_and_inferred_steps(self, strategy, x, steps_per_epoch,
class_weight, distribute):
"""Configure the `_dataset` and `_inferred_steps` attributes."""
del x
dataset = self._adapter.get_dataset()
if class_weight:
dataset = dataset.map(_make_class_weight_map_fn(class_weight))
self._inferred_steps = self._infer_steps(steps_per_epoch, dataset)
# `PreprocessingLayer.adapt` does not currently support distributed
# datasets, so we pass `distribute=False` there.
if distribute and not _is_distributed_dataset(dataset):
dataset = strategy.experimental_distribute_dataset(dataset)
self._dataset = dataset
self._validate_data_handler() | [
"def",
"_configure_dataset_and_inferred_steps",
"(",
"self",
",",
"strategy",
",",
"x",
",",
"steps_per_epoch",
",",
"class_weight",
",",
"distribute",
")",
":",
"del",
"x",
"dataset",
"=",
"self",
".",
"_adapter",
".",
"get_dataset",
"(",
")",
"if",
"class_weight",
":",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"_make_class_weight_map_fn",
"(",
"class_weight",
")",
")",
"self",
".",
"_inferred_steps",
"=",
"self",
".",
"_infer_steps",
"(",
"steps_per_epoch",
",",
"dataset",
")",
"# `PreprocessingLayer.adapt` does not currently support distributed",
"# datasets, so we pass `distribute=False` there.",
"if",
"distribute",
"and",
"not",
"_is_distributed_dataset",
"(",
"dataset",
")",
":",
"dataset",
"=",
"strategy",
".",
"experimental_distribute_dataset",
"(",
"dataset",
")",
"self",
".",
"_dataset",
"=",
"dataset",
"self",
".",
"_validate_data_handler",
"(",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/data_adapter.py#L1172-L1186 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_NULL_KDF_SCHEME.fromTpm | (buf) | return buf.createObj(TPMS_NULL_KDF_SCHEME) | Returns new TPMS_NULL_KDF_SCHEME object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPMS_NULL_KDF_SCHEME object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPMS_NULL_KDF_SCHEME",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPMS_NULL_KDF_SCHEME object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPMS_NULL_KDF_SCHEME) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPMS_NULL_KDF_SCHEME",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6904-L6908 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/fractions.py | python | Fraction.__floor__ | (a) | return a.numerator // a.denominator | Will be math.floor(a) in 3.0. | Will be math.floor(a) in 3.0. | [
"Will",
"be",
"math",
".",
"floor",
"(",
"a",
")",
"in",
"3",
".",
"0",
"."
] | def __floor__(a):
"""Will be math.floor(a) in 3.0."""
return a.numerator // a.denominator | [
"def",
"__floor__",
"(",
"a",
")",
":",
"return",
"a",
".",
"numerator",
"//",
"a",
".",
"denominator"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/fractions.py#L511-L513 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow2/tf_graph_pass/rewrite_control_flow_functions.py | python | _eliminate_loop_cond_nodes | (tf_ssa, fn) | Eliminate loop condition nodes, such as loop_counters, max_iterations from
the cond sub-graph and body sub-graph of tf.while_loop.
Parameters
----------
tf_ssa: NetworkEnsemble
An object that contains multiple functions / sub-graphs.
fn: SSAFunction
Function that contains graph to operate on.
Examples
--------
Input:
Before pass "main" graph:
[while/maximum_iterations] -----\
[while/loop_counter] -------> [while] --> [identity]
[placeholder/args_0] ----------/
Before pass "cond" graph:
[const/mean] -------\
[placeholder] --> [mean] --> [greater]
[const/greater/y] --------------/
[while_maximum_iterations], [while_loop_counter] (not connected)
Before pass "body" graph:
[const/sub/y] ------\
[placeholder] ---> [sub]
[const/add/y] ------------\
[while_loop_counter] --> [add]
[while_maximum_iterations] (not connected)
Output:
After pass "main" graph:
[placeholder/args_0] --> [while] --> [identity]
After pass "cond" graph:
[const/mean] -------\
[placeholder] --> [mean] --> [greater]
[const/greater/y] --------------/
After pass "body" graph:
[const/sub/y] ------\
[placeholder] ---> [sub] | Eliminate loop condition nodes, such as loop_counters, max_iterations from
the cond sub-graph and body sub-graph of tf.while_loop. | [
"Eliminate",
"loop",
"condition",
"nodes",
"such",
"as",
"loop_counters",
"max_iterations",
"from",
"the",
"cond",
"sub",
"-",
"graph",
"and",
"body",
"sub",
"-",
"graph",
"of",
"tf",
".",
"while_loop",
"."
] | def _eliminate_loop_cond_nodes(tf_ssa, fn):
"""
Eliminate loop condition nodes, such as loop_counters, max_iterations from
the cond sub-graph and body sub-graph of tf.while_loop.
Parameters
----------
tf_ssa: NetworkEnsemble
An object that contains multiple functions / sub-graphs.
fn: SSAFunction
Function that contains graph to operate on.
Examples
--------
Input:
Before pass "main" graph:
[while/maximum_iterations] -----\
[while/loop_counter] -------> [while] --> [identity]
[placeholder/args_0] ----------/
Before pass "cond" graph:
[const/mean] -------\
[placeholder] --> [mean] --> [greater]
[const/greater/y] --------------/
[while_maximum_iterations], [while_loop_counter] (not connected)
Before pass "body" graph:
[const/sub/y] ------\
[placeholder] ---> [sub]
[const/add/y] ------------\
[while_loop_counter] --> [add]
[while_maximum_iterations] (not connected)
Output:
After pass "main" graph:
[placeholder/args_0] --> [while] --> [identity]
After pass "cond" graph:
[const/mean] -------\
[placeholder] --> [mean] --> [greater]
[const/greater/y] --------------/
After pass "body" graph:
[const/sub/y] ------\
[placeholder] ---> [sub]
"""
for name, node in fn.graph.copy().items():
if node.op not in {"StatelessWhile", "While"}:
continue
cond_fn = tf_ssa.functions.get(node.attr.get("cond"))
body_fn = tf_ssa.functions.get(node.attr.get("body"))
cond_lc_nodes = {cond_fn.inputs.pop(0), cond_fn.inputs.pop(0)}
logging.info("Removing {} from cond graph".format(cond_lc_nodes))
for n in cond_lc_nodes:
delete_node(cond_fn.graph, n)
body_lc_nodes = {body_fn.inputs.pop(0), body_fn.inputs.pop(0)}
q = list(body_lc_nodes)
# delete entire sub-fn
while len(q) > 0:
n = body_fn.graph[q.pop(0)]
for o in n.outputs:
if o not in body_lc_nodes:
q.append(o)
body_lc_nodes.add(o)
for i in body_fn.graph[o].inputs:
if i not in body_lc_nodes:
q.append(i)
body_lc_nodes.add(i)
# remove if in outputs
for n in body_lc_nodes:
if n in body_fn.outputs:
msg = "Removing '{}' ({}) from body fn outputs"
logging.info(msg.format(n, body_fn.graph[n].op))
body_fn.outputs.remove(n)
logging.info("Removing {} from body graph".format(body_lc_nodes))
for n in body_lc_nodes:
delete_node(body_fn.graph, n) | [
"def",
"_eliminate_loop_cond_nodes",
"(",
"tf_ssa",
",",
"fn",
")",
":",
"for",
"name",
",",
"node",
"in",
"fn",
".",
"graph",
".",
"copy",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"node",
".",
"op",
"not",
"in",
"{",
"\"StatelessWhile\"",
",",
"\"While\"",
"}",
":",
"continue",
"cond_fn",
"=",
"tf_ssa",
".",
"functions",
".",
"get",
"(",
"node",
".",
"attr",
".",
"get",
"(",
"\"cond\"",
")",
")",
"body_fn",
"=",
"tf_ssa",
".",
"functions",
".",
"get",
"(",
"node",
".",
"attr",
".",
"get",
"(",
"\"body\"",
")",
")",
"cond_lc_nodes",
"=",
"{",
"cond_fn",
".",
"inputs",
".",
"pop",
"(",
"0",
")",
",",
"cond_fn",
".",
"inputs",
".",
"pop",
"(",
"0",
")",
"}",
"logging",
".",
"info",
"(",
"\"Removing {} from cond graph\"",
".",
"format",
"(",
"cond_lc_nodes",
")",
")",
"for",
"n",
"in",
"cond_lc_nodes",
":",
"delete_node",
"(",
"cond_fn",
".",
"graph",
",",
"n",
")",
"body_lc_nodes",
"=",
"{",
"body_fn",
".",
"inputs",
".",
"pop",
"(",
"0",
")",
",",
"body_fn",
".",
"inputs",
".",
"pop",
"(",
"0",
")",
"}",
"q",
"=",
"list",
"(",
"body_lc_nodes",
")",
"# delete entire sub-fn",
"while",
"len",
"(",
"q",
")",
">",
"0",
":",
"n",
"=",
"body_fn",
".",
"graph",
"[",
"q",
".",
"pop",
"(",
"0",
")",
"]",
"for",
"o",
"in",
"n",
".",
"outputs",
":",
"if",
"o",
"not",
"in",
"body_lc_nodes",
":",
"q",
".",
"append",
"(",
"o",
")",
"body_lc_nodes",
".",
"add",
"(",
"o",
")",
"for",
"i",
"in",
"body_fn",
".",
"graph",
"[",
"o",
"]",
".",
"inputs",
":",
"if",
"i",
"not",
"in",
"body_lc_nodes",
":",
"q",
".",
"append",
"(",
"i",
")",
"body_lc_nodes",
".",
"add",
"(",
"i",
")",
"# remove if in outputs",
"for",
"n",
"in",
"body_lc_nodes",
":",
"if",
"n",
"in",
"body_fn",
".",
"outputs",
":",
"msg",
"=",
"\"Removing '{}' ({}) from body fn outputs\"",
"logging",
".",
"info",
"(",
"msg",
".",
"format",
"(",
"n",
",",
"body_fn",
".",
"graph",
"[",
"n",
"]",
".",
"op",
")",
")",
"body_fn",
".",
"outputs",
".",
"remove",
"(",
"n",
")",
"logging",
".",
"info",
"(",
"\"Removing {} from body graph\"",
".",
"format",
"(",
"body_lc_nodes",
")",
")",
"for",
"n",
"in",
"body_lc_nodes",
":",
"delete_node",
"(",
"body_fn",
".",
"graph",
",",
"n",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow2/tf_graph_pass/rewrite_control_flow_functions.py#L312-L406 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/client.py | python | OAuth2Credentials._updateFromCredential | (self, other) | Update this Credential from another instance. | Update this Credential from another instance. | [
"Update",
"this",
"Credential",
"from",
"another",
"instance",
"."
] | def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
self.__dict__.update(other.__getstate__()) | [
"def",
"_updateFromCredential",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"other",
".",
"__getstate__",
"(",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/client.py#L718-L720 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ensurepip/__init__.py | python | _bootstrap | (*, root=None, upgrade=False, user=False,
altinstall=False, default_pip=False,
verbosity=0) | Bootstrap pip into the current Python installation (or the given root
directory). Returns pip command status code.
Note that calling this function will alter both sys.path and os.environ. | Bootstrap pip into the current Python installation (or the given root
directory). Returns pip command status code. | [
"Bootstrap",
"pip",
"into",
"the",
"current",
"Python",
"installation",
"(",
"or",
"the",
"given",
"root",
"directory",
")",
".",
"Returns",
"pip",
"command",
"status",
"code",
"."
] | def _bootstrap(*, root=None, upgrade=False, user=False,
altinstall=False, default_pip=False,
verbosity=0):
"""
Bootstrap pip into the current Python installation (or the given root
directory). Returns pip command status code.
Note that calling this function will alter both sys.path and os.environ.
"""
if altinstall and default_pip:
raise ValueError("Cannot use altinstall and default_pip together")
sys.audit("ensurepip.bootstrap", root)
_disable_pip_configuration_settings()
# By default, installing pip and setuptools installs all of the
# following scripts (X.Y == running Python version):
#
# pip, pipX, pipX.Y, easy_install, easy_install-X.Y
#
# pip 1.5+ allows ensurepip to request that some of those be left out
if altinstall:
# omit pip, pipX and easy_install
os.environ["ENSUREPIP_OPTIONS"] = "altinstall"
elif not default_pip:
# omit pip and easy_install
os.environ["ENSUREPIP_OPTIONS"] = "install"
with tempfile.TemporaryDirectory() as tmpdir:
# Put our bundled wheels into a temporary directory and construct the
# additional paths that need added to sys.path
additional_paths = []
for project, version, py_tag in _PROJECTS:
wheel_name = "{}-{}-{}-none-any.whl".format(project, version, py_tag)
whl = resources.read_binary(
_bundled,
wheel_name,
)
with open(os.path.join(tmpdir, wheel_name), "wb") as fp:
fp.write(whl)
additional_paths.append(os.path.join(tmpdir, wheel_name))
# Construct the arguments to be passed to the pip command
args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
if root:
args += ["--root", root]
if upgrade:
args += ["--upgrade"]
if user:
args += ["--user"]
if verbosity:
args += ["-" + "v" * verbosity]
return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) | [
"def",
"_bootstrap",
"(",
"*",
",",
"root",
"=",
"None",
",",
"upgrade",
"=",
"False",
",",
"user",
"=",
"False",
",",
"altinstall",
"=",
"False",
",",
"default_pip",
"=",
"False",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"altinstall",
"and",
"default_pip",
":",
"raise",
"ValueError",
"(",
"\"Cannot use altinstall and default_pip together\"",
")",
"sys",
".",
"audit",
"(",
"\"ensurepip.bootstrap\"",
",",
"root",
")",
"_disable_pip_configuration_settings",
"(",
")",
"# By default, installing pip and setuptools installs all of the",
"# following scripts (X.Y == running Python version):",
"#",
"# pip, pipX, pipX.Y, easy_install, easy_install-X.Y",
"#",
"# pip 1.5+ allows ensurepip to request that some of those be left out",
"if",
"altinstall",
":",
"# omit pip, pipX and easy_install",
"os",
".",
"environ",
"[",
"\"ENSUREPIP_OPTIONS\"",
"]",
"=",
"\"altinstall\"",
"elif",
"not",
"default_pip",
":",
"# omit pip and easy_install",
"os",
".",
"environ",
"[",
"\"ENSUREPIP_OPTIONS\"",
"]",
"=",
"\"install\"",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"tmpdir",
":",
"# Put our bundled wheels into a temporary directory and construct the",
"# additional paths that need added to sys.path",
"additional_paths",
"=",
"[",
"]",
"for",
"project",
",",
"version",
",",
"py_tag",
"in",
"_PROJECTS",
":",
"wheel_name",
"=",
"\"{}-{}-{}-none-any.whl\"",
".",
"format",
"(",
"project",
",",
"version",
",",
"py_tag",
")",
"whl",
"=",
"resources",
".",
"read_binary",
"(",
"_bundled",
",",
"wheel_name",
",",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"wheel_name",
")",
",",
"\"wb\"",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"whl",
")",
"additional_paths",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"wheel_name",
")",
")",
"# Construct the arguments to be passed to the pip command",
"args",
"=",
"[",
"\"install\"",
",",
"\"--no-cache-dir\"",
",",
"\"--no-index\"",
",",
"\"--find-links\"",
",",
"tmpdir",
"]",
"if",
"root",
":",
"args",
"+=",
"[",
"\"--root\"",
",",
"root",
"]",
"if",
"upgrade",
":",
"args",
"+=",
"[",
"\"--upgrade\"",
"]",
"if",
"user",
":",
"args",
"+=",
"[",
"\"--user\"",
"]",
"if",
"verbosity",
":",
"args",
"+=",
"[",
"\"-\"",
"+",
"\"v\"",
"*",
"verbosity",
"]",
"return",
"_run_pip",
"(",
"args",
"+",
"[",
"p",
"[",
"0",
"]",
"for",
"p",
"in",
"_PROJECTS",
"]",
",",
"additional_paths",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ensurepip/__init__.py#L70-L125 | ||
NASA-Tensegrity-Robotics-Toolkit/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | scripts/learning/src/evolution/evolution_job.py | python | EvolutionJob.startJob | (self) | Override this to start the NTRT instance and pass it the relevant parameters.. This is called
by NTRTJobMaster when it wants to start this NTRT process. | Override this to start the NTRT instance and pass it the relevant parameters.. This is called
by NTRTJobMaster when it wants to start this NTRT process. | [
"Override",
"this",
"to",
"start",
"the",
"NTRT",
"instance",
"and",
"pass",
"it",
"the",
"relevant",
"parameters",
"..",
"This",
"is",
"called",
"by",
"NTRTJobMaster",
"when",
"it",
"wants",
"to",
"start",
"this",
"NTRT",
"process",
"."
] | def startJob(self):
"""
Override this to start the NTRT instance and pass it the relevant parameters.. This is called
by NTRTJobMaster when it wants to start this NTRT process.
"""
logging.info("STARTING job with args %r" % self.args)
self.pid = os.fork()
if self.pid == 0:
# Redirect the stdout output to dev null in the child.
logPath = self.args['resourcePrefix'] + self.args['path'] + self.args['filename'] + '_log.txt'
logFile = open(logPath, 'wb')
# A set of jobs. Currently [0 0] is flat ground, [1 0] is a block field, [0 1] is hilly terrain, and [1 1] is both
# This will expand in the future.
terrainMatrix = self.args['terrain']
# Update this if the subprocess call gets changed
if len(terrainMatrix[0]) < 4:
raise NTRTMasterError("Not enough terrain args!")
# Run through a set of binary job options. Currently handles terrain switches
for run in terrainMatrix:
if (len(run)) >= 5:
trialLength = run[4]
else:
trialLength = self.args['length']
#TODO improve error handling here
subprocess.check_call([self.args['executable'], "-l", self.args['filename'], "-P", self.args['path'], "-s", str(trialLength), "-b", str(run[0]), "-H", str(run[1]), "-a", str(run[2]), "-B", str(run[3])], stdout=logFile)
sys.exit() | [
"def",
"startJob",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"STARTING job with args %r\"",
"%",
"self",
".",
"args",
")",
"self",
".",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"self",
".",
"pid",
"==",
"0",
":",
"# Redirect the stdout output to dev null in the child.",
"logPath",
"=",
"self",
".",
"args",
"[",
"'resourcePrefix'",
"]",
"+",
"self",
".",
"args",
"[",
"'path'",
"]",
"+",
"self",
".",
"args",
"[",
"'filename'",
"]",
"+",
"'_log.txt'",
"logFile",
"=",
"open",
"(",
"logPath",
",",
"'wb'",
")",
"# A set of jobs. Currently [0 0] is flat ground, [1 0] is a block field, [0 1] is hilly terrain, and [1 1] is both",
"# This will expand in the future.",
"terrainMatrix",
"=",
"self",
".",
"args",
"[",
"'terrain'",
"]",
"# Update this if the subprocess call gets changed",
"if",
"len",
"(",
"terrainMatrix",
"[",
"0",
"]",
")",
"<",
"4",
":",
"raise",
"NTRTMasterError",
"(",
"\"Not enough terrain args!\"",
")",
"# Run through a set of binary job options. Currently handles terrain switches",
"for",
"run",
"in",
"terrainMatrix",
":",
"if",
"(",
"len",
"(",
"run",
")",
")",
">=",
"5",
":",
"trialLength",
"=",
"run",
"[",
"4",
"]",
"else",
":",
"trialLength",
"=",
"self",
".",
"args",
"[",
"'length'",
"]",
"#TODO improve error handling here",
"subprocess",
".",
"check_call",
"(",
"[",
"self",
".",
"args",
"[",
"'executable'",
"]",
",",
"\"-l\"",
",",
"self",
".",
"args",
"[",
"'filename'",
"]",
",",
"\"-P\"",
",",
"self",
".",
"args",
"[",
"'path'",
"]",
",",
"\"-s\"",
",",
"str",
"(",
"trialLength",
")",
",",
"\"-b\"",
",",
"str",
"(",
"run",
"[",
"0",
"]",
")",
",",
"\"-H\"",
",",
"str",
"(",
"run",
"[",
"1",
"]",
")",
",",
"\"-a\"",
",",
"str",
"(",
"run",
"[",
"2",
"]",
")",
",",
"\"-B\"",
",",
"str",
"(",
"run",
"[",
"3",
"]",
")",
"]",
",",
"stdout",
"=",
"logFile",
")",
"sys",
".",
"exit",
"(",
")"
] | https://github.com/NASA-Tensegrity-Robotics-Toolkit/NTRTsim/blob/0443cbd542e12e23c04adf79ea0d8d003c428baa/scripts/learning/src/evolution/evolution_job.py#L32-L61 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/xrc.py | python | XmlResource.LoadBitmap | (*args, **kwargs) | return _xrc.XmlResource_LoadBitmap(*args, **kwargs) | LoadBitmap(self, String name) -> Bitmap | LoadBitmap(self, String name) -> Bitmap | [
"LoadBitmap",
"(",
"self",
"String",
"name",
")",
"-",
">",
"Bitmap"
] | def LoadBitmap(*args, **kwargs):
"""LoadBitmap(self, String name) -> Bitmap"""
return _xrc.XmlResource_LoadBitmap(*args, **kwargs) | [
"def",
"LoadBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResource_LoadBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L175-L177 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/mooseutils/PerfGraphReporterReader.py | python | PerfGraphObject.selfMemory | (self) | return self._sumAllNodes(lambda node: node._memory) | Returns the memory added by only this (not including children) in Megabytes. | Returns the memory added by only this (not including children) in Megabytes. | [
"Returns",
"the",
"memory",
"added",
"by",
"only",
"this",
"(",
"not",
"including",
"children",
")",
"in",
"Megabytes",
"."
] | def selfMemory(self):
"""
Returns the memory added by only this (not including children) in Megabytes.
"""
return self._sumAllNodes(lambda node: node._memory) | [
"def",
"selfMemory",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sumAllNodes",
"(",
"lambda",
"node",
":",
"node",
".",
"_memory",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/PerfGraphReporterReader.py#L95-L99 | |
liulei01/DRBox | b5c76e033c555c9009590ab384e1f7bd3c66c237 | scripts/cpp_lint.py | python | Search | (pattern, s) | return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. | Searches the string for the pattern, caching the compiled regexp. | [
"Searches",
"the",
"string",
"for",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | [
"def",
"Search",
"(",
"pattern",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pattern",
"]",
".",
"search",
"(",
"s",
")"
] | https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L543-L547 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/scripts.py | python | ScriptMaker.make | (self, specification, options=None) | return filenames | Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to. | [] | def make(self, specification, options=None):
"""
Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to.
"""
filenames = []
entry = get_export_entry(specification)
if entry is None:
self._copy_script(specification, filenames)
else:
self._make_script(entry, filenames, options=options)
return filenames | [
"def",
"make",
"(",
"self",
",",
"specification",
",",
"options",
"=",
"None",
")",
":",
"filenames",
"=",
"[",
"]",
"entry",
"=",
"get_export_entry",
"(",
"specification",
")",
"if",
"entry",
"is",
"None",
":",
"self",
".",
"_copy_script",
"(",
"specification",
",",
"filenames",
")",
"else",
":",
"self",
".",
"_make_script",
"(",
"entry",
",",
"filenames",
",",
"options",
"=",
"options",
")",
"return",
"filenames"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/scripts.py#L781-L815 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/openvino/runtime/opset3/ops.py | python | rnn_cell | (
X: NodeInput,
initial_hidden_state: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str],
activations_alpha: List[float],
activations_beta: List[float],
clip: float = 0.0,
name: Optional[str] = None,
) | return _get_node_factory_opset3().create("RNNCell", input_nodes, attributes) | Perform RNNCell operation on tensor from input node.
It follows notation and equations defined as in ONNX standard:
https://github.com/onnx/onnx/blob/master/docs/Operators.md#RNN
Note this class represents only single *cell* and not whole RNN *layer*.
@param X: The input tensor with shape: [batch_size, input_size].
@param initial_hidden_state: The hidden state tensor at current time step with shape:
[batch_size, hidden_size].
@param W: The weight tensor with shape: [hidden_size, input_size].
@param R: The recurrence weight tensor with shape: [hidden_size,
hidden_size].
@param B: The sum of biases (weight and recurrence) with shape: [hidden_size].
@param hidden_size: The number of hidden units for recurrent cell.
Specifies hidden state size.
@param activations: The vector of activation functions used inside recurrent cell.
@param activation_alpha: The vector of alpha parameters for activation functions in
order respective to activation list.
@param activation_beta: The vector of beta parameters for activation functions in order
respective to activation list.
@param clip: The value defining clipping range [-clip, clip] on input of
activation functions.
@param name: Optional output node name.
@return The new node performing a RNNCell operation on tensor from input node. | Perform RNNCell operation on tensor from input node. | [
"Perform",
"RNNCell",
"operation",
"on",
"tensor",
"from",
"input",
"node",
"."
] | def rnn_cell(
X: NodeInput,
initial_hidden_state: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str],
activations_alpha: List[float],
activations_beta: List[float],
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
"""Perform RNNCell operation on tensor from input node.
It follows notation and equations defined as in ONNX standard:
https://github.com/onnx/onnx/blob/master/docs/Operators.md#RNN
Note this class represents only single *cell* and not whole RNN *layer*.
@param X: The input tensor with shape: [batch_size, input_size].
@param initial_hidden_state: The hidden state tensor at current time step with shape:
[batch_size, hidden_size].
@param W: The weight tensor with shape: [hidden_size, input_size].
@param R: The recurrence weight tensor with shape: [hidden_size,
hidden_size].
@param B: The sum of biases (weight and recurrence) with shape: [hidden_size].
@param hidden_size: The number of hidden units for recurrent cell.
Specifies hidden state size.
@param activations: The vector of activation functions used inside recurrent cell.
@param activation_alpha: The vector of alpha parameters for activation functions in
order respective to activation list.
@param activation_beta: The vector of beta parameters for activation functions in order
respective to activation list.
@param clip: The value defining clipping range [-clip, clip] on input of
activation functions.
@param name: Optional output node name.
@return The new node performing a RNNCell operation on tensor from input node.
"""
if activations is None:
activations = ["tanh"]
if activations_alpha is None:
activations_alpha = []
if activations_beta is None:
activations_beta = []
input_nodes = as_nodes(X, initial_hidden_state, W, R, B)
attributes = {
"hidden_size": hidden_size,
"activations": activations,
"activations_alpha": activations_alpha,
"activations_beta": activations_beta,
"clip": clip,
}
return _get_node_factory_opset3().create("RNNCell", input_nodes, attributes) | [
"def",
"rnn_cell",
"(",
"X",
":",
"NodeInput",
",",
"initial_hidden_state",
":",
"NodeInput",
",",
"W",
":",
"NodeInput",
",",
"R",
":",
"NodeInput",
",",
"B",
":",
"NodeInput",
",",
"hidden_size",
":",
"int",
",",
"activations",
":",
"List",
"[",
"str",
"]",
",",
"activations_alpha",
":",
"List",
"[",
"float",
"]",
",",
"activations_beta",
":",
"List",
"[",
"float",
"]",
",",
"clip",
":",
"float",
"=",
"0.0",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"if",
"activations",
"is",
"None",
":",
"activations",
"=",
"[",
"\"tanh\"",
"]",
"if",
"activations_alpha",
"is",
"None",
":",
"activations_alpha",
"=",
"[",
"]",
"if",
"activations_beta",
"is",
"None",
":",
"activations_beta",
"=",
"[",
"]",
"input_nodes",
"=",
"as_nodes",
"(",
"X",
",",
"initial_hidden_state",
",",
"W",
",",
"R",
",",
"B",
")",
"attributes",
"=",
"{",
"\"hidden_size\"",
":",
"hidden_size",
",",
"\"activations\"",
":",
"activations",
",",
"\"activations_alpha\"",
":",
"activations_alpha",
",",
"\"activations_beta\"",
":",
"activations_beta",
",",
"\"clip\"",
":",
"clip",
",",
"}",
"return",
"_get_node_factory_opset3",
"(",
")",
".",
"create",
"(",
"\"RNNCell\"",
",",
"input_nodes",
",",
"attributes",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset3/ops.py#L388-L442 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | CommandLineParser.parseoptions | (self, args) | return None | Parse command line options | Parse command line options | [
"Parse",
"command",
"line",
"options"
] | def parseoptions(self, args):
"Parse command line options"
if len(args) == 0:
return None
while len(args) > 0 and args[0].startswith('--'):
key, value = self.readoption(args)
if not key:
return 'Option ' + value + ' not recognized'
if not value:
return 'Option ' + key + ' needs a value'
setattr(self.options, key, value)
return None | [
"def",
"parseoptions",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"return",
"None",
"while",
"len",
"(",
"args",
")",
">",
"0",
"and",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"'--'",
")",
":",
"key",
",",
"value",
"=",
"self",
".",
"readoption",
"(",
"args",
")",
"if",
"not",
"key",
":",
"return",
"'Option '",
"+",
"value",
"+",
"' not recognized'",
"if",
"not",
"value",
":",
"return",
"'Option '",
"+",
"key",
"+",
"' needs a value'",
"setattr",
"(",
"self",
".",
"options",
",",
"key",
",",
"value",
")",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L999-L1010 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/fft/_pocketfft.py | python | rfft | (a, n=None, axis=-1, norm=None) | return output | Compute the one-dimensional discrete Fourier Transform for real input.
This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) of a real-valued array by means of an efficient algorithm
called the Fast Fourier Transform (FFT).
Parameters
----------
a : array_like
Input array
n : int, optional
Number of points along transformation axis in the input to use.
If `n` is smaller than the length of the input, the input is cropped.
If it is larger, the input is padded with zeros. If `n` is not given,
the length of the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the FFT. If not given, the last axis is
used.
norm : {None, "ortho"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is None.
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
If `n` is even, the length of the transformed axis is ``(n/2)+1``.
If `n` is odd, the length is ``(n+1)/2``.
Raises
------
IndexError
If `axis` is larger than the last axis of `a`.
See Also
--------
numpy.fft : For definition of the DFT and conventions used.
irfft : The inverse of `rfft`.
fft : The one-dimensional FFT of general (complex) input.
fftn : The *n*-dimensional FFT.
rfftn : The *n*-dimensional FFT of real input.
Notes
-----
When the DFT is computed for purely real input, the output is
Hermitian-symmetric, i.e. the negative frequency terms are just the complex
conjugates of the corresponding positive-frequency terms, and the
negative-frequency terms are therefore redundant. This function does not
compute the negative frequency terms, and the length of the transformed
axis of the output is therefore ``n//2 + 1``.
When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains
the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
If `n` is even, ``A[-1]`` contains the term representing both positive
and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
the largest positive frequency (fs/2*(n-1)/n), and is complex in the
general case.
If the input `a` contains an imaginary part, it is silently discarded.
Examples
--------
>>> np.fft.fft([0, 1, 0, 0])
array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
>>> np.fft.rfft([0, 1, 0, 0])
array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
Notice how the final element of the `fft` output is the complex conjugate
of the second element, for real input. For `rfft`, this symmetry is
exploited to compute only the non-negative frequency terms. | Compute the one-dimensional discrete Fourier Transform for real input. | [
"Compute",
"the",
"one",
"-",
"dimensional",
"discrete",
"Fourier",
"Transform",
"for",
"real",
"input",
"."
] | def rfft(a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional discrete Fourier Transform for real input.
This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) of a real-valued array by means of an efficient algorithm
called the Fast Fourier Transform (FFT).
Parameters
----------
a : array_like
Input array
n : int, optional
Number of points along transformation axis in the input to use.
If `n` is smaller than the length of the input, the input is cropped.
If it is larger, the input is padded with zeros. If `n` is not given,
the length of the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the FFT. If not given, the last axis is
used.
norm : {None, "ortho"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is None.
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
If `n` is even, the length of the transformed axis is ``(n/2)+1``.
If `n` is odd, the length is ``(n+1)/2``.
Raises
------
IndexError
If `axis` is larger than the last axis of `a`.
See Also
--------
numpy.fft : For definition of the DFT and conventions used.
irfft : The inverse of `rfft`.
fft : The one-dimensional FFT of general (complex) input.
fftn : The *n*-dimensional FFT.
rfftn : The *n*-dimensional FFT of real input.
Notes
-----
When the DFT is computed for purely real input, the output is
Hermitian-symmetric, i.e. the negative frequency terms are just the complex
conjugates of the corresponding positive-frequency terms, and the
negative-frequency terms are therefore redundant. This function does not
compute the negative frequency terms, and the length of the transformed
axis of the output is therefore ``n//2 + 1``.
When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains
the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
If `n` is even, ``A[-1]`` contains the term representing both positive
and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
the largest positive frequency (fs/2*(n-1)/n), and is complex in the
general case.
If the input `a` contains an imaginary part, it is silently discarded.
Examples
--------
>>> np.fft.fft([0, 1, 0, 0])
array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
>>> np.fft.rfft([0, 1, 0, 0])
array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
Notice how the final element of the `fft` output is the complex conjugate
of the second element, for real input. For `rfft`, this symmetry is
exploited to compute only the non-negative frequency terms.
"""
a = asarray(a)
inv_norm = 1
if norm is not None and _unitary(norm):
if n is None:
n = a.shape[axis]
inv_norm = sqrt(n)
output = _raw_fft(a, n, axis, True, True, inv_norm)
return output | [
"def",
"rfft",
"(",
"a",
",",
"n",
"=",
"None",
",",
"axis",
"=",
"-",
"1",
",",
"norm",
"=",
"None",
")",
":",
"a",
"=",
"asarray",
"(",
"a",
")",
"inv_norm",
"=",
"1",
"if",
"norm",
"is",
"not",
"None",
"and",
"_unitary",
"(",
"norm",
")",
":",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"a",
".",
"shape",
"[",
"axis",
"]",
"inv_norm",
"=",
"sqrt",
"(",
"n",
")",
"output",
"=",
"_raw_fft",
"(",
"a",
",",
"n",
",",
"axis",
",",
"True",
",",
"True",
",",
"inv_norm",
")",
"return",
"output"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/fft/_pocketfft.py#L290-L375 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/registry.py | python | CPUTarget.nested_context | (self, typing_context, target_context) | return self._nested.nested(typing_context, target_context) | A context manager temporarily replacing the contexts with the
given ones, for the current thread of execution. | A context manager temporarily replacing the contexts with the
given ones, for the current thread of execution. | [
"A",
"context",
"manager",
"temporarily",
"replacing",
"the",
"contexts",
"with",
"the",
"given",
"ones",
"for",
"the",
"current",
"thread",
"of",
"execution",
"."
] | def nested_context(self, typing_context, target_context):
"""
A context manager temporarily replacing the contexts with the
given ones, for the current thread of execution.
"""
return self._nested.nested(typing_context, target_context) | [
"def",
"nested_context",
"(",
"self",
",",
"typing_context",
",",
"target_context",
")",
":",
"return",
"self",
".",
"_nested",
".",
"nested",
"(",
"typing_context",
",",
"target_context",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/registry.py#L63-L68 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ColorbarPlugin.py | python | ColorbarPlugin.updateResultOptions | (self) | Update the ExodusResult options. | Update the ExodusResult options. | [
"Update",
"the",
"ExodusResult",
"options",
"."
] | def updateResultOptions(self):
"""
Update the ExodusResult options.
"""
if (self._variable is None):# or (self._result is None):
self.setEnabled(False)
return
else:
self.setEnabled(True)
# ExodusResult options
result_options = dict()
# Min./Max. range
result_options['min'] = self._setLimitHelper(self.RangeMinimumMode, self.RangeMinimum)
result_options['max'] = self._setLimitHelper(self.RangeMaximumMode, self.RangeMaximum)
# Colormap
result_options['cmap'] = str(self.ColorMapList.currentText())
result_options['cmap_reverse'] = self.ColorMapReverse.isChecked()
result_options['local_range'] = self.ColorBarRangeType.isChecked()
# Components
result_options['component'] = self._component
# Colorbar options
self.resultOptionsChanged.emit(result_options) | [
"def",
"updateResultOptions",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_variable",
"is",
"None",
")",
":",
"# or (self._result is None):",
"self",
".",
"setEnabled",
"(",
"False",
")",
"return",
"else",
":",
"self",
".",
"setEnabled",
"(",
"True",
")",
"# ExodusResult options",
"result_options",
"=",
"dict",
"(",
")",
"# Min./Max. range",
"result_options",
"[",
"'min'",
"]",
"=",
"self",
".",
"_setLimitHelper",
"(",
"self",
".",
"RangeMinimumMode",
",",
"self",
".",
"RangeMinimum",
")",
"result_options",
"[",
"'max'",
"]",
"=",
"self",
".",
"_setLimitHelper",
"(",
"self",
".",
"RangeMaximumMode",
",",
"self",
".",
"RangeMaximum",
")",
"# Colormap",
"result_options",
"[",
"'cmap'",
"]",
"=",
"str",
"(",
"self",
".",
"ColorMapList",
".",
"currentText",
"(",
")",
")",
"result_options",
"[",
"'cmap_reverse'",
"]",
"=",
"self",
".",
"ColorMapReverse",
".",
"isChecked",
"(",
")",
"result_options",
"[",
"'local_range'",
"]",
"=",
"self",
".",
"ColorBarRangeType",
".",
"isChecked",
"(",
")",
"# Components",
"result_options",
"[",
"'component'",
"]",
"=",
"self",
".",
"_component",
"# Colorbar options",
"self",
".",
"resultOptionsChanged",
".",
"emit",
"(",
"result_options",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ColorbarPlugin.py#L178-L204 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Variables/PathVariable.py | python | _PathVariableClass.PathIsFile | (self, key, val, env) | Validator to check if Path is a file | Validator to check if Path is a file | [
"Validator",
"to",
"check",
"if",
"Path",
"is",
"a",
"file"
] | def PathIsFile(self, key, val, env):
"""Validator to check if Path is a file"""
if not os.path.isfile(val):
if os.path.isdir(val):
m = 'File path for option %s is a directory: %s'
else:
m = 'File path for option %s does not exist: %s'
raise SCons.Errors.UserError(m % (key, val)) | [
"def",
"PathIsFile",
"(",
"self",
",",
"key",
",",
"val",
",",
"env",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"val",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"val",
")",
":",
"m",
"=",
"'File path for option %s is a directory: %s'",
"else",
":",
"m",
"=",
"'File path for option %s does not exist: %s'",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"m",
"%",
"(",
"key",
",",
"val",
")",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Variables/PathVariable.py#L103-L110 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py | python | IncrementalParser.prepareParser | (self, source) | This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing. | This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing. | [
"This",
"method",
"is",
"called",
"by",
"the",
"parse",
"implementation",
"to",
"allow",
"the",
"SAX",
"2",
".",
"0",
"driver",
"to",
"prepare",
"itself",
"for",
"parsing",
"."
] | def prepareParser(self, source):
"""This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing."""
raise NotImplementedError("prepareParser must be overridden!") | [
"def",
"prepareParser",
"(",
"self",
",",
"source",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"prepareParser must be overridden!\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py#L138-L141 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | bindings/python/oidres.py | python | pack | (next_avail) | return '%s%s' % (OIDRES_HEADER, next_avail) | Serialize next_avail into a RAMCloud object. | Serialize next_avail into a RAMCloud object. | [
"Serialize",
"next_avail",
"into",
"a",
"RAMCloud",
"object",
"."
] | def pack(next_avail):
"""Serialize next_avail into a RAMCloud object."""
next_avail = ctypes.c_uint64(next_avail)
sb = ctypes.create_string_buffer(8)
ctypes.memmove(ctypes.addressof(sb), ctypes.addressof(next_avail), 8)
next_avail = sb.raw
return '%s%s' % (OIDRES_HEADER, next_avail) | [
"def",
"pack",
"(",
"next_avail",
")",
":",
"next_avail",
"=",
"ctypes",
".",
"c_uint64",
"(",
"next_avail",
")",
"sb",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"8",
")",
"ctypes",
".",
"memmove",
"(",
"ctypes",
".",
"addressof",
"(",
"sb",
")",
",",
"ctypes",
".",
"addressof",
"(",
"next_avail",
")",
",",
"8",
")",
"next_avail",
"=",
"sb",
".",
"raw",
"return",
"'%s%s'",
"%",
"(",
"OIDRES_HEADER",
",",
"next_avail",
")"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/bindings/python/oidres.py#L37-L45 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/req.py | python | RequirementSet.cleanup_files | (self, bundle=False) | Clean up files, remove builds. | Clean up files, remove builds. | [
"Clean",
"up",
"files",
"remove",
"builds",
"."
] | def cleanup_files(self, bundle=False):
"""Clean up files, remove builds."""
logger.notify('Cleaning up...')
logger.indent += 2
for req in self.reqs_to_cleanup:
req.remove_temporary_source()
remove_dir = []
if self._pip_has_created_build_dir():
remove_dir.append(self.build_dir)
# The source dir of a bundle can always be removed.
# FIXME: not if it pre-existed the bundle!
if bundle:
remove_dir.append(self.src_dir)
for dir in remove_dir:
if os.path.exists(dir):
logger.info('Removing temporary dir %s...' % dir)
rmtree(dir)
logger.indent -= 2 | [
"def",
"cleanup_files",
"(",
"self",
",",
"bundle",
"=",
"False",
")",
":",
"logger",
".",
"notify",
"(",
"'Cleaning up...'",
")",
"logger",
".",
"indent",
"+=",
"2",
"for",
"req",
"in",
"self",
".",
"reqs_to_cleanup",
":",
"req",
".",
"remove_temporary_source",
"(",
")",
"remove_dir",
"=",
"[",
"]",
"if",
"self",
".",
"_pip_has_created_build_dir",
"(",
")",
":",
"remove_dir",
".",
"append",
"(",
"self",
".",
"build_dir",
")",
"# The source dir of a bundle can always be removed.",
"# FIXME: not if it pre-existed the bundle!",
"if",
"bundle",
":",
"remove_dir",
".",
"append",
"(",
"self",
".",
"src_dir",
")",
"for",
"dir",
"in",
"remove_dir",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
")",
":",
"logger",
".",
"info",
"(",
"'Removing temporary dir %s...'",
"%",
"dir",
")",
"rmtree",
"(",
"dir",
")",
"logger",
".",
"indent",
"-=",
"2"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/req.py#L1190-L1211 | ||
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/unicycler.py | python | print_intro_message | (args, full_command, out_dir_message) | Prints a message at the start of the program's execution. | Prints a message at the start of the program's execution. | [
"Prints",
"a",
"message",
"at",
"the",
"start",
"of",
"the",
"program",
"s",
"execution",
"."
] | def print_intro_message(args, full_command, out_dir_message):
"""
Prints a message at the start of the program's execution.
"""
log.log_section_header('Starting Unicycler', single_newline=True)
short_reads_available = bool(args.short1)
long_reads_available = bool(args.long)
intro_message = 'Welcome to Unicycler, an assembly pipeline for bacterial genomes. '
if short_reads_available and long_reads_available:
intro_message += ('Since you provided both short and long reads, Unicycler will perform a '
'hybrid assembly. It will first use SPAdes to make a short-read '
'assembly graph, and then it will use various methods to scaffold '
'that graph with the long reads.')
elif short_reads_available:
intro_message += ('Since you provided only short reads, Unicycler will essentially '
'function as a SPAdes-optimiser. It will try many k-mer sizes, choose '
'the best based on contig length and graph connectivity, and scaffold '
'the graph using SPAdes repeat resolution.')
elif long_reads_available:
intro_message += ('Since you provided only long reads, Unicycler will assemble the reads '
'with miniasm and then run repeated polishing rounds using Racon.')
log.log_explanation(intro_message, extra_empty_lines_after=0)
log.log_explanation('For more information, please see https://github.com/rrwick/Unicycler')
log.log('Command: ' + bold(full_command))
log.log('')
log.log('Unicycler version: v' + __version__)
log.log('Using ' + str(args.threads) + ' thread' + ('' if args.threads == 1 else 's'))
log.log('')
if args.threads > 2 * multiprocessing.cpu_count():
log.log(red('Warning: you have specified a lot more threads than this machine seems to '
'have! Was this intentional?'))
log.log('')
log.log(out_dir_message)
if short_reads_available:
log.log('', 2)
if args.mode == 0:
log.log('Bridging mode: conservative', 2)
if args.min_bridge_qual == settings.CONSERVATIVE_MIN_BRIDGE_QUAL:
log.log(' using default conservative bridge quality cutoff: ', 2, end='')
else:
log.log(' using user-specified bridge quality cutoff: ', 2, end='')
elif args.mode == 1:
log.log('Bridging mode: normal', 2)
if args.min_bridge_qual == settings.NORMAL_MIN_BRIDGE_QUAL:
log.log(' using default normal bridge quality cutoff: ', 2, end='')
else:
log.log(' using user-specified bridge quality cutoff: ', 2, end='')
else: # args.mode == 2
log.log('Bridging mode: bold', 2)
if args.min_bridge_qual == settings.BOLD_MIN_BRIDGE_QUAL:
log.log(' using default bold bridge quality cutoff: ', 2, end='')
else:
log.log(' using user-specified bridge quality cutoff: ', 2, end='')
log.log(float_to_str(args.min_bridge_qual, 2), 2) | [
"def",
"print_intro_message",
"(",
"args",
",",
"full_command",
",",
"out_dir_message",
")",
":",
"log",
".",
"log_section_header",
"(",
"'Starting Unicycler'",
",",
"single_newline",
"=",
"True",
")",
"short_reads_available",
"=",
"bool",
"(",
"args",
".",
"short1",
")",
"long_reads_available",
"=",
"bool",
"(",
"args",
".",
"long",
")",
"intro_message",
"=",
"'Welcome to Unicycler, an assembly pipeline for bacterial genomes. '",
"if",
"short_reads_available",
"and",
"long_reads_available",
":",
"intro_message",
"+=",
"(",
"'Since you provided both short and long reads, Unicycler will perform a '",
"'hybrid assembly. It will first use SPAdes to make a short-read '",
"'assembly graph, and then it will use various methods to scaffold '",
"'that graph with the long reads.'",
")",
"elif",
"short_reads_available",
":",
"intro_message",
"+=",
"(",
"'Since you provided only short reads, Unicycler will essentially '",
"'function as a SPAdes-optimiser. It will try many k-mer sizes, choose '",
"'the best based on contig length and graph connectivity, and scaffold '",
"'the graph using SPAdes repeat resolution.'",
")",
"elif",
"long_reads_available",
":",
"intro_message",
"+=",
"(",
"'Since you provided only long reads, Unicycler will assemble the reads '",
"'with miniasm and then run repeated polishing rounds using Racon.'",
")",
"log",
".",
"log_explanation",
"(",
"intro_message",
",",
"extra_empty_lines_after",
"=",
"0",
")",
"log",
".",
"log_explanation",
"(",
"'For more information, please see https://github.com/rrwick/Unicycler'",
")",
"log",
".",
"log",
"(",
"'Command: '",
"+",
"bold",
"(",
"full_command",
")",
")",
"log",
".",
"log",
"(",
"''",
")",
"log",
".",
"log",
"(",
"'Unicycler version: v'",
"+",
"__version__",
")",
"log",
".",
"log",
"(",
"'Using '",
"+",
"str",
"(",
"args",
".",
"threads",
")",
"+",
"' thread'",
"+",
"(",
"''",
"if",
"args",
".",
"threads",
"==",
"1",
"else",
"'s'",
")",
")",
"log",
".",
"log",
"(",
"''",
")",
"if",
"args",
".",
"threads",
">",
"2",
"*",
"multiprocessing",
".",
"cpu_count",
"(",
")",
":",
"log",
".",
"log",
"(",
"red",
"(",
"'Warning: you have specified a lot more threads than this machine seems to '",
"'have! Was this intentional?'",
")",
")",
"log",
".",
"log",
"(",
"''",
")",
"log",
".",
"log",
"(",
"out_dir_message",
")",
"if",
"short_reads_available",
":",
"log",
".",
"log",
"(",
"''",
",",
"2",
")",
"if",
"args",
".",
"mode",
"==",
"0",
":",
"log",
".",
"log",
"(",
"'Bridging mode: conservative'",
",",
"2",
")",
"if",
"args",
".",
"min_bridge_qual",
"==",
"settings",
".",
"CONSERVATIVE_MIN_BRIDGE_QUAL",
":",
"log",
".",
"log",
"(",
"' using default conservative bridge quality cutoff: '",
",",
"2",
",",
"end",
"=",
"''",
")",
"else",
":",
"log",
".",
"log",
"(",
"' using user-specified bridge quality cutoff: '",
",",
"2",
",",
"end",
"=",
"''",
")",
"elif",
"args",
".",
"mode",
"==",
"1",
":",
"log",
".",
"log",
"(",
"'Bridging mode: normal'",
",",
"2",
")",
"if",
"args",
".",
"min_bridge_qual",
"==",
"settings",
".",
"NORMAL_MIN_BRIDGE_QUAL",
":",
"log",
".",
"log",
"(",
"' using default normal bridge quality cutoff: '",
",",
"2",
",",
"end",
"=",
"''",
")",
"else",
":",
"log",
".",
"log",
"(",
"' using user-specified bridge quality cutoff: '",
",",
"2",
",",
"end",
"=",
"''",
")",
"else",
":",
"# args.mode == 2",
"log",
".",
"log",
"(",
"'Bridging mode: bold'",
",",
"2",
")",
"if",
"args",
".",
"min_bridge_qual",
"==",
"settings",
".",
"BOLD_MIN_BRIDGE_QUAL",
":",
"log",
".",
"log",
"(",
"' using default bold bridge quality cutoff: '",
",",
"2",
",",
"end",
"=",
"''",
")",
"else",
":",
"log",
".",
"log",
"(",
"' using user-specified bridge quality cutoff: '",
",",
"2",
",",
"end",
"=",
"''",
")",
"log",
".",
"log",
"(",
"float_to_str",
"(",
"args",
".",
"min_bridge_qual",
",",
"2",
")",
",",
"2",
")"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/unicycler.py#L599-L656 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | HtmlEasyPrinting.SetName | (*args, **kwargs) | return _html.HtmlEasyPrinting_SetName(*args, **kwargs) | SetName(self, String name) | SetName(self, String name) | [
"SetName",
"(",
"self",
"String",
"name",
")"
] | def SetName(*args, **kwargs):
"""SetName(self, String name)"""
return _html.HtmlEasyPrinting_SetName(*args, **kwargs) | [
"def",
"SetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlEasyPrinting_SetName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1392-L1394 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiManager.CreateFloatingFrame | (*args, **kwargs) | return _aui.AuiManager_CreateFloatingFrame(*args, **kwargs) | CreateFloatingFrame(self, Window parent, AuiPaneInfo p) -> AuiFloatingFrame | CreateFloatingFrame(self, Window parent, AuiPaneInfo p) -> AuiFloatingFrame | [
"CreateFloatingFrame",
"(",
"self",
"Window",
"parent",
"AuiPaneInfo",
"p",
")",
"-",
">",
"AuiFloatingFrame"
] | def CreateFloatingFrame(*args, **kwargs):
"""CreateFloatingFrame(self, Window parent, AuiPaneInfo p) -> AuiFloatingFrame"""
return _aui.AuiManager_CreateFloatingFrame(*args, **kwargs) | [
"def",
"CreateFloatingFrame",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiManager_CreateFloatingFrame",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L703-L705 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | TreeListCtrl.GetSelection | (*args, **kwargs) | return _gizmos.TreeListCtrl_GetSelection(*args, **kwargs) | GetSelection(self) -> TreeItemId | GetSelection(self) -> TreeItemId | [
"GetSelection",
"(",
"self",
")",
"-",
">",
"TreeItemId"
] | def GetSelection(*args, **kwargs):
"""GetSelection(self) -> TreeItemId"""
return _gizmos.TreeListCtrl_GetSelection(*args, **kwargs) | [
"def",
"GetSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_GetSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L750-L752 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateSpan.GetYears | (*args, **kwargs) | return _misc_.DateSpan_GetYears(*args, **kwargs) | GetYears(self) -> int | GetYears(self) -> int | [
"GetYears",
"(",
"self",
")",
"-",
">",
"int"
] | def GetYears(*args, **kwargs):
"""GetYears(self) -> int"""
return _misc_.DateSpan_GetYears(*args, **kwargs) | [
"def",
"GetYears",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_GetYears",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4669-L4671 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Tools/pybench/CommandLine.py | python | fileopen | (name, mode='wb', encoding=None) | Open a file using mode.
Default mode is 'wb' meaning to open the file for writing in
binary mode. If encoding is given, I/O to and from the file is
transparently encoded using the given encoding.
Files opened for writing are chmod()ed to 0600. | Open a file using mode. | [
"Open",
"a",
"file",
"using",
"mode",
"."
] | def fileopen(name, mode='wb', encoding=None):
""" Open a file using mode.
Default mode is 'wb' meaning to open the file for writing in
binary mode. If encoding is given, I/O to and from the file is
transparently encoded using the given encoding.
Files opened for writing are chmod()ed to 0600.
"""
if name == 'stdout':
return sys.stdout
elif name == 'stderr':
return sys.stderr
elif name == 'stdin':
return sys.stdin
else:
if encoding is not None:
import codecs
f = codecs.open(name, mode, encoding)
else:
f = open(name, mode)
if 'w' in mode:
os.chmod(name, 0600)
return f | [
"def",
"fileopen",
"(",
"name",
",",
"mode",
"=",
"'wb'",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"name",
"==",
"'stdout'",
":",
"return",
"sys",
".",
"stdout",
"elif",
"name",
"==",
"'stderr'",
":",
"return",
"sys",
".",
"stderr",
"elif",
"name",
"==",
"'stdin'",
":",
"return",
"sys",
".",
"stdin",
"else",
":",
"if",
"encoding",
"is",
"not",
"None",
":",
"import",
"codecs",
"f",
"=",
"codecs",
".",
"open",
"(",
"name",
",",
"mode",
",",
"encoding",
")",
"else",
":",
"f",
"=",
"open",
"(",
"name",
",",
"mode",
")",
"if",
"'w'",
"in",
"mode",
":",
"os",
".",
"chmod",
"(",
"name",
",",
"0600",
")",
"return",
"f"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/pybench/CommandLine.py#L61-L86 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStr.IsHexInt64 | (self, *args) | return _snap.TStr_IsHexInt64(self, *args) | IsHexInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: int64 const &
MxVal: int64 const &
Val: int64 &
IsHexInt64(TStr self, int64 & Val) -> bool
Parameters:
Val: int64 &
IsHexInt64(TStr self) -> bool
Parameters:
self: TStr const * | IsHexInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool | [
"IsHexInt64",
"(",
"TStr",
"self",
"bool",
"const",
"&",
"Check",
"int64",
"const",
"&",
"MnVal",
"int64",
"const",
"&",
"MxVal",
"int64",
"&",
"Val",
")",
"-",
">",
"bool"
] | def IsHexInt64(self, *args):
"""
IsHexInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: int64 const &
MxVal: int64 const &
Val: int64 &
IsHexInt64(TStr self, int64 & Val) -> bool
Parameters:
Val: int64 &
IsHexInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsHexInt64(self, *args) | [
"def",
"IsHexInt64",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStr_IsHexInt64",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L10528-L10549 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | clang/docs/tools/dump_ast_matchers.py | python | sort_table | (matcher_type, matcher_map) | return ('<!-- START_%(type)s_MATCHERS -->\n' +
'%(table)s' +
'<!--END_%(type)s_MATCHERS -->') % {
'type': matcher_type,
'table': table,
} | Returns the sorted html table for the given row map. | Returns the sorted html table for the given row map. | [
"Returns",
"the",
"sorted",
"html",
"table",
"for",
"the",
"given",
"row",
"map",
"."
] | def sort_table(matcher_type, matcher_map):
"""Returns the sorted html table for the given row map."""
table = ''
for key in sorted(matcher_map.keys()):
table += matcher_map[key] + '\n'
return ('<!-- START_%(type)s_MATCHERS -->\n' +
'%(table)s' +
'<!--END_%(type)s_MATCHERS -->') % {
'type': matcher_type,
'table': table,
} | [
"def",
"sort_table",
"(",
"matcher_type",
",",
"matcher_map",
")",
":",
"table",
"=",
"''",
"for",
"key",
"in",
"sorted",
"(",
"matcher_map",
".",
"keys",
"(",
")",
")",
":",
"table",
"+=",
"matcher_map",
"[",
"key",
"]",
"+",
"'\\n'",
"return",
"(",
"'<!-- START_%(type)s_MATCHERS -->\\n'",
"+",
"'%(table)s'",
"+",
"'<!--END_%(type)s_MATCHERS -->'",
")",
"%",
"{",
"'type'",
":",
"matcher_type",
",",
"'table'",
":",
"table",
",",
"}"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/docs/tools/dump_ast_matchers.py#L441-L451 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/config.py | python | ConfigHandler._deprecated_config_handler | (self, func, msg, warning_class) | return config_handler | this function will wrap around parameters that are deprecated
:param msg: deprecation message
:param warning_class: class of warning exception to be raised
:param func: function to be wrapped around | this function will wrap around parameters that are deprecated | [
"this",
"function",
"will",
"wrap",
"around",
"parameters",
"that",
"are",
"deprecated"
] | def _deprecated_config_handler(self, func, msg, warning_class):
"""this function will wrap around parameters that are deprecated
:param msg: deprecation message
:param warning_class: class of warning exception to be raised
:param func: function to be wrapped around
"""
@wraps(func)
def config_handler(*args, **kwargs):
warnings.warn(msg, warning_class)
return func(*args, **kwargs)
return config_handler | [
"def",
"_deprecated_config_handler",
"(",
"self",
",",
"func",
",",
"msg",
",",
"warning_class",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"config_handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"msg",
",",
"warning_class",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"config_handler"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/config.py#L500-L513 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/multiprocessing/spawn.py | python | get_preparation_data | (name) | return d | Return info about parent needed by child to unpickle process object | Return info about parent needed by child to unpickle process object | [
"Return",
"info",
"about",
"parent",
"needed",
"by",
"child",
"to",
"unpickle",
"process",
"object"
] | def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object
'''
_check_not_importing_main()
d = dict(
log_to_stderr=util._log_to_stderr,
authkey=process.current_process().authkey,
)
if util._logger is not None:
d['log_level'] = util._logger.getEffectiveLevel()
sys_path=sys.path.copy()
try:
i = sys_path.index('')
except ValueError:
pass
else:
sys_path[i] = process.ORIGINAL_DIR
d.update(
name=name,
sys_path=sys_path,
sys_argv=sys.argv,
orig_dir=process.ORIGINAL_DIR,
dir=os.getcwd(),
start_method=get_start_method(),
)
# Figure out whether to initialise main in the subprocess as a module
# or through direct execution (or to leave it alone entirely)
main_module = sys.modules['__main__']
main_mod_name = getattr(main_module.__spec__, "name", None)
if main_mod_name is not None:
d['init_main_from_name'] = main_mod_name
elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
main_path = getattr(main_module, '__file__', None)
if main_path is not None:
if (not os.path.isabs(main_path) and
process.ORIGINAL_DIR is not None):
main_path = os.path.join(process.ORIGINAL_DIR, main_path)
d['init_main_from_path'] = os.path.normpath(main_path)
return d | [
"def",
"get_preparation_data",
"(",
"name",
")",
":",
"_check_not_importing_main",
"(",
")",
"d",
"=",
"dict",
"(",
"log_to_stderr",
"=",
"util",
".",
"_log_to_stderr",
",",
"authkey",
"=",
"process",
".",
"current_process",
"(",
")",
".",
"authkey",
",",
")",
"if",
"util",
".",
"_logger",
"is",
"not",
"None",
":",
"d",
"[",
"'log_level'",
"]",
"=",
"util",
".",
"_logger",
".",
"getEffectiveLevel",
"(",
")",
"sys_path",
"=",
"sys",
".",
"path",
".",
"copy",
"(",
")",
"try",
":",
"i",
"=",
"sys_path",
".",
"index",
"(",
"''",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"sys_path",
"[",
"i",
"]",
"=",
"process",
".",
"ORIGINAL_DIR",
"d",
".",
"update",
"(",
"name",
"=",
"name",
",",
"sys_path",
"=",
"sys_path",
",",
"sys_argv",
"=",
"sys",
".",
"argv",
",",
"orig_dir",
"=",
"process",
".",
"ORIGINAL_DIR",
",",
"dir",
"=",
"os",
".",
"getcwd",
"(",
")",
",",
"start_method",
"=",
"get_start_method",
"(",
")",
",",
")",
"# Figure out whether to initialise main in the subprocess as a module",
"# or through direct execution (or to leave it alone entirely)",
"main_module",
"=",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"main_mod_name",
"=",
"getattr",
"(",
"main_module",
".",
"__spec__",
",",
"\"name\"",
",",
"None",
")",
"if",
"main_mod_name",
"is",
"not",
"None",
":",
"d",
"[",
"'init_main_from_name'",
"]",
"=",
"main_mod_name",
"elif",
"sys",
".",
"platform",
"!=",
"'win32'",
"or",
"(",
"not",
"WINEXE",
"and",
"not",
"WINSERVICE",
")",
":",
"main_path",
"=",
"getattr",
"(",
"main_module",
",",
"'__file__'",
",",
"None",
")",
"if",
"main_path",
"is",
"not",
"None",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"main_path",
")",
"and",
"process",
".",
"ORIGINAL_DIR",
"is",
"not",
"None",
")",
":",
"main_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"process",
".",
"ORIGINAL_DIR",
",",
"main_path",
")",
"d",
"[",
"'init_main_from_path'",
"]",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"main_path",
")",
"return",
"d"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/spawn.py#L150-L194 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/lib/io/file_io.py | python | rename | (oldname, newname, overwrite=False) | Rename or move a file / directory.
Args:
oldname: string, pathname for a file
newname: string, pathname to which the file needs to be moved
overwrite: boolean, if false its an error for newpath to be occupied by an
existing file.
Raises:
errors.OpError: If the operation fails. | Rename or move a file / directory. | [
"Rename",
"or",
"move",
"a",
"file",
"/",
"directory",
"."
] | def rename(oldname, newname, overwrite=False):
"""Rename or move a file / directory.
Args:
oldname: string, pathname for a file
newname: string, pathname to which the file needs to be moved
overwrite: boolean, if false its an error for newpath to be occupied by an
existing file.
Raises:
errors.OpError: If the operation fails.
"""
with errors.raise_exception_on_not_ok_status() as status:
pywrap_tensorflow.RenameFile(
compat.as_bytes(oldname), compat.as_bytes(newname), overwrite, status) | [
"def",
"rename",
"(",
"oldname",
",",
"newname",
",",
"overwrite",
"=",
"False",
")",
":",
"with",
"errors",
".",
"raise_exception_on_not_ok_status",
"(",
")",
"as",
"status",
":",
"pywrap_tensorflow",
".",
"RenameFile",
"(",
"compat",
".",
"as_bytes",
"(",
"oldname",
")",
",",
"compat",
".",
"as_bytes",
"(",
"newname",
")",
",",
"overwrite",
",",
"status",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/lib/io/file_io.py#L387-L401 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/mox.py | python | MockMethod.WithSideEffects | (self, side_effects) | return self | Set the side effects that are simulated when this method is called.
Args:
side_effects: A callable which modifies the parameters or other relevant
state which a given test case depends on.
Returns:
Self for chaining with AndReturn and AndRaise. | Set the side effects that are simulated when this method is called. | [
"Set",
"the",
"side",
"effects",
"that",
"are",
"simulated",
"when",
"this",
"method",
"is",
"called",
"."
] | def WithSideEffects(self, side_effects):
"""Set the side effects that are simulated when this method is called.
Args:
side_effects: A callable which modifies the parameters or other relevant
state which a given test case depends on.
Returns:
Self for chaining with AndReturn and AndRaise.
"""
self._side_effects = side_effects
return self | [
"def",
"WithSideEffects",
"(",
"self",
",",
"side_effects",
")",
":",
"self",
".",
"_side_effects",
"=",
"side_effects",
"return",
"self"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/mox.py#L738-L749 | |
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/ctml2yaml.py | python | Reaction.to_yaml | (cls, representer, data) | return representer.represent_dict(data.attribs) | Serialize the class instance to YAML format suitable for ruamel.yaml.
:param representer:
An instance of a ruamel.yaml representer type.
:param data:
An instance of this class that will be serialized.
The class instance should have an instance attribute called ``attribs`` which
is a dictionary representing the information about the instance. The dictionary
is serialized using the ``represent_dict`` method of the ``representer``. | Serialize the class instance to YAML format suitable for ruamel.yaml. | [
"Serialize",
"the",
"class",
"instance",
"to",
"YAML",
"format",
"suitable",
"for",
"ruamel",
".",
"yaml",
"."
] | def to_yaml(cls, representer, data):
"""Serialize the class instance to YAML format suitable for ruamel.yaml.
:param representer:
An instance of a ruamel.yaml representer type.
:param data:
An instance of this class that will be serialized.
The class instance should have an instance attribute called ``attribs`` which
is a dictionary representing the information about the instance. The dictionary
is serialized using the ``represent_dict`` method of the ``representer``.
"""
return representer.represent_dict(data.attribs) | [
"def",
"to_yaml",
"(",
"cls",
",",
"representer",
",",
"data",
")",
":",
"return",
"representer",
".",
"represent_dict",
"(",
"data",
".",
"attribs",
")"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml2yaml.py#L2128-L2140 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/segmentbk.py | python | SegmentBook.InsertPage | (self, index, page, text, select=False, image_id=-1) | Insert a page a the given index
@param index: index to insert page at
@param page: page to add to book
@param text: page text
@keyword select: bool
@keyword image_id: image list index | Insert a page a the given index
@param index: index to insert page at
@param page: page to add to book
@param text: page text
@keyword select: bool
@keyword image_id: image list index | [
"Insert",
"a",
"page",
"a",
"the",
"given",
"index",
"@param",
"index",
":",
"index",
"to",
"insert",
"page",
"at",
"@param",
"page",
":",
"page",
"to",
"add",
"to",
"book",
"@param",
"text",
":",
"page",
"text",
"@keyword",
"select",
":",
"bool",
"@keyword",
"image_id",
":",
"image",
"list",
"index"
] | def InsertPage(self, index, page, text, select=False, image_id=-1):
"""Insert a page a the given index
@param index: index to insert page at
@param page: page to add to book
@param text: page text
@keyword select: bool
@keyword image_id: image list index
"""
raise NotImplementedError | [
"def",
"InsertPage",
"(",
"self",
",",
"index",
",",
"page",
",",
"text",
",",
"select",
"=",
"False",
",",
"image_id",
"=",
"-",
"1",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/segmentbk.py#L372-L381 | ||
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/python/flatbuffers/flexbuffers.py | python | Ref.MutateBool | (self, value) | return self.IsBool and \
_Mutate(U, self._buf, value, self._parent_width, BitWidth.W8) | Mutates underlying boolean value bytes in place.
Args:
value: New boolean value.
Returns:
Whether the value was mutated or not. | Mutates underlying boolean value bytes in place. | [
"Mutates",
"underlying",
"boolean",
"value",
"bytes",
"in",
"place",
"."
] | def MutateBool(self, value):
"""Mutates underlying boolean value bytes in place.
Args:
value: New boolean value.
Returns:
Whether the value was mutated or not.
"""
return self.IsBool and \
_Mutate(U, self._buf, value, self._parent_width, BitWidth.W8) | [
"def",
"MutateBool",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"IsBool",
"and",
"_Mutate",
"(",
"U",
",",
"self",
".",
"_buf",
",",
"value",
",",
"self",
".",
"_parent_width",
",",
"BitWidth",
".",
"W8",
")"
] | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/flexbuffers.py#L587-L597 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py | python | TimeDeltaBlock.to_native_types | (self, slicer=None, na_rep=None, quoting=None, **kwargs) | return rvalues | convert to our native types format, slicing if desired | convert to our native types format, slicing if desired | [
"convert",
"to",
"our",
"native",
"types",
"format",
"slicing",
"if",
"desired"
] | def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
values = self.values
if slicer is not None:
values = values[:, slicer]
mask = isna(values)
rvalues = np.empty(values.shape, dtype=object)
if na_rep is None:
na_rep = "NaT"
rvalues[mask] = na_rep
imask = (~mask).ravel()
# FIXME:
# should use the formats.format.Timedelta64Formatter here
# to figure what format to pass to the Timedelta
# e.g. to not show the decimals say
rvalues.flat[imask] = np.array(
[Timedelta(val)._repr_base(format="all") for val in values.ravel()[imask]],
dtype=object,
)
return rvalues | [
"def",
"to_native_types",
"(",
"self",
",",
"slicer",
"=",
"None",
",",
"na_rep",
"=",
"None",
",",
"quoting",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"self",
".",
"values",
"if",
"slicer",
"is",
"not",
"None",
":",
"values",
"=",
"values",
"[",
":",
",",
"slicer",
"]",
"mask",
"=",
"isna",
"(",
"values",
")",
"rvalues",
"=",
"np",
".",
"empty",
"(",
"values",
".",
"shape",
",",
"dtype",
"=",
"object",
")",
"if",
"na_rep",
"is",
"None",
":",
"na_rep",
"=",
"\"NaT\"",
"rvalues",
"[",
"mask",
"]",
"=",
"na_rep",
"imask",
"=",
"(",
"~",
"mask",
")",
".",
"ravel",
"(",
")",
"# FIXME:",
"# should use the formats.format.Timedelta64Formatter here",
"# to figure what format to pass to the Timedelta",
"# e.g. to not show the decimals say",
"rvalues",
".",
"flat",
"[",
"imask",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"Timedelta",
"(",
"val",
")",
".",
"_repr_base",
"(",
"format",
"=",
"\"all\"",
")",
"for",
"val",
"in",
"values",
".",
"ravel",
"(",
")",
"[",
"imask",
"]",
"]",
",",
"dtype",
"=",
"object",
",",
")",
"return",
"rvalues"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L2522-L2544 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/variables.py | python | Variable.set_shape | (self, shape) | Overrides the shape for this variable.
Args:
shape: the `TensorShape` representing the overridden shape. | Overrides the shape for this variable. | [
"Overrides",
"the",
"shape",
"for",
"this",
"variable",
"."
] | def set_shape(self, shape):
"""Overrides the shape for this variable.
Args:
shape: the `TensorShape` representing the overridden shape.
"""
self._ref().set_shape(shape)
self.value().set_shape(shape) | [
"def",
"set_shape",
"(",
"self",
",",
"shape",
")",
":",
"self",
".",
"_ref",
"(",
")",
".",
"set_shape",
"(",
"shape",
")",
"self",
".",
"value",
"(",
")",
".",
"set_shape",
"(",
"shape",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/variables.py#L435-L442 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/graph_to_function_def.py | python | _add_op_node | (op, func, input_dict) | Converts an op to a function def node and add it to `func`. | Converts an op to a function def node and add it to `func`. | [
"Converts",
"an",
"op",
"to",
"a",
"function",
"def",
"node",
"and",
"add",
"it",
"to",
"func",
"."
] | def _add_op_node(op, func, input_dict):
"""Converts an op to a function def node and add it to `func`."""
# Add an entry in func.node_def
# Note that extend() makes a copy in this case, see:
# https://developers.google.com/protocol-buffers/docs/reference/python-generated#repeated-message-fields
func.node_def.extend([_get_node_def(op)])
node_def = func.node_def[-1]
for i in range(len(node_def.input)):
if not node_def.input[i].startswith("^"):
assert node_def.input[i] in input_dict, ("%s missing from %s" %
(node_def.input[i],
input_dict.items()))
node_def.input[i] = input_dict[node_def.input[i]] | [
"def",
"_add_op_node",
"(",
"op",
",",
"func",
",",
"input_dict",
")",
":",
"# Add an entry in func.node_def",
"# Note that extend() makes a copy in this case, see:",
"# https://developers.google.com/protocol-buffers/docs/reference/python-generated#repeated-message-fields",
"func",
".",
"node_def",
".",
"extend",
"(",
"[",
"_get_node_def",
"(",
"op",
")",
"]",
")",
"node_def",
"=",
"func",
".",
"node_def",
"[",
"-",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"node_def",
".",
"input",
")",
")",
":",
"if",
"not",
"node_def",
".",
"input",
"[",
"i",
"]",
".",
"startswith",
"(",
"\"^\"",
")",
":",
"assert",
"node_def",
".",
"input",
"[",
"i",
"]",
"in",
"input_dict",
",",
"(",
"\"%s missing from %s\"",
"%",
"(",
"node_def",
".",
"input",
"[",
"i",
"]",
",",
"input_dict",
".",
"items",
"(",
")",
")",
")",
"node_def",
".",
"input",
"[",
"i",
"]",
"=",
"input_dict",
"[",
"node_def",
".",
"input",
"[",
"i",
"]",
"]"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/graph_to_function_def.py#L99-L112 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/summary/writer/writer.py | python | FileWriter.close | (self) | Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore. | Flushes the event file to disk and close the file. | [
"Flushes",
"the",
"event",
"file",
"to",
"disk",
"and",
"close",
"the",
"file",
"."
] | def close(self):
"""Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore.
"""
self.event_writer.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"event_writer",
".",
"close",
"(",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/summary/writer/writer.py#L359-L364 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiTabContainer.ButtonHitTest | (*args, **kwargs) | return _aui.AuiTabContainer_ButtonHitTest(*args, **kwargs) | ButtonHitTest(self, int x, int y, AuiTabContainerButton hit) -> bool | ButtonHitTest(self, int x, int y, AuiTabContainerButton hit) -> bool | [
"ButtonHitTest",
"(",
"self",
"int",
"x",
"int",
"y",
"AuiTabContainerButton",
"hit",
")",
"-",
">",
"bool"
] | def ButtonHitTest(*args, **kwargs):
"""ButtonHitTest(self, int x, int y, AuiTabContainerButton hit) -> bool"""
return _aui.AuiTabContainer_ButtonHitTest(*args, **kwargs) | [
"def",
"ButtonHitTest",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiTabContainer_ButtonHitTest",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1180-L1182 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/linalg/_sketches.py | python | cwt_matrix | (n_rows, n_columns, seed=None) | return S | r""""
Generate a matrix S for the Clarkson-Woodruff sketch.
Given the desired size of matrix, the method returns a matrix S of size
(n_rows, n_columns) where each column has all the entries set to 0 less one
position which has been randomly set to +1 or -1 with equal probability.
Parameters
----------
n_rows: int
Number of rows of S
n_columns: int
Number of columns of S
seed : None or int or `numpy.random.RandomState` instance, optional
This parameter defines the ``RandomState`` object to use for drawing
random variates.
If None (or ``np.random``), the global ``np.random`` state is used.
If integer, it is used to seed the local ``RandomState`` instance.
Default is None.
Returns
-------
S : (n_rows, n_columns) array_like
Notes
-----
Given a matrix A, with probability at least 9/10,
.. math:: ||SA|| == (1 \pm \epsilon)||A||
Where epsilon is related to the size of S | r""""
Generate a matrix S for the Clarkson-Woodruff sketch. | [
"r",
"Generate",
"a",
"matrix",
"S",
"for",
"the",
"Clarkson",
"-",
"Woodruff",
"sketch",
"."
] | def cwt_matrix(n_rows, n_columns, seed=None):
r""""
Generate a matrix S for the Clarkson-Woodruff sketch.
Given the desired size of matrix, the method returns a matrix S of size
(n_rows, n_columns) where each column has all the entries set to 0 less one
position which has been randomly set to +1 or -1 with equal probability.
Parameters
----------
n_rows: int
Number of rows of S
n_columns: int
Number of columns of S
seed : None or int or `numpy.random.RandomState` instance, optional
This parameter defines the ``RandomState`` object to use for drawing
random variates.
If None (or ``np.random``), the global ``np.random`` state is used.
If integer, it is used to seed the local ``RandomState`` instance.
Default is None.
Returns
-------
S : (n_rows, n_columns) array_like
Notes
-----
Given a matrix A, with probability at least 9/10,
.. math:: ||SA|| == (1 \pm \epsilon)||A||
Where epsilon is related to the size of S
"""
S = np.zeros((n_rows, n_columns))
nz_positions = np.random.randint(0, n_rows, n_columns)
rng = check_random_state(seed)
values = rng.choice([1, -1], n_columns)
for i in range(n_columns):
S[nz_positions[i]][i] = values[i]
return S | [
"def",
"cwt_matrix",
"(",
"n_rows",
",",
"n_columns",
",",
"seed",
"=",
"None",
")",
":",
"S",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_rows",
",",
"n_columns",
")",
")",
"nz_positions",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"n_rows",
",",
"n_columns",
")",
"rng",
"=",
"check_random_state",
"(",
"seed",
")",
"values",
"=",
"rng",
".",
"choice",
"(",
"[",
"1",
",",
"-",
"1",
"]",
",",
"n_columns",
")",
"for",
"i",
"in",
"range",
"(",
"n_columns",
")",
":",
"S",
"[",
"nz_positions",
"[",
"i",
"]",
"]",
"[",
"i",
"]",
"=",
"values",
"[",
"i",
"]",
"return",
"S"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/_sketches.py#L15-L53 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/decimal.py | python | Decimal.radix | (self) | return Decimal(10) | Just returns 10, as this is Decimal, :) | Just returns 10, as this is Decimal, :) | [
"Just",
"returns",
"10",
"as",
"this",
"is",
"Decimal",
":",
")"
] | def radix(self):
"""Just returns 10, as this is Decimal, :)"""
return Decimal(10) | [
"def",
"radix",
"(",
"self",
")",
":",
"return",
"Decimal",
"(",
"10",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L3526-L3528 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/opsworks/layer1.py | python | OpsWorksConnection.register_volume | (self, stack_id, ec_2_volume_id=None) | return self.make_request(action='RegisterVolume',
body=json.dumps(params)) | Registers an Amazon EBS volume with a specified stack. A
volume can be registered with only one stack at a time. If the
volume is already registered, you must first deregister it by
calling DeregisterVolume. For more information, see `Resource
Management`_.
**Required Permissions**: To use this action, an IAM user must
have a Manage permissions level for the stack, or an attached
policy that explicitly grants permissions. For more
information on user permissions, see `Managing User
Permissions`_.
:type ec_2_volume_id: string
:param ec_2_volume_id: The Amazon EBS volume ID.
:type stack_id: string
:param stack_id: The stack ID. | Registers an Amazon EBS volume with a specified stack. A
volume can be registered with only one stack at a time. If the
volume is already registered, you must first deregister it by
calling DeregisterVolume. For more information, see `Resource
Management`_. | [
"Registers",
"an",
"Amazon",
"EBS",
"volume",
"with",
"a",
"specified",
"stack",
".",
"A",
"volume",
"can",
"be",
"registered",
"with",
"only",
"one",
"stack",
"at",
"a",
"time",
".",
"If",
"the",
"volume",
"is",
"already",
"registered",
"you",
"must",
"first",
"deregister",
"it",
"by",
"calling",
"DeregisterVolume",
".",
"For",
"more",
"information",
"see",
"Resource",
"Management",
"_",
"."
] | def register_volume(self, stack_id, ec_2_volume_id=None):
"""
Registers an Amazon EBS volume with a specified stack. A
volume can be registered with only one stack at a time. If the
volume is already registered, you must first deregister it by
calling DeregisterVolume. For more information, see `Resource
Management`_.
**Required Permissions**: To use this action, an IAM user must
have a Manage permissions level for the stack, or an attached
policy that explicitly grants permissions. For more
information on user permissions, see `Managing User
Permissions`_.
:type ec_2_volume_id: string
:param ec_2_volume_id: The Amazon EBS volume ID.
:type stack_id: string
:param stack_id: The stack ID.
"""
params = {'StackId': stack_id, }
if ec_2_volume_id is not None:
params['Ec2VolumeId'] = ec_2_volume_id
return self.make_request(action='RegisterVolume',
body=json.dumps(params)) | [
"def",
"register_volume",
"(",
"self",
",",
"stack_id",
",",
"ec_2_volume_id",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'StackId'",
":",
"stack_id",
",",
"}",
"if",
"ec_2_volume_id",
"is",
"not",
"None",
":",
"params",
"[",
"'Ec2VolumeId'",
"]",
"=",
"ec_2_volume_id",
"return",
"self",
".",
"make_request",
"(",
"action",
"=",
"'RegisterVolume'",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"params",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/opsworks/layer1.py#L2142-L2167 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py | python | CCompiler._fix_compile_args | (self, output_dir, macros, include_dirs) | return output_dir, macros, include_dirs | Typecheck and fix-up some of the arguments to the 'compile()'
method, and return fixed-up values. Specifically: if 'output_dir'
is None, replaces it with 'self.output_dir'; ensures that 'macros'
is a list, and augments it with 'self.macros'; ensures that
'include_dirs' is a list, and augments it with 'self.include_dirs'.
Guarantees that the returned values are of the correct type,
i.e. for 'output_dir' either string or None, and for 'macros' and
'include_dirs' either list or None. | Typecheck and fix-up some of the arguments to the 'compile()'
method, and return fixed-up values. Specifically: if 'output_dir'
is None, replaces it with 'self.output_dir'; ensures that 'macros'
is a list, and augments it with 'self.macros'; ensures that
'include_dirs' is a list, and augments it with 'self.include_dirs'.
Guarantees that the returned values are of the correct type,
i.e. for 'output_dir' either string or None, and for 'macros' and
'include_dirs' either list or None. | [
"Typecheck",
"and",
"fix",
"-",
"up",
"some",
"of",
"the",
"arguments",
"to",
"the",
"compile",
"()",
"method",
"and",
"return",
"fixed",
"-",
"up",
"values",
".",
"Specifically",
":",
"if",
"output_dir",
"is",
"None",
"replaces",
"it",
"with",
"self",
".",
"output_dir",
";",
"ensures",
"that",
"macros",
"is",
"a",
"list",
"and",
"augments",
"it",
"with",
"self",
".",
"macros",
";",
"ensures",
"that",
"include_dirs",
"is",
"a",
"list",
"and",
"augments",
"it",
"with",
"self",
".",
"include_dirs",
".",
"Guarantees",
"that",
"the",
"returned",
"values",
"are",
"of",
"the",
"correct",
"type",
"i",
".",
"e",
".",
"for",
"output_dir",
"either",
"string",
"or",
"None",
"and",
"for",
"macros",
"and",
"include_dirs",
"either",
"list",
"or",
"None",
"."
] | def _fix_compile_args(self, output_dir, macros, include_dirs):
"""Typecheck and fix-up some of the arguments to the 'compile()'
method, and return fixed-up values. Specifically: if 'output_dir'
is None, replaces it with 'self.output_dir'; ensures that 'macros'
is a list, and augments it with 'self.macros'; ensures that
'include_dirs' is a list, and augments it with 'self.include_dirs'.
Guarantees that the returned values are of the correct type,
i.e. for 'output_dir' either string or None, and for 'macros' and
'include_dirs' either list or None.
"""
if output_dir is None:
output_dir = self.output_dir
elif not isinstance(output_dir, str):
raise TypeError, "'output_dir' must be a string or None"
if macros is None:
macros = self.macros
elif isinstance(macros, list):
macros = macros + (self.macros or [])
else:
raise TypeError, "'macros' (if supplied) must be a list of tuples"
if include_dirs is None:
include_dirs = self.include_dirs
elif isinstance(include_dirs, (list, tuple)):
include_dirs = list (include_dirs) + (self.include_dirs or [])
else:
raise TypeError, \
"'include_dirs' (if supplied) must be a list of strings"
return output_dir, macros, include_dirs | [
"def",
"_fix_compile_args",
"(",
"self",
",",
"output_dir",
",",
"macros",
",",
"include_dirs",
")",
":",
"if",
"output_dir",
"is",
"None",
":",
"output_dir",
"=",
"self",
".",
"output_dir",
"elif",
"not",
"isinstance",
"(",
"output_dir",
",",
"str",
")",
":",
"raise",
"TypeError",
",",
"\"'output_dir' must be a string or None\"",
"if",
"macros",
"is",
"None",
":",
"macros",
"=",
"self",
".",
"macros",
"elif",
"isinstance",
"(",
"macros",
",",
"list",
")",
":",
"macros",
"=",
"macros",
"+",
"(",
"self",
".",
"macros",
"or",
"[",
"]",
")",
"else",
":",
"raise",
"TypeError",
",",
"\"'macros' (if supplied) must be a list of tuples\"",
"if",
"include_dirs",
"is",
"None",
":",
"include_dirs",
"=",
"self",
".",
"include_dirs",
"elif",
"isinstance",
"(",
"include_dirs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"include_dirs",
"=",
"list",
"(",
"include_dirs",
")",
"+",
"(",
"self",
".",
"include_dirs",
"or",
"[",
"]",
")",
"else",
":",
"raise",
"TypeError",
",",
"\"'include_dirs' (if supplied) must be a list of strings\"",
"return",
"output_dir",
",",
"macros",
",",
"include_dirs"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py#L376-L406 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/android/pylib/ports.py | python | AllocateTestServerPort | () | return port | Allocate a port incrementally.
Returns:
Returns a valid port which should be in between TEST_SERVER_PORT_FIRST and
TEST_SERVER_PORT_LAST. Returning 0 means no more valid port can be used. | Allocate a port incrementally. | [
"Allocate",
"a",
"port",
"incrementally",
"."
] | def AllocateTestServerPort():
"""Allocate a port incrementally.
Returns:
Returns a valid port which should be in between TEST_SERVER_PORT_FIRST and
TEST_SERVER_PORT_LAST. Returning 0 means no more valid port can be used.
"""
port = 0
ports_tried = []
try:
fp_lock = open(constants.TEST_SERVER_PORT_LOCKFILE, 'w')
fcntl.flock(fp_lock, fcntl.LOCK_EX)
# Get current valid port and calculate next valid port.
assert os.path.exists(constants.TEST_SERVER_PORT_FILE)
with open(constants.TEST_SERVER_PORT_FILE, 'r+') as fp:
port = int(fp.read())
ports_tried.append(port)
while IsHostPortUsed(port):
port += 1
ports_tried.append(port)
if (port > constants.TEST_SERVER_PORT_LAST or
port < constants.TEST_SERVER_PORT_FIRST):
port = 0
else:
fp.seek(0, os.SEEK_SET)
fp.write('%d' % (port + 1))
except Exception as e:
logging.info(e)
finally:
if fp_lock:
fcntl.flock(fp_lock, fcntl.LOCK_UN)
fp_lock.close()
if port:
logging.info('Allocate port %d for test server.', port)
else:
logging.error('Could not allocate port for test server. '
'List of ports tried: %s', str(ports_tried))
return port | [
"def",
"AllocateTestServerPort",
"(",
")",
":",
"port",
"=",
"0",
"ports_tried",
"=",
"[",
"]",
"try",
":",
"fp_lock",
"=",
"open",
"(",
"constants",
".",
"TEST_SERVER_PORT_LOCKFILE",
",",
"'w'",
")",
"fcntl",
".",
"flock",
"(",
"fp_lock",
",",
"fcntl",
".",
"LOCK_EX",
")",
"# Get current valid port and calculate next valid port.",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"TEST_SERVER_PORT_FILE",
")",
"with",
"open",
"(",
"constants",
".",
"TEST_SERVER_PORT_FILE",
",",
"'r+'",
")",
"as",
"fp",
":",
"port",
"=",
"int",
"(",
"fp",
".",
"read",
"(",
")",
")",
"ports_tried",
".",
"append",
"(",
"port",
")",
"while",
"IsHostPortUsed",
"(",
"port",
")",
":",
"port",
"+=",
"1",
"ports_tried",
".",
"append",
"(",
"port",
")",
"if",
"(",
"port",
">",
"constants",
".",
"TEST_SERVER_PORT_LAST",
"or",
"port",
"<",
"constants",
".",
"TEST_SERVER_PORT_FIRST",
")",
":",
"port",
"=",
"0",
"else",
":",
"fp",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"fp",
".",
"write",
"(",
"'%d'",
"%",
"(",
"port",
"+",
"1",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"info",
"(",
"e",
")",
"finally",
":",
"if",
"fp_lock",
":",
"fcntl",
".",
"flock",
"(",
"fp_lock",
",",
"fcntl",
".",
"LOCK_UN",
")",
"fp_lock",
".",
"close",
"(",
")",
"if",
"port",
":",
"logging",
".",
"info",
"(",
"'Allocate port %d for test server.'",
",",
"port",
")",
"else",
":",
"logging",
".",
"error",
"(",
"'Could not allocate port for test server. '",
"'List of ports tried: %s'",
",",
"str",
"(",
"ports_tried",
")",
")",
"return",
"port"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/pylib/ports.py#L41-L78 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/symbol/symbol.py | python | ones | (shape, dtype=None, **kwargs) | return _internal._ones(shape=shape, dtype=dtype, **kwargs) | Returns a new symbol of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol | Returns a new symbol of given shape and type, filled with ones. | [
"Returns",
"a",
"new",
"symbol",
"of",
"given",
"shape",
"and",
"type",
"filled",
"with",
"ones",
"."
] | def ones(shape, dtype=None, **kwargs):
"""Returns a new symbol of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array.
dtype : str or numpy.dtype, optional
The value type of the inner value, default to ``np.float32``.
Returns
-------
out : Symbol
The created Symbol
"""
if dtype is None:
dtype = _numpy.float32
return _internal._ones(shape=shape, dtype=dtype, **kwargs) | [
"def",
"ones",
"(",
"shape",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"_numpy",
".",
"float32",
"return",
"_internal",
".",
"_ones",
"(",
"shape",
"=",
"shape",
",",
"dtype",
"=",
"dtype",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/symbol/symbol.py#L3045-L3062 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBVariablesOptions.SetInScopeOnly | (self, *args) | return _lldb.SBVariablesOptions_SetInScopeOnly(self, *args) | SetInScopeOnly(self, bool arg0) | SetInScopeOnly(self, bool arg0) | [
"SetInScopeOnly",
"(",
"self",
"bool",
"arg0",
")"
] | def SetInScopeOnly(self, *args):
"""SetInScopeOnly(self, bool arg0)"""
return _lldb.SBVariablesOptions_SetInScopeOnly(self, *args) | [
"def",
"SetInScopeOnly",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBVariablesOptions_SetInScopeOnly",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L12539-L12541 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/summary/impl/directory_watcher.py | python | DirectoryWatcher.__init__ | (self, directory, loader_factory, path_filter=lambda x: True) | Constructs a new DirectoryWatcher.
Args:
directory: The directory to load files from.
loader_factory: A factory for creating loaders. The factory should take a
path and return an object that has a Load method returning an
iterator that will yield all events that have not been yielded yet.
path_filter: If specified, only paths matching this filter are loaded.
Raises:
ValueError: If path_provider or loader_factory are None. | Constructs a new DirectoryWatcher. | [
"Constructs",
"a",
"new",
"DirectoryWatcher",
"."
] | def __init__(self, directory, loader_factory, path_filter=lambda x: True):
"""Constructs a new DirectoryWatcher.
Args:
directory: The directory to load files from.
loader_factory: A factory for creating loaders. The factory should take a
path and return an object that has a Load method returning an
iterator that will yield all events that have not been yielded yet.
path_filter: If specified, only paths matching this filter are loaded.
Raises:
ValueError: If path_provider or loader_factory are None.
"""
if directory is None:
raise ValueError('A directory is required')
if loader_factory is None:
raise ValueError('A loader factory is required')
self._directory = directory
self._path = None
self._loader_factory = loader_factory
self._loader = None
self._path_filter = path_filter
self._ooo_writes_detected = False
# The file size for each file at the time it was finalized.
self._finalized_sizes = {} | [
"def",
"__init__",
"(",
"self",
",",
"directory",
",",
"loader_factory",
",",
"path_filter",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"if",
"directory",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'A directory is required'",
")",
"if",
"loader_factory",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'A loader factory is required'",
")",
"self",
".",
"_directory",
"=",
"directory",
"self",
".",
"_path",
"=",
"None",
"self",
".",
"_loader_factory",
"=",
"loader_factory",
"self",
".",
"_loader",
"=",
"None",
"self",
".",
"_path_filter",
"=",
"path_filter",
"self",
".",
"_ooo_writes_detected",
"=",
"False",
"# The file size for each file at the time it was finalized.",
"self",
".",
"_finalized_sizes",
"=",
"{",
"}"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/summary/impl/directory_watcher.py#L43-L67 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.EndTextColour | (*args, **kwargs) | return _richtext.RichTextBuffer_EndTextColour(*args, **kwargs) | EndTextColour(self) -> bool | EndTextColour(self) -> bool | [
"EndTextColour",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndTextColour(*args, **kwargs):
"""EndTextColour(self) -> bool"""
return _richtext.RichTextBuffer_EndTextColour(*args, **kwargs) | [
"def",
"EndTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_EndTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2377-L2379 | |
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/genvk.py | python | genTarget | (args) | Create an API generator and corresponding generator options based on
the requested target and command line options.
This is encapsulated in a function so it can be profiled and/or timed.
The args parameter is an parsed argument object containing the following
fields that are used:
- target - target to generate
- directory - directory to generate it in
- protect - True if re-inclusion wrappers should be created
- extensions - list of additional extensions to include in generated interfaces | Create an API generator and corresponding generator options based on
the requested target and command line options. | [
"Create",
"an",
"API",
"generator",
"and",
"corresponding",
"generator",
"options",
"based",
"on",
"the",
"requested",
"target",
"and",
"command",
"line",
"options",
"."
] | def genTarget(args):
"""Create an API generator and corresponding generator options based on
the requested target and command line options.
This is encapsulated in a function so it can be profiled and/or timed.
The args parameter is an parsed argument object containing the following
fields that are used:
- target - target to generate
- directory - directory to generate it in
- protect - True if re-inclusion wrappers should be created
- extensions - list of additional extensions to include in generated interfaces"""
# Create generator options with parameters specified on command line
makeGenOpts(args)
# pdb.set_trace()
# Select a generator matching the requested target
if args.target in genOpts:
createGenerator = genOpts[args.target][0]
options = genOpts[args.target][1]
logDiag('* Building', options.filename)
logDiag('* options.versions =', options.versions)
logDiag('* options.emitversions =', options.emitversions)
logDiag('* options.defaultExtensions =', options.defaultExtensions)
logDiag('* options.addExtensions =', options.addExtensions)
logDiag('* options.removeExtensions =', options.removeExtensions)
logDiag('* options.emitExtensions =', options.emitExtensions)
logDiag('* options.emitSpirv =', options.emitSpirv)
logDiag('* options.emitFormats =', options.emitFormats)
gen = createGenerator(errFile=errWarn,
warnFile=errWarn,
diagFile=diag)
return (gen, options)
else:
logErr('No generator options for unknown target:', args.target)
return None | [
"def",
"genTarget",
"(",
"args",
")",
":",
"# Create generator options with parameters specified on command line",
"makeGenOpts",
"(",
"args",
")",
"# pdb.set_trace()",
"# Select a generator matching the requested target",
"if",
"args",
".",
"target",
"in",
"genOpts",
":",
"createGenerator",
"=",
"genOpts",
"[",
"args",
".",
"target",
"]",
"[",
"0",
"]",
"options",
"=",
"genOpts",
"[",
"args",
".",
"target",
"]",
"[",
"1",
"]",
"logDiag",
"(",
"'* Building'",
",",
"options",
".",
"filename",
")",
"logDiag",
"(",
"'* options.versions ='",
",",
"options",
".",
"versions",
")",
"logDiag",
"(",
"'* options.emitversions ='",
",",
"options",
".",
"emitversions",
")",
"logDiag",
"(",
"'* options.defaultExtensions ='",
",",
"options",
".",
"defaultExtensions",
")",
"logDiag",
"(",
"'* options.addExtensions ='",
",",
"options",
".",
"addExtensions",
")",
"logDiag",
"(",
"'* options.removeExtensions ='",
",",
"options",
".",
"removeExtensions",
")",
"logDiag",
"(",
"'* options.emitExtensions ='",
",",
"options",
".",
"emitExtensions",
")",
"logDiag",
"(",
"'* options.emitSpirv ='",
",",
"options",
".",
"emitSpirv",
")",
"logDiag",
"(",
"'* options.emitFormats ='",
",",
"options",
".",
"emitFormats",
")",
"gen",
"=",
"createGenerator",
"(",
"errFile",
"=",
"errWarn",
",",
"warnFile",
"=",
"errWarn",
",",
"diagFile",
"=",
"diag",
")",
"return",
"(",
"gen",
",",
"options",
")",
"else",
":",
"logErr",
"(",
"'No generator options for unknown target:'",
",",
"args",
".",
"target",
")",
"return",
"None"
] | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/genvk.py#L653-L692 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/fnmatch.py | python | _purge | () | Clear the pattern cache | Clear the pattern cache | [
"Clear",
"the",
"pattern",
"cache"
] | def _purge():
"""Clear the pattern cache"""
_cache.clear() | [
"def",
"_purge",
"(",
")",
":",
"_cache",
".",
"clear",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/fnmatch.py#L20-L22 | ||
svn2github/webrtc | 0e4615a75ed555ec866cd5543bfea586f3385ceb | tools/network_emulator/network_emulator.py | python | _run_ipfw_command | (command, fail_msg=None) | return output.strip() | Executes a command and prefixes the appropriate command for
Windows or Linux/UNIX.
Args:
command: Command list to execute.
fail_msg: Message describing the error in case the command fails.
Raises:
NetworkEmulatorError: If command fails a message is set by the fail_msg
parameter. | Executes a command and prefixes the appropriate command for
Windows or Linux/UNIX. | [
"Executes",
"a",
"command",
"and",
"prefixes",
"the",
"appropriate",
"command",
"for",
"Windows",
"or",
"Linux",
"/",
"UNIX",
"."
] | def _run_ipfw_command(command, fail_msg=None):
"""Executes a command and prefixes the appropriate command for
Windows or Linux/UNIX.
Args:
command: Command list to execute.
fail_msg: Message describing the error in case the command fails.
Raises:
NetworkEmulatorError: If command fails a message is set by the fail_msg
parameter.
"""
if sys.platform == 'win32':
ipfw_command = ['ipfw.exe']
else:
ipfw_command = ['sudo', '-n', 'ipfw']
cmd_list = ipfw_command[:] + [str(x) for x in command]
cmd_string = ' '.join(cmd_list)
logging.debug('Running command: %s', cmd_string)
process = subprocess.Popen(cmd_list, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, error = process.communicate()
if process.returncode != 0:
raise NetworkEmulatorError(fail_msg, cmd_string, process.returncode, output,
error)
return output.strip() | [
"def",
"_run_ipfw_command",
"(",
"command",
",",
"fail_msg",
"=",
"None",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"ipfw_command",
"=",
"[",
"'ipfw.exe'",
"]",
"else",
":",
"ipfw_command",
"=",
"[",
"'sudo'",
",",
"'-n'",
",",
"'ipfw'",
"]",
"cmd_list",
"=",
"ipfw_command",
"[",
":",
"]",
"+",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"command",
"]",
"cmd_string",
"=",
"' '",
".",
"join",
"(",
"cmd_list",
")",
"logging",
".",
"debug",
"(",
"'Running command: %s'",
",",
"cmd_string",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd_list",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"output",
",",
"error",
"=",
"process",
".",
"communicate",
"(",
")",
"if",
"process",
".",
"returncode",
"!=",
"0",
":",
"raise",
"NetworkEmulatorError",
"(",
"fail_msg",
",",
"cmd_string",
",",
"process",
".",
"returncode",
",",
"output",
",",
"error",
")",
"return",
"output",
".",
"strip",
"(",
")"
] | https://github.com/svn2github/webrtc/blob/0e4615a75ed555ec866cd5543bfea586f3385ceb/tools/network_emulator/network_emulator.py#L163-L189 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | MULAN_universal_lesion_analysis/maskrcnn/data/datasets/evaluation/coco/coco_eval.py | python | evaluate_box_proposals | (
predictions, dataset, thresholds=None, area="all", limit=None
) | return {
"ar": ar,
"recalls": recalls,
"thresholds": thresholds,
"gt_overlaps": gt_overlaps,
"num_pos": num_pos,
} | Evaluate detection proposal recall metrics. This function is a much
faster alternative to the official COCO API recall evaluation code. However,
it produces slightly different results. | Evaluate detection proposal recall metrics. This function is a much
faster alternative to the official COCO API recall evaluation code. However,
it produces slightly different results. | [
"Evaluate",
"detection",
"proposal",
"recall",
"metrics",
".",
"This",
"function",
"is",
"a",
"much",
"faster",
"alternative",
"to",
"the",
"official",
"COCO",
"API",
"recall",
"evaluation",
"code",
".",
"However",
"it",
"produces",
"slightly",
"different",
"results",
"."
] | def evaluate_box_proposals(
predictions, dataset, thresholds=None, area="all", limit=None
):
"""Evaluate detection proposal recall metrics. This function is a much
faster alternative to the official COCO API recall evaluation code. However,
it produces slightly different results.
"""
# Record max overlap value for each gt box
# Return vector of overlap values
areas = {
"all": 0,
"small": 1,
"medium": 2,
"large": 3,
"96-128": 4,
"128-256": 5,
"256-512": 6,
"512-inf": 7,
}
area_ranges = [
[0 ** 2, 1e5 ** 2], # all
[0 ** 2, 32 ** 2], # small
[32 ** 2, 96 ** 2], # medium
[96 ** 2, 1e5 ** 2], # large
[96 ** 2, 128 ** 2], # 96-128
[128 ** 2, 256 ** 2], # 128-256
[256 ** 2, 512 ** 2], # 256-512
[512 ** 2, 1e5 ** 2],
] # 512-inf
assert area in areas, "Unknown area range: {}".format(area)
area_range = area_ranges[areas[area]]
gt_overlaps = []
num_pos = 0
for image_id, prediction in enumerate(predictions):
original_id = dataset.id_to_img_map[image_id]
# TODO replace with get_img_info?
image_width = dataset.coco.imgs[original_id]["width"]
image_height = dataset.coco.imgs[original_id]["height"]
prediction = prediction.resize((image_width, image_height))
# sort predictions in descending order
# TODO maybe remove this and make it explicit in the documentation
inds = prediction.get_field("objectness").sort(descending=True)[1]
prediction = prediction[inds]
ann_ids = dataset.coco.getAnnIds(imgIds=original_id)
anno = dataset.coco.loadAnns(ann_ids)
gt_boxes = [obj["bbox"] for obj in anno if obj["iscrowd"] == 0]
gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4) # guard against no boxes
gt_boxes = BoxList(gt_boxes, (image_width, image_height), mode="xywh").convert(
"xyxy"
)
gt_areas = torch.as_tensor([obj["area"] for obj in anno if obj["iscrowd"] == 0])
if len(gt_boxes) == 0:
continue
valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1])
gt_boxes = gt_boxes[valid_gt_inds]
num_pos += len(gt_boxes)
if len(gt_boxes) == 0:
continue
if len(prediction) == 0:
continue
if limit is not None and len(prediction) > limit:
prediction = prediction[:limit]
overlaps = boxlist_iou(prediction, gt_boxes)
_gt_overlaps = torch.zeros(len(gt_boxes))
for j in range(min(len(prediction), len(gt_boxes))):
# find which proposal box maximally covers each gt box
# and get the iou amount of coverage for each gt box
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
# find which gt box is 'best' covered (i.e. 'best' = most iou)
gt_ovr, gt_ind = max_overlaps.max(dim=0)
assert gt_ovr >= 0
# find the proposal box that covers the best covered gt box
box_ind = argmax_overlaps[gt_ind]
# record the iou coverage of this gt box
_gt_overlaps[j] = overlaps[box_ind, gt_ind]
assert _gt_overlaps[j] == gt_ovr
# mark the proposal box and the gt box as used
overlaps[box_ind, :] = -1
overlaps[:, gt_ind] = -1
# append recorded iou coverage level
gt_overlaps.append(_gt_overlaps)
gt_overlaps = torch.cat(gt_overlaps, dim=0)
gt_overlaps, _ = torch.sort(gt_overlaps)
if thresholds is None:
step = 0.05
thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32)
recalls = torch.zeros_like(thresholds)
# compute recall for each iou threshold
for i, t in enumerate(thresholds):
recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos)
# ar = 2 * np.trapz(recalls, thresholds)
ar = recalls.mean()
return {
"ar": ar,
"recalls": recalls,
"thresholds": thresholds,
"gt_overlaps": gt_overlaps,
"num_pos": num_pos,
} | [
"def",
"evaluate_box_proposals",
"(",
"predictions",
",",
"dataset",
",",
"thresholds",
"=",
"None",
",",
"area",
"=",
"\"all\"",
",",
"limit",
"=",
"None",
")",
":",
"# Record max overlap value for each gt box",
"# Return vector of overlap values",
"areas",
"=",
"{",
"\"all\"",
":",
"0",
",",
"\"small\"",
":",
"1",
",",
"\"medium\"",
":",
"2",
",",
"\"large\"",
":",
"3",
",",
"\"96-128\"",
":",
"4",
",",
"\"128-256\"",
":",
"5",
",",
"\"256-512\"",
":",
"6",
",",
"\"512-inf\"",
":",
"7",
",",
"}",
"area_ranges",
"=",
"[",
"[",
"0",
"**",
"2",
",",
"1e5",
"**",
"2",
"]",
",",
"# all",
"[",
"0",
"**",
"2",
",",
"32",
"**",
"2",
"]",
",",
"# small",
"[",
"32",
"**",
"2",
",",
"96",
"**",
"2",
"]",
",",
"# medium",
"[",
"96",
"**",
"2",
",",
"1e5",
"**",
"2",
"]",
",",
"# large",
"[",
"96",
"**",
"2",
",",
"128",
"**",
"2",
"]",
",",
"# 96-128",
"[",
"128",
"**",
"2",
",",
"256",
"**",
"2",
"]",
",",
"# 128-256",
"[",
"256",
"**",
"2",
",",
"512",
"**",
"2",
"]",
",",
"# 256-512",
"[",
"512",
"**",
"2",
",",
"1e5",
"**",
"2",
"]",
",",
"]",
"# 512-inf",
"assert",
"area",
"in",
"areas",
",",
"\"Unknown area range: {}\"",
".",
"format",
"(",
"area",
")",
"area_range",
"=",
"area_ranges",
"[",
"areas",
"[",
"area",
"]",
"]",
"gt_overlaps",
"=",
"[",
"]",
"num_pos",
"=",
"0",
"for",
"image_id",
",",
"prediction",
"in",
"enumerate",
"(",
"predictions",
")",
":",
"original_id",
"=",
"dataset",
".",
"id_to_img_map",
"[",
"image_id",
"]",
"# TODO replace with get_img_info?",
"image_width",
"=",
"dataset",
".",
"coco",
".",
"imgs",
"[",
"original_id",
"]",
"[",
"\"width\"",
"]",
"image_height",
"=",
"dataset",
".",
"coco",
".",
"imgs",
"[",
"original_id",
"]",
"[",
"\"height\"",
"]",
"prediction",
"=",
"prediction",
".",
"resize",
"(",
"(",
"image_width",
",",
"image_height",
")",
")",
"# sort predictions in descending order",
"# TODO maybe remove this and make it explicit in the documentation",
"inds",
"=",
"prediction",
".",
"get_field",
"(",
"\"objectness\"",
")",
".",
"sort",
"(",
"descending",
"=",
"True",
")",
"[",
"1",
"]",
"prediction",
"=",
"prediction",
"[",
"inds",
"]",
"ann_ids",
"=",
"dataset",
".",
"coco",
".",
"getAnnIds",
"(",
"imgIds",
"=",
"original_id",
")",
"anno",
"=",
"dataset",
".",
"coco",
".",
"loadAnns",
"(",
"ann_ids",
")",
"gt_boxes",
"=",
"[",
"obj",
"[",
"\"bbox\"",
"]",
"for",
"obj",
"in",
"anno",
"if",
"obj",
"[",
"\"iscrowd\"",
"]",
"==",
"0",
"]",
"gt_boxes",
"=",
"torch",
".",
"as_tensor",
"(",
"gt_boxes",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"4",
")",
"# guard against no boxes",
"gt_boxes",
"=",
"BoxList",
"(",
"gt_boxes",
",",
"(",
"image_width",
",",
"image_height",
")",
",",
"mode",
"=",
"\"xywh\"",
")",
".",
"convert",
"(",
"\"xyxy\"",
")",
"gt_areas",
"=",
"torch",
".",
"as_tensor",
"(",
"[",
"obj",
"[",
"\"area\"",
"]",
"for",
"obj",
"in",
"anno",
"if",
"obj",
"[",
"\"iscrowd\"",
"]",
"==",
"0",
"]",
")",
"if",
"len",
"(",
"gt_boxes",
")",
"==",
"0",
":",
"continue",
"valid_gt_inds",
"=",
"(",
"gt_areas",
">=",
"area_range",
"[",
"0",
"]",
")",
"&",
"(",
"gt_areas",
"<=",
"area_range",
"[",
"1",
"]",
")",
"gt_boxes",
"=",
"gt_boxes",
"[",
"valid_gt_inds",
"]",
"num_pos",
"+=",
"len",
"(",
"gt_boxes",
")",
"if",
"len",
"(",
"gt_boxes",
")",
"==",
"0",
":",
"continue",
"if",
"len",
"(",
"prediction",
")",
"==",
"0",
":",
"continue",
"if",
"limit",
"is",
"not",
"None",
"and",
"len",
"(",
"prediction",
")",
">",
"limit",
":",
"prediction",
"=",
"prediction",
"[",
":",
"limit",
"]",
"overlaps",
"=",
"boxlist_iou",
"(",
"prediction",
",",
"gt_boxes",
")",
"_gt_overlaps",
"=",
"torch",
".",
"zeros",
"(",
"len",
"(",
"gt_boxes",
")",
")",
"for",
"j",
"in",
"range",
"(",
"min",
"(",
"len",
"(",
"prediction",
")",
",",
"len",
"(",
"gt_boxes",
")",
")",
")",
":",
"# find which proposal box maximally covers each gt box",
"# and get the iou amount of coverage for each gt box",
"max_overlaps",
",",
"argmax_overlaps",
"=",
"overlaps",
".",
"max",
"(",
"dim",
"=",
"0",
")",
"# find which gt box is 'best' covered (i.e. 'best' = most iou)",
"gt_ovr",
",",
"gt_ind",
"=",
"max_overlaps",
".",
"max",
"(",
"dim",
"=",
"0",
")",
"assert",
"gt_ovr",
">=",
"0",
"# find the proposal box that covers the best covered gt box",
"box_ind",
"=",
"argmax_overlaps",
"[",
"gt_ind",
"]",
"# record the iou coverage of this gt box",
"_gt_overlaps",
"[",
"j",
"]",
"=",
"overlaps",
"[",
"box_ind",
",",
"gt_ind",
"]",
"assert",
"_gt_overlaps",
"[",
"j",
"]",
"==",
"gt_ovr",
"# mark the proposal box and the gt box as used",
"overlaps",
"[",
"box_ind",
",",
":",
"]",
"=",
"-",
"1",
"overlaps",
"[",
":",
",",
"gt_ind",
"]",
"=",
"-",
"1",
"# append recorded iou coverage level",
"gt_overlaps",
".",
"append",
"(",
"_gt_overlaps",
")",
"gt_overlaps",
"=",
"torch",
".",
"cat",
"(",
"gt_overlaps",
",",
"dim",
"=",
"0",
")",
"gt_overlaps",
",",
"_",
"=",
"torch",
".",
"sort",
"(",
"gt_overlaps",
")",
"if",
"thresholds",
"is",
"None",
":",
"step",
"=",
"0.05",
"thresholds",
"=",
"torch",
".",
"arange",
"(",
"0.5",
",",
"0.95",
"+",
"1e-5",
",",
"step",
",",
"dtype",
"=",
"torch",
".",
"float32",
")",
"recalls",
"=",
"torch",
".",
"zeros_like",
"(",
"thresholds",
")",
"# compute recall for each iou threshold",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"thresholds",
")",
":",
"recalls",
"[",
"i",
"]",
"=",
"(",
"gt_overlaps",
">=",
"t",
")",
".",
"float",
"(",
")",
".",
"sum",
"(",
")",
"/",
"float",
"(",
"num_pos",
")",
"# ar = 2 * np.trapz(recalls, thresholds)",
"ar",
"=",
"recalls",
".",
"mean",
"(",
")",
"return",
"{",
"\"ar\"",
":",
"ar",
",",
"\"recalls\"",
":",
"recalls",
",",
"\"thresholds\"",
":",
"thresholds",
",",
"\"gt_overlaps\"",
":",
"gt_overlaps",
",",
"\"num_pos\"",
":",
"num_pos",
",",
"}"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/MULAN_universal_lesion_analysis/maskrcnn/data/datasets/evaluation/coco/coco_eval.py#L156-L269 | |
openweave/openweave-core | 11ceb6b7efd39fe05de7f79229247a5774d56766 | src/device-manager/python/weave-device-mgr.py | python | DeviceMgrCmd.do_disarmfailsafe | (self, line) | disarm-fail-safe
Disarm the currently active configuration fail-safe on the device. | disarm-fail-safe | [
"disarm",
"-",
"fail",
"-",
"safe"
] | def do_disarmfailsafe(self, line):
"""
disarm-fail-safe
Disarm the currently active configuration fail-safe on the device.
"""
args = shlex.split(line)
if (len(args) > 0):
print("Unexpected argument: " + args[0])
return
try:
self.devMgr.DisarmFailSafe()
except WeaveStack.WeaveStackException as ex:
print(str(ex))
return
print("Disarm fail-safe complete") | [
"def",
"do_disarmfailsafe",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"if",
"(",
"len",
"(",
"args",
")",
">",
"0",
")",
":",
"print",
"(",
"\"Unexpected argument: \"",
"+",
"args",
"[",
"0",
"]",
")",
"return",
"try",
":",
"self",
".",
"devMgr",
".",
"DisarmFailSafe",
"(",
")",
"except",
"WeaveStack",
".",
"WeaveStackException",
"as",
"ex",
":",
"print",
"(",
"str",
"(",
"ex",
")",
")",
"return",
"print",
"(",
"\"Disarm fail-safe complete\"",
")"
] | https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/weave-device-mgr.py#L2135-L2154 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py | python | MH.getpath | (self) | return self.path | Return the path (the name of the collection's directory). | Return the path (the name of the collection's directory). | [
"Return",
"the",
"path",
"(",
"the",
"name",
"of",
"the",
"collection",
"s",
"directory",
")",
"."
] | def getpath(self):
"""Return the path (the name of the collection's directory)."""
return self.path | [
"def",
"getpath",
"(",
"self",
")",
":",
"return",
"self",
".",
"path"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py#L126-L128 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/data/dataloader.py | python | worker_loop_v1 | (dataset, key_queue, data_queue, batchify_fn) | Worker loop for multiprocessing DataLoader. | Worker loop for multiprocessing DataLoader. | [
"Worker",
"loop",
"for",
"multiprocessing",
"DataLoader",
"."
] | def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn):
"""Worker loop for multiprocessing DataLoader."""
while True:
idx, samples = key_queue.get()
if idx is None:
break
batch = batchify_fn([dataset[i] for i in samples])
data_queue.put((idx, batch)) | [
"def",
"worker_loop_v1",
"(",
"dataset",
",",
"key_queue",
",",
"data_queue",
",",
"batchify_fn",
")",
":",
"while",
"True",
":",
"idx",
",",
"samples",
"=",
"key_queue",
".",
"get",
"(",
")",
"if",
"idx",
"is",
"None",
":",
"break",
"batch",
"=",
"batchify_fn",
"(",
"[",
"dataset",
"[",
"i",
"]",
"for",
"i",
"in",
"samples",
"]",
")",
"data_queue",
".",
"put",
"(",
"(",
"idx",
",",
"batch",
")",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/data/dataloader.py#L186-L193 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/nyan/nyan_structs.py | python | NyanMember.get_operator | (self) | return self._operator | Returns the operator of the member. | Returns the operator of the member. | [
"Returns",
"the",
"operator",
"of",
"the",
"member",
"."
] | def get_operator(self):
"""
Returns the operator of the member.
"""
return self._operator | [
"def",
"get_operator",
"(",
"self",
")",
":",
"return",
"self",
".",
"_operator"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/nyan_structs.py#L894-L898 | |
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | scripts/cpp_lint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"_NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"nesting_state",
".",
"CheckCompletedBlocks",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/scripts/cpp_lint.py#L4648-L4691 | ||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | BaseNode.name_relative | (self) | return self.__name.name_relative | Node name, relative to the current drakefile. | Node name, relative to the current drakefile. | [
"Node",
"name",
"relative",
"to",
"the",
"current",
"drakefile",
"."
] | def name_relative(self):
"""Node name, relative to the current drakefile."""
return self.__name.name_relative | [
"def",
"name_relative",
"(",
"self",
")",
":",
"return",
"self",
".",
"__name",
".",
"name_relative"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L1345-L1347 | |
stack-of-tasks/pinocchio | 593d4d43fded997bb9aa2421f4e55294dbd233c4 | bindings/python/pinocchio/visualize/gepetto_visualizer.py | python | GepettoVisualizer.initViewer | (self, viewer=None, windowName="python-pinocchio", sceneName="world", loadModel=False) | Init GepettoViewer by loading the gui and creating a window. | Init GepettoViewer by loading the gui and creating a window. | [
"Init",
"GepettoViewer",
"by",
"loading",
"the",
"gui",
"and",
"creating",
"a",
"window",
"."
] | def initViewer(self, viewer=None, windowName="python-pinocchio", sceneName="world", loadModel=False):
"""Init GepettoViewer by loading the gui and creating a window."""
try:
import gepetto.corbaserver
except ImportError:
import warnings
msg = ("Error while importing the viewer client.\n"
"Check whether gepetto-gui is properly installed"
)
warnings.warn(msg, category=UserWarning, stacklevel=2)
try:
self.viewer = gepetto.corbaserver.Client() if viewer is None else viewer
gui = self.viewer.gui
# Create window
window_l = gui.getWindowList()
if not windowName in window_l:
self.windowID = self.viewer.gui.createWindow(windowName)
else:
self.windowID = self.viewer.gui.getWindowID(windowName)
# Create scene if needed
scene_l = gui.getSceneList()
if sceneName not in scene_l:
gui.createScene(sceneName)
self.sceneName = sceneName
gui.addSceneToWindow(sceneName, self.windowID)
if loadModel:
self.loadViewerModel()
except:
import warnings
msg = ("Error while starting the viewer client.\n"
"Check whether gepetto-viewer is properly started"
)
warnings.warn(msg, category=UserWarning, stacklevel=2) | [
"def",
"initViewer",
"(",
"self",
",",
"viewer",
"=",
"None",
",",
"windowName",
"=",
"\"python-pinocchio\"",
",",
"sceneName",
"=",
"\"world\"",
",",
"loadModel",
"=",
"False",
")",
":",
"try",
":",
"import",
"gepetto",
".",
"corbaserver",
"except",
"ImportError",
":",
"import",
"warnings",
"msg",
"=",
"(",
"\"Error while importing the viewer client.\\n\"",
"\"Check whether gepetto-gui is properly installed\"",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"category",
"=",
"UserWarning",
",",
"stacklevel",
"=",
"2",
")",
"try",
":",
"self",
".",
"viewer",
"=",
"gepetto",
".",
"corbaserver",
".",
"Client",
"(",
")",
"if",
"viewer",
"is",
"None",
"else",
"viewer",
"gui",
"=",
"self",
".",
"viewer",
".",
"gui",
"# Create window",
"window_l",
"=",
"gui",
".",
"getWindowList",
"(",
")",
"if",
"not",
"windowName",
"in",
"window_l",
":",
"self",
".",
"windowID",
"=",
"self",
".",
"viewer",
".",
"gui",
".",
"createWindow",
"(",
"windowName",
")",
"else",
":",
"self",
".",
"windowID",
"=",
"self",
".",
"viewer",
".",
"gui",
".",
"getWindowID",
"(",
"windowName",
")",
"# Create scene if needed",
"scene_l",
"=",
"gui",
".",
"getSceneList",
"(",
")",
"if",
"sceneName",
"not",
"in",
"scene_l",
":",
"gui",
".",
"createScene",
"(",
"sceneName",
")",
"self",
".",
"sceneName",
"=",
"sceneName",
"gui",
".",
"addSceneToWindow",
"(",
"sceneName",
",",
"self",
".",
"windowID",
")",
"if",
"loadModel",
":",
"self",
".",
"loadViewerModel",
"(",
")",
"except",
":",
"import",
"warnings",
"msg",
"=",
"(",
"\"Error while starting the viewer client.\\n\"",
"\"Check whether gepetto-viewer is properly started\"",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"category",
"=",
"UserWarning",
",",
"stacklevel",
"=",
"2",
")"
] | https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/visualize/gepetto_visualizer.py#L25-L62 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/pykmip.py | python | assign_ports | (ctx, config, initial_port) | return role_endpoints | Assign port numbers starting from @initial_port | Assign port numbers starting from | [
"Assign",
"port",
"numbers",
"starting",
"from"
] | def assign_ports(ctx, config, initial_port):
"""
Assign port numbers starting from @initial_port
"""
port = initial_port
role_endpoints = {}
for remote, roles_for_host in ctx.cluster.remotes.items():
for role in roles_for_host:
if role in config:
r = get_remote_for_role(ctx, role)
role_endpoints[role] = r.ip_address, port, r.hostname
port += 1
return role_endpoints | [
"def",
"assign_ports",
"(",
"ctx",
",",
"config",
",",
"initial_port",
")",
":",
"port",
"=",
"initial_port",
"role_endpoints",
"=",
"{",
"}",
"for",
"remote",
",",
"roles_for_host",
"in",
"ctx",
".",
"cluster",
".",
"remotes",
".",
"items",
"(",
")",
":",
"for",
"role",
"in",
"roles_for_host",
":",
"if",
"role",
"in",
"config",
":",
"r",
"=",
"get_remote_for_role",
"(",
"ctx",
",",
"role",
")",
"role_endpoints",
"[",
"role",
"]",
"=",
"r",
".",
"ip_address",
",",
"port",
",",
"r",
".",
"hostname",
"port",
"+=",
"1",
"return",
"role_endpoints"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/pykmip.py#L155-L168 | |
HPCToolkit/hpctoolkit | e06dd3496e2f9b6f6d63882efe159c7ec177b077 | src/tool/misc/lushpp.py | python | parseCmdLine | (argv, shortOpts, longOpts) | Given the inputs for getopt, return the parsed argv line as a
(dictionary-of-options, rest-of-arguments) tuple. Note that argv
should contain the full command line | Given the inputs for getopt, return the parsed argv line as a
(dictionary-of-options, rest-of-arguments) tuple. Note that argv
should contain the full command line | [
"Given",
"the",
"inputs",
"for",
"getopt",
"return",
"the",
"parsed",
"argv",
"line",
"as",
"a",
"(",
"dictionary",
"-",
"of",
"-",
"options",
"rest",
"-",
"of",
"-",
"arguments",
")",
"tuple",
".",
"Note",
"that",
"argv",
"should",
"contain",
"the",
"full",
"command",
"line"
] | def parseCmdLine(argv, shortOpts, longOpts):
"""Given the inputs for getopt, return the parsed argv line as a
(dictionary-of-options, rest-of-arguments) tuple. Note that argv
should contain the full command line"""
try:
(opts, args) = getopt.getopt(argv[1:], shortOpts, longOpts)
except (getopt.error), msg:
raise UsageExcept(msg)
else:
dashRE = re.compile(r"^-{1,2}") # find leading dashes
dict = { }
for (o, a) in opts:
o = dashRE.sub('', o) # strip off leading dashes
dict[o] = a
return (dict, args) | [
"def",
"parseCmdLine",
"(",
"argv",
",",
"shortOpts",
",",
"longOpts",
")",
":",
"try",
":",
"(",
"opts",
",",
"args",
")",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
"[",
"1",
":",
"]",
",",
"shortOpts",
",",
"longOpts",
")",
"except",
"(",
"getopt",
".",
"error",
")",
",",
"msg",
":",
"raise",
"UsageExcept",
"(",
"msg",
")",
"else",
":",
"dashRE",
"=",
"re",
".",
"compile",
"(",
"r\"^-{1,2}\"",
")",
"# find leading dashes",
"dict",
"=",
"{",
"}",
"for",
"(",
"o",
",",
"a",
")",
"in",
"opts",
":",
"o",
"=",
"dashRE",
".",
"sub",
"(",
"''",
",",
"o",
")",
"# strip off leading dashes",
"dict",
"[",
"o",
"]",
"=",
"a",
"return",
"(",
"dict",
",",
"args",
")"
] | https://github.com/HPCToolkit/hpctoolkit/blob/e06dd3496e2f9b6f6d63882efe159c7ec177b077/src/tool/misc/lushpp.py#L109-L123 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Node/__init__.py | python | Node.get_abspath | (self) | return str(self) | Return an absolute path to the Node. This will return simply
str(Node) by default, but for Node types that have a concept of
relative path, this might return something different. | Return an absolute path to the Node. This will return simply
str(Node) by default, but for Node types that have a concept of
relative path, this might return something different. | [
"Return",
"an",
"absolute",
"path",
"to",
"the",
"Node",
".",
"This",
"will",
"return",
"simply",
"str",
"(",
"Node",
")",
"by",
"default",
"but",
"for",
"Node",
"types",
"that",
"have",
"a",
"concept",
"of",
"relative",
"path",
"this",
"might",
"return",
"something",
"different",
"."
] | def get_abspath(self):
"""
Return an absolute path to the Node. This will return simply
str(Node) by default, but for Node types that have a concept of
relative path, this might return something different.
"""
return str(self) | [
"def",
"get_abspath",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/__init__.py#L1558-L1564 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/libs/metaparse/tools/benchmark/char_stat.py | python | main | () | The main function of the script | The main function of the script | [
"The",
"main",
"function",
"of",
"the",
"script"
] | def main():
"""The main function of the script"""
desc = 'Generate character statistics from a source tree'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
'--src',
dest='src',
required=True,
help='The root of the source tree'
)
parser.add_argument(
'--out',
dest='out',
default='chars.py',
help='The output filename'
)
args = parser.parse_args()
stats = generate_statistics(args.src)
with open(args.out, 'wb') as out_f:
out_f.write('CHARS={0}\n'.format(stats)) | [
"def",
"main",
"(",
")",
":",
"desc",
"=",
"'Generate character statistics from a source tree'",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"'--src'",
",",
"dest",
"=",
"'src'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'The root of the source tree'",
")",
"parser",
".",
"add_argument",
"(",
"'--out'",
",",
"dest",
"=",
"'out'",
",",
"default",
"=",
"'chars.py'",
",",
"help",
"=",
"'The output filename'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"stats",
"=",
"generate_statistics",
"(",
"args",
".",
"src",
")",
"with",
"open",
"(",
"args",
".",
"out",
",",
"'wb'",
")",
"as",
"out_f",
":",
"out_f",
".",
"write",
"(",
"'CHARS={0}\\n'",
".",
"format",
"(",
"stats",
")",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/libs/metaparse/tools/benchmark/char_stat.py#L34-L55 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/benchmarks/analyze.py | python | main | (evg_api_config: str, task_id: str, suite: str) | Analyze performance results of Google Benchmarks. | Analyze performance results of Google Benchmarks. | [
"Analyze",
"performance",
"results",
"of",
"Google",
"Benchmarks",
"."
] | def main(evg_api_config: str, task_id: str, suite: str) -> None:
"""Analyze performance results of Google Benchmarks."""
enable_logging(verbose=False)
LOGGER.info("Looking for a baseline task...")
baseline_task_id = get_baseline_task_id(evg_api_config, task_id)
if baseline_task_id:
LOGGER.info("Found baseline task.", task_id=baseline_task_id)
else:
LOGGER.warning("")
LOGGER.warning("Baseline task not found in Evergreen.")
LOGGER.warning("If you think that this is unexpected,"
" please reach out to #server-testing")
LOGGER.warning("")
LOGGER.info("Getting performance data...")
cedar_api = CedarApi(evg_api_config)
current_data = cedar_api.get_perf_data_by_task_id(task_id)
baseline_data = []
try:
baseline_data = cedar_api.get_perf_data_by_task_id(baseline_task_id)
# Swallow HTTPError, since for a new benchmark there might not be historic perf data
except HTTPError as err:
if baseline_task_id:
LOGGER.warning("")
LOGGER.warning("Could not get performance data for a baseline task from Cedar",
task_id=baseline_task_id)
LOGGER.warning("", error=err)
LOGGER.warning("If you think that this is unexpected,"
" please reach out to #performance-tooling-users")
LOGGER.warning("")
LOGGER.info("Comparing the current performance data with a baseline data.")
result = compare_data(suite, current_data, baseline_data)
LOGGER.info(f"Performance analysis result:\n{result}")
if not result.passed:
LOGGER.error("Performance data delta has exceeded threshold.")
sys.exit(1) | [
"def",
"main",
"(",
"evg_api_config",
":",
"str",
",",
"task_id",
":",
"str",
",",
"suite",
":",
"str",
")",
"->",
"None",
":",
"enable_logging",
"(",
"verbose",
"=",
"False",
")",
"LOGGER",
".",
"info",
"(",
"\"Looking for a baseline task...\"",
")",
"baseline_task_id",
"=",
"get_baseline_task_id",
"(",
"evg_api_config",
",",
"task_id",
")",
"if",
"baseline_task_id",
":",
"LOGGER",
".",
"info",
"(",
"\"Found baseline task.\"",
",",
"task_id",
"=",
"baseline_task_id",
")",
"else",
":",
"LOGGER",
".",
"warning",
"(",
"\"\"",
")",
"LOGGER",
".",
"warning",
"(",
"\"Baseline task not found in Evergreen.\"",
")",
"LOGGER",
".",
"warning",
"(",
"\"If you think that this is unexpected,\"",
"\" please reach out to #server-testing\"",
")",
"LOGGER",
".",
"warning",
"(",
"\"\"",
")",
"LOGGER",
".",
"info",
"(",
"\"Getting performance data...\"",
")",
"cedar_api",
"=",
"CedarApi",
"(",
"evg_api_config",
")",
"current_data",
"=",
"cedar_api",
".",
"get_perf_data_by_task_id",
"(",
"task_id",
")",
"baseline_data",
"=",
"[",
"]",
"try",
":",
"baseline_data",
"=",
"cedar_api",
".",
"get_perf_data_by_task_id",
"(",
"baseline_task_id",
")",
"# Swallow HTTPError, since for a new benchmark there might not be historic perf data",
"except",
"HTTPError",
"as",
"err",
":",
"if",
"baseline_task_id",
":",
"LOGGER",
".",
"warning",
"(",
"\"\"",
")",
"LOGGER",
".",
"warning",
"(",
"\"Could not get performance data for a baseline task from Cedar\"",
",",
"task_id",
"=",
"baseline_task_id",
")",
"LOGGER",
".",
"warning",
"(",
"\"\"",
",",
"error",
"=",
"err",
")",
"LOGGER",
".",
"warning",
"(",
"\"If you think that this is unexpected,\"",
"\" please reach out to #performance-tooling-users\"",
")",
"LOGGER",
".",
"warning",
"(",
"\"\"",
")",
"LOGGER",
".",
"info",
"(",
"\"Comparing the current performance data with a baseline data.\"",
")",
"result",
"=",
"compare_data",
"(",
"suite",
",",
"current_data",
",",
"baseline_data",
")",
"LOGGER",
".",
"info",
"(",
"f\"Performance analysis result:\\n{result}\"",
")",
"if",
"not",
"result",
".",
"passed",
":",
"LOGGER",
".",
"error",
"(",
"\"Performance data delta has exceeded threshold.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/benchmarks/analyze.py#L49-L87 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py | python | _pairwise_callable | (X, Y, metric, force_all_finite=True, **kwds) | return out | Handle the callable case for pairwise_{distances,kernels} | Handle the callable case for pairwise_{distances,kernels} | [
"Handle",
"the",
"callable",
"case",
"for",
"pairwise_",
"{",
"distances",
"kernels",
"}"
] | def _pairwise_callable(X, Y, metric, force_all_finite=True, **kwds):
"""Handle the callable case for pairwise_{distances,kernels}
"""
X, Y = check_pairwise_arrays(X, Y, force_all_finite=force_all_finite)
if X is Y:
# Only calculate metric for upper triangle
out = np.zeros((X.shape[0], Y.shape[0]), dtype='float')
iterator = itertools.combinations(range(X.shape[0]), 2)
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
# Make symmetric
# NB: out += out.T will produce incorrect results
out = out + out.T
# Calculate diagonal
# NB: nonzero diagonals are allowed for both metrics and kernels
for i in range(X.shape[0]):
x = X[i]
out[i, i] = metric(x, x, **kwds)
else:
# Calculate all cells
out = np.empty((X.shape[0], Y.shape[0]), dtype='float')
iterator = itertools.product(range(X.shape[0]), range(Y.shape[0]))
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
return out | [
"def",
"_pairwise_callable",
"(",
"X",
",",
"Y",
",",
"metric",
",",
"force_all_finite",
"=",
"True",
",",
"*",
"*",
"kwds",
")",
":",
"X",
",",
"Y",
"=",
"check_pairwise_arrays",
"(",
"X",
",",
"Y",
",",
"force_all_finite",
"=",
"force_all_finite",
")",
"if",
"X",
"is",
"Y",
":",
"# Only calculate metric for upper triangle",
"out",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"Y",
".",
"shape",
"[",
"0",
"]",
")",
",",
"dtype",
"=",
"'float'",
")",
"iterator",
"=",
"itertools",
".",
"combinations",
"(",
"range",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
")",
",",
"2",
")",
"for",
"i",
",",
"j",
"in",
"iterator",
":",
"out",
"[",
"i",
",",
"j",
"]",
"=",
"metric",
"(",
"X",
"[",
"i",
"]",
",",
"Y",
"[",
"j",
"]",
",",
"*",
"*",
"kwds",
")",
"# Make symmetric",
"# NB: out += out.T will produce incorrect results",
"out",
"=",
"out",
"+",
"out",
".",
"T",
"# Calculate diagonal",
"# NB: nonzero diagonals are allowed for both metrics and kernels",
"for",
"i",
"in",
"range",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
")",
":",
"x",
"=",
"X",
"[",
"i",
"]",
"out",
"[",
"i",
",",
"i",
"]",
"=",
"metric",
"(",
"x",
",",
"x",
",",
"*",
"*",
"kwds",
")",
"else",
":",
"# Calculate all cells",
"out",
"=",
"np",
".",
"empty",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"Y",
".",
"shape",
"[",
"0",
"]",
")",
",",
"dtype",
"=",
"'float'",
")",
"iterator",
"=",
"itertools",
".",
"product",
"(",
"range",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
")",
",",
"range",
"(",
"Y",
".",
"shape",
"[",
"0",
"]",
")",
")",
"for",
"i",
",",
"j",
"in",
"iterator",
":",
"out",
"[",
"i",
",",
"j",
"]",
"=",
"metric",
"(",
"X",
"[",
"i",
"]",
",",
"Y",
"[",
"j",
"]",
",",
"*",
"*",
"kwds",
")",
"return",
"out"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py#L1365-L1394 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/base.py | python | ExtensionArray.view | (self, dtype=None) | return self[:] | Return a view on the array.
Parameters
----------
dtype : str, np.dtype, or ExtensionDtype, optional
Default None.
Returns
-------
ExtensionArray
A view of the :class:`ExtensionArray`. | Return a view on the array. | [
"Return",
"a",
"view",
"on",
"the",
"array",
"."
] | def view(self, dtype=None) -> Union[ABCExtensionArray, np.ndarray]:
"""
Return a view on the array.
Parameters
----------
dtype : str, np.dtype, or ExtensionDtype, optional
Default None.
Returns
-------
ExtensionArray
A view of the :class:`ExtensionArray`.
"""
# NB:
# - This must return a *new* object referencing the same data, not self.
# - The only case that *must* be implemented is with dtype=None,
# giving a view with the same dtype as self.
if dtype is not None:
raise NotImplementedError(dtype)
return self[:] | [
"def",
"view",
"(",
"self",
",",
"dtype",
"=",
"None",
")",
"->",
"Union",
"[",
"ABCExtensionArray",
",",
"np",
".",
"ndarray",
"]",
":",
"# NB:",
"# - This must return a *new* object referencing the same data, not self.",
"# - The only case that *must* be implemented is with dtype=None,",
"# giving a view with the same dtype as self.",
"if",
"dtype",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"dtype",
")",
"return",
"self",
"[",
":",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/base.py#L922-L942 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/agents/ppo/utility.py | python | diag_normal_logpdf | (mean, logstd, loc) | return tf.reduce_sum(constant + value, -1) | Log density of a normal with diagonal covariance. | Log density of a normal with diagonal covariance. | [
"Log",
"density",
"of",
"a",
"normal",
"with",
"diagonal",
"covariance",
"."
] | def diag_normal_logpdf(mean, logstd, loc):
"""Log density of a normal with diagonal covariance."""
constant = -0.5 * (math.log(2 * math.pi) + logstd)
value = -0.5 * ((loc - mean) / tf.exp(logstd))**2
return tf.reduce_sum(constant + value, -1) | [
"def",
"diag_normal_logpdf",
"(",
"mean",
",",
"logstd",
",",
"loc",
")",
":",
"constant",
"=",
"-",
"0.5",
"*",
"(",
"math",
".",
"log",
"(",
"2",
"*",
"math",
".",
"pi",
")",
"+",
"logstd",
")",
"value",
"=",
"-",
"0.5",
"*",
"(",
"(",
"loc",
"-",
"mean",
")",
"/",
"tf",
".",
"exp",
"(",
"logstd",
")",
")",
"**",
"2",
"return",
"tf",
".",
"reduce_sum",
"(",
"constant",
"+",
"value",
",",
"-",
"1",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/ppo/utility.py#L139-L143 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm._define_distance_to_clusters | (self, data) | Defines the Mahalanobis distance to the assigned Gaussian. | Defines the Mahalanobis distance to the assigned Gaussian. | [
"Defines",
"the",
"Mahalanobis",
"distance",
"to",
"the",
"assigned",
"Gaussian",
"."
] | def _define_distance_to_clusters(self, data):
"""Defines the Mahalanobis distance to the assigned Gaussian."""
# TODO(xavigonzalvo): reuse (input - mean) * cov^-1 * (input -
# mean) from log probability function.
self._all_scores = []
for shard in data:
all_scores = []
shard = tf.expand_dims(shard, 0)
for c in xrange(self._num_classes):
if self._covariance_type == FULL_COVARIANCE:
cov = self._covs[c, :, :]
elif self._covariance_type == DIAG_COVARIANCE:
cov = tf.diag(self._covs[c, :])
inverse = tf.matrix_inverse(cov + self._min_var)
inv_cov = tf.tile(
tf.expand_dims(inverse, 0),
tf.pack([self._num_examples, 1, 1]))
diff = tf.transpose(shard - self._means[c, :, :], perm=[1, 0, 2])
m_left = tf.batch_matmul(diff, inv_cov)
all_scores.append(tf.sqrt(tf.batch_matmul(
m_left, tf.transpose(diff, perm=[0, 2, 1])
)))
self._all_scores.append(tf.reshape(
tf.concat(1, all_scores),
tf.pack([self._num_examples, self._num_classes])))
# Distance to the associated class.
self._all_scores = tf.concat(0, self._all_scores)
assignments = tf.concat(0, self.assignments())
rows = tf.to_int64(tf.range(0, self._num_examples))
indices = tf.concat(1, [tf.expand_dims(rows, 1),
tf.expand_dims(assignments, 1)])
self._scores = tf.gather_nd(self._all_scores, indices) | [
"def",
"_define_distance_to_clusters",
"(",
"self",
",",
"data",
")",
":",
"# TODO(xavigonzalvo): reuse (input - mean) * cov^-1 * (input -",
"# mean) from log probability function.",
"self",
".",
"_all_scores",
"=",
"[",
"]",
"for",
"shard",
"in",
"data",
":",
"all_scores",
"=",
"[",
"]",
"shard",
"=",
"tf",
".",
"expand_dims",
"(",
"shard",
",",
"0",
")",
"for",
"c",
"in",
"xrange",
"(",
"self",
".",
"_num_classes",
")",
":",
"if",
"self",
".",
"_covariance_type",
"==",
"FULL_COVARIANCE",
":",
"cov",
"=",
"self",
".",
"_covs",
"[",
"c",
",",
":",
",",
":",
"]",
"elif",
"self",
".",
"_covariance_type",
"==",
"DIAG_COVARIANCE",
":",
"cov",
"=",
"tf",
".",
"diag",
"(",
"self",
".",
"_covs",
"[",
"c",
",",
":",
"]",
")",
"inverse",
"=",
"tf",
".",
"matrix_inverse",
"(",
"cov",
"+",
"self",
".",
"_min_var",
")",
"inv_cov",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"inverse",
",",
"0",
")",
",",
"tf",
".",
"pack",
"(",
"[",
"self",
".",
"_num_examples",
",",
"1",
",",
"1",
"]",
")",
")",
"diff",
"=",
"tf",
".",
"transpose",
"(",
"shard",
"-",
"self",
".",
"_means",
"[",
"c",
",",
":",
",",
":",
"]",
",",
"perm",
"=",
"[",
"1",
",",
"0",
",",
"2",
"]",
")",
"m_left",
"=",
"tf",
".",
"batch_matmul",
"(",
"diff",
",",
"inv_cov",
")",
"all_scores",
".",
"append",
"(",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"batch_matmul",
"(",
"m_left",
",",
"tf",
".",
"transpose",
"(",
"diff",
",",
"perm",
"=",
"[",
"0",
",",
"2",
",",
"1",
"]",
")",
")",
")",
")",
"self",
".",
"_all_scores",
".",
"append",
"(",
"tf",
".",
"reshape",
"(",
"tf",
".",
"concat",
"(",
"1",
",",
"all_scores",
")",
",",
"tf",
".",
"pack",
"(",
"[",
"self",
".",
"_num_examples",
",",
"self",
".",
"_num_classes",
"]",
")",
")",
")",
"# Distance to the associated class.",
"self",
".",
"_all_scores",
"=",
"tf",
".",
"concat",
"(",
"0",
",",
"self",
".",
"_all_scores",
")",
"assignments",
"=",
"tf",
".",
"concat",
"(",
"0",
",",
"self",
".",
"assignments",
"(",
")",
")",
"rows",
"=",
"tf",
".",
"to_int64",
"(",
"tf",
".",
"range",
"(",
"0",
",",
"self",
".",
"_num_examples",
")",
")",
"indices",
"=",
"tf",
".",
"concat",
"(",
"1",
",",
"[",
"tf",
".",
"expand_dims",
"(",
"rows",
",",
"1",
")",
",",
"tf",
".",
"expand_dims",
"(",
"assignments",
",",
"1",
")",
"]",
")",
"self",
".",
"_scores",
"=",
"tf",
".",
"gather_nd",
"(",
"self",
".",
"_all_scores",
",",
"indices",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L376-L408 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/tz.py | python | tzutc.is_ambiguous | (self, dt) | return False | Whether or not the "wall time" of a given datetime is ambiguous in this
zone.
:param dt:
A :py:class:`datetime.datetime`, naive or time zone aware.
:return:
Returns ``True`` if ambiguous, ``False`` otherwise.
.. versionadded:: 2.6.0 | Whether or not the "wall time" of a given datetime is ambiguous in this
zone. | [
"Whether",
"or",
"not",
"the",
"wall",
"time",
"of",
"a",
"given",
"datetime",
"is",
"ambiguous",
"in",
"this",
"zone",
"."
] | def is_ambiguous(self, dt):
"""
Whether or not the "wall time" of a given datetime is ambiguous in this
zone.
:param dt:
A :py:class:`datetime.datetime`, naive or time zone aware.
:return:
Returns ``True`` if ambiguous, ``False`` otherwise.
.. versionadded:: 2.6.0
"""
return False | [
"def",
"is_ambiguous",
"(",
"self",
",",
"dt",
")",
":",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/tz.py#L46-L60 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | PseudoDC.DrawRectangleRect | (*args, **kwargs) | return _gdi_.PseudoDC_DrawRectangleRect(*args, **kwargs) | DrawRectangleRect(self, Rect rect)
Draws a rectangle with the given top left corner, and with the given
size. The current pen is used for the outline and the current brush
for filling the shape. | DrawRectangleRect(self, Rect rect) | [
"DrawRectangleRect",
"(",
"self",
"Rect",
"rect",
")"
] | def DrawRectangleRect(*args, **kwargs):
"""
DrawRectangleRect(self, Rect rect)
Draws a rectangle with the given top left corner, and with the given
size. The current pen is used for the outline and the current brush
for filling the shape.
"""
return _gdi_.PseudoDC_DrawRectangleRect(*args, **kwargs) | [
"def",
"DrawRectangleRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"PseudoDC_DrawRectangleRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7899-L7907 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.cursor_save | (self) | Save current cursor position. | Save current cursor position. | [
"Save",
"current",
"cursor",
"position",
"."
] | def cursor_save (self): # <ESC>[s
'''Save current cursor position.'''
self.cursor_save_attrs() | [
"def",
"cursor_save",
"(",
"self",
")",
":",
"# <ESC>[s",
"self",
".",
"cursor_save_attrs",
"(",
")"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L318-L321 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/posixpath.py | python | samestat | (s1, s2) | return s1.st_ino == s2.st_ino and \
s1.st_dev == s2.st_dev | Test whether two stat buffers reference the same file | Test whether two stat buffers reference the same file | [
"Test",
"whether",
"two",
"stat",
"buffers",
"reference",
"the",
"same",
"file"
] | def samestat(s1, s2):
"""Test whether two stat buffers reference the same file"""
return s1.st_ino == s2.st_ino and \
s1.st_dev == s2.st_dev | [
"def",
"samestat",
"(",
"s1",
",",
"s2",
")",
":",
"return",
"s1",
".",
"st_ino",
"==",
"s2",
".",
"st_ino",
"and",
"s1",
".",
"st_dev",
"==",
"s2",
".",
"st_dev"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/posixpath.py#L170-L173 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/FrameWork.py | python | Window.do_postopen | (self) | Tell our parent we exist | Tell our parent we exist | [
"Tell",
"our",
"parent",
"we",
"exist"
] | def do_postopen(self):
"""Tell our parent we exist"""
self.parent.appendwindow(self.wid, self) | [
"def",
"do_postopen",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"appendwindow",
"(",
"self",
".",
"wid",
",",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/FrameWork.py#L761-L763 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/ext-py/thrift_sasl-0.4.3/thrift_sasl/__init__.py | python | TSaslClientTransport.__init__ | (self, sasl_client_factory, mechanism, trans) | @param sasl_client_factory: a callable that returns a new sasl.Client object
@param mechanism: the SASL mechanism (e.g. "GSSAPI")
@param trans: the underlying transport over which to communicate. | [] | def __init__(self, sasl_client_factory, mechanism, trans):
"""
@param sasl_client_factory: a callable that returns a new sasl.Client object
@param mechanism: the SASL mechanism (e.g. "GSSAPI")
@param trans: the underlying transport over which to communicate.
"""
self._trans = trans
self.sasl_client_factory = sasl_client_factory
self.sasl = None
self.mechanism = mechanism
self.__wbuf = BufferIO()
self.__rbuf = BufferIO()
self.opened = False
self.encode = None | [
"def",
"__init__",
"(",
"self",
",",
"sasl_client_factory",
",",
"mechanism",
",",
"trans",
")",
":",
"self",
".",
"_trans",
"=",
"trans",
"self",
".",
"sasl_client_factory",
"=",
"sasl_client_factory",
"self",
".",
"sasl",
"=",
"None",
"self",
".",
"mechanism",
"=",
"mechanism",
"self",
".",
"__wbuf",
"=",
"BufferIO",
"(",
")",
"self",
".",
"__rbuf",
"=",
"BufferIO",
"(",
")",
"self",
".",
"opened",
"=",
"False",
"self",
".",
"encode",
"=",
"None"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/ext-py/thrift_sasl-0.4.3/thrift_sasl/__init__.py#L46-L59 | |||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.UpperCase | (*args, **kwargs) | return _stc.StyledTextCtrl_UpperCase(*args, **kwargs) | UpperCase(self)
Transform the selection to upper case. | UpperCase(self) | [
"UpperCase",
"(",
"self",
")"
] | def UpperCase(*args, **kwargs):
"""
UpperCase(self)
Transform the selection to upper case.
"""
return _stc.StyledTextCtrl_UpperCase(*args, **kwargs) | [
"def",
"UpperCase",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_UpperCase",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4676-L4682 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/build_sdk.py | python | LocalHTTPServer.GetURL | (self, rel_url) | return 'http://localhost:%d/%s' % (self.port, rel_url) | Get the full url for a file on the local HTTP server.
Args:
rel_url: A URL fragment to convert to a full URL. For example,
GetURL('foobar.baz') -> 'http://localhost:1234/foobar.baz' | Get the full url for a file on the local HTTP server. | [
"Get",
"the",
"full",
"url",
"for",
"a",
"file",
"on",
"the",
"local",
"HTTP",
"server",
"."
] | def GetURL(self, rel_url):
"""Get the full url for a file on the local HTTP server.
Args:
rel_url: A URL fragment to convert to a full URL. For example,
GetURL('foobar.baz') -> 'http://localhost:1234/foobar.baz'
"""
return 'http://localhost:%d/%s' % (self.port, rel_url) | [
"def",
"GetURL",
"(",
"self",
",",
"rel_url",
")",
":",
"return",
"'http://localhost:%d/%s'",
"%",
"(",
"self",
".",
"port",
",",
"rel_url",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/build_sdk.py#L107-L114 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py | python | ConfigDialog.create_extension_frame | (self, ext_name) | return | Create a frame holding the widgets to configure one extension | Create a frame holding the widgets to configure one extension | [
"Create",
"a",
"frame",
"holding",
"the",
"widgets",
"to",
"configure",
"one",
"extension"
] | def create_extension_frame(self, ext_name):
"""Create a frame holding the widgets to configure one extension"""
f = VerticalScrolledFrame(self.details_frame, height=250, width=250)
self.config_frame[ext_name] = f
entry_area = f.interior
# Create an entry for each configuration option.
for row, opt in enumerate(self.extensions[ext_name]):
# Create a row with a label and entry/checkbutton.
label = Label(entry_area, text=opt['name'])
label.grid(row=row, column=0, sticky=NW)
var = opt['var']
if opt['type'] == 'bool':
Checkbutton(entry_area, variable=var,
onvalue='True', offvalue='False', width=8
).grid(row=row, column=1, sticky=W, padx=7)
elif opt['type'] == 'int':
Entry(entry_area, textvariable=var, validate='key',
validatecommand=(self.is_int, '%P'), width=10
).grid(row=row, column=1, sticky=NSEW, padx=7)
else: # type == 'str'
# Limit size to fit non-expanding space with larger font.
Entry(entry_area, textvariable=var, width=15
).grid(row=row, column=1, sticky=NSEW, padx=7)
return | [
"def",
"create_extension_frame",
"(",
"self",
",",
"ext_name",
")",
":",
"f",
"=",
"VerticalScrolledFrame",
"(",
"self",
".",
"details_frame",
",",
"height",
"=",
"250",
",",
"width",
"=",
"250",
")",
"self",
".",
"config_frame",
"[",
"ext_name",
"]",
"=",
"f",
"entry_area",
"=",
"f",
".",
"interior",
"# Create an entry for each configuration option.",
"for",
"row",
",",
"opt",
"in",
"enumerate",
"(",
"self",
".",
"extensions",
"[",
"ext_name",
"]",
")",
":",
"# Create a row with a label and entry/checkbutton.",
"label",
"=",
"Label",
"(",
"entry_area",
",",
"text",
"=",
"opt",
"[",
"'name'",
"]",
")",
"label",
".",
"grid",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"0",
",",
"sticky",
"=",
"NW",
")",
"var",
"=",
"opt",
"[",
"'var'",
"]",
"if",
"opt",
"[",
"'type'",
"]",
"==",
"'bool'",
":",
"Checkbutton",
"(",
"entry_area",
",",
"variable",
"=",
"var",
",",
"onvalue",
"=",
"'True'",
",",
"offvalue",
"=",
"'False'",
",",
"width",
"=",
"8",
")",
".",
"grid",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"W",
",",
"padx",
"=",
"7",
")",
"elif",
"opt",
"[",
"'type'",
"]",
"==",
"'int'",
":",
"Entry",
"(",
"entry_area",
",",
"textvariable",
"=",
"var",
",",
"validate",
"=",
"'key'",
",",
"validatecommand",
"=",
"(",
"self",
".",
"is_int",
",",
"'%P'",
")",
",",
"width",
"=",
"10",
")",
".",
"grid",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"NSEW",
",",
"padx",
"=",
"7",
")",
"else",
":",
"# type == 'str'",
"# Limit size to fit non-expanding space with larger font.",
"Entry",
"(",
"entry_area",
",",
"textvariable",
"=",
"var",
",",
"width",
"=",
"15",
")",
".",
"grid",
"(",
"row",
"=",
"row",
",",
"column",
"=",
"1",
",",
"sticky",
"=",
"NSEW",
",",
"padx",
"=",
"7",
")",
"return"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py#L368-L392 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_PolicyCommandCode_REQUEST.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeInt(self.code) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeInt",
"(",
"self",
".",
"code",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L14701-L14703 | ||
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | docs/examples/use_cases/tensorflow/efficientdet/pipeline/anchors_utils/box_list.py | python | BoxList.set | (self, boxes) | Convenience function for setting box coordinates.
Args:
boxes: a tensor of shape [N, 4] representing box corners
Raises:
ValueError: if invalid dimensions for bbox data | Convenience function for setting box coordinates. | [
"Convenience",
"function",
"for",
"setting",
"box",
"coordinates",
"."
] | def set(self, boxes):
"""Convenience function for setting box coordinates.
Args:
boxes: a tensor of shape [N, 4] representing box corners
Raises:
ValueError: if invalid dimensions for bbox data
"""
if len(boxes.get_shape()) != 2 or boxes.get_shape()[-1] != 4:
raise ValueError("Invalid dimensions for box data.")
self.data["boxes"] = boxes | [
"def",
"set",
"(",
"self",
",",
"boxes",
")",
":",
"if",
"len",
"(",
"boxes",
".",
"get_shape",
"(",
")",
")",
"!=",
"2",
"or",
"boxes",
".",
"get_shape",
"(",
")",
"[",
"-",
"1",
"]",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"Invalid dimensions for box data.\"",
")",
"self",
".",
"data",
"[",
"\"boxes\"",
"]",
"=",
"boxes"
] | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/pipeline/anchors_utils/box_list.py#L108-L119 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/generic.py | python | NDFrame.asfreq | (self, freq, method=None, how=None, normalize=False,
fill_value=None) | return asfreq(self, freq, method=method, how=how, normalize=normalize,
fill_value=fill_value) | Convert TimeSeries to specified frequency.
Optionally provide filling method to pad/backfill missing values.
Returns the original data conformed to a new index with the specified
frequency. ``resample`` is more appropriate if an operation, such as
summarization, is necessary to represent the data at the new frequency.
Parameters
----------
freq : DateOffset object, or string
method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
Method to use for filling holes in reindexed Series (note this
does not fill NaNs that already were present):
* 'pad' / 'ffill': propagate last valid observation forward to next
valid
* 'backfill' / 'bfill': use NEXT valid observation to fill
how : {'start', 'end'}, default end
For PeriodIndex only, see PeriodIndex.asfreq
normalize : bool, default False
Whether to reset output index to midnight
fill_value : scalar, optional
Value to use for missing values, applied during upsampling (note
this does not fill NaNs that already were present).
.. versionadded:: 0.20.0
Returns
-------
converted : same type as caller
See Also
--------
reindex
Notes
-----
To learn more about the frequency strings, please see `this link
<http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
Examples
--------
Start by creating a series with 4 one minute timestamps.
>>> index = pd.date_range('1/1/2000', periods=4, freq='T')
>>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
>>> df = pd.DataFrame({'s':series})
>>> df
s
2000-01-01 00:00:00 0.0
2000-01-01 00:01:00 NaN
2000-01-01 00:02:00 2.0
2000-01-01 00:03:00 3.0
Upsample the series into 30 second bins.
>>> df.asfreq(freq='30S')
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 NaN
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 NaN
2000-01-01 00:03:00 3.0
Upsample again, providing a ``fill value``.
>>> df.asfreq(freq='30S', fill_value=9.0)
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 9.0
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 9.0
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 9.0
2000-01-01 00:03:00 3.0
Upsample again, providing a ``method``.
>>> df.asfreq(freq='30S', method='bfill')
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 2.0
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 3.0
2000-01-01 00:03:00 3.0 | Convert TimeSeries to specified frequency. | [
"Convert",
"TimeSeries",
"to",
"specified",
"frequency",
"."
] | def asfreq(self, freq, method=None, how=None, normalize=False,
fill_value=None):
"""
Convert TimeSeries to specified frequency.
Optionally provide filling method to pad/backfill missing values.
Returns the original data conformed to a new index with the specified
frequency. ``resample`` is more appropriate if an operation, such as
summarization, is necessary to represent the data at the new frequency.
Parameters
----------
freq : DateOffset object, or string
method : {'backfill'/'bfill', 'pad'/'ffill'}, default None
Method to use for filling holes in reindexed Series (note this
does not fill NaNs that already were present):
* 'pad' / 'ffill': propagate last valid observation forward to next
valid
* 'backfill' / 'bfill': use NEXT valid observation to fill
how : {'start', 'end'}, default end
For PeriodIndex only, see PeriodIndex.asfreq
normalize : bool, default False
Whether to reset output index to midnight
fill_value : scalar, optional
Value to use for missing values, applied during upsampling (note
this does not fill NaNs that already were present).
.. versionadded:: 0.20.0
Returns
-------
converted : same type as caller
See Also
--------
reindex
Notes
-----
To learn more about the frequency strings, please see `this link
<http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
Examples
--------
Start by creating a series with 4 one minute timestamps.
>>> index = pd.date_range('1/1/2000', periods=4, freq='T')
>>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)
>>> df = pd.DataFrame({'s':series})
>>> df
s
2000-01-01 00:00:00 0.0
2000-01-01 00:01:00 NaN
2000-01-01 00:02:00 2.0
2000-01-01 00:03:00 3.0
Upsample the series into 30 second bins.
>>> df.asfreq(freq='30S')
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 NaN
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 NaN
2000-01-01 00:03:00 3.0
Upsample again, providing a ``fill value``.
>>> df.asfreq(freq='30S', fill_value=9.0)
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 9.0
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 9.0
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 9.0
2000-01-01 00:03:00 3.0
Upsample again, providing a ``method``.
>>> df.asfreq(freq='30S', method='bfill')
s
2000-01-01 00:00:00 0.0
2000-01-01 00:00:30 NaN
2000-01-01 00:01:00 NaN
2000-01-01 00:01:30 2.0
2000-01-01 00:02:00 2.0
2000-01-01 00:02:30 3.0
2000-01-01 00:03:00 3.0
"""
from pandas.core.resample import asfreq
return asfreq(self, freq, method=method, how=how, normalize=normalize,
fill_value=fill_value) | [
"def",
"asfreq",
"(",
"self",
",",
"freq",
",",
"method",
"=",
"None",
",",
"how",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"fill_value",
"=",
"None",
")",
":",
"from",
"pandas",
".",
"core",
".",
"resample",
"import",
"asfreq",
"return",
"asfreq",
"(",
"self",
",",
"freq",
",",
"method",
"=",
"method",
",",
"how",
"=",
"how",
",",
"normalize",
"=",
"normalize",
",",
"fill_value",
"=",
"fill_value",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L7634-L7731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.