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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/devicearray.py | python | DeviceNDArray.reshape | (self, *newshape, **kws) | Reshape the array without changing its contents, similarly to
:meth:`numpy.ndarray.reshape`. Example::
d_arr = d_arr.reshape(20, 50, order='F') | Reshape the array without changing its contents, similarly to
:meth:`numpy.ndarray.reshape`. Example:: | [
"Reshape",
"the",
"array",
"without",
"changing",
"its",
"contents",
"similarly",
"to",
":",
"meth",
":",
"numpy",
".",
"ndarray",
".",
"reshape",
".",
"Example",
"::"
] | def reshape(self, *newshape, **kws):
"""
Reshape the array without changing its contents, similarly to
:meth:`numpy.ndarray.reshape`. Example::
d_arr = d_arr.reshape(20, 50, order='F')
"""
if len(newshape) == 1 and isinstance(newshape[0], (tuple, list)):
newshape = newshape[0]
cls = type(self)
if newshape == self.shape:
# nothing to do
return cls(shape=self.shape, strides=self.strides,
dtype=self.dtype, dgpu_data=self.dgpu_data)
newarr, extents = self._dummy.reshape(*newshape, **kws)
if extents == [self._dummy.extent]:
return cls(shape=newarr.shape, strides=newarr.strides,
dtype=self.dtype, dgpu_data=self.dgpu_data)
else:
raise NotImplementedError("operation requires copying") | [
"def",
"reshape",
"(",
"self",
",",
"*",
"newshape",
",",
"*",
"*",
"kws",
")",
":",
"if",
"len",
"(",
"newshape",
")",
"==",
"1",
"and",
"isinstance",
"(",
"newshape",
"[",
"0",
"]",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"newshape",
"=",
"newshape",
"[",
"0",
"]",
"cls",
"=",
"type",
"(",
"self",
")",
"if",
"newshape",
"==",
"self",
".",
"shape",
":",
"# nothing to do",
"return",
"cls",
"(",
"shape",
"=",
"self",
".",
"shape",
",",
"strides",
"=",
"self",
".",
"strides",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"dgpu_data",
"=",
"self",
".",
"dgpu_data",
")",
"newarr",
",",
"extents",
"=",
"self",
".",
"_dummy",
".",
"reshape",
"(",
"*",
"newshape",
",",
"*",
"*",
"kws",
")",
"if",
"extents",
"==",
"[",
"self",
".",
"_dummy",
".",
"extent",
"]",
":",
"return",
"cls",
"(",
"shape",
"=",
"newarr",
".",
"shape",
",",
"strides",
"=",
"newarr",
".",
"strides",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"dgpu_data",
"=",
"self",
".",
"dgpu_data",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"operation requires copying\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/devicearray.py#L268-L290 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | PBXProject.RootGroupsTakeOverOnlyChildren | (self, recurse=False) | Calls TakeOverOnlyChild for all groups in the main group. | Calls TakeOverOnlyChild for all groups in the main group. | [
"Calls",
"TakeOverOnlyChild",
"for",
"all",
"groups",
"in",
"the",
"main",
"group",
"."
] | def RootGroupsTakeOverOnlyChildren(self, recurse=False):
"""Calls TakeOverOnlyChild for all groups in the main group."""
for group in self._properties["mainGroup"]._properties["children"]:
if isinstance(group, PBXGroup):
group.TakeOverOnlyChild(recurse) | [
"def",
"RootGroupsTakeOverOnlyChildren",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"for",
"group",
"in",
"self",
".",
"_properties",
"[",
"\"mainGroup\"",
"]",
".",
"_properties",
"[",
"\"children\"",
"]",
":",
"if",
"isinstance",
"(",
"group",
",",
"PBXGroup",
")",
":",
"group",
".",
"TakeOverOnlyChild",
"(",
"recurse",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L2886-L2891 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Source/bindings/scripts/v8_utilities.py | python | ExposureSet.issubset | (self, other) | return self_set.issubset(other_set) | Returns true if |self|'s exposure set is a subset of
|other|'s exposure set. This function doesn't care about
RuntimeEnabled. | Returns true if |self|'s exposure set is a subset of
|other|'s exposure set. This function doesn't care about
RuntimeEnabled. | [
"Returns",
"true",
"if",
"|self|",
"s",
"exposure",
"set",
"is",
"a",
"subset",
"of",
"|other|",
"s",
"exposure",
"set",
".",
"This",
"function",
"doesn",
"t",
"care",
"about",
"RuntimeEnabled",
"."
] | def issubset(self, other):
"""Returns true if |self|'s exposure set is a subset of
|other|'s exposure set. This function doesn't care about
RuntimeEnabled."""
self_set = self._extended(set(e.exposed for e in self.exposures))
other_set = self._extended(set(e.exposed for e in other.exposures))
return self_set.issubset(other_set) | [
"def",
"issubset",
"(",
"self",
",",
"other",
")",
":",
"self_set",
"=",
"self",
".",
"_extended",
"(",
"set",
"(",
"e",
".",
"exposed",
"for",
"e",
"in",
"self",
".",
"exposures",
")",
")",
"other_set",
"=",
"self",
".",
"_extended",
"(",
"set",
"(",
"e",
".",
"exposed",
"for",
"e",
"in",
"other",
".",
"exposures",
")",
")",
"return",
"self_set",
".",
"issubset",
"(",
"other_set",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/v8_utilities.py#L267-L273 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py | python | CheckpointSaver.__init__ | (self,
checkpoint_dir,
save_secs=None,
save_steps=None,
saver=None,
checkpoint_basename="model.ckpt",
scaffold=None) | Initialize CheckpointSaver monitor.
Args:
checkpoint_dir: `str`, base directory for the checkpoint files.
save_secs: `int`, save every N secs.
save_steps: `int`, save every N steps.
saver: `Saver` object, used for saving.
checkpoint_basename: `str`, base name for the checkpoint files.
scaffold: `Scaffold`, use to get saver object.
Raises:
ValueError: If both `save_steps` and `save_secs` are not `None`.
ValueError: If both `save_steps` and `save_secs` are `None`. | Initialize CheckpointSaver monitor. | [
"Initialize",
"CheckpointSaver",
"monitor",
"."
] | def __init__(self,
checkpoint_dir,
save_secs=None,
save_steps=None,
saver=None,
checkpoint_basename="model.ckpt",
scaffold=None):
"""Initialize CheckpointSaver monitor.
Args:
checkpoint_dir: `str`, base directory for the checkpoint files.
save_secs: `int`, save every N secs.
save_steps: `int`, save every N steps.
saver: `Saver` object, used for saving.
checkpoint_basename: `str`, base name for the checkpoint files.
scaffold: `Scaffold`, use to get saver object.
Raises:
ValueError: If both `save_steps` and `save_secs` are not `None`.
ValueError: If both `save_steps` and `save_secs` are `None`.
"""
logging.info("Create CheckpointSaver")
super(CheckpointSaver, self).__init__()
self._saver = saver
self._summary_writer = SummaryWriterCache.get(checkpoint_dir)
self._save_path = os.path.join(checkpoint_dir, checkpoint_basename)
self._scaffold = scaffold
self._save_secs = save_secs
self._save_steps = save_steps
self._last_saved_time = None
self._last_begin_step = None
self._last_saved_step = None
if save_steps is None and save_secs is None:
raise ValueError("Either save_steps or save_secs should be provided")
if (save_steps is not None) and (save_secs is not None):
raise ValueError("Can not provide both save_steps and save_secs.") | [
"def",
"__init__",
"(",
"self",
",",
"checkpoint_dir",
",",
"save_secs",
"=",
"None",
",",
"save_steps",
"=",
"None",
",",
"saver",
"=",
"None",
",",
"checkpoint_basename",
"=",
"\"model.ckpt\"",
",",
"scaffold",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"Create CheckpointSaver\"",
")",
"super",
"(",
"CheckpointSaver",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_saver",
"=",
"saver",
"self",
".",
"_summary_writer",
"=",
"SummaryWriterCache",
".",
"get",
"(",
"checkpoint_dir",
")",
"self",
".",
"_save_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"checkpoint_dir",
",",
"checkpoint_basename",
")",
"self",
".",
"_scaffold",
"=",
"scaffold",
"self",
".",
"_save_secs",
"=",
"save_secs",
"self",
".",
"_save_steps",
"=",
"save_steps",
"self",
".",
"_last_saved_time",
"=",
"None",
"self",
".",
"_last_begin_step",
"=",
"None",
"self",
".",
"_last_saved_step",
"=",
"None",
"if",
"save_steps",
"is",
"None",
"and",
"save_secs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Either save_steps or save_secs should be provided\"",
")",
"if",
"(",
"save_steps",
"is",
"not",
"None",
")",
"and",
"(",
"save_secs",
"is",
"not",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"Can not provide both save_steps and save_secs.\"",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L938-L974 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py | python | get_meth_func | (obj) | Return method function object | Return method function object | [
"Return",
"method",
"function",
"object"
] | def get_meth_func(obj):
"""Return method function object"""
if PY2:
# Python 2
return obj.im_func
else:
# Python 3
return obj.__func__ | [
"def",
"get_meth_func",
"(",
"obj",
")",
":",
"if",
"PY2",
":",
"# Python 2",
"return",
"obj",
".",
"im_func",
"else",
":",
"# Python 3",
"return",
"obj",
".",
"__func__"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py#L178-L185 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Text.mark_unset | (self, *markNames) | Delete all marks in MARKNAMES. | Delete all marks in MARKNAMES. | [
"Delete",
"all",
"marks",
"in",
"MARKNAMES",
"."
] | def mark_unset(self, *markNames):
"""Delete all marks in MARKNAMES."""
self.tk.call((self._w, 'mark', 'unset') + markNames) | [
"def",
"mark_unset",
"(",
"self",
",",
"*",
"markNames",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'mark'",
",",
"'unset'",
")",
"+",
"markNames",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3061-L3063 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/asyncio/sslproto.py | python | SSLProtocol.connection_lost | (self, exc) | Called when the low-level connection is lost or closed.
The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was
aborted or closed). | Called when the low-level connection is lost or closed. | [
"Called",
"when",
"the",
"low",
"-",
"level",
"connection",
"is",
"lost",
"or",
"closed",
"."
] | def connection_lost(self, exc):
"""Called when the low-level connection is lost or closed.
The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was
aborted or closed).
"""
if self._session_established:
self._session_established = False
self._loop.call_soon(self._app_protocol.connection_lost, exc)
else:
# Most likely an exception occurred while in SSL handshake.
# Just mark the app transport as closed so that its __del__
# doesn't complain.
if self._app_transport is not None:
self._app_transport._closed = True
self._transport = None
self._app_transport = None
if getattr(self, '_handshake_timeout_handle', None):
self._handshake_timeout_handle.cancel()
self._wakeup_waiter(exc)
self._app_protocol = None
self._sslpipe = None | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
")",
":",
"if",
"self",
".",
"_session_established",
":",
"self",
".",
"_session_established",
"=",
"False",
"self",
".",
"_loop",
".",
"call_soon",
"(",
"self",
".",
"_app_protocol",
".",
"connection_lost",
",",
"exc",
")",
"else",
":",
"# Most likely an exception occurred while in SSL handshake.",
"# Just mark the app transport as closed so that its __del__",
"# doesn't complain.",
"if",
"self",
".",
"_app_transport",
"is",
"not",
"None",
":",
"self",
".",
"_app_transport",
".",
"_closed",
"=",
"True",
"self",
".",
"_transport",
"=",
"None",
"self",
".",
"_app_transport",
"=",
"None",
"if",
"getattr",
"(",
"self",
",",
"'_handshake_timeout_handle'",
",",
"None",
")",
":",
"self",
".",
"_handshake_timeout_handle",
".",
"cancel",
"(",
")",
"self",
".",
"_wakeup_waiter",
"(",
"exc",
")",
"self",
".",
"_app_protocol",
"=",
"None",
"self",
".",
"_sslpipe",
"=",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/sslproto.py#L484-L506 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.IndicatorSetUnder | (*args, **kwargs) | return _stc.StyledTextCtrl_IndicatorSetUnder(*args, **kwargs) | IndicatorSetUnder(self, int indic, bool under)
Set an indicator to draw under text or over(default). | IndicatorSetUnder(self, int indic, bool under) | [
"IndicatorSetUnder",
"(",
"self",
"int",
"indic",
"bool",
"under",
")"
] | def IndicatorSetUnder(*args, **kwargs):
"""
IndicatorSetUnder(self, int indic, bool under)
Set an indicator to draw under text or over(default).
"""
return _stc.StyledTextCtrl_IndicatorSetUnder(*args, **kwargs) | [
"def",
"IndicatorSetUnder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_IndicatorSetUnder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2897-L2903 | |
BVLC/caffe | 9b891540183ddc834a02b2bd81b31afae71b2153 | python/caffe/coord_map.py | python | crop_params | (fn) | return (axis, offset) | Extract the crop layer parameters with defaults. | Extract the crop layer parameters with defaults. | [
"Extract",
"the",
"crop",
"layer",
"parameters",
"with",
"defaults",
"."
] | def crop_params(fn):
"""
Extract the crop layer parameters with defaults.
"""
params = fn.params.get('crop_param', fn.params)
axis = params.get('axis', 2) # default to spatial crop for N, C, H, W
offset = np.array(params.get('offset', 0), ndmin=1)
return (axis, offset) | [
"def",
"crop_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'crop_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"2",
")",
"# default to spatial crop for N, C, H, W",
"offset",
"=",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
",",
"ndmin",
"=",
"1",
")",
"return",
"(",
"axis",
",",
"offset",
")"
] | https://github.com/BVLC/caffe/blob/9b891540183ddc834a02b2bd81b31afae71b2153/python/caffe/coord_map.py#L40-L47 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | TypeHandler.WriteCmdSizeTest | (self, func, file) | Writes the size test for a command. | Writes the size test for a command. | [
"Writes",
"the",
"size",
"test",
"for",
"a",
"command",
"."
] | def WriteCmdSizeTest(self, func, file):
"""Writes the size test for a command."""
file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n") | [
"def",
"WriteCmdSizeTest",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"file",
".",
"Write",
"(",
"\" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\\n\"",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L1945-L1947 | ||
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | scripts/cpp_lint.py | python | CheckEmptyBlockBody | (filename, clean_lines, linenum, error) | Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Look for empty loop/conditional body with only a single semicolon. | [
"Look",
"for",
"empty",
"loop",
"/",
"conditional",
"body",
"with",
"only",
"a",
"single",
"semicolon",
"."
] | def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue') | [
"def",
"CheckEmptyBlockBody",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Search for loop keywords at the beginning of the line. Because only",
"# whitespaces are allowed before the keywords, this will also ignore most",
"# do-while-loops, since those lines should start with closing brace.",
"#",
"# We also check \"if\" blocks here, since an empty conditional block",
"# is likely an error.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"matched",
"=",
"Match",
"(",
"r'\\s*(for|while|if)\\s*\\('",
",",
"line",
")",
"if",
"matched",
":",
"# Find the end of the conditional expression",
"(",
"end_line",
",",
"end_linenum",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"line",
".",
"find",
"(",
"'('",
")",
")",
"# Output warning if what follows the condition expression is a semicolon.",
"# No warning for all other cases, including whitespace or newline, since we",
"# have a separate check for semicolons preceded by whitespace.",
"if",
"end_pos",
">=",
"0",
"and",
"Match",
"(",
"r';'",
",",
"end_line",
"[",
"end_pos",
":",
"]",
")",
":",
"if",
"matched",
".",
"group",
"(",
"1",
")",
"==",
"'if'",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_conditional_body'",
",",
"5",
",",
"'Empty conditional bodies should use {}'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_loop_body'",
",",
"5",
",",
"'Empty loop bodies should use {} or continue'",
")"
] | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L3243-L3275 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/mstats_basic.py | python | ttest_ind | (a, b, axis=0, equal_var=True) | return Ttest_indResult(t, probs.squeeze()) | Calculates the T-test for the means of TWO INDEPENDENT samples of scores.
Parameters
----------
a, b : array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int or None, optional
Axis along which to compute test. If None, compute over the whole
arrays, `a`, and `b`.
equal_var : bool, optional
If True, perform a standard independent 2 sample test that assumes equal
population variances.
If False, perform Welch's t-test, which does not assume equal population
variance.
.. versionadded:: 0.17.0
Returns
-------
statistic : float or array
The calculated t-statistic.
pvalue : float or array
The two-tailed p-value.
Notes
-----
For more details on `ttest_ind`, see `stats.ttest_ind`. | Calculates the T-test for the means of TWO INDEPENDENT samples of scores. | [
"Calculates",
"the",
"T",
"-",
"test",
"for",
"the",
"means",
"of",
"TWO",
"INDEPENDENT",
"samples",
"of",
"scores",
"."
] | def ttest_ind(a, b, axis=0, equal_var=True):
"""
Calculates the T-test for the means of TWO INDEPENDENT samples of scores.
Parameters
----------
a, b : array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int or None, optional
Axis along which to compute test. If None, compute over the whole
arrays, `a`, and `b`.
equal_var : bool, optional
If True, perform a standard independent 2 sample test that assumes equal
population variances.
If False, perform Welch's t-test, which does not assume equal population
variance.
.. versionadded:: 0.17.0
Returns
-------
statistic : float or array
The calculated t-statistic.
pvalue : float or array
The two-tailed p-value.
Notes
-----
For more details on `ttest_ind`, see `stats.ttest_ind`.
"""
a, b, axis = _chk2_asarray(a, b, axis)
if a.size == 0 or b.size == 0:
return Ttest_indResult(np.nan, np.nan)
(x1, x2) = (a.mean(axis), b.mean(axis))
(v1, v2) = (a.var(axis=axis, ddof=1), b.var(axis=axis, ddof=1))
(n1, n2) = (a.count(axis), b.count(axis))
if equal_var:
# force df to be an array for masked division not to throw a warning
df = ma.asanyarray(n1 + n2 - 2.0)
svar = ((n1-1)*v1+(n2-1)*v2) / df
denom = ma.sqrt(svar*(1.0/n1 + 1.0/n2)) # n-D computation here!
else:
vn1 = v1/n1
vn2 = v2/n2
with np.errstate(divide='ignore', invalid='ignore'):
df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
# If df is undefined, variances are zero.
# It doesn't matter what df is as long as it is not NaN.
df = np.where(np.isnan(df), 1, df)
denom = ma.sqrt(vn1 + vn2)
with np.errstate(divide='ignore', invalid='ignore'):
t = (x1-x2) / denom
probs = special.betainc(0.5*df, 0.5, df/(df + t*t)).reshape(t.shape)
return Ttest_indResult(t, probs.squeeze()) | [
"def",
"ttest_ind",
"(",
"a",
",",
"b",
",",
"axis",
"=",
"0",
",",
"equal_var",
"=",
"True",
")",
":",
"a",
",",
"b",
",",
"axis",
"=",
"_chk2_asarray",
"(",
"a",
",",
"b",
",",
"axis",
")",
"if",
"a",
".",
"size",
"==",
"0",
"or",
"b",
".",
"size",
"==",
"0",
":",
"return",
"Ttest_indResult",
"(",
"np",
".",
"nan",
",",
"np",
".",
"nan",
")",
"(",
"x1",
",",
"x2",
")",
"=",
"(",
"a",
".",
"mean",
"(",
"axis",
")",
",",
"b",
".",
"mean",
"(",
"axis",
")",
")",
"(",
"v1",
",",
"v2",
")",
"=",
"(",
"a",
".",
"var",
"(",
"axis",
"=",
"axis",
",",
"ddof",
"=",
"1",
")",
",",
"b",
".",
"var",
"(",
"axis",
"=",
"axis",
",",
"ddof",
"=",
"1",
")",
")",
"(",
"n1",
",",
"n2",
")",
"=",
"(",
"a",
".",
"count",
"(",
"axis",
")",
",",
"b",
".",
"count",
"(",
"axis",
")",
")",
"if",
"equal_var",
":",
"# force df to be an array for masked division not to throw a warning",
"df",
"=",
"ma",
".",
"asanyarray",
"(",
"n1",
"+",
"n2",
"-",
"2.0",
")",
"svar",
"=",
"(",
"(",
"n1",
"-",
"1",
")",
"*",
"v1",
"+",
"(",
"n2",
"-",
"1",
")",
"*",
"v2",
")",
"/",
"df",
"denom",
"=",
"ma",
".",
"sqrt",
"(",
"svar",
"*",
"(",
"1.0",
"/",
"n1",
"+",
"1.0",
"/",
"n2",
")",
")",
"# n-D computation here!",
"else",
":",
"vn1",
"=",
"v1",
"/",
"n1",
"vn2",
"=",
"v2",
"/",
"n2",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"'ignore'",
",",
"invalid",
"=",
"'ignore'",
")",
":",
"df",
"=",
"(",
"vn1",
"+",
"vn2",
")",
"**",
"2",
"/",
"(",
"vn1",
"**",
"2",
"/",
"(",
"n1",
"-",
"1",
")",
"+",
"vn2",
"**",
"2",
"/",
"(",
"n2",
"-",
"1",
")",
")",
"# If df is undefined, variances are zero.",
"# It doesn't matter what df is as long as it is not NaN.",
"df",
"=",
"np",
".",
"where",
"(",
"np",
".",
"isnan",
"(",
"df",
")",
",",
"1",
",",
"df",
")",
"denom",
"=",
"ma",
".",
"sqrt",
"(",
"vn1",
"+",
"vn2",
")",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"'ignore'",
",",
"invalid",
"=",
"'ignore'",
")",
":",
"t",
"=",
"(",
"x1",
"-",
"x2",
")",
"/",
"denom",
"probs",
"=",
"special",
".",
"betainc",
"(",
"0.5",
"*",
"df",
",",
"0.5",
",",
"df",
"/",
"(",
"df",
"+",
"t",
"*",
"t",
")",
")",
".",
"reshape",
"(",
"t",
".",
"shape",
")",
"return",
"Ttest_indResult",
"(",
"t",
",",
"probs",
".",
"squeeze",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/mstats_basic.py#L1018-L1079 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | PyControl.DoSetSize | (*args, **kwargs) | return _controls_.PyControl_DoSetSize(*args, **kwargs) | DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO) | DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO) | [
"DoSetSize",
"(",
"self",
"int",
"x",
"int",
"y",
"int",
"width",
"int",
"height",
"int",
"sizeFlags",
"=",
"SIZE_AUTO",
")"
] | def DoSetSize(*args, **kwargs):
"""DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)"""
return _controls_.PyControl_DoSetSize(*args, **kwargs) | [
"def",
"DoSetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"PyControl_DoSetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5846-L5848 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/make.py | python | WriteAutoRegenerationRule | (params, root_makefile, makefile_name,
build_files) | Write the target to regenerate the Makefile. | Write the target to regenerate the Makefile. | [
"Write",
"the",
"target",
"to",
"regenerate",
"the",
"Makefile",
"."
] | def WriteAutoRegenerationRule(params, root_makefile, makefile_name,
build_files):
"""Write the target to regenerate the Makefile."""
options = params['options']
build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir)
for filename in params['build_files_arg']]
gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'],
options.toplevel_dir)
if not gyp_binary.startswith(os.sep):
gyp_binary = os.path.join('.', gyp_binary)
root_makefile.write(
"quiet_cmd_regen_makefile = ACTION Regenerating $@\n"
"cmd_regen_makefile = cd $(srcdir); %(cmd)s\n"
"%(makefile_name)s: %(deps)s\n"
"\t$(call do_cmd,regen_makefile)\n\n" % {
'makefile_name': makefile_name,
'deps': ' '.join(SourceifyAndQuoteSpaces(bf) for bf in build_files),
'cmd': gyp.common.EncodePOSIXShellList(
[gyp_binary, '-fmake'] +
gyp.RegenerateFlags(options) +
build_files_args)}) | [
"def",
"WriteAutoRegenerationRule",
"(",
"params",
",",
"root_makefile",
",",
"makefile_name",
",",
"build_files",
")",
":",
"options",
"=",
"params",
"[",
"'options'",
"]",
"build_files_args",
"=",
"[",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"filename",
",",
"options",
".",
"toplevel_dir",
")",
"for",
"filename",
"in",
"params",
"[",
"'build_files_arg'",
"]",
"]",
"gyp_binary",
"=",
"gyp",
".",
"common",
".",
"FixIfRelativePath",
"(",
"params",
"[",
"'gyp_binary'",
"]",
",",
"options",
".",
"toplevel_dir",
")",
"if",
"not",
"gyp_binary",
".",
"startswith",
"(",
"os",
".",
"sep",
")",
":",
"gyp_binary",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"gyp_binary",
")",
"root_makefile",
".",
"write",
"(",
"\"quiet_cmd_regen_makefile = ACTION Regenerating $@\\n\"",
"\"cmd_regen_makefile = cd $(srcdir); %(cmd)s\\n\"",
"\"%(makefile_name)s: %(deps)s\\n\"",
"\"\\t$(call do_cmd,regen_makefile)\\n\\n\"",
"%",
"{",
"'makefile_name'",
":",
"makefile_name",
",",
"'deps'",
":",
"' '",
".",
"join",
"(",
"SourceifyAndQuoteSpaces",
"(",
"bf",
")",
"for",
"bf",
"in",
"build_files",
")",
",",
"'cmd'",
":",
"gyp",
".",
"common",
".",
"EncodePOSIXShellList",
"(",
"[",
"gyp_binary",
",",
"'-fmake'",
"]",
"+",
"gyp",
".",
"RegenerateFlags",
"(",
"options",
")",
"+",
"build_files_args",
")",
"}",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/make.py#L1962-L1984 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/ma/extras.py | python | issequence | (seq) | return isinstance(seq, (ndarray, tuple, list)) | Is seq a sequence (ndarray, list or tuple)? | Is seq a sequence (ndarray, list or tuple)? | [
"Is",
"seq",
"a",
"sequence",
"(",
"ndarray",
"list",
"or",
"tuple",
")",
"?"
] | def issequence(seq):
"""
Is seq a sequence (ndarray, list or tuple)?
"""
return isinstance(seq, (ndarray, tuple, list)) | [
"def",
"issequence",
"(",
"seq",
")",
":",
"return",
"isinstance",
"(",
"seq",
",",
"(",
"ndarray",
",",
"tuple",
",",
"list",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/extras.py#L45-L50 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/codelite.py | python | vsnode.get_waf | (self) | return '%s/%s' % (self.ctx.srcnode.abspath(), getattr(self.ctx, 'waf_command', 'waf')) | Override in subclasses... | Override in subclasses... | [
"Override",
"in",
"subclasses",
"..."
] | def get_waf(self):
"""
Override in subclasses...
"""
return '%s/%s' % (self.ctx.srcnode.abspath(), getattr(self.ctx, 'waf_command', 'waf')) | [
"def",
"get_waf",
"(",
"self",
")",
":",
"return",
"'%s/%s'",
"%",
"(",
"self",
".",
"ctx",
".",
"srcnode",
".",
"abspath",
"(",
")",
",",
"getattr",
"(",
"self",
".",
"ctx",
",",
"'waf_command'",
",",
"'waf'",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/codelite.py#L402-L406 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32com/server/register.py | python | GetUnregisterServerKeys | (clsid, progID=None, verProgID=None, customKeys=None) | return ret | Given a server, return a list of of ("key", root), which are keys recursively
and uncondtionally deleted at unregister or uninstall time. | Given a server, return a list of of ("key", root), which are keys recursively
and uncondtionally deleted at unregister or uninstall time. | [
"Given",
"a",
"server",
"return",
"a",
"list",
"of",
"of",
"(",
"key",
"root",
")",
"which",
"are",
"keys",
"recursively",
"and",
"uncondtionally",
"deleted",
"at",
"unregister",
"or",
"uninstall",
"time",
"."
] | def GetUnregisterServerKeys(clsid, progID=None, verProgID=None, customKeys=None):
"""Given a server, return a list of of ("key", root), which are keys recursively
and uncondtionally deleted at unregister or uninstall time.
"""
# remove the main CLSID registration
ret = [("CLSID\\%s" % str(clsid), win32con.HKEY_CLASSES_ROOT)]
# remove the versioned ProgID registration
if verProgID:
ret.append((verProgID, win32con.HKEY_CLASSES_ROOT))
# blow away the independent ProgID. we can't leave it since we just
# torched the class.
### could potentially check the CLSID... ?
if progID:
ret.append((progID, win32con.HKEY_CLASSES_ROOT))
# The DCOM config tool may write settings to the AppID key for our CLSID
ret.append(("AppID\\%s" % str(clsid), win32con.HKEY_CLASSES_ROOT))
# Any custom keys?
if customKeys:
ret = ret + customKeys
return ret | [
"def",
"GetUnregisterServerKeys",
"(",
"clsid",
",",
"progID",
"=",
"None",
",",
"verProgID",
"=",
"None",
",",
"customKeys",
"=",
"None",
")",
":",
"# remove the main CLSID registration",
"ret",
"=",
"[",
"(",
"\"CLSID\\\\%s\"",
"%",
"str",
"(",
"clsid",
")",
",",
"win32con",
".",
"HKEY_CLASSES_ROOT",
")",
"]",
"# remove the versioned ProgID registration",
"if",
"verProgID",
":",
"ret",
".",
"append",
"(",
"(",
"verProgID",
",",
"win32con",
".",
"HKEY_CLASSES_ROOT",
")",
")",
"# blow away the independent ProgID. we can't leave it since we just",
"# torched the class.",
"### could potentially check the CLSID... ?",
"if",
"progID",
":",
"ret",
".",
"append",
"(",
"(",
"progID",
",",
"win32con",
".",
"HKEY_CLASSES_ROOT",
")",
")",
"# The DCOM config tool may write settings to the AppID key for our CLSID",
"ret",
".",
"append",
"(",
"(",
"\"AppID\\\\%s\"",
"%",
"str",
"(",
"clsid",
")",
",",
"win32con",
".",
"HKEY_CLASSES_ROOT",
")",
")",
"# Any custom keys?",
"if",
"customKeys",
":",
"ret",
"=",
"ret",
"+",
"customKeys",
"return",
"ret"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/server/register.py#L337-L357 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/jedi/jedi/api_classes.py | python | CallDef.call_name | (self) | return unicode(self._executable.name) | The name (e.g. 'isinstance') as a string. | The name (e.g. 'isinstance') as a string. | [
"The",
"name",
"(",
"e",
".",
"g",
".",
"isinstance",
")",
"as",
"a",
"string",
"."
] | def call_name(self):
""" The name (e.g. 'isinstance') as a string. """
return unicode(self._executable.name) | [
"def",
"call_name",
"(",
"self",
")",
":",
"return",
"unicode",
"(",
"self",
".",
"_executable",
".",
"name",
")"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/api_classes.py#L622-L624 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/collective_all_reduce_strategy.py | python | CollectiveAllReduceExtended._use_merge_call | (self) | return True | XLA is not supported for multi-worker strategy. | XLA is not supported for multi-worker strategy. | [
"XLA",
"is",
"not",
"supported",
"for",
"multi",
"-",
"worker",
"strategy",
"."
] | def _use_merge_call(self):
"""XLA is not supported for multi-worker strategy."""
return True | [
"def",
"_use_merge_call",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/collective_all_reduce_strategy.py#L335-L337 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py | python | CommandSpec.from_param | (cls, param) | return cls.from_string(param) | Construct a CommandSpec from a parameter to build_scripts, which may
be None. | Construct a CommandSpec from a parameter to build_scripts, which may
be None. | [
"Construct",
"a",
"CommandSpec",
"from",
"a",
"parameter",
"to",
"build_scripts",
"which",
"may",
"be",
"None",
"."
] | def from_param(cls, param):
"""
Construct a CommandSpec from a parameter to build_scripts, which may
be None.
"""
if isinstance(param, cls):
return param
if isinstance(param, list):
return cls(param)
if param is None:
return cls.from_environment()
# otherwise, assume it's a string.
return cls.from_string(param) | [
"def",
"from_param",
"(",
"cls",
",",
"param",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"cls",
")",
":",
"return",
"param",
"if",
"isinstance",
"(",
"param",
",",
"list",
")",
":",
"return",
"cls",
"(",
"param",
")",
"if",
"param",
"is",
"None",
":",
"return",
"cls",
".",
"from_environment",
"(",
")",
"# otherwise, assume it's a string.",
"return",
"cls",
".",
"from_string",
"(",
"param",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L1999-L2011 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/sparse_ops.py | python | sparse_to_indicator | (sp_input, vocab_size, name=None) | Converts a `SparseTensor` of ids into a dense bool indicator tensor.
The last dimension of `sp_input.indices` is discarded and replaced with
the values of `sp_input`. If `sp_input.dense_shape = [D0, D1, ..., Dn, K]`,
then `output.shape = [D0, D1, ..., Dn, vocab_size]`, where
output[d_0, d_1, ..., d_n, sp_input[d_0, d_1, ..., d_n, k]] = True
and False elsewhere in `output`.
For example, if `sp_input.dense_shape = [2, 3, 4]` with non-empty values:
[0, 0, 0]: 0
[0, 1, 0]: 10
[1, 0, 3]: 103
[1, 1, 2]: 150
[1, 1, 3]: 149
[1, 1, 4]: 150
[1, 2, 1]: 121
and `vocab_size = 200`, then the output will be a `[2, 3, 200]` dense bool
tensor with False everywhere except at positions
(0, 0, 0), (0, 1, 10), (1, 0, 103), (1, 1, 149), (1, 1, 150),
(1, 2, 121).
Note that repeats are allowed in the input SparseTensor.
This op is useful for converting `SparseTensor`s into dense formats for
compatibility with ops that expect dense tensors.
The input `SparseTensor` must be in row-major order.
Args:
sp_input: A `SparseTensor` with `values` property of type `int32` or
`int64`.
vocab_size: A scalar int64 Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_input.values < vocab_size)`.
name: A name prefix for the returned tensors (optional)
Returns:
A dense bool indicator tensor representing the indices with specified value.
Raises:
TypeError: If `sp_input` is not a `SparseTensor`. | Converts a `SparseTensor` of ids into a dense bool indicator tensor. | [
"Converts",
"a",
"SparseTensor",
"of",
"ids",
"into",
"a",
"dense",
"bool",
"indicator",
"tensor",
"."
] | def sparse_to_indicator(sp_input, vocab_size, name=None):
"""Converts a `SparseTensor` of ids into a dense bool indicator tensor.
The last dimension of `sp_input.indices` is discarded and replaced with
the values of `sp_input`. If `sp_input.dense_shape = [D0, D1, ..., Dn, K]`,
then `output.shape = [D0, D1, ..., Dn, vocab_size]`, where
output[d_0, d_1, ..., d_n, sp_input[d_0, d_1, ..., d_n, k]] = True
and False elsewhere in `output`.
For example, if `sp_input.dense_shape = [2, 3, 4]` with non-empty values:
[0, 0, 0]: 0
[0, 1, 0]: 10
[1, 0, 3]: 103
[1, 1, 2]: 150
[1, 1, 3]: 149
[1, 1, 4]: 150
[1, 2, 1]: 121
and `vocab_size = 200`, then the output will be a `[2, 3, 200]` dense bool
tensor with False everywhere except at positions
(0, 0, 0), (0, 1, 10), (1, 0, 103), (1, 1, 149), (1, 1, 150),
(1, 2, 121).
Note that repeats are allowed in the input SparseTensor.
This op is useful for converting `SparseTensor`s into dense formats for
compatibility with ops that expect dense tensors.
The input `SparseTensor` must be in row-major order.
Args:
sp_input: A `SparseTensor` with `values` property of type `int32` or
`int64`.
vocab_size: A scalar int64 Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_input.values < vocab_size)`.
name: A name prefix for the returned tensors (optional)
Returns:
A dense bool indicator tensor representing the indices with specified value.
Raises:
TypeError: If `sp_input` is not a `SparseTensor`.
"""
sp_input = _convert_to_sparse_tensor(sp_input)
with ops.name_scope(name, "SparseToIndicator", [sp_input]) as name:
num_entries = array_ops.shape(sp_input.indices)[0]
new_values = array_ops.fill(array_ops.expand_dims(num_entries, 0), True)
sp_values = sparse_tensor.SparseTensor(
sp_input.indices, new_values, sp_input.dense_shape)
sp_new = sparse_merge(sp_input, sp_values, vocab_size, name)
# validate_indices may be False because we allow duplicates in new_indices:
# repeated indices are allowed when creating an indicator matrix.
return sparse_tensor_to_dense(
sp_new, default_value=False, validate_indices=False, name=name) | [
"def",
"sparse_to_indicator",
"(",
"sp_input",
",",
"vocab_size",
",",
"name",
"=",
"None",
")",
":",
"sp_input",
"=",
"_convert_to_sparse_tensor",
"(",
"sp_input",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"SparseToIndicator\"",
",",
"[",
"sp_input",
"]",
")",
"as",
"name",
":",
"num_entries",
"=",
"array_ops",
".",
"shape",
"(",
"sp_input",
".",
"indices",
")",
"[",
"0",
"]",
"new_values",
"=",
"array_ops",
".",
"fill",
"(",
"array_ops",
".",
"expand_dims",
"(",
"num_entries",
",",
"0",
")",
",",
"True",
")",
"sp_values",
"=",
"sparse_tensor",
".",
"SparseTensor",
"(",
"sp_input",
".",
"indices",
",",
"new_values",
",",
"sp_input",
".",
"dense_shape",
")",
"sp_new",
"=",
"sparse_merge",
"(",
"sp_input",
",",
"sp_values",
",",
"vocab_size",
",",
"name",
")",
"# validate_indices may be False because we allow duplicates in new_indices:",
"# repeated indices are allowed when creating an indicator matrix.",
"return",
"sparse_tensor_to_dense",
"(",
"sp_new",
",",
"default_value",
"=",
"False",
",",
"validate_indices",
"=",
"False",
",",
"name",
"=",
"name",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/sparse_ops.py#L979-L1038 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py | python | GroupBy.size | (self) | return self._reindex_output(result, fill_value=0) | Compute group sizes.
Returns
-------
Series
Number of rows in each group. | Compute group sizes. | [
"Compute",
"group",
"sizes",
"."
] | def size(self):
"""
Compute group sizes.
Returns
-------
Series
Number of rows in each group.
"""
result = self.grouper.size()
if isinstance(self.obj, Series):
result.name = self.obj.name
return self._reindex_output(result, fill_value=0) | [
"def",
"size",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"grouper",
".",
"size",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"obj",
",",
"Series",
")",
":",
"result",
".",
"name",
"=",
"self",
".",
"obj",
".",
"name",
"return",
"self",
".",
"_reindex_output",
"(",
"result",
",",
"fill_value",
"=",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py#L1320-L1333 | |
intel/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | object_analytics_visualization/scripts/image_publisher.py | python | SynchronizedSubscriber._draw_measures | (self, cv_image) | Draw measure result on the left up | Draw measure result on the left up | [
"Draw",
"measure",
"result",
"on",
"the",
"left",
"up"
] | def _draw_measures(self, cv_image):
"""Draw measure result on the left up"""
text = "\n".join(" ".join((str(m) for m in self._measures)))
for idx, m in enumerate(self._measures):
cv2.putText(cv_image, str(m), (2, 15+idx*15), ObjectItem.FONT,
ObjectItem.FONT_SIZE, ObjectItem.RED, 1, cv2.LINE_AA) | [
"def",
"_draw_measures",
"(",
"self",
",",
"cv_image",
")",
":",
"text",
"=",
"\"\\n\"",
".",
"join",
"(",
"\" \"",
".",
"join",
"(",
"(",
"str",
"(",
"m",
")",
"for",
"m",
"in",
"self",
".",
"_measures",
")",
")",
")",
"for",
"idx",
",",
"m",
"in",
"enumerate",
"(",
"self",
".",
"_measures",
")",
":",
"cv2",
".",
"putText",
"(",
"cv_image",
",",
"str",
"(",
"m",
")",
",",
"(",
"2",
",",
"15",
"+",
"idx",
"*",
"15",
")",
",",
"ObjectItem",
".",
"FONT",
",",
"ObjectItem",
".",
"FONT_SIZE",
",",
"ObjectItem",
".",
"RED",
",",
"1",
",",
"cv2",
".",
"LINE_AA",
")"
] | https://github.com/intel/ros_object_analytics/blob/eb0208edbb6da67e5d5c4092fd2964a2c8d9838e/object_analytics_visualization/scripts/image_publisher.py#L198-L203 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/platform.py | python | python_version | () | return _sys_version()[1] | Returns the Python version as string 'major.minor.patchlevel'
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0). | Returns the Python version as string 'major.minor.patchlevel' | [
"Returns",
"the",
"Python",
"version",
"as",
"string",
"major",
".",
"minor",
".",
"patchlevel"
] | def python_version():
""" Returns the Python version as string 'major.minor.patchlevel'
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0).
"""
return _sys_version()[1] | [
"def",
"python_version",
"(",
")",
":",
"return",
"_sys_version",
"(",
")",
"[",
"1",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/platform.py#L1266-L1274 | |
weichengkuo/DeepBox | c4f8c065b6a51cf296540cc453a44f0519aaacc9 | caffe-fast-rcnn/scripts/cpp_lint.py | python | CheckStyle | (filename, clean_lines, linenum, file_extension, nesting_state,
error) | Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks rules from the 'C++ style rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"style",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
if line.find('\t') != -1:
error(filename, linenum, 'whitespace/tab', 1,
'Tab found; better to use spaces')
# One or three blank spaces at the beginning of the line is weird; it's
# hard to reconcile that with 2-space indents.
# NOTE: here are the conditions rob pike used for his tests. Mine aren't
# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
# if(RLENGTH > 20) complain = 0;
# if(match($0, " +(error|private|public|protected):")) complain = 0;
# if(match(prev, "&& *$")) complain = 0;
# if(match(prev, "\\|\\| *$")) complain = 0;
# if(match(prev, "[\",=><] *$")) complain = 0;
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
if line and line[-1].isspace():
error(filename, linenum, 'whitespace/end_of_line', 4,
'Line ends in whitespace. Consider deleting these extra spaces.')
# There are certain situations we allow one space, notably for section labels
elif ((initial_spaces == 1 or initial_spaces == 3) and
not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
# Check if the line is a header guard.
is_header_guard = False
if file_extension == 'h':
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
line.startswith('#endif // %s' % cppvar)):
is_header_guard = True
# #include lines and header guards can be long, since there's no clean way to
# split them.
#
# URLs can be long too. It's possible to split these, but it makes them
# harder to cut&paste.
#
# The "$Id:...$" comment may also get very long without it being the
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
extended_length = int((_line_length * 1.25))
if line_width > extended_length:
error(filename, linenum, 'whitespace/line_length', 4,
'Lines should very rarely be longer than %i characters' %
extended_length)
elif line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
cleansed_line.find('for') == -1 and
(GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
# It's ok to have many commands in a switch case that fits in 1 line
not ((cleansed_line.find('case ') != -1 or
cleansed_line.find('default:') != -1) and
cleansed_line.find('break;') != -1)):
error(filename, linenum, 'whitespace/newline', 0,
'More than one command on the same line')
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckAccess(filename, clean_lines, linenum, nesting_state, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
if classinfo:
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) | [
"def",
"CheckStyle",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
"# raw strings,",
"raw_lines",
"=",
"clean_lines",
".",
"lines_without_raw_strings",
"line",
"=",
"raw_lines",
"[",
"linenum",
"]",
"if",
"line",
".",
"find",
"(",
"'\\t'",
")",
"!=",
"-",
"1",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/tab'",
",",
"1",
",",
"'Tab found; better to use spaces'",
")",
"# One or three blank spaces at the beginning of the line is weird; it's",
"# hard to reconcile that with 2-space indents.",
"# NOTE: here are the conditions rob pike used for his tests. Mine aren't",
"# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces",
"# if(RLENGTH > 20) complain = 0;",
"# if(match($0, \" +(error|private|public|protected):\")) complain = 0;",
"# if(match(prev, \"&& *$\")) complain = 0;",
"# if(match(prev, \"\\\\|\\\\| *$\")) complain = 0;",
"# if(match(prev, \"[\\\",=><] *$\")) complain = 0;",
"# if(match($0, \" <<\")) complain = 0;",
"# if(match(prev, \" +for \\\\(\")) complain = 0;",
"# if(prevodd && match(prevprev, \" +for \\\\(\")) complain = 0;",
"initial_spaces",
"=",
"0",
"cleansed_line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"while",
"initial_spaces",
"<",
"len",
"(",
"line",
")",
"and",
"line",
"[",
"initial_spaces",
"]",
"==",
"' '",
":",
"initial_spaces",
"+=",
"1",
"if",
"line",
"and",
"line",
"[",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/end_of_line'",
",",
"4",
",",
"'Line ends in whitespace. Consider deleting these extra spaces.'",
")",
"# There are certain situations we allow one space, notably for section labels",
"elif",
"(",
"(",
"initial_spaces",
"==",
"1",
"or",
"initial_spaces",
"==",
"3",
")",
"and",
"not",
"Match",
"(",
"r'\\s*\\w+\\s*:\\s*$'",
",",
"cleansed_line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/indent'",
",",
"3",
",",
"'Weird number of spaces at line-start. '",
"'Are you using a 2-space indent?'",
")",
"# Check if the line is a header guard.",
"is_header_guard",
"=",
"False",
"if",
"file_extension",
"==",
"'h'",
":",
"cppvar",
"=",
"GetHeaderGuardCPPVariable",
"(",
"filename",
")",
"if",
"(",
"line",
".",
"startswith",
"(",
"'#ifndef %s'",
"%",
"cppvar",
")",
"or",
"line",
".",
"startswith",
"(",
"'#define %s'",
"%",
"cppvar",
")",
"or",
"line",
".",
"startswith",
"(",
"'#endif // %s'",
"%",
"cppvar",
")",
")",
":",
"is_header_guard",
"=",
"True",
"# #include lines and header guards can be long, since there's no clean way to",
"# split them.",
"#",
"# URLs can be long too. It's possible to split these, but it makes them",
"# harder to cut&paste.",
"#",
"# The \"$Id:...$\" comment may also get very long without it being the",
"# developers fault.",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"'#include'",
")",
"and",
"not",
"is_header_guard",
"and",
"not",
"Match",
"(",
"r'^\\s*//.*http(s?)://\\S*$'",
",",
"line",
")",
"and",
"not",
"Match",
"(",
"r'^// \\$Id:.*#[0-9]+ \\$$'",
",",
"line",
")",
")",
":",
"line_width",
"=",
"GetLineWidth",
"(",
"line",
")",
"extended_length",
"=",
"int",
"(",
"(",
"_line_length",
"*",
"1.25",
")",
")",
"if",
"line_width",
">",
"extended_length",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/line_length'",
",",
"4",
",",
"'Lines should very rarely be longer than %i characters'",
"%",
"extended_length",
")",
"elif",
"line_width",
">",
"_line_length",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/line_length'",
",",
"2",
",",
"'Lines should be <= %i characters long'",
"%",
"_line_length",
")",
"if",
"(",
"cleansed_line",
".",
"count",
"(",
"';'",
")",
">",
"1",
"and",
"# for loops are allowed two ;'s (and may run over two lines).",
"cleansed_line",
".",
"find",
"(",
"'for'",
")",
"==",
"-",
"1",
"and",
"(",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
".",
"find",
"(",
"'for'",
")",
"==",
"-",
"1",
"or",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
".",
"find",
"(",
"';'",
")",
"!=",
"-",
"1",
")",
"and",
"# It's ok to have many commands in a switch case that fits in 1 line",
"not",
"(",
"(",
"cleansed_line",
".",
"find",
"(",
"'case '",
")",
"!=",
"-",
"1",
"or",
"cleansed_line",
".",
"find",
"(",
"'default:'",
")",
"!=",
"-",
"1",
")",
"and",
"cleansed_line",
".",
"find",
"(",
"'break;'",
")",
"!=",
"-",
"1",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"0",
",",
"'More than one command on the same line'",
")",
"# Some more style checks",
"CheckBraces",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"CheckEmptyBlockBody",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"CheckAccess",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
"CheckCheck",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"classinfo",
":",
"CheckSectionSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"classinfo",
",",
"linenum",
",",
"error",
")"
] | https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L3459-L3563 | ||
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/generator.py | python | NativeClass.static_methods_clean | (self) | return ret | clean list of static methods (without the ones that should be skipped) | clean list of static methods (without the ones that should be skipped) | [
"clean",
"list",
"of",
"static",
"methods",
"(",
"without",
"the",
"ones",
"that",
"should",
"be",
"skipped",
")"
] | def static_methods_clean(self):
'''
clean list of static methods (without the ones that should be skipped)
'''
ret = []
for name, impl in self.static_methods.iteritems():
should_skip = self.generator.should_skip(self.class_name, name)
if not should_skip:
ret.append({"name": name, "impl": impl})
return ret | [
"def",
"static_methods_clean",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"name",
",",
"impl",
"in",
"self",
".",
"static_methods",
".",
"iteritems",
"(",
")",
":",
"should_skip",
"=",
"self",
".",
"generator",
".",
"should_skip",
"(",
"self",
".",
"class_name",
",",
"name",
")",
"if",
"not",
"should_skip",
":",
"ret",
".",
"append",
"(",
"{",
"\"name\"",
":",
"name",
",",
"\"impl\"",
":",
"impl",
"}",
")",
"return",
"ret"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/generator.py#L769-L778 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/universe_generation/galaxy.py | python | enforce_max_distance | (positions, adjacency_grid) | Adds extra positions between groups of positions to guarantee
that no groups of positions are separated from all other groups
of positions by more than universe_tables.MAX_STARLANE_LENGTH
Find all groups of positions, where every member is within
MAX_STARLANE_LENGTH of at least one other member of the group,
but all members of the group are more than MAX_STARLANE_LENGTH
from all positions in other groups.
For each group:
- Remove it from the adjacency grid and find its nearest neighboring position.
- Add positions between the nearest neighbor and the group to
ensure every position has at least one neighbor within
MAX_STARLANE_LENGTH. | Adds extra positions between groups of positions to guarantee
that no groups of positions are separated from all other groups
of positions by more than universe_tables.MAX_STARLANE_LENGTH | [
"Adds",
"extra",
"positions",
"between",
"groups",
"of",
"positions",
"to",
"guarantee",
"that",
"no",
"groups",
"of",
"positions",
"are",
"separated",
"from",
"all",
"other",
"groups",
"of",
"positions",
"by",
"more",
"than",
"universe_tables",
".",
"MAX_STARLANE_LENGTH"
] | def enforce_max_distance(positions, adjacency_grid):
"""
Adds extra positions between groups of positions to guarantee
that no groups of positions are separated from all other groups
of positions by more than universe_tables.MAX_STARLANE_LENGTH
Find all groups of positions, where every member is within
MAX_STARLANE_LENGTH of at least one other member of the group,
but all members of the group are more than MAX_STARLANE_LENGTH
from all positions in other groups.
For each group:
- Remove it from the adjacency grid and find its nearest neighboring position.
- Add positions between the nearest neighbor and the group to
ensure every position has at least one neighbor within
MAX_STARLANE_LENGTH.
"""
# Find all clusters
clusterer = Clusterer(positions, adjacency_grid)
if len(clusterer) == 1:
print("All systems positioned in a single connected cluster")
else:
print(
"{} clusters separated by more than the MAX_STARLANE_LENGTH."
" Starting to fill gaps.".format(len(clusterer))
)
while len(clusterer) > 1:
smallest_cluster = clusterer.smallest_isolated_cluster()
print(
"Searching for nearest neighbor position to a cluster " "with {} positions.".format(len(smallest_cluster))
)
for pos in smallest_cluster:
adjacency_grid.remove_pos(pos)
# Find nearest neighbour
(_, p1, p2) = min(
[
(util.distance(pos, nn), pos, nn)
for pos in smallest_cluster
for nn in [adjacency_grid.nearest_neighbor(pos)]
if nn
]
)
for pos in smallest_cluster:
adjacency_grid.insert_pos(pos)
# Add extra positions
extra_positions = stitching_positions(p1, p2)
for i_extra, p3 in enumerate(extra_positions):
print(
"Adding {} of {} extra positions at {} to enforce "
"max spacing between {} and {}.".format(i_extra + 1, len(extra_positions), p3, p1, p2)
)
adjacency_grid.insert_pos(p3)
positions.append(p3)
clusterer.stitch_clusters(p1, p2, extra_positions)
if len(clusterer) == 1:
print("All systems now positioned in a single connected cluster")
else:
print(
"{} clusters separated by more the MAX_STARLANE_LENGTH. "
"Continuing to fill gaps.".format(len(clusterer))
) | [
"def",
"enforce_max_distance",
"(",
"positions",
",",
"adjacency_grid",
")",
":",
"# Find all clusters",
"clusterer",
"=",
"Clusterer",
"(",
"positions",
",",
"adjacency_grid",
")",
"if",
"len",
"(",
"clusterer",
")",
"==",
"1",
":",
"print",
"(",
"\"All systems positioned in a single connected cluster\"",
")",
"else",
":",
"print",
"(",
"\"{} clusters separated by more than the MAX_STARLANE_LENGTH.\"",
"\" Starting to fill gaps.\"",
".",
"format",
"(",
"len",
"(",
"clusterer",
")",
")",
")",
"while",
"len",
"(",
"clusterer",
")",
">",
"1",
":",
"smallest_cluster",
"=",
"clusterer",
".",
"smallest_isolated_cluster",
"(",
")",
"print",
"(",
"\"Searching for nearest neighbor position to a cluster \"",
"\"with {} positions.\"",
".",
"format",
"(",
"len",
"(",
"smallest_cluster",
")",
")",
")",
"for",
"pos",
"in",
"smallest_cluster",
":",
"adjacency_grid",
".",
"remove_pos",
"(",
"pos",
")",
"# Find nearest neighbour",
"(",
"_",
",",
"p1",
",",
"p2",
")",
"=",
"min",
"(",
"[",
"(",
"util",
".",
"distance",
"(",
"pos",
",",
"nn",
")",
",",
"pos",
",",
"nn",
")",
"for",
"pos",
"in",
"smallest_cluster",
"for",
"nn",
"in",
"[",
"adjacency_grid",
".",
"nearest_neighbor",
"(",
"pos",
")",
"]",
"if",
"nn",
"]",
")",
"for",
"pos",
"in",
"smallest_cluster",
":",
"adjacency_grid",
".",
"insert_pos",
"(",
"pos",
")",
"# Add extra positions",
"extra_positions",
"=",
"stitching_positions",
"(",
"p1",
",",
"p2",
")",
"for",
"i_extra",
",",
"p3",
"in",
"enumerate",
"(",
"extra_positions",
")",
":",
"print",
"(",
"\"Adding {} of {} extra positions at {} to enforce \"",
"\"max spacing between {} and {}.\"",
".",
"format",
"(",
"i_extra",
"+",
"1",
",",
"len",
"(",
"extra_positions",
")",
",",
"p3",
",",
"p1",
",",
"p2",
")",
")",
"adjacency_grid",
".",
"insert_pos",
"(",
"p3",
")",
"positions",
".",
"append",
"(",
"p3",
")",
"clusterer",
".",
"stitch_clusters",
"(",
"p1",
",",
"p2",
",",
"extra_positions",
")",
"if",
"len",
"(",
"clusterer",
")",
"==",
"1",
":",
"print",
"(",
"\"All systems now positioned in a single connected cluster\"",
")",
"else",
":",
"print",
"(",
"\"{} clusters separated by more the MAX_STARLANE_LENGTH. \"",
"\"Continuing to fill gaps.\"",
".",
"format",
"(",
"len",
"(",
"clusterer",
")",
")",
")"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/galaxy.py#L329-L393 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/libmintsmolecule.py | python | LibmintsMolecule.__init__ | (self) | Initialize Molecule object from string in psi4 format | Initialize Molecule object from string in psi4 format | [
"Initialize",
"Molecule",
"object",
"from",
"string",
"in",
"psi4",
"format"
] | def __init__(self):
"""Initialize Molecule object from string in psi4 format"""
# <<< Basic Molecule Information >>>
# Molecule (or fragment) name
self.PYname = 'default'
# Molecule comment
self.PYcomment = ''
# Molecule origin
self.PYprovenance = []
# Molecule connectivity
self.PYconnectivity = []
# The molecular charge
self.PYmolecular_charge = 0
# The multiplicity (defined as 2Ms + 1)
self.PYmultiplicity = 1
# The units used to define the geometry
self.PYunits = 'Angstrom'
# The conversion factor to take input units to Bohr
self.PYinput_units_to_au = 1.0 / qcel.constants.bohr2angstroms
# Whether this molecule has at least one zmatrix entry
self.zmat = False # TODO None?
# Whether this molecule has at least one Cartesian entry
self.cart = False # TODO None?
# <<< Coordinates >>>
# Atom info vector (no knowledge of dummy atoms)
self.atoms = []
# Atom info vector (includes dummy atoms)
self.full_atoms = []
# A list of all variables known, whether they have been set or not.
self.all_variables = []
# A listing of the variables used to define the geometries
self.geometry_variables = {}
# Limited lifetime efficiency boost
self.wholegeom = None
# <<< Fragmentation >>>
# The list of atom ranges defining each fragment from parent molecule
self.fragments = []
# A list describing how to handle each fragment
self.fragment_types = []
# The charge of each fragment
self.fragment_charges = []
# The multiplicity of each fragment
self.fragment_multiplicities = []
# <<< Frame >>>
# Move to center of mass or not?
self.PYmove_to_com = True
# Reorient or not? UNUSED
self.PYfix_orientation = False
# Reinterpret the coord entries or not (Default is true, except for findif)
self.PYreinterpret_coordentries = True
# Nilpotence boolean (flagged upon first determination of symmetry frame,
# reset each time a substantiative change is made)
self.lock_frame = False
# <<< Symmetry >>>
# Point group to use with this molecule
self.pg = None
# Full point group
self.full_pg = 'C1'
# n of the highest rotational axis Cn
self.PYfull_pg_n = 1
# Symmetry string from geometry specification
self.PYsymmetry_from_input = None
# Number of unique atoms
self.PYnunique = 0
# Number of equivalent atoms per unique atom (length nunique)
self.nequiv = 0
# Equivalent atom mapping array (length 1st dim nunique)
self.equiv = 0
# Atom to unique atom mapping array (length natom)
self.PYatom_to_unique = 0 | [
"def",
"__init__",
"(",
"self",
")",
":",
"# <<< Basic Molecule Information >>>",
"# Molecule (or fragment) name",
"self",
".",
"PYname",
"=",
"'default'",
"# Molecule comment",
"self",
".",
"PYcomment",
"=",
"''",
"# Molecule origin",
"self",
".",
"PYprovenance",
"=",
"[",
"]",
"# Molecule connectivity",
"self",
".",
"PYconnectivity",
"=",
"[",
"]",
"# The molecular charge",
"self",
".",
"PYmolecular_charge",
"=",
"0",
"# The multiplicity (defined as 2Ms + 1)",
"self",
".",
"PYmultiplicity",
"=",
"1",
"# The units used to define the geometry",
"self",
".",
"PYunits",
"=",
"'Angstrom'",
"# The conversion factor to take input units to Bohr",
"self",
".",
"PYinput_units_to_au",
"=",
"1.0",
"/",
"qcel",
".",
"constants",
".",
"bohr2angstroms",
"# Whether this molecule has at least one zmatrix entry",
"self",
".",
"zmat",
"=",
"False",
"# TODO None?",
"# Whether this molecule has at least one Cartesian entry",
"self",
".",
"cart",
"=",
"False",
"# TODO None?",
"# <<< Coordinates >>>",
"# Atom info vector (no knowledge of dummy atoms)",
"self",
".",
"atoms",
"=",
"[",
"]",
"# Atom info vector (includes dummy atoms)",
"self",
".",
"full_atoms",
"=",
"[",
"]",
"# A list of all variables known, whether they have been set or not.",
"self",
".",
"all_variables",
"=",
"[",
"]",
"# A listing of the variables used to define the geometries",
"self",
".",
"geometry_variables",
"=",
"{",
"}",
"# Limited lifetime efficiency boost",
"self",
".",
"wholegeom",
"=",
"None",
"# <<< Fragmentation >>>",
"# The list of atom ranges defining each fragment from parent molecule",
"self",
".",
"fragments",
"=",
"[",
"]",
"# A list describing how to handle each fragment",
"self",
".",
"fragment_types",
"=",
"[",
"]",
"# The charge of each fragment",
"self",
".",
"fragment_charges",
"=",
"[",
"]",
"# The multiplicity of each fragment",
"self",
".",
"fragment_multiplicities",
"=",
"[",
"]",
"# <<< Frame >>>",
"# Move to center of mass or not?",
"self",
".",
"PYmove_to_com",
"=",
"True",
"# Reorient or not? UNUSED",
"self",
".",
"PYfix_orientation",
"=",
"False",
"# Reinterpret the coord entries or not (Default is true, except for findif)",
"self",
".",
"PYreinterpret_coordentries",
"=",
"True",
"# Nilpotence boolean (flagged upon first determination of symmetry frame,",
"# reset each time a substantiative change is made)",
"self",
".",
"lock_frame",
"=",
"False",
"# <<< Symmetry >>>",
"# Point group to use with this molecule",
"self",
".",
"pg",
"=",
"None",
"# Full point group",
"self",
".",
"full_pg",
"=",
"'C1'",
"# n of the highest rotational axis Cn",
"self",
".",
"PYfull_pg_n",
"=",
"1",
"# Symmetry string from geometry specification",
"self",
".",
"PYsymmetry_from_input",
"=",
"None",
"# Number of unique atoms",
"self",
".",
"PYnunique",
"=",
"0",
"# Number of equivalent atoms per unique atom (length nunique)",
"self",
".",
"nequiv",
"=",
"0",
"# Equivalent atom mapping array (length 1st dim nunique)",
"self",
".",
"equiv",
"=",
"0",
"# Atom to unique atom mapping array (length natom)",
"self",
".",
"PYatom_to_unique",
"=",
"0"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L83-L163 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/dockart.py | python | ModernDockArt.DrawPaneButton | (self, dc, window, button, button_state, rect, pane) | Draws a pane button in the pane caption area.
:param `dc`: a :class:`DC` device context;
:param `window`: an instance of :class:`Window`;
:param integer `button`: the button to be drawn;
:param integer `button_state`: the pane button state;
:param Rect `rect`: the pane caption rectangle;
:param `pane`: the pane for which the button is drawn. | Draws a pane button in the pane caption area. | [
"Draws",
"a",
"pane",
"button",
"in",
"the",
"pane",
"caption",
"area",
"."
] | def DrawPaneButton(self, dc, window, button, button_state, rect, pane):
"""
Draws a pane button in the pane caption area.
:param `dc`: a :class:`DC` device context;
:param `window`: an instance of :class:`Window`;
:param integer `button`: the button to be drawn;
:param integer `button_state`: the pane button state;
:param Rect `rect`: the pane caption rectangle;
:param `pane`: the pane for which the button is drawn.
"""
if self.usingTheme:
hTheme = self.hTheme1
# Get the real button position (compensating for borders)
drect = wx.Rect(rect.x, rect.y, self._button_size, self._button_size)
# Draw the themed close button
rc = RECT(0, 0, 0, 0)
if pane.HasCaptionLeft():
rc.top = rect.x + self._button_border_size
rc.left = int(rect.y + 1.5*self._button_border_size)
rc.right = rect.x + self._button_size + self._button_border_size
rc.bottom = int(rect.y + self._button_size + 1.5*self._button_border_size)
else:
rc.top = rect.x - self._button_border_size
rc.left = int(rect.y + 1.5*self._button_border_size)
rc.right = rect.x + self._button_size- self._button_border_size
rc.bottom = int(rect.y + self._button_size + 1.5*self._button_border_size)
if button == AUI_BUTTON_CLOSE:
btntype = 19
elif button == AUI_BUTTON_PIN:
btntype = 23
elif button == AUI_BUTTON_MAXIMIZE_RESTORE:
if not pane.IsMaximized():
btntype = 17
else:
btntype = 21
else:
btntype = 15
state = 4 # CBS_DISABLED
if pane.state & optionActive:
if button_state == AUI_BUTTON_STATE_NORMAL:
state = 1 # CBS_NORMAL
elif button_state == AUI_BUTTON_STATE_HOVER:
state = 2 # CBS_HOT
elif button_state == AUI_BUTTON_STATE_PRESSED:
state = 3 # CBS_PUSHED
else:
raise Exception("ERROR: Unknown State.")
else: # inactive pane
if button_state == AUI_BUTTON_STATE_NORMAL:
state = 5 # CBS_NORMAL
elif button_state == AUI_BUTTON_STATE_HOVER:
state = 6 # CBS_HOT
elif button_state == AUI_BUTTON_STATE_PRESSED:
state = 7 # CBS_PUSHED
else:
raise Exception("ERROR: Unknown State.")
try:
winxptheme.DrawThemeBackground(hTheme, dc.GetHDC(), btntype, state, (rc.top, rc.left, rc.right, rc.bottom), None)
except TypeError:
return
else:
# Fallback to default closebutton if themes are not enabled
rect2 = wx.Rect(rect.x-4, rect.y+2, rect.width, rect.height)
AuiDefaultDockArt.DrawPaneButton(self, dc, window, button, button_state, rect2, pane) | [
"def",
"DrawPaneButton",
"(",
"self",
",",
"dc",
",",
"window",
",",
"button",
",",
"button_state",
",",
"rect",
",",
"pane",
")",
":",
"if",
"self",
".",
"usingTheme",
":",
"hTheme",
"=",
"self",
".",
"hTheme1",
"# Get the real button position (compensating for borders)",
"drect",
"=",
"wx",
".",
"Rect",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"self",
".",
"_button_size",
",",
"self",
".",
"_button_size",
")",
"# Draw the themed close button",
"rc",
"=",
"RECT",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"if",
"pane",
".",
"HasCaptionLeft",
"(",
")",
":",
"rc",
".",
"top",
"=",
"rect",
".",
"x",
"+",
"self",
".",
"_button_border_size",
"rc",
".",
"left",
"=",
"int",
"(",
"rect",
".",
"y",
"+",
"1.5",
"*",
"self",
".",
"_button_border_size",
")",
"rc",
".",
"right",
"=",
"rect",
".",
"x",
"+",
"self",
".",
"_button_size",
"+",
"self",
".",
"_button_border_size",
"rc",
".",
"bottom",
"=",
"int",
"(",
"rect",
".",
"y",
"+",
"self",
".",
"_button_size",
"+",
"1.5",
"*",
"self",
".",
"_button_border_size",
")",
"else",
":",
"rc",
".",
"top",
"=",
"rect",
".",
"x",
"-",
"self",
".",
"_button_border_size",
"rc",
".",
"left",
"=",
"int",
"(",
"rect",
".",
"y",
"+",
"1.5",
"*",
"self",
".",
"_button_border_size",
")",
"rc",
".",
"right",
"=",
"rect",
".",
"x",
"+",
"self",
".",
"_button_size",
"-",
"self",
".",
"_button_border_size",
"rc",
".",
"bottom",
"=",
"int",
"(",
"rect",
".",
"y",
"+",
"self",
".",
"_button_size",
"+",
"1.5",
"*",
"self",
".",
"_button_border_size",
")",
"if",
"button",
"==",
"AUI_BUTTON_CLOSE",
":",
"btntype",
"=",
"19",
"elif",
"button",
"==",
"AUI_BUTTON_PIN",
":",
"btntype",
"=",
"23",
"elif",
"button",
"==",
"AUI_BUTTON_MAXIMIZE_RESTORE",
":",
"if",
"not",
"pane",
".",
"IsMaximized",
"(",
")",
":",
"btntype",
"=",
"17",
"else",
":",
"btntype",
"=",
"21",
"else",
":",
"btntype",
"=",
"15",
"state",
"=",
"4",
"# CBS_DISABLED",
"if",
"pane",
".",
"state",
"&",
"optionActive",
":",
"if",
"button_state",
"==",
"AUI_BUTTON_STATE_NORMAL",
":",
"state",
"=",
"1",
"# CBS_NORMAL",
"elif",
"button_state",
"==",
"AUI_BUTTON_STATE_HOVER",
":",
"state",
"=",
"2",
"# CBS_HOT",
"elif",
"button_state",
"==",
"AUI_BUTTON_STATE_PRESSED",
":",
"state",
"=",
"3",
"# CBS_PUSHED",
"else",
":",
"raise",
"Exception",
"(",
"\"ERROR: Unknown State.\"",
")",
"else",
":",
"# inactive pane",
"if",
"button_state",
"==",
"AUI_BUTTON_STATE_NORMAL",
":",
"state",
"=",
"5",
"# CBS_NORMAL",
"elif",
"button_state",
"==",
"AUI_BUTTON_STATE_HOVER",
":",
"state",
"=",
"6",
"# CBS_HOT",
"elif",
"button_state",
"==",
"AUI_BUTTON_STATE_PRESSED",
":",
"state",
"=",
"7",
"# CBS_PUSHED",
"else",
":",
"raise",
"Exception",
"(",
"\"ERROR: Unknown State.\"",
")",
"try",
":",
"winxptheme",
".",
"DrawThemeBackground",
"(",
"hTheme",
",",
"dc",
".",
"GetHDC",
"(",
")",
",",
"btntype",
",",
"state",
",",
"(",
"rc",
".",
"top",
",",
"rc",
".",
"left",
",",
"rc",
".",
"right",
",",
"rc",
".",
"bottom",
")",
",",
"None",
")",
"except",
"TypeError",
":",
"return",
"else",
":",
"# Fallback to default closebutton if themes are not enabled",
"rect2",
"=",
"wx",
".",
"Rect",
"(",
"rect",
".",
"x",
"-",
"4",
",",
"rect",
".",
"y",
"+",
"2",
",",
"rect",
".",
"width",
",",
"rect",
".",
"height",
")",
"AuiDefaultDockArt",
".",
"DrawPaneButton",
"(",
"self",
",",
"dc",
",",
"window",
",",
"button",
",",
"button_state",
",",
"rect2",
",",
"pane",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/dockart.py#L1101-L1186 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/distribute_coordinator.py | python | _WorkerContext.__init__ | (self,
strategy,
cluster_spec,
task_type,
task_id,
session_config=None,
rpc_layer="grpc",
worker_barrier=None) | Initialize the worker context object.
Args:
strategy: a `DistributionStrategy` object.
cluster_spec: a ClusterSpec object. It can be empty or None in the local
training case.
task_type: a string indicating the role of the corresponding task, such as
"worker" or "ps". It can be None if it is local training or in-graph
replicated training.
task_id: an integer indicating id of the corresponding task. It can be
None if it is local training or in-graph replicated training.
session_config: an optional `tf.compat.v1.ConfigProto` object.
rpc_layer: optional string specifying the RPC protocol for communication
with worker masters. If None or empty, hosts in the `cluster_spec` will
be used directly.
worker_barrier: optional, the barrier object for worker synchronization. | Initialize the worker context object. | [
"Initialize",
"the",
"worker",
"context",
"object",
"."
] | def __init__(self,
strategy,
cluster_spec,
task_type,
task_id,
session_config=None,
rpc_layer="grpc",
worker_barrier=None):
"""Initialize the worker context object.
Args:
strategy: a `DistributionStrategy` object.
cluster_spec: a ClusterSpec object. It can be empty or None in the local
training case.
task_type: a string indicating the role of the corresponding task, such as
"worker" or "ps". It can be None if it is local training or in-graph
replicated training.
task_id: an integer indicating id of the corresponding task. It can be
None if it is local training or in-graph replicated training.
session_config: an optional `tf.compat.v1.ConfigProto` object.
rpc_layer: optional string specifying the RPC protocol for communication
with worker masters. If None or empty, hosts in the `cluster_spec` will
be used directly.
worker_barrier: optional, the barrier object for worker synchronization.
"""
self._strategy = strategy
self._cluster_spec = cluster_spec
self._task_type = task_type
self._task_id = task_id
self._session_config = session_config
self._worker_barrier = worker_barrier
self._rpc_layer = rpc_layer
self._master_target = self._get_master_target()
self._num_workers = _get_num_workers(cluster_spec)
self._is_chief_node = self._is_chief() | [
"def",
"__init__",
"(",
"self",
",",
"strategy",
",",
"cluster_spec",
",",
"task_type",
",",
"task_id",
",",
"session_config",
"=",
"None",
",",
"rpc_layer",
"=",
"\"grpc\"",
",",
"worker_barrier",
"=",
"None",
")",
":",
"self",
".",
"_strategy",
"=",
"strategy",
"self",
".",
"_cluster_spec",
"=",
"cluster_spec",
"self",
".",
"_task_type",
"=",
"task_type",
"self",
".",
"_task_id",
"=",
"task_id",
"self",
".",
"_session_config",
"=",
"session_config",
"self",
".",
"_worker_barrier",
"=",
"worker_barrier",
"self",
".",
"_rpc_layer",
"=",
"rpc_layer",
"self",
".",
"_master_target",
"=",
"self",
".",
"_get_master_target",
"(",
")",
"self",
".",
"_num_workers",
"=",
"_get_num_workers",
"(",
"cluster_spec",
")",
"self",
".",
"_is_chief_node",
"=",
"self",
".",
"_is_chief",
"(",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/distribute_coordinator.py#L112-L146 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.data | (self) | return self.dispatcher._checkResultString(
Indigo._lib.indigoData(self.id)
) | Data s-group method returns data
Returns:
str: s-group data | Data s-group method returns data | [
"Data",
"s",
"-",
"group",
"method",
"returns",
"data"
] | def data(self):
"""Data s-group method returns data
Returns:
str: s-group data
"""
self.dispatcher._setSessionId()
return self.dispatcher._checkResultString(
Indigo._lib.indigoData(self.id)
) | [
"def",
"data",
"(",
"self",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"_checkResultString",
"(",
"Indigo",
".",
"_lib",
".",
"indigoData",
"(",
"self",
".",
"id",
")",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L1554-L1563 | |
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py | python | Timestamp.GetCurrentTime | (self) | Get the current UTC into Timestamp. | Get the current UTC into Timestamp. | [
"Get",
"the",
"current",
"UTC",
"into",
"Timestamp",
"."
] | def GetCurrentTime(self):
"""Get the current UTC into Timestamp."""
self.FromDatetime(datetime.utcnow()) | [
"def",
"GetCurrentTime",
"(",
"self",
")",
":",
"self",
".",
"FromDatetime",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L184-L186 | ||
google/nucleus | 68d3947fafba1337f294c0668a6e1c7f3f1273e3 | nucleus/io/tfrecord.py | python | read_tfrecords | (path, proto=None, max_records=None, compression_type=None) | Yields the parsed records in a TFRecord file path.
Note that path can be sharded filespec (path@N) in which case this function
will read each shard in order; i.e. shard 0 will read each entry in order,
then shard 1, ...
Args:
path: String. A path to a TFRecord file containing protos.
proto: A proto class. proto.FromString() will be called on each serialized
record in path to parse it.
max_records: int >= 0 or None. Maximum number of records to read from path.
If None, the default, all records will be read.
compression_type: 'GZIP', 'ZLIB', '' (uncompressed), or None to autodetect
based on file extension.
Yields:
proto.FromString() values on each record in path in order. | Yields the parsed records in a TFRecord file path. | [
"Yields",
"the",
"parsed",
"records",
"in",
"a",
"TFRecord",
"file",
"path",
"."
] | def read_tfrecords(path, proto=None, max_records=None, compression_type=None):
"""Yields the parsed records in a TFRecord file path.
Note that path can be sharded filespec (path@N) in which case this function
will read each shard in order; i.e. shard 0 will read each entry in order,
then shard 1, ...
Args:
path: String. A path to a TFRecord file containing protos.
proto: A proto class. proto.FromString() will be called on each serialized
record in path to parse it.
max_records: int >= 0 or None. Maximum number of records to read from path.
If None, the default, all records will be read.
compression_type: 'GZIP', 'ZLIB', '' (uncompressed), or None to autodetect
based on file extension.
Yields:
proto.FromString() values on each record in path in order.
"""
if sharded_file_utils.is_sharded_file_spec(path):
paths = sharded_file_utils.generate_sharded_filenames(path)
else:
paths = [path]
i = 0
for path in paths:
with Reader(path, proto, compression_type=compression_type) as reader:
for record in reader.iterate():
i += 1
if max_records is not None and i > max_records:
return
yield record | [
"def",
"read_tfrecords",
"(",
"path",
",",
"proto",
"=",
"None",
",",
"max_records",
"=",
"None",
",",
"compression_type",
"=",
"None",
")",
":",
"if",
"sharded_file_utils",
".",
"is_sharded_file_spec",
"(",
"path",
")",
":",
"paths",
"=",
"sharded_file_utils",
".",
"generate_sharded_filenames",
"(",
"path",
")",
"else",
":",
"paths",
"=",
"[",
"path",
"]",
"i",
"=",
"0",
"for",
"path",
"in",
"paths",
":",
"with",
"Reader",
"(",
"path",
",",
"proto",
",",
"compression_type",
"=",
"compression_type",
")",
"as",
"reader",
":",
"for",
"record",
"in",
"reader",
".",
"iterate",
"(",
")",
":",
"i",
"+=",
"1",
"if",
"max_records",
"is",
"not",
"None",
"and",
"i",
">",
"max_records",
":",
"return",
"yield",
"record"
] | https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/tfrecord.py#L56-L87 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/uuid.py | python | UUID.__init__ | (self, hex=None, bytes=None, bytes_le=None, fields=None,
int=None, version=None,
*, is_safe=SafeUUID.unknown) | r"""Create a UUID from either a string of 32 hexadecimal digits,
a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
in little-endian order as the 'bytes_le' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
the 'fields' argument, or a single 128-bit integer as the 'int'
argument. When a string of hex digits is given, curly braces,
hyphens, and a URN prefix are all optional. For example, these
expressions all yield the same UUID:
UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes='\x12\x34\x56\x78'*4)
UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
be given. The 'version' argument is optional; if given, the resulting
UUID will have its variant and version set according to RFC 4122,
overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
is_safe is an enum exposed as an attribute on the instance. It
indicates whether the UUID has been generated in a way that is safe
for multiprocessing applications, via uuid_generate_time_safe(3). | r"""Create a UUID from either a string of 32 hexadecimal digits,
a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
in little-endian order as the 'bytes_le' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
the 'fields' argument, or a single 128-bit integer as the 'int'
argument. When a string of hex digits is given, curly braces,
hyphens, and a URN prefix are all optional. For example, these
expressions all yield the same UUID: | [
"r",
"Create",
"a",
"UUID",
"from",
"either",
"a",
"string",
"of",
"32",
"hexadecimal",
"digits",
"a",
"string",
"of",
"16",
"bytes",
"as",
"the",
"bytes",
"argument",
"a",
"string",
"of",
"16",
"bytes",
"in",
"little",
"-",
"endian",
"order",
"as",
"the",
"bytes_le",
"argument",
"a",
"tuple",
"of",
"six",
"integers",
"(",
"32",
"-",
"bit",
"time_low",
"16",
"-",
"bit",
"time_mid",
"16",
"-",
"bit",
"time_hi_version",
"8",
"-",
"bit",
"clock_seq_hi_variant",
"8",
"-",
"bit",
"clock_seq_low",
"48",
"-",
"bit",
"node",
")",
"as",
"the",
"fields",
"argument",
"or",
"a",
"single",
"128",
"-",
"bit",
"integer",
"as",
"the",
"int",
"argument",
".",
"When",
"a",
"string",
"of",
"hex",
"digits",
"is",
"given",
"curly",
"braces",
"hyphens",
"and",
"a",
"URN",
"prefix",
"are",
"all",
"optional",
".",
"For",
"example",
"these",
"expressions",
"all",
"yield",
"the",
"same",
"UUID",
":"
] | def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
int=None, version=None,
*, is_safe=SafeUUID.unknown):
r"""Create a UUID from either a string of 32 hexadecimal digits,
a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
in little-endian order as the 'bytes_le' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
the 'fields' argument, or a single 128-bit integer as the 'int'
argument. When a string of hex digits is given, curly braces,
hyphens, and a URN prefix are all optional. For example, these
expressions all yield the same UUID:
UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes='\x12\x34\x56\x78'*4)
UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)
Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
be given. The 'version' argument is optional; if given, the resulting
UUID will have its variant and version set according to RFC 4122,
overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
is_safe is an enum exposed as an attribute on the instance. It
indicates whether the UUID has been generated in a way that is safe
for multiprocessing applications, via uuid_generate_time_safe(3).
"""
if [hex, bytes, bytes_le, fields, int].count(None) != 4:
raise TypeError('one of the hex, bytes, bytes_le, fields, '
'or int arguments must be given')
if hex is not None:
hex = hex.replace('urn:', '').replace('uuid:', '')
hex = hex.strip('{}').replace('-', '')
if len(hex) != 32:
raise ValueError('badly formed hexadecimal UUID string')
int = int_(hex, 16)
if bytes_le is not None:
if len(bytes_le) != 16:
raise ValueError('bytes_le is not a 16-char string')
bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
bytes_le[8-1:6-1:-1] + bytes_le[8:])
if bytes is not None:
if len(bytes) != 16:
raise ValueError('bytes is not a 16-char string')
assert isinstance(bytes, bytes_), repr(bytes)
int = int_.from_bytes(bytes, byteorder='big')
if fields is not None:
if len(fields) != 6:
raise ValueError('fields is not a 6-tuple')
(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node) = fields
if not 0 <= time_low < 1<<32:
raise ValueError('field 1 out of range (need a 32-bit value)')
if not 0 <= time_mid < 1<<16:
raise ValueError('field 2 out of range (need a 16-bit value)')
if not 0 <= time_hi_version < 1<<16:
raise ValueError('field 3 out of range (need a 16-bit value)')
if not 0 <= clock_seq_hi_variant < 1<<8:
raise ValueError('field 4 out of range (need an 8-bit value)')
if not 0 <= clock_seq_low < 1<<8:
raise ValueError('field 5 out of range (need an 8-bit value)')
if not 0 <= node < 1<<48:
raise ValueError('field 6 out of range (need a 48-bit value)')
clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
int = ((time_low << 96) | (time_mid << 80) |
(time_hi_version << 64) | (clock_seq << 48) | node)
if int is not None:
if not 0 <= int < 1<<128:
raise ValueError('int is out of range (need a 128-bit value)')
if version is not None:
if not 1 <= version <= 5:
raise ValueError('illegal version number')
# Set the variant to RFC 4122.
int &= ~(0xc000 << 48)
int |= 0x8000 << 48
# Set the version number.
int &= ~(0xf000 << 64)
int |= version << 76
self.__dict__['int'] = int
self.__dict__['is_safe'] = is_safe | [
"def",
"__init__",
"(",
"self",
",",
"hex",
"=",
"None",
",",
"bytes",
"=",
"None",
",",
"bytes_le",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"int",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
",",
"is_safe",
"=",
"SafeUUID",
".",
"unknown",
")",
":",
"if",
"[",
"hex",
",",
"bytes",
",",
"bytes_le",
",",
"fields",
",",
"int",
"]",
".",
"count",
"(",
"None",
")",
"!=",
"4",
":",
"raise",
"TypeError",
"(",
"'one of the hex, bytes, bytes_le, fields, '",
"'or int arguments must be given'",
")",
"if",
"hex",
"is",
"not",
"None",
":",
"hex",
"=",
"hex",
".",
"replace",
"(",
"'urn:'",
",",
"''",
")",
".",
"replace",
"(",
"'uuid:'",
",",
"''",
")",
"hex",
"=",
"hex",
".",
"strip",
"(",
"'{}'",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"if",
"len",
"(",
"hex",
")",
"!=",
"32",
":",
"raise",
"ValueError",
"(",
"'badly formed hexadecimal UUID string'",
")",
"int",
"=",
"int_",
"(",
"hex",
",",
"16",
")",
"if",
"bytes_le",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"bytes_le",
")",
"!=",
"16",
":",
"raise",
"ValueError",
"(",
"'bytes_le is not a 16-char string'",
")",
"bytes",
"=",
"(",
"bytes_le",
"[",
"4",
"-",
"1",
":",
":",
"-",
"1",
"]",
"+",
"bytes_le",
"[",
"6",
"-",
"1",
":",
"4",
"-",
"1",
":",
"-",
"1",
"]",
"+",
"bytes_le",
"[",
"8",
"-",
"1",
":",
"6",
"-",
"1",
":",
"-",
"1",
"]",
"+",
"bytes_le",
"[",
"8",
":",
"]",
")",
"if",
"bytes",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"bytes",
")",
"!=",
"16",
":",
"raise",
"ValueError",
"(",
"'bytes is not a 16-char string'",
")",
"assert",
"isinstance",
"(",
"bytes",
",",
"bytes_",
")",
",",
"repr",
"(",
"bytes",
")",
"int",
"=",
"int_",
".",
"from_bytes",
"(",
"bytes",
",",
"byteorder",
"=",
"'big'",
")",
"if",
"fields",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"fields",
")",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"'fields is not a 6-tuple'",
")",
"(",
"time_low",
",",
"time_mid",
",",
"time_hi_version",
",",
"clock_seq_hi_variant",
",",
"clock_seq_low",
",",
"node",
")",
"=",
"fields",
"if",
"not",
"0",
"<=",
"time_low",
"<",
"1",
"<<",
"32",
":",
"raise",
"ValueError",
"(",
"'field 1 out of range (need a 32-bit value)'",
")",
"if",
"not",
"0",
"<=",
"time_mid",
"<",
"1",
"<<",
"16",
":",
"raise",
"ValueError",
"(",
"'field 2 out of range (need a 16-bit value)'",
")",
"if",
"not",
"0",
"<=",
"time_hi_version",
"<",
"1",
"<<",
"16",
":",
"raise",
"ValueError",
"(",
"'field 3 out of range (need a 16-bit value)'",
")",
"if",
"not",
"0",
"<=",
"clock_seq_hi_variant",
"<",
"1",
"<<",
"8",
":",
"raise",
"ValueError",
"(",
"'field 4 out of range (need an 8-bit value)'",
")",
"if",
"not",
"0",
"<=",
"clock_seq_low",
"<",
"1",
"<<",
"8",
":",
"raise",
"ValueError",
"(",
"'field 5 out of range (need an 8-bit value)'",
")",
"if",
"not",
"0",
"<=",
"node",
"<",
"1",
"<<",
"48",
":",
"raise",
"ValueError",
"(",
"'field 6 out of range (need a 48-bit value)'",
")",
"clock_seq",
"=",
"(",
"clock_seq_hi_variant",
"<<",
"8",
")",
"|",
"clock_seq_low",
"int",
"=",
"(",
"(",
"time_low",
"<<",
"96",
")",
"|",
"(",
"time_mid",
"<<",
"80",
")",
"|",
"(",
"time_hi_version",
"<<",
"64",
")",
"|",
"(",
"clock_seq",
"<<",
"48",
")",
"|",
"node",
")",
"if",
"int",
"is",
"not",
"None",
":",
"if",
"not",
"0",
"<=",
"int",
"<",
"1",
"<<",
"128",
":",
"raise",
"ValueError",
"(",
"'int is out of range (need a 128-bit value)'",
")",
"if",
"version",
"is",
"not",
"None",
":",
"if",
"not",
"1",
"<=",
"version",
"<=",
"5",
":",
"raise",
"ValueError",
"(",
"'illegal version number'",
")",
"# Set the variant to RFC 4122.",
"int",
"&=",
"~",
"(",
"0xc000",
"<<",
"48",
")",
"int",
"|=",
"0x8000",
"<<",
"48",
"# Set the version number.",
"int",
"&=",
"~",
"(",
"0xf000",
"<<",
"64",
")",
"int",
"|=",
"version",
"<<",
"76",
"self",
".",
"__dict__",
"[",
"'int'",
"]",
"=",
"int",
"self",
".",
"__dict__",
"[",
"'is_safe'",
"]",
"=",
"is_safe"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/uuid.py#L121-L205 | ||
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/mox.py | python | Mox.__init__ | (self) | Initialize a new Mox. | Initialize a new Mox. | [
"Initialize",
"a",
"new",
"Mox",
"."
] | def __init__(self):
"""Initialize a new Mox."""
self._mock_objects = []
self.stubs = stubout.StubOutForTesting() | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_mock_objects",
"=",
"[",
"]",
"self",
".",
"stubs",
"=",
"stubout",
".",
"StubOutForTesting",
"(",
")"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/mox.py#L158-L162 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/__init__.py | python | _comp_method_SERIES | (cls, op, special) | return wrapper | Wrapper function for Series arithmetic operations, to avoid
code duplication. | Wrapper function for Series arithmetic operations, to avoid
code duplication. | [
"Wrapper",
"function",
"for",
"Series",
"arithmetic",
"operations",
"to",
"avoid",
"code",
"duplication",
"."
] | def _comp_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
@unpack_zerodim_and_defer(op_name)
def wrapper(self, other):
res_name = get_op_result_name(self, other)
if isinstance(other, ABCSeries) and not self._indexed_same(other):
raise ValueError("Can only compare identically-labeled Series objects")
lvalues = extract_array(self, extract_numpy=True)
rvalues = extract_array(other, extract_numpy=True)
res_values = comparison_op(lvalues, rvalues, op)
return _construct_result(self, res_values, index=self.index, name=res_name)
wrapper.__name__ = op_name
return wrapper | [
"def",
"_comp_method_SERIES",
"(",
"cls",
",",
"op",
",",
"special",
")",
":",
"op_name",
"=",
"_get_op_name",
"(",
"op",
",",
"special",
")",
"@",
"unpack_zerodim_and_defer",
"(",
"op_name",
")",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"res_name",
"=",
"get_op_result_name",
"(",
"self",
",",
"other",
")",
"if",
"isinstance",
"(",
"other",
",",
"ABCSeries",
")",
"and",
"not",
"self",
".",
"_indexed_same",
"(",
"other",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only compare identically-labeled Series objects\"",
")",
"lvalues",
"=",
"extract_array",
"(",
"self",
",",
"extract_numpy",
"=",
"True",
")",
"rvalues",
"=",
"extract_array",
"(",
"other",
",",
"extract_numpy",
"=",
"True",
")",
"res_values",
"=",
"comparison_op",
"(",
"lvalues",
",",
"rvalues",
",",
"op",
")",
"return",
"_construct_result",
"(",
"self",
",",
"res_values",
",",
"index",
"=",
"self",
".",
"index",
",",
"name",
"=",
"res_name",
")",
"wrapper",
".",
"__name__",
"=",
"op_name",
"return",
"wrapper"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/__init__.py#L511-L534 | |
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | scripts/cpp_lint.py | python | _NamespaceInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Check end of namespace comments. | Check end of namespace comments. | [
"Check",
"end",
"of",
"namespace",
"comments",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace"') | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
"# Check how many lines is enclosed in this namespace. Don't issue",
"# warning for missing namespace comments if there aren't enough",
"# lines. However, do apply checks if there is already an end of",
"# namespace comment and it's incorrect.",
"#",
"# TODO(unknown): We always want to check end of namespace comments",
"# if a namespace is large, but sometimes we also want to apply the",
"# check if a short namespace contained nontrivial things (something",
"# other than forward declarations). There is currently no logic on",
"# deciding what these nontrivial things are, so this check is",
"# triggered by namespace size only, which works most of the time.",
"if",
"(",
"linenum",
"-",
"self",
".",
"starting_linenum",
"<",
"10",
"and",
"not",
"Match",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace\\b'",
",",
"line",
")",
")",
":",
"return",
"# Look for matching comment at end of namespace.",
"#",
"# Note that we accept C style \"/* */\" comments for terminating",
"# namespaces, so that code that terminate namespaces inside",
"# preprocessor macros can be cpplint clean.",
"#",
"# We also accept stuff like \"// end of namespace <name>.\" with the",
"# period at the end.",
"#",
"# Besides these, we don't accept anything else, otherwise we might",
"# get false negatives when existing comment is a substring of the",
"# expected namespace.",
"if",
"self",
".",
"name",
":",
"# Named namespace",
"if",
"not",
"Match",
"(",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace\\s+'",
"+",
"re",
".",
"escape",
"(",
"self",
".",
"name",
")",
"+",
"r'[\\*/\\.\\\\\\s]*$'",
")",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/namespace'",
",",
"5",
",",
"'Namespace should be terminated with \"// namespace %s\"'",
"%",
"self",
".",
"name",
")",
"else",
":",
"# Anonymous namespace",
"if",
"not",
"Match",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/namespace'",
",",
"5",
",",
"'Namespace should be terminated with \"// namespace\"'",
")"
] | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L1860-L1903 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/framework/python/ops/variables.py | python | get_variables_by_name | (given_name, scope=None) | return get_variables(scope=scope, suffix=suffix) | Gets the list of variables that were given that name.
Args:
given_name: name given to the variable without any scope.
scope: an optional scope for filtering the variables to return.
Returns:
a copied list of variables with the given name and scope. | Gets the list of variables that were given that name. | [
"Gets",
"the",
"list",
"of",
"variables",
"that",
"were",
"given",
"that",
"name",
"."
] | def get_variables_by_name(given_name, scope=None):
"""Gets the list of variables that were given that name.
Args:
given_name: name given to the variable without any scope.
scope: an optional scope for filtering the variables to return.
Returns:
a copied list of variables with the given name and scope.
"""
suffix = '/' + given_name + ':|^' + given_name + ':'
return get_variables(scope=scope, suffix=suffix) | [
"def",
"get_variables_by_name",
"(",
"given_name",
",",
"scope",
"=",
"None",
")",
":",
"suffix",
"=",
"'/'",
"+",
"given_name",
"+",
"':|^'",
"+",
"given_name",
"+",
"':'",
"return",
"get_variables",
"(",
"scope",
"=",
"scope",
",",
"suffix",
"=",
"suffix",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/framework/python/ops/variables.py#L386-L397 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/urlhandler/protocol_socket.py | python | Serial.in_waiting | (self) | return len(lr) | Return the number of bytes currently in the input buffer. | Return the number of bytes currently in the input buffer. | [
"Return",
"the",
"number",
"of",
"bytes",
"currently",
"in",
"the",
"input",
"buffer",
"."
] | def in_waiting(self):
"""Return the number of bytes currently in the input buffer."""
if not self.is_open:
raise portNotOpenError
# Poll the socket to see if it is ready for reading.
# If ready, at least one byte will be to read.
lr, lw, lx = select.select([self._socket], [], [], 0)
return len(lr) | [
"def",
"in_waiting",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"portNotOpenError",
"# Poll the socket to see if it is ready for reading.",
"# If ready, at least one byte will be to read.",
"lr",
",",
"lw",
",",
"lx",
"=",
"select",
".",
"select",
"(",
"[",
"self",
".",
"_socket",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"0",
")",
"return",
"len",
"(",
"lr",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/urlhandler/protocol_socket.py#L134-L141 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/classifier/boosted_trees_classifier.py | python | BoostedTreesClassifier.__str__ | (self) | return self.__repr__() | Return a string description of the model to the ``print`` method.
Returns
-------
out : string
A description of the model. | Return a string description of the model to the ``print`` method. | [
"Return",
"a",
"string",
"description",
"of",
"the",
"model",
"to",
"the",
"print",
"method",
"."
] | def __str__(self):
"""
Return a string description of the model to the ``print`` method.
Returns
-------
out : string
A description of the model.
"""
return self.__repr__() | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"__repr__",
"(",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/classifier/boosted_trees_classifier.py#L71-L80 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/queue.py | python | Queue.qsize | (self) | Return the approximate size of the queue (not reliable!). | Return the approximate size of the queue (not reliable!). | [
"Return",
"the",
"approximate",
"size",
"of",
"the",
"queue",
"(",
"not",
"reliable!",
")",
"."
] | def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize() | [
"def",
"qsize",
"(",
"self",
")",
":",
"with",
"self",
".",
"mutex",
":",
"return",
"self",
".",
"_qsize",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/queue.py#L91-L94 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/oracle/connector.py | python | OracleDBConnector.getSqlDictionary | (self) | return sql_dict | Returns the dictionary for SQL dialog. | Returns the dictionary for SQL dialog. | [
"Returns",
"the",
"dictionary",
"for",
"SQL",
"dialog",
"."
] | def getSqlDictionary(self):
"""Returns the dictionary for SQL dialog."""
from .sql_dictionary import getSqlDictionary
sql_dict = getSqlDictionary()
# get schemas, tables and field names
items = []
# First look into the cache if available
if self.hasCache():
sql = u"""
SELECT DISTINCT tablename FROM "oracle_{0}"
UNION
SELECT DISTINCT ownername FROM "oracle_{0}"
""".format(self.connName)
if self.userTablesOnly:
sql = u"""
SELECT DISTINCT tablename
FROM "oracle_{conn}" WHERE ownername = '{user}'
UNION
SELECT DISTINCT ownername
FROM "oracle_{conn}" WHERE ownername = '{user}'
""".format(conn=self.connName, user=self.user)
c = self.cache_connection.cursor()
c.execute(sql)
for row in c.fetchall():
items.append(row[0])
c.close()
if self.hasCache():
sql = u"""
SELECT DISTINCT COLUMN_NAME FROM {}_TAB_COLUMNS
""".format(u"USER" if self.userTablesOnly else
u"ALL")
elif self.userTablesOnly:
sql = u"""
SELECT DISTINCT TABLE_NAME FROM USER_ALL_TABLES
UNION
SELECT USER FROM DUAL
UNION
SELECT DISTINCT COLUMN_NAME FROM USER_TAB_COLUMNS
"""
else:
sql = u"""
SELECT TABLE_NAME FROM ALL_ALL_TABLES
UNION
SELECT DISTINCT OWNER FROM ALL_ALL_TABLES
UNION
SELECT DISTINCT COLUMN_NAME FROM ALL_TAB_COLUMNS
"""
c = self._execute(None, sql)
for row in self._fetchall(c):
items.append(row[0])
c.close()
sql_dict["identifier"] = items
return sql_dict | [
"def",
"getSqlDictionary",
"(",
"self",
")",
":",
"from",
".",
"sql_dictionary",
"import",
"getSqlDictionary",
"sql_dict",
"=",
"getSqlDictionary",
"(",
")",
"# get schemas, tables and field names",
"items",
"=",
"[",
"]",
"# First look into the cache if available",
"if",
"self",
".",
"hasCache",
"(",
")",
":",
"sql",
"=",
"u\"\"\"\n SELECT DISTINCT tablename FROM \"oracle_{0}\"\n UNION\n SELECT DISTINCT ownername FROM \"oracle_{0}\"\n \"\"\"",
".",
"format",
"(",
"self",
".",
"connName",
")",
"if",
"self",
".",
"userTablesOnly",
":",
"sql",
"=",
"u\"\"\"\n SELECT DISTINCT tablename\n FROM \"oracle_{conn}\" WHERE ownername = '{user}'\n UNION\n SELECT DISTINCT ownername\n FROM \"oracle_{conn}\" WHERE ownername = '{user}'\n \"\"\"",
".",
"format",
"(",
"conn",
"=",
"self",
".",
"connName",
",",
"user",
"=",
"self",
".",
"user",
")",
"c",
"=",
"self",
".",
"cache_connection",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"sql",
")",
"for",
"row",
"in",
"c",
".",
"fetchall",
"(",
")",
":",
"items",
".",
"append",
"(",
"row",
"[",
"0",
"]",
")",
"c",
".",
"close",
"(",
")",
"if",
"self",
".",
"hasCache",
"(",
")",
":",
"sql",
"=",
"u\"\"\"\n SELECT DISTINCT COLUMN_NAME FROM {}_TAB_COLUMNS\n \"\"\"",
".",
"format",
"(",
"u\"USER\"",
"if",
"self",
".",
"userTablesOnly",
"else",
"u\"ALL\"",
")",
"elif",
"self",
".",
"userTablesOnly",
":",
"sql",
"=",
"u\"\"\"\n SELECT DISTINCT TABLE_NAME FROM USER_ALL_TABLES\n UNION\n SELECT USER FROM DUAL\n UNION\n SELECT DISTINCT COLUMN_NAME FROM USER_TAB_COLUMNS\n \"\"\"",
"else",
":",
"sql",
"=",
"u\"\"\"\n SELECT TABLE_NAME FROM ALL_ALL_TABLES\n UNION\n SELECT DISTINCT OWNER FROM ALL_ALL_TABLES\n UNION\n SELECT DISTINCT COLUMN_NAME FROM ALL_TAB_COLUMNS\n \"\"\"",
"c",
"=",
"self",
".",
"_execute",
"(",
"None",
",",
"sql",
")",
"for",
"row",
"in",
"self",
".",
"_fetchall",
"(",
"c",
")",
":",
"items",
".",
"append",
"(",
"row",
"[",
"0",
"]",
")",
"c",
".",
"close",
"(",
")",
"sql_dict",
"[",
"\"identifier\"",
"]",
"=",
"items",
"return",
"sql_dict"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/oracle/connector.py#L1684-L1742 | |
microsoft/DirectXShaderCompiler | 8348ff8d9e0287610ba05d3a828e10af981a1c05 | utils/hct/CodeTags.py | python | Test.verify | (self) | return '==================== Verify failed!\n--- Before:%s+++ After:%s=== Expected:%s====================\n' % (
self.before, self.after, self.expected
) | Returns nothing if passed, or failure message if failed. | Returns nothing if passed, or failure message if failed. | [
"Returns",
"nothing",
"if",
"passed",
"or",
"failure",
"message",
"if",
"failed",
"."
] | def verify(self):
"Returns nothing if passed, or failure message if failed."
if self.after == self.expected:
return
return '==================== Verify failed!\n--- Before:%s+++ After:%s=== Expected:%s====================\n' % (
self.before, self.after, self.expected
) | [
"def",
"verify",
"(",
"self",
")",
":",
"if",
"self",
".",
"after",
"==",
"self",
".",
"expected",
":",
"return",
"return",
"'==================== Verify failed!\\n--- Before:%s+++ After:%s=== Expected:%s====================\\n'",
"%",
"(",
"self",
".",
"before",
",",
"self",
".",
"after",
",",
"self",
".",
"expected",
")"
] | https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/utils/hct/CodeTags.py#L263-L269 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/ccompiler.py | python | CCompiler._fix_object_args | (self, objects, output_dir) | return (objects, output_dir) | Typecheck and fix up some arguments supplied to various methods.
Specifically: ensure that 'objects' is a list; if output_dir is
None, replace with self.output_dir. Return fixed versions of
'objects' and 'output_dir'. | Typecheck and fix up some arguments supplied to various methods.
Specifically: ensure that 'objects' is a list; if output_dir is
None, replace with self.output_dir. Return fixed versions of
'objects' and 'output_dir'. | [
"Typecheck",
"and",
"fix",
"up",
"some",
"arguments",
"supplied",
"to",
"various",
"methods",
".",
"Specifically",
":",
"ensure",
"that",
"objects",
"is",
"a",
"list",
";",
"if",
"output_dir",
"is",
"None",
"replace",
"with",
"self",
".",
"output_dir",
".",
"Return",
"fixed",
"versions",
"of",
"objects",
"and",
"output_dir",
"."
] | def _fix_object_args(self, objects, output_dir):
"""Typecheck and fix up some arguments supplied to various methods.
Specifically: ensure that 'objects' is a list; if output_dir is
None, replace with self.output_dir. Return fixed versions of
'objects' and 'output_dir'.
"""
if not isinstance(objects, (list, tuple)):
raise TypeError("'objects' must be a list or tuple of strings")
objects = list(objects)
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")
return (objects, output_dir) | [
"def",
"_fix_object_args",
"(",
"self",
",",
"objects",
",",
"output_dir",
")",
":",
"if",
"not",
"isinstance",
"(",
"objects",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"'objects' must be a list or tuple of strings\"",
")",
"objects",
"=",
"list",
"(",
"objects",
")",
"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\"",
")",
"return",
"(",
"objects",
",",
"output_dir",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/ccompiler.py#L410-L425 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir_utils.py | python | guard | (func, *args, **kwargs) | Run a function with given set of arguments, and guard against
any GuardException raised by the function by returning None,
or the expected return results if no such exception was raised. | Run a function with given set of arguments, and guard against
any GuardException raised by the function by returning None,
or the expected return results if no such exception was raised. | [
"Run",
"a",
"function",
"with",
"given",
"set",
"of",
"arguments",
"and",
"guard",
"against",
"any",
"GuardException",
"raised",
"by",
"the",
"function",
"by",
"returning",
"None",
"or",
"the",
"expected",
"return",
"results",
"if",
"no",
"such",
"exception",
"was",
"raised",
"."
] | def guard(func, *args, **kwargs):
"""
Run a function with given set of arguments, and guard against
any GuardException raised by the function by returning None,
or the expected return results if no such exception was raised.
"""
try:
return func(*args, **kwargs)
except GuardException:
return None | [
"def",
"guard",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"GuardException",
":",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir_utils.py#L1430-L1439 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgi.py | python | FieldStorage.getlist | (self, key) | Return list of received values. | Return list of received values. | [
"Return",
"list",
"of",
"received",
"values",
"."
] | def getlist(self, key):
""" Return list of received values."""
if key in self:
value = self[key]
if isinstance(value, list):
return [x.value for x in value]
else:
return [value.value]
else:
return [] | [
"def",
"getlist",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
":",
"value",
"=",
"self",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"value",
"]",
"else",
":",
"return",
"[",
"value",
".",
"value",
"]",
"else",
":",
"return",
"[",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgi.py#L570-L579 | ||
meganz/sdk | 00ace479a434b2d5c329cfe4f7178392fcfd1cdb | examples/python/crud_example.py | python | AppListener.onRequestTemporaryError | (self, api, request, error) | Called upon a temprary error of the API operation. To be continued
(involving further callbacks).
:param api: Reference to the API object.
:param request: Reference to the request this operation belongs to.
:param eror: Error information. | Called upon a temprary error of the API operation. To be continued
(involving further callbacks). | [
"Called",
"upon",
"a",
"temprary",
"error",
"of",
"the",
"API",
"operation",
".",
"To",
"be",
"continued",
"(",
"involving",
"further",
"callbacks",
")",
"."
] | def onRequestTemporaryError(self, api, request, error):
"""
Called upon a temprary error of the API operation. To be continued
(involving further callbacks).
:param api: Reference to the API object.
:param request: Reference to the request this operation belongs to.
:param eror: Error information.
"""
logging.info('Request temporary error ({}); Error: {}'
.format(request, error)) | [
"def",
"onRequestTemporaryError",
"(",
"self",
",",
"api",
",",
"request",
",",
"error",
")",
":",
"logging",
".",
"info",
"(",
"'Request temporary error ({}); Error: {}'",
".",
"format",
"(",
"request",
",",
"error",
")",
")"
] | https://github.com/meganz/sdk/blob/00ace479a434b2d5c329cfe4f7178392fcfd1cdb/examples/python/crud_example.py#L105-L115 | ||
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | plugins/wb.admin/backend/wb_server_control.py | python | ServerControlWMI.get_status | (self, verbose=1) | return result | Returned value is one of running, stopping, starting, stopped, unknown | Returned value is one of running, stopping, starting, stopped, unknown | [
"Returned",
"value",
"is",
"one",
"of",
"running",
"stopping",
"starting",
"stopped",
"unknown"
] | def get_status(self, verbose=1):
"Returned value is one of running, stopping, starting, stopped, unknown"
service = self.profile.wmi_service_name
action = "status"
if verbose > 1:
self.info("Checking service status of instance %s..." % service)
result = self.wmi.wmiServiceControl(self.wmi_session_id_for_current_thread, service, action)
if verbose:
self.info("Status check of service '%s' returned %s" % (service, result))
# translate status to something more displayable
if result == "stop pending":
result = "stopping"
elif result == "start pending":
result = "starting"
return result | [
"def",
"get_status",
"(",
"self",
",",
"verbose",
"=",
"1",
")",
":",
"service",
"=",
"self",
".",
"profile",
".",
"wmi_service_name",
"action",
"=",
"\"status\"",
"if",
"verbose",
">",
"1",
":",
"self",
".",
"info",
"(",
"\"Checking service status of instance %s...\"",
"%",
"service",
")",
"result",
"=",
"self",
".",
"wmi",
".",
"wmiServiceControl",
"(",
"self",
".",
"wmi_session_id_for_current_thread",
",",
"service",
",",
"action",
")",
"if",
"verbose",
":",
"self",
".",
"info",
"(",
"\"Status check of service '%s' returned %s\"",
"%",
"(",
"service",
",",
"result",
")",
")",
"# translate status to something more displayable",
"if",
"result",
"==",
"\"stop pending\"",
":",
"result",
"=",
"\"stopping\"",
"elif",
"result",
"==",
"\"start pending\"",
":",
"result",
"=",
"\"starting\"",
"return",
"result"
] | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/plugins/wb.admin/backend/wb_server_control.py#L876-L891 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | Context.abs | (self, a) | return a.__abs__(context=self) | Returns the absolute value of the operand.
If the operand is negative, the result is the same as using the minus
operation on the operand. Otherwise, the result is the same as using
the plus operation on the operand.
>>> ExtendedContext.abs(Decimal('2.1'))
Decimal('2.1')
>>> ExtendedContext.abs(Decimal('-100'))
Decimal('100')
>>> ExtendedContext.abs(Decimal('101.5'))
Decimal('101.5')
>>> ExtendedContext.abs(Decimal('-101.5'))
Decimal('101.5')
>>> ExtendedContext.abs(-1)
Decimal('1') | Returns the absolute value of the operand. | [
"Returns",
"the",
"absolute",
"value",
"of",
"the",
"operand",
"."
] | def abs(self, a):
"""Returns the absolute value of the operand.
If the operand is negative, the result is the same as using the minus
operation on the operand. Otherwise, the result is the same as using
the plus operation on the operand.
>>> ExtendedContext.abs(Decimal('2.1'))
Decimal('2.1')
>>> ExtendedContext.abs(Decimal('-100'))
Decimal('100')
>>> ExtendedContext.abs(Decimal('101.5'))
Decimal('101.5')
>>> ExtendedContext.abs(Decimal('-101.5'))
Decimal('101.5')
>>> ExtendedContext.abs(-1)
Decimal('1')
"""
a = _convert_other(a, raiseit=True)
return a.__abs__(context=self) | [
"def",
"abs",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"__abs__",
"(",
"context",
"=",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L4129-L4148 | |
commaai/openpilot | 4416c21b1e738ab7d04147c5ae52b5135e0cdb40 | pyextra/acados_template/acados_ocp.py | python | AcadosOcpCost.Zl_e | (self) | return self.__Zl_e | :math:`Z_l^e` - diagonal of Hessian wrt lower slack at terminal shooting node (N).
Default: :code:`np.array([])`. | :math:`Z_l^e` - diagonal of Hessian wrt lower slack at terminal shooting node (N).
Default: :code:`np.array([])`. | [
":",
"math",
":",
"Z_l^e",
"-",
"diagonal",
"of",
"Hessian",
"wrt",
"lower",
"slack",
"at",
"terminal",
"shooting",
"node",
"(",
"N",
")",
".",
"Default",
":",
":",
"code",
":",
"np",
".",
"array",
"(",
"[]",
")",
"."
] | def Zl_e(self):
""":math:`Z_l^e` - diagonal of Hessian wrt lower slack at terminal shooting node (N).
Default: :code:`np.array([])`.
"""
return self.__Zl_e | [
"def",
"Zl_e",
"(",
"self",
")",
":",
"return",
"self",
".",
"__Zl_e"
] | https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L855-L859 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/code.py | python | InteractiveConsole.__init__ | (self, locals=None, filename="<console>") | Constructor.
The optional locals argument will be passed to the
InteractiveInterpreter base class.
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks. | Constructor. | [
"Constructor",
"."
] | def __init__(self, locals=None, filename="<console>"):
"""Constructor.
The optional locals argument will be passed to the
InteractiveInterpreter base class.
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks.
"""
InteractiveInterpreter.__init__(self, locals)
self.filename = filename
self.resetbuffer() | [
"def",
"__init__",
"(",
"self",
",",
"locals",
"=",
"None",
",",
"filename",
"=",
"\"<console>\"",
")",
":",
"InteractiveInterpreter",
".",
"__init__",
"(",
"self",
",",
"locals",
")",
"self",
".",
"filename",
"=",
"filename",
"self",
".",
"resetbuffer",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/code.py#L170-L182 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | StaticLine.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LI_HORIZONTAL,
String name=StaticLineNameStr) -> StaticLine | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LI_HORIZONTAL,
String name=StaticLineNameStr) -> StaticLine | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"LI_HORIZONTAL",
"String",
"name",
"=",
"StaticLineNameStr",
")",
"-",
">",
"StaticLine"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=LI_HORIZONTAL,
String name=StaticLineNameStr) -> StaticLine
"""
_controls_.StaticLine_swiginit(self,_controls_.new_StaticLine(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"StaticLine_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_StaticLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L909-L916 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py | python | matmul_shape_inference | (a, b, c, transpose_a, transpose_b, adjoint_a,
adjoint_b) | return c_handle | Helper function for matmul to set the result matrix's handle data. | Helper function for matmul to set the result matrix's handle data. | [
"Helper",
"function",
"for",
"matmul",
"to",
"set",
"the",
"result",
"matrix",
"s",
"handle",
"data",
"."
] | def matmul_shape_inference(a, b, c, transpose_a, transpose_b, adjoint_a,
adjoint_b):
"""Helper function for matmul to set the result matrix's handle data."""
c_handle = getattr(c, "_handle_data", None)
a_shape_and_type = get_shape_and_type(a)
b_shape_and_type = get_shape_and_type(b)
if (c_handle is None and a_shape_and_type is not None and
b_shape_and_type is not None):
transpose_a = transpose_a or adjoint_a
transpose_b = transpose_b or adjoint_b
a_shape = a_shape_and_type.shape
b_shape = b_shape_and_type.shape
rank = len(a_shape.dim)
# Creates the output shape.
c_rows = a_shape.dim[rank - (1 if transpose_a else 2)].size
c_cols = b_shape.dim[rank - (2 if transpose_b else 1)].size
c_shape = tensor_shape.TensorShape(a_shape)
c_shape = tensor_shape.TensorShape(c_shape[:rank - 2] + [c_rows, c_cols])
c_handle = _create_handle_data_proto(c_shape.as_proto(),
a_shape_and_type.dtype)
return c_handle | [
"def",
"matmul_shape_inference",
"(",
"a",
",",
"b",
",",
"c",
",",
"transpose_a",
",",
"transpose_b",
",",
"adjoint_a",
",",
"adjoint_b",
")",
":",
"c_handle",
"=",
"getattr",
"(",
"c",
",",
"\"_handle_data\"",
",",
"None",
")",
"a_shape_and_type",
"=",
"get_shape_and_type",
"(",
"a",
")",
"b_shape_and_type",
"=",
"get_shape_and_type",
"(",
"b",
")",
"if",
"(",
"c_handle",
"is",
"None",
"and",
"a_shape_and_type",
"is",
"not",
"None",
"and",
"b_shape_and_type",
"is",
"not",
"None",
")",
":",
"transpose_a",
"=",
"transpose_a",
"or",
"adjoint_a",
"transpose_b",
"=",
"transpose_b",
"or",
"adjoint_b",
"a_shape",
"=",
"a_shape_and_type",
".",
"shape",
"b_shape",
"=",
"b_shape_and_type",
".",
"shape",
"rank",
"=",
"len",
"(",
"a_shape",
".",
"dim",
")",
"# Creates the output shape.",
"c_rows",
"=",
"a_shape",
".",
"dim",
"[",
"rank",
"-",
"(",
"1",
"if",
"transpose_a",
"else",
"2",
")",
"]",
".",
"size",
"c_cols",
"=",
"b_shape",
".",
"dim",
"[",
"rank",
"-",
"(",
"2",
"if",
"transpose_b",
"else",
"1",
")",
"]",
".",
"size",
"c_shape",
"=",
"tensor_shape",
".",
"TensorShape",
"(",
"a_shape",
")",
"c_shape",
"=",
"tensor_shape",
".",
"TensorShape",
"(",
"c_shape",
"[",
":",
"rank",
"-",
"2",
"]",
"+",
"[",
"c_rows",
",",
"c_cols",
"]",
")",
"c_handle",
"=",
"_create_handle_data_proto",
"(",
"c_shape",
".",
"as_proto",
"(",
")",
",",
"a_shape_and_type",
".",
"dtype",
")",
"return",
"c_handle"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py#L115-L138 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_uninstall.py | python | UninstallPathSet._allowed_to_proceed | (self, verbose) | return ask('Proceed (y/n)? ', ('y', 'n')) == 'y' | Display which files would be deleted and prompt for confirmation | Display which files would be deleted and prompt for confirmation | [
"Display",
"which",
"files",
"would",
"be",
"deleted",
"and",
"prompt",
"for",
"confirmation"
] | def _allowed_to_proceed(self, verbose):
"""Display which files would be deleted and prompt for confirmation
"""
def _display(msg, paths):
if not paths:
return
logger.info(msg)
with indent_log():
for path in sorted(compact(paths)):
logger.info(path)
if not verbose:
will_remove, will_skip = compress_for_output_listing(self.paths)
else:
# In verbose mode, display all the files that are going to be
# deleted.
will_remove = list(self.paths)
will_skip = set()
_display('Would remove:', will_remove)
_display('Would not remove (might be manually added):', will_skip)
_display('Would not remove (outside of prefix):', self._refuse)
if verbose:
_display('Will actually move:', compress_for_rename(self.paths))
return ask('Proceed (y/n)? ', ('y', 'n')) == 'y' | [
"def",
"_allowed_to_proceed",
"(",
"self",
",",
"verbose",
")",
":",
"def",
"_display",
"(",
"msg",
",",
"paths",
")",
":",
"if",
"not",
"paths",
":",
"return",
"logger",
".",
"info",
"(",
"msg",
")",
"with",
"indent_log",
"(",
")",
":",
"for",
"path",
"in",
"sorted",
"(",
"compact",
"(",
"paths",
")",
")",
":",
"logger",
".",
"info",
"(",
"path",
")",
"if",
"not",
"verbose",
":",
"will_remove",
",",
"will_skip",
"=",
"compress_for_output_listing",
"(",
"self",
".",
"paths",
")",
"else",
":",
"# In verbose mode, display all the files that are going to be",
"# deleted.",
"will_remove",
"=",
"list",
"(",
"self",
".",
"paths",
")",
"will_skip",
"=",
"set",
"(",
")",
"_display",
"(",
"'Would remove:'",
",",
"will_remove",
")",
"_display",
"(",
"'Would not remove (might be manually added):'",
",",
"will_skip",
")",
"_display",
"(",
"'Would not remove (outside of prefix):'",
",",
"self",
".",
"_refuse",
")",
"if",
"verbose",
":",
"_display",
"(",
"'Will actually move:'",
",",
"compress_for_rename",
"(",
"self",
".",
"paths",
")",
")",
"return",
"ask",
"(",
"'Proceed (y/n)? '",
",",
"(",
"'y'",
",",
"'n'",
")",
")",
"==",
"'y'"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_uninstall.py#L368-L395 | |
LLNL/Caliper | 60e06980fc65057e1da01296e6eebbbed30f59c8 | src/mpi/services/mpiwrap/wrap.py | python | sub | (out, scope, args, children) | {{sub <string> <regexp> <substitution>}}
Replaces value of <string> with all instances of <regexp> replaced with <substitution>. | {{sub <string> <regexp> <substitution>}}
Replaces value of <string> with all instances of <regexp> replaced with <substitution>. | [
"{{",
"sub",
"<string",
">",
"<regexp",
">",
"<substitution",
">",
"}}",
"Replaces",
"value",
"of",
"<string",
">",
"with",
"all",
"instances",
"of",
"<regexp",
">",
"replaced",
"with",
"<substitution",
">",
"."
] | def sub(out, scope, args, children):
"""{{sub <string> <regexp> <substitution>}}
Replaces value of <string> with all instances of <regexp> replaced with <substitution>.
"""
len(args) == 3 or syntax_error("'sub' macro takes exactly 4 arguments.")
string, regex, substitution = args
if isinstance(string, list):
return [re.sub(regex, substitution, s) for s in string]
if not isinstance(regex, str):
syntax_error("Invalid regular expression in 'sub' macro: '%s'" % regex)
else:
return re.sub(regex, substitution, string) | [
"def",
"sub",
"(",
"out",
",",
"scope",
",",
"args",
",",
"children",
")",
":",
"len",
"(",
"args",
")",
"==",
"3",
"or",
"syntax_error",
"(",
"\"'sub' macro takes exactly 4 arguments.\"",
")",
"string",
",",
"regex",
",",
"substitution",
"=",
"args",
"if",
"isinstance",
"(",
"string",
",",
"list",
")",
":",
"return",
"[",
"re",
".",
"sub",
"(",
"regex",
",",
"substitution",
",",
"s",
")",
"for",
"s",
"in",
"string",
"]",
"if",
"not",
"isinstance",
"(",
"regex",
",",
"str",
")",
":",
"syntax_error",
"(",
"\"Invalid regular expression in 'sub' macro: '%s'\"",
"%",
"regex",
")",
"else",
":",
"return",
"re",
".",
"sub",
"(",
"regex",
",",
"substitution",
",",
"string",
")"
] | https://github.com/LLNL/Caliper/blob/60e06980fc65057e1da01296e6eebbbed30f59c8/src/mpi/services/mpiwrap/wrap.py#L1054-L1065 | ||
p4lang/PI | 38d87e81253feff9fff0660d662c885be78fb719 | tools/cpplint.py | python | _SetOutputFormat | (output_format) | Sets the module's output format. | Sets the module's output format. | [
"Sets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _SetOutputFormat(output_format):
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format) | [
"def",
"_SetOutputFormat",
"(",
"output_format",
")",
":",
"_cpplint_state",
".",
"SetOutputFormat",
"(",
"output_format",
")"
] | https://github.com/p4lang/PI/blob/38d87e81253feff9fff0660d662c885be78fb719/tools/cpplint.py#L1421-L1423 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/concurrent/futures/process.py | python | _add_call_item_to_queue | (pending_work_items,
work_ids,
call_queue) | Fills call_queue with _WorkItems from pending_work_items.
This function never blocks.
Args:
pending_work_items: A dict mapping work ids to _WorkItems e.g.
{5: <_WorkItem...>, 6: <_WorkItem...>, ...}
work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
are consumed and the corresponding _WorkItems from
pending_work_items are transformed into _CallItems and put in
call_queue.
call_queue: A multiprocessing.Queue that will be filled with _CallItems
derived from _WorkItems. | Fills call_queue with _WorkItems from pending_work_items. | [
"Fills",
"call_queue",
"with",
"_WorkItems",
"from",
"pending_work_items",
"."
] | def _add_call_item_to_queue(pending_work_items,
work_ids,
call_queue):
"""Fills call_queue with _WorkItems from pending_work_items.
This function never blocks.
Args:
pending_work_items: A dict mapping work ids to _WorkItems e.g.
{5: <_WorkItem...>, 6: <_WorkItem...>, ...}
work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
are consumed and the corresponding _WorkItems from
pending_work_items are transformed into _CallItems and put in
call_queue.
call_queue: A multiprocessing.Queue that will be filled with _CallItems
derived from _WorkItems.
"""
while True:
if call_queue.full():
return
try:
work_id = work_ids.get(block=False)
except queue.Empty:
return
else:
work_item = pending_work_items[work_id]
if work_item.future.set_running_or_notify_cancel():
call_queue.put(_CallItem(work_id,
work_item.fn,
work_item.args,
work_item.kwargs),
block=True)
else:
del pending_work_items[work_id]
continue | [
"def",
"_add_call_item_to_queue",
"(",
"pending_work_items",
",",
"work_ids",
",",
"call_queue",
")",
":",
"while",
"True",
":",
"if",
"call_queue",
".",
"full",
"(",
")",
":",
"return",
"try",
":",
"work_id",
"=",
"work_ids",
".",
"get",
"(",
"block",
"=",
"False",
")",
"except",
"queue",
".",
"Empty",
":",
"return",
"else",
":",
"work_item",
"=",
"pending_work_items",
"[",
"work_id",
"]",
"if",
"work_item",
".",
"future",
".",
"set_running_or_notify_cancel",
"(",
")",
":",
"call_queue",
".",
"put",
"(",
"_CallItem",
"(",
"work_id",
",",
"work_item",
".",
"fn",
",",
"work_item",
".",
"args",
",",
"work_item",
".",
"kwargs",
")",
",",
"block",
"=",
"True",
")",
"else",
":",
"del",
"pending_work_items",
"[",
"work_id",
"]",
"continue"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/concurrent/futures/process.py#L137-L172 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/constant_op.py | python | constant | (value, dtype=None, shape=None, name="Const") | return const_tensor | Creates a constant tensor.
The resulting tensor is populated with values of type `dtype`, as
specified by arguments `value` and (optionally) `shape` (see examples
below).
The argument `value` can be a constant value, or a list of values of type
`dtype`. If `value` is a list, then the length of the list must be less
than or equal to the number of elements implied by the `shape` argument (if
specified). In the case where the list length is less than the number of
elements specified by `shape`, the last element in the list will be used
to fill the remaining entries.
The argument `shape` is optional. If present, it specifies the dimensions of
the resulting tensor. If not present, the shape of `value` is used.
If the argument `dtype` is not specified, then the type is inferred from
the type of `value`.
For example:
```python
# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
```
Args:
value: A constant value (or list) of output type `dtype`.
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
Returns:
A Constant Tensor. | Creates a constant tensor. | [
"Creates",
"a",
"constant",
"tensor",
"."
] | def constant(value, dtype=None, shape=None, name="Const"):
"""Creates a constant tensor.
The resulting tensor is populated with values of type `dtype`, as
specified by arguments `value` and (optionally) `shape` (see examples
below).
The argument `value` can be a constant value, or a list of values of type
`dtype`. If `value` is a list, then the length of the list must be less
than or equal to the number of elements implied by the `shape` argument (if
specified). In the case where the list length is less than the number of
elements specified by `shape`, the last element in the list will be used
to fill the remaining entries.
The argument `shape` is optional. If present, it specifies the dimensions of
the resulting tensor. If not present, the shape of `value` is used.
If the argument `dtype` is not specified, then the type is inferred from
the type of `value`.
For example:
```python
# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
```
Args:
value: A constant value (or list) of output type `dtype`.
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
Returns:
A Constant Tensor.
"""
g = ops.get_default_graph()
tensor_value = attr_value_pb2.AttrValue()
tensor_value.tensor.CopyFrom(
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
const_tensor = g.create_op(
"Const", [], [dtype_value.type],
attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0]
return const_tensor | [
"def",
"constant",
"(",
"value",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"name",
"=",
"\"Const\"",
")",
":",
"g",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
"tensor_value",
"=",
"attr_value_pb2",
".",
"AttrValue",
"(",
")",
"tensor_value",
".",
"tensor",
".",
"CopyFrom",
"(",
"tensor_util",
".",
"make_tensor_proto",
"(",
"value",
",",
"dtype",
"=",
"dtype",
",",
"shape",
"=",
"shape",
")",
")",
"dtype_value",
"=",
"attr_value_pb2",
".",
"AttrValue",
"(",
"type",
"=",
"tensor_value",
".",
"tensor",
".",
"dtype",
")",
"const_tensor",
"=",
"g",
".",
"create_op",
"(",
"\"Const\"",
",",
"[",
"]",
",",
"[",
"dtype_value",
".",
"type",
"]",
",",
"attrs",
"=",
"{",
"\"value\"",
":",
"tensor_value",
",",
"\"dtype\"",
":",
"dtype_value",
"}",
",",
"name",
"=",
"name",
")",
".",
"outputs",
"[",
"0",
"]",
"return",
"const_tensor"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/constant_op.py#L117-L168 | |
leosac/leosac | 932a2a90bd2e75483d46b24fdbc8f02e0809d731 | python/leosacpy/wsclient.py | python | LowLevelWSClient.send_raw | (self, obj: Union[str, dict]) | Send something to leosac.
Note: Prefer using send() instead
The behavior differ based on the type of `obj`.
+ str: send as is.
+ dict: serialize to json and send.
:param obj: | Send something to leosac.
Note: Prefer using send() instead
The behavior differ based on the type of `obj`.
+ str: send as is.
+ dict: serialize to json and send.
:param obj: | [
"Send",
"something",
"to",
"leosac",
".",
"Note",
":",
"Prefer",
"using",
"send",
"()",
"instead",
"The",
"behavior",
"differ",
"based",
"on",
"the",
"type",
"of",
"obj",
".",
"+",
"str",
":",
"send",
"as",
"is",
".",
"+",
"dict",
":",
"serialize",
"to",
"json",
"and",
"send",
".",
":",
"param",
"obj",
":"
] | async def send_raw(self, obj: Union[str, dict]):
"""
Send something to leosac.
Note: Prefer using send() instead
The behavior differ based on the type of `obj`.
+ str: send as is.
+ dict: serialize to json and send.
:param obj:
"""
assert self.ws
payload = obj if isinstance(obj, str) else json.dumps(obj)
await self.ws.send(payload) | [
"async",
"def",
"send_raw",
"(",
"self",
",",
"obj",
":",
"Union",
"[",
"str",
",",
"dict",
"]",
")",
":",
"assert",
"self",
".",
"ws",
"payload",
"=",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"json",
".",
"dumps",
"(",
"obj",
")",
"await",
"self",
".",
"ws",
".",
"send",
"(",
"payload",
")"
] | https://github.com/leosac/leosac/blob/932a2a90bd2e75483d46b24fdbc8f02e0809d731/python/leosacpy/wsclient.py#L192-L207 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/shutil.py | python | register_archive_format | (name, function, extra_args=None, description='') | Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function. | Registers an archive format. | [
"Registers",
"an",
"archive",
"format",
"."
] | def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not isinstance(function, collections.Callable):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2 :
raise TypeError('extra_args elements are : (arg_name, value)')
_ARCHIVE_FORMATS[name] = (function, extra_args, description) | [
"def",
"register_archive_format",
"(",
"name",
",",
"function",
",",
"extra_args",
"=",
"None",
",",
"description",
"=",
"''",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"function",
",",
"collections",
".",
"Callable",
")",
":",
"raise",
"TypeError",
"(",
"'The %s object is not callable'",
"%",
"function",
")",
"if",
"not",
"isinstance",
"(",
"extra_args",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"(",
"'extra_args needs to be a sequence'",
")",
"for",
"element",
"in",
"extra_args",
":",
"if",
"not",
"isinstance",
"(",
"element",
",",
"(",
"tuple",
",",
"list",
")",
")",
"or",
"len",
"(",
"element",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"'extra_args elements are : (arg_name, value)'",
")",
"_ARCHIVE_FORMATS",
"[",
"name",
"]",
"=",
"(",
"function",
",",
"extra_args",
",",
"description",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/shutil.py#L480-L499 | ||
happynear/caffe-windows | 967eedf25009e334b7f6f933bb5e17aaaff5bef6 | python/caffe/coord_map.py | python | conv_params | (fn) | return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1)) | Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters. | Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation. | [
"Extract",
"the",
"spatial",
"parameters",
"that",
"determine",
"the",
"coordinate",
"mapping",
":",
"kernel",
"size",
"stride",
"padding",
"and",
"dilation",
"."
] | def conv_params(fn):
"""
Extract the spatial parameters that determine the coordinate mapping:
kernel size, stride, padding, and dilation.
Implementation detail: Convolution, Deconvolution, and Im2col layers
define these in the convolution_param message, while Pooling has its
own fields in pooling_param. This method deals with these details to
extract canonical parameters.
"""
params = fn.params.get('convolution_param', fn.params)
axis = params.get('axis', 1)
ks = np.array(params['kernel_size'], ndmin=1)
dilation = np.array(params.get('dilation', 1), ndmin=1)
assert len({'pad_h', 'pad_w', 'kernel_h', 'kernel_w', 'stride_h',
'stride_w'} & set(fn.params)) == 0, \
'cropping does not support legacy _h/_w params'
return (axis, np.array(params.get('stride', 1), ndmin=1),
(ks - 1) * dilation + 1,
np.array(params.get('pad', 0), ndmin=1)) | [
"def",
"conv_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'convolution_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"1",
")",
"ks",
"=",
"np",
".",
"array",
"(",
"params",
"[",
"'kernel_size'",
"]",
",",
"ndmin",
"=",
"1",
")",
"dilation",
"=",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'dilation'",
",",
"1",
")",
",",
"ndmin",
"=",
"1",
")",
"assert",
"len",
"(",
"{",
"'pad_h'",
",",
"'pad_w'",
",",
"'kernel_h'",
",",
"'kernel_w'",
",",
"'stride_h'",
",",
"'stride_w'",
"}",
"&",
"set",
"(",
"fn",
".",
"params",
")",
")",
"==",
"0",
",",
"'cropping does not support legacy _h/_w params'",
"return",
"(",
"axis",
",",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'stride'",
",",
"1",
")",
",",
"ndmin",
"=",
"1",
")",
",",
"(",
"ks",
"-",
"1",
")",
"*",
"dilation",
"+",
"1",
",",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'pad'",
",",
"0",
")",
",",
"ndmin",
"=",
"1",
")",
")"
] | https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/python/caffe/coord_map.py#L18-L37 | |
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/mini-cluster/relocate_binaries_for_mini_cluster.py | python | prep_artifact_dirs | (config) | Create any required artifact output directories, if needed. | Create any required artifact output directories, if needed. | [
"Create",
"any",
"required",
"artifact",
"output",
"directories",
"if",
"needed",
"."
] | def prep_artifact_dirs(config):
"""
Create any required artifact output directories, if needed.
"""
if not os.path.exists(config[ARTIFACT_ROOT]):
os.makedirs(config[ARTIFACT_ROOT], mode=0o755)
if not os.path.exists(config[ARTIFACT_BIN_DIR]):
os.makedirs(config[ARTIFACT_BIN_DIR], mode=0o755)
if not os.path.exists(config[ARTIFACT_LIB_DIR]):
os.makedirs(config[ARTIFACT_LIB_DIR], mode=0o755) | [
"def",
"prep_artifact_dirs",
"(",
"config",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
"[",
"ARTIFACT_ROOT",
"]",
")",
":",
"os",
".",
"makedirs",
"(",
"config",
"[",
"ARTIFACT_ROOT",
"]",
",",
"mode",
"=",
"0o755",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
"[",
"ARTIFACT_BIN_DIR",
"]",
")",
":",
"os",
".",
"makedirs",
"(",
"config",
"[",
"ARTIFACT_BIN_DIR",
"]",
",",
"mode",
"=",
"0o755",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
"[",
"ARTIFACT_LIB_DIR",
"]",
")",
":",
"os",
".",
"makedirs",
"(",
"config",
"[",
"ARTIFACT_LIB_DIR",
"]",
",",
"mode",
"=",
"0o755",
")"
] | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/mini-cluster/relocate_binaries_for_mini_cluster.py#L269-L279 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py3/pygments/filters/__init__.py | python | get_all_filters | () | Return a generator of all filter names. | Return a generator of all filter names. | [
"Return",
"a",
"generator",
"of",
"all",
"filter",
"names",
"."
] | def get_all_filters():
"""Return a generator of all filter names."""
yield from FILTERS
for name, _ in find_plugin_filters():
yield name | [
"def",
"get_all_filters",
"(",
")",
":",
"yield",
"from",
"FILTERS",
"for",
"name",
",",
"_",
"in",
"find_plugin_filters",
"(",
")",
":",
"yield",
"name"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/filters/__init__.py#L45-L49 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/score-of-parentheses.py | python | Solution2.scoreOfParentheses | (self, S) | return stack[0] | :type S: str
:rtype: int | :type S: str
:rtype: int | [
":",
"type",
"S",
":",
"str",
":",
"rtype",
":",
"int"
] | def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = [0]
for c in S:
if c == '(':
stack.append(0)
else:
last = stack.pop()
stack[-1] += max(1, 2*last)
return stack[0] | [
"def",
"scoreOfParentheses",
"(",
"self",
",",
"S",
")",
":",
"stack",
"=",
"[",
"0",
"]",
"for",
"c",
"in",
"S",
":",
"if",
"c",
"==",
"'('",
":",
"stack",
".",
"append",
"(",
"0",
")",
"else",
":",
"last",
"=",
"stack",
".",
"pop",
"(",
")",
"stack",
"[",
"-",
"1",
"]",
"+=",
"max",
"(",
"1",
",",
"2",
"*",
"last",
")",
"return",
"stack",
"[",
"0",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/score-of-parentheses.py#L25-L37 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/D7YIGPositionCalibration.py | python | D7YIGPositionCalibration._print_parameter_file | (self, wavelength, pixel_offsets, bank_offsets, bank_slopes) | Prints the pixel positions as a Instrument Parameter
File that can be later used by the D7 loader. | Prints the pixel positions as a Instrument Parameter
File that can be later used by the D7 loader. | [
"Prints",
"the",
"pixel",
"positions",
"as",
"a",
"Instrument",
"Parameter",
"File",
"that",
"can",
"be",
"later",
"used",
"by",
"the",
"D7",
"loader",
"."
] | def _print_parameter_file(self, wavelength, pixel_offsets, bank_offsets, bank_slopes):
"""Prints the pixel positions as a Instrument Parameter
File that can be later used by the D7 loader."""
param_file = ET.Element('parameter-file')
param_file.set('instrument', 'D7')
date_today = date.today()
param_file.set('date', str(date_today))
# include the fitted wavelength in the output IPF
detector = ET.SubElement(param_file, 'component-link')
detector.set('name', 'detector')
param = ET.SubElement(detector, 'parameter')
param.set('name', 'wavelength')
value = ET.SubElement(param, 'value')
value.set('val', str(wavelength))
for bank_no in range(int(self._D7NumberPixels / self._D7NumberPixelsBank)):
bank = ET.SubElement(param_file, 'component-link')
bank.set('name', 'bank'+str(bank_no+2))
offset = ET.SubElement(bank, 'parameter')
offset.set('name', 'offset')
value = ET.SubElement(offset, 'value')
value.set('val', str(bank_offsets[bank_no]))
gradient = ET.SubElement(bank, 'parameter')
gradient.set('name', 'gradient')
value = ET.SubElement(gradient, 'value')
value.set('val', str(bank_slopes[bank_no]))
for pixel_no in range(self._D7NumberPixelsBank):
pixel = ET.SubElement(bank, 'parameter')
pixel.set('name', 'twoTheta_pixel_{0}'.format(pixel_no+1))
value = ET.SubElement(pixel, 'value')
value.set('val', str(pixel_offsets[bank_no*self._D7NumberPixelsBank + pixel_no]))
filename = self.getPropertyValue('CalibrationOutputFile')
output_path = filename
if not os.path.isabs(filename):
output_path = os.path.join(ConfigService.Instance().getString('defaultsave.directory'), filename)
with open(output_path, "w") as outfile:
outfile.write(self._prettify(param_file)) | [
"def",
"_print_parameter_file",
"(",
"self",
",",
"wavelength",
",",
"pixel_offsets",
",",
"bank_offsets",
",",
"bank_slopes",
")",
":",
"param_file",
"=",
"ET",
".",
"Element",
"(",
"'parameter-file'",
")",
"param_file",
".",
"set",
"(",
"'instrument'",
",",
"'D7'",
")",
"date_today",
"=",
"date",
".",
"today",
"(",
")",
"param_file",
".",
"set",
"(",
"'date'",
",",
"str",
"(",
"date_today",
")",
")",
"# include the fitted wavelength in the output IPF",
"detector",
"=",
"ET",
".",
"SubElement",
"(",
"param_file",
",",
"'component-link'",
")",
"detector",
".",
"set",
"(",
"'name'",
",",
"'detector'",
")",
"param",
"=",
"ET",
".",
"SubElement",
"(",
"detector",
",",
"'parameter'",
")",
"param",
".",
"set",
"(",
"'name'",
",",
"'wavelength'",
")",
"value",
"=",
"ET",
".",
"SubElement",
"(",
"param",
",",
"'value'",
")",
"value",
".",
"set",
"(",
"'val'",
",",
"str",
"(",
"wavelength",
")",
")",
"for",
"bank_no",
"in",
"range",
"(",
"int",
"(",
"self",
".",
"_D7NumberPixels",
"/",
"self",
".",
"_D7NumberPixelsBank",
")",
")",
":",
"bank",
"=",
"ET",
".",
"SubElement",
"(",
"param_file",
",",
"'component-link'",
")",
"bank",
".",
"set",
"(",
"'name'",
",",
"'bank'",
"+",
"str",
"(",
"bank_no",
"+",
"2",
")",
")",
"offset",
"=",
"ET",
".",
"SubElement",
"(",
"bank",
",",
"'parameter'",
")",
"offset",
".",
"set",
"(",
"'name'",
",",
"'offset'",
")",
"value",
"=",
"ET",
".",
"SubElement",
"(",
"offset",
",",
"'value'",
")",
"value",
".",
"set",
"(",
"'val'",
",",
"str",
"(",
"bank_offsets",
"[",
"bank_no",
"]",
")",
")",
"gradient",
"=",
"ET",
".",
"SubElement",
"(",
"bank",
",",
"'parameter'",
")",
"gradient",
".",
"set",
"(",
"'name'",
",",
"'gradient'",
")",
"value",
"=",
"ET",
".",
"SubElement",
"(",
"gradient",
",",
"'value'",
")",
"value",
".",
"set",
"(",
"'val'",
",",
"str",
"(",
"bank_slopes",
"[",
"bank_no",
"]",
")",
")",
"for",
"pixel_no",
"in",
"range",
"(",
"self",
".",
"_D7NumberPixelsBank",
")",
":",
"pixel",
"=",
"ET",
".",
"SubElement",
"(",
"bank",
",",
"'parameter'",
")",
"pixel",
".",
"set",
"(",
"'name'",
",",
"'twoTheta_pixel_{0}'",
".",
"format",
"(",
"pixel_no",
"+",
"1",
")",
")",
"value",
"=",
"ET",
".",
"SubElement",
"(",
"pixel",
",",
"'value'",
")",
"value",
".",
"set",
"(",
"'val'",
",",
"str",
"(",
"pixel_offsets",
"[",
"bank_no",
"*",
"self",
".",
"_D7NumberPixelsBank",
"+",
"pixel_no",
"]",
")",
")",
"filename",
"=",
"self",
".",
"getPropertyValue",
"(",
"'CalibrationOutputFile'",
")",
"output_path",
"=",
"filename",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ConfigService",
".",
"Instance",
"(",
")",
".",
"getString",
"(",
"'defaultsave.directory'",
")",
",",
"filename",
")",
"with",
"open",
"(",
"output_path",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"self",
".",
"_prettify",
"(",
"param_file",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/D7YIGPositionCalibration.py#L576-L617 | ||
shichaoy/pop_up_slam | 237dba5448eaeacc588f2339365774f9247bce3c | pop_up_python/python/pop_up_python/pop_up_fun.py | python | python_get_contours | (label_map) | return ground_contour[0:-1:20] | label_map: ground is 0, wall is 1 | label_map: ground is 0, wall is 1 | [
"label_map",
":",
"ground",
"is",
"0",
"wall",
"is",
"1"
] | def python_get_contours(label_map):
'''
label_map: ground is 0, wall is 1
'''
contours=find_contours(label_map, 0) # row ind, col ind y x
final_line_segs=np.array([]);final_extend_segs=np.array([]);final_lines_in_extend_ind=np.array([]);
if contours !=[]:
# there might be several contours, find the longest one
contour_lengths=np.zeros(len(contours))
for contour_ind in xrange(len(contours)):
bg_end_diff=contours[contour_ind][0,:]-contours[contour_ind][-1,:]
length=np.sum(np.linalg.norm(bg_end_diff))
contour_lengths[contour_ind]=length
ground_contour_ind=np.argmax(contour_lengths)
ground_contour=contours[ground_contour_ind].copy() # whether swap x and y
ground_contour[:,0]=contours[ground_contour_ind][:,1]
ground_contour[:,1]=contours[ground_contour_ind][:,0]
return ground_contour[0:-1:20] | [
"def",
"python_get_contours",
"(",
"label_map",
")",
":",
"contours",
"=",
"find_contours",
"(",
"label_map",
",",
"0",
")",
"# row ind, col ind y x",
"final_line_segs",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"final_extend_segs",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"final_lines_in_extend_ind",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"contours",
"!=",
"[",
"]",
":",
"# there might be several contours, find the longest one",
"contour_lengths",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"contours",
")",
")",
"for",
"contour_ind",
"in",
"xrange",
"(",
"len",
"(",
"contours",
")",
")",
":",
"bg_end_diff",
"=",
"contours",
"[",
"contour_ind",
"]",
"[",
"0",
",",
":",
"]",
"-",
"contours",
"[",
"contour_ind",
"]",
"[",
"-",
"1",
",",
":",
"]",
"length",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"bg_end_diff",
")",
")",
"contour_lengths",
"[",
"contour_ind",
"]",
"=",
"length",
"ground_contour_ind",
"=",
"np",
".",
"argmax",
"(",
"contour_lengths",
")",
"ground_contour",
"=",
"contours",
"[",
"ground_contour_ind",
"]",
".",
"copy",
"(",
")",
"# whether swap x and y",
"ground_contour",
"[",
":",
",",
"0",
"]",
"=",
"contours",
"[",
"ground_contour_ind",
"]",
"[",
":",
",",
"1",
"]",
"ground_contour",
"[",
":",
",",
"1",
"]",
"=",
"contours",
"[",
"ground_contour_ind",
"]",
"[",
":",
",",
"0",
"]",
"return",
"ground_contour",
"[",
"0",
":",
"-",
"1",
":",
"20",
"]"
] | https://github.com/shichaoy/pop_up_slam/blob/237dba5448eaeacc588f2339365774f9247bce3c/pop_up_python/python/pop_up_python/pop_up_fun.py#L85-L104 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/losses/python/losses/loss_ops.py | python | softmax_cross_entropy | (logits, onehot_labels, weight=1.0,
label_smoothing=0, scope=None) | Creates a cross-entropy loss using tf.nn.softmax_cross_entropy_with_logits.
`weight` acts as a coefficient for the loss. If a scalar is provided,
then the loss is simply scaled by the given value. If `weight` is a
tensor of size [`batch_size`], then the loss weights apply to each
corresponding sample.
If `label_smoothing` is nonzero, smooth the labels towards 1/num_classes:
new_onehot_labels = onehot_labels * (1 - label_smoothing)
+ label_smoothing / num_classes
Args:
logits: [batch_size, num_classes] logits outputs of the network .
onehot_labels: [batch_size, num_classes] target one_hot_encoded labels.
weight: Coefficients for the loss. The tensor must be a scalar or a tensor
of shape [batch_size].
label_smoothing: If greater than 0 then smooth the labels.
scope: the scope for the operations performed in computing the loss.
Returns:
A scalar `Tensor` representing the loss value.
Raises:
ValueError: If the shape of `logits` doesn't match that of `onehot_labels`
or if the shape of `weight` is invalid or if `weight` is None. | Creates a cross-entropy loss using tf.nn.softmax_cross_entropy_with_logits. | [
"Creates",
"a",
"cross",
"-",
"entropy",
"loss",
"using",
"tf",
".",
"nn",
".",
"softmax_cross_entropy_with_logits",
"."
] | def softmax_cross_entropy(logits, onehot_labels, weight=1.0,
label_smoothing=0, scope=None):
"""Creates a cross-entropy loss using tf.nn.softmax_cross_entropy_with_logits.
`weight` acts as a coefficient for the loss. If a scalar is provided,
then the loss is simply scaled by the given value. If `weight` is a
tensor of size [`batch_size`], then the loss weights apply to each
corresponding sample.
If `label_smoothing` is nonzero, smooth the labels towards 1/num_classes:
new_onehot_labels = onehot_labels * (1 - label_smoothing)
+ label_smoothing / num_classes
Args:
logits: [batch_size, num_classes] logits outputs of the network .
onehot_labels: [batch_size, num_classes] target one_hot_encoded labels.
weight: Coefficients for the loss. The tensor must be a scalar or a tensor
of shape [batch_size].
label_smoothing: If greater than 0 then smooth the labels.
scope: the scope for the operations performed in computing the loss.
Returns:
A scalar `Tensor` representing the loss value.
Raises:
ValueError: If the shape of `logits` doesn't match that of `onehot_labels`
or if the shape of `weight` is invalid or if `weight` is None.
"""
with ops.name_scope(scope, "softmax_cross_entropy_loss",
[logits, onehot_labels]):
logits.get_shape().assert_is_compatible_with(onehot_labels.get_shape())
onehot_labels = math_ops.cast(onehot_labels, logits.dtype)
if label_smoothing > 0:
num_classes = math_ops.cast(
array_ops.shape(onehot_labels)[1], logits.dtype)
smooth_positives = 1.0 - label_smoothing
smooth_negatives = label_smoothing / num_classes
onehot_labels = onehot_labels * smooth_positives + smooth_negatives
losses = nn.softmax_cross_entropy_with_logits(logits, onehot_labels,
name="xentropy")
return compute_weighted_loss(losses, weight) | [
"def",
"softmax_cross_entropy",
"(",
"logits",
",",
"onehot_labels",
",",
"weight",
"=",
"1.0",
",",
"label_smoothing",
"=",
"0",
",",
"scope",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"scope",
",",
"\"softmax_cross_entropy_loss\"",
",",
"[",
"logits",
",",
"onehot_labels",
"]",
")",
":",
"logits",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"onehot_labels",
".",
"get_shape",
"(",
")",
")",
"onehot_labels",
"=",
"math_ops",
".",
"cast",
"(",
"onehot_labels",
",",
"logits",
".",
"dtype",
")",
"if",
"label_smoothing",
">",
"0",
":",
"num_classes",
"=",
"math_ops",
".",
"cast",
"(",
"array_ops",
".",
"shape",
"(",
"onehot_labels",
")",
"[",
"1",
"]",
",",
"logits",
".",
"dtype",
")",
"smooth_positives",
"=",
"1.0",
"-",
"label_smoothing",
"smooth_negatives",
"=",
"label_smoothing",
"/",
"num_classes",
"onehot_labels",
"=",
"onehot_labels",
"*",
"smooth_positives",
"+",
"smooth_negatives",
"losses",
"=",
"nn",
".",
"softmax_cross_entropy_with_logits",
"(",
"logits",
",",
"onehot_labels",
",",
"name",
"=",
"\"xentropy\"",
")",
"return",
"compute_weighted_loss",
"(",
"losses",
",",
"weight",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/losses/python/losses/loss_ops.py#L344-L387 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_style.py | python | NullStyleItem | () | return item | Create a null style item
@return: empty style item that cannot be merged | Create a null style item
@return: empty style item that cannot be merged | [
"Create",
"a",
"null",
"style",
"item",
"@return",
":",
"empty",
"style",
"item",
"that",
"cannot",
"be",
"merged"
] | def NullStyleItem():
"""Create a null style item
@return: empty style item that cannot be merged
"""
item = StyleItem()
item.null = True
return item | [
"def",
"NullStyleItem",
"(",
")",
":",
"item",
"=",
"StyleItem",
"(",
")",
"item",
".",
"null",
"=",
"True",
"return",
"item"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_style.py#L996-L1003 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/gdb/libpython.py | python | PyFrameObjectPtr.get_var_by_name | (self, name) | return None, None | Look for the named local variable, returning a (PyObjectPtr, scope) pair
where scope is a string 'local', 'global', 'builtin'
If not found, return (None, None) | Look for the named local variable, returning a (PyObjectPtr, scope) pair
where scope is a string 'local', 'global', 'builtin' | [
"Look",
"for",
"the",
"named",
"local",
"variable",
"returning",
"a",
"(",
"PyObjectPtr",
"scope",
")",
"pair",
"where",
"scope",
"is",
"a",
"string",
"local",
"global",
"builtin"
] | def get_var_by_name(self, name):
'''
Look for the named local variable, returning a (PyObjectPtr, scope) pair
where scope is a string 'local', 'global', 'builtin'
If not found, return (None, None)
'''
for pyop_name, pyop_value in self.iter_locals():
if name == pyop_name.proxyval(set()):
return pyop_value, 'local'
for pyop_name, pyop_value in self.iter_globals():
if name == pyop_name.proxyval(set()):
return pyop_value, 'global'
for pyop_name, pyop_value in self.iter_builtins():
if name == pyop_name.proxyval(set()):
return pyop_value, 'builtin'
return None, None | [
"def",
"get_var_by_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"pyop_name",
",",
"pyop_value",
"in",
"self",
".",
"iter_locals",
"(",
")",
":",
"if",
"name",
"==",
"pyop_name",
".",
"proxyval",
"(",
"set",
"(",
")",
")",
":",
"return",
"pyop_value",
",",
"'local'",
"for",
"pyop_name",
",",
"pyop_value",
"in",
"self",
".",
"iter_globals",
"(",
")",
":",
"if",
"name",
"==",
"pyop_name",
".",
"proxyval",
"(",
"set",
"(",
")",
")",
":",
"return",
"pyop_value",
",",
"'global'",
"for",
"pyop_name",
",",
"pyop_value",
"in",
"self",
".",
"iter_builtins",
"(",
")",
":",
"if",
"name",
"==",
"pyop_name",
".",
"proxyval",
"(",
"set",
"(",
")",
")",
":",
"return",
"pyop_value",
",",
"'builtin'",
"return",
"None",
",",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/gdb/libpython.py#L902-L918 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | tools/idl_parser/idl_parser.py | python | IDLParser.p_ExceptionMembersError | (self, p) | ExceptionMembers : error | ExceptionMembers : error | [
"ExceptionMembers",
":",
"error"
] | def p_ExceptionMembersError(self, p):
"""ExceptionMembers : error"""
p[0] = self.BuildError(p, 'ExceptionMembers') | [
"def",
"p_ExceptionMembersError",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"BuildError",
"(",
"p",
",",
"'ExceptionMembers'",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/tools/idl_parser/idl_parser.py#L343-L345 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/wheel.py | python | Wheel.tags | (self) | return itertools.product(
self.py_version.split('.'),
self.abi.split('.'),
self.platform.split('.'),
) | List tags (py_version, abi, platform) supported by this wheel. | List tags (py_version, abi, platform) supported by this wheel. | [
"List",
"tags",
"(",
"py_version",
"abi",
"platform",
")",
"supported",
"by",
"this",
"wheel",
"."
] | def tags(self):
'''List tags (py_version, abi, platform) supported by this wheel.'''
return itertools.product(
self.py_version.split('.'),
self.abi.split('.'),
self.platform.split('.'),
) | [
"def",
"tags",
"(",
"self",
")",
":",
"return",
"itertools",
".",
"product",
"(",
"self",
".",
"py_version",
".",
"split",
"(",
"'.'",
")",
",",
"self",
".",
"abi",
".",
"split",
"(",
"'.'",
")",
",",
"self",
".",
"platform",
".",
"split",
"(",
"'.'",
")",
",",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/wheel.py#L66-L72 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/clang_format.py | python | get_tar_path | (version, tar_path) | return CLANG_FORMAT_SOURCE_TAR_BASE.substitute(
version=version,
tar_path=tar_path) | Get the path to clang-format in the llvm tarball | Get the path to clang-format in the llvm tarball | [
"Get",
"the",
"path",
"to",
"clang",
"-",
"format",
"in",
"the",
"llvm",
"tarball"
] | def get_tar_path(version, tar_path):
""" Get the path to clang-format in the llvm tarball
"""
return CLANG_FORMAT_SOURCE_TAR_BASE.substitute(
version=version,
tar_path=tar_path) | [
"def",
"get_tar_path",
"(",
"version",
",",
"tar_path",
")",
":",
"return",
"CLANG_FORMAT_SOURCE_TAR_BASE",
".",
"substitute",
"(",
"version",
"=",
"version",
",",
"tar_path",
"=",
"tar_path",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/clang_format.py#L63-L68 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/functional.py | python | margin_ranking_loss | (
input1: Tensor,
input2: Tensor,
target: Tensor,
margin: float = 0,
size_average: Optional[bool] = None,
reduce: Optional[bool] = None,
reduction: str = "mean",
) | return torch.margin_ranking_loss(input1, input2, target, margin, reduction_enum) | r"""margin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor
See :class:`~torch.nn.MarginRankingLoss` for details. | r"""margin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor | [
"r",
"margin_ranking_loss",
"(",
"input1",
"input2",
"target",
"margin",
"=",
"0",
"size_average",
"=",
"None",
"reduce",
"=",
"None",
"reduction",
"=",
"mean",
")",
"-",
">",
"Tensor"
] | def margin_ranking_loss(
input1: Tensor,
input2: Tensor,
target: Tensor,
margin: float = 0,
size_average: Optional[bool] = None,
reduce: Optional[bool] = None,
reduction: str = "mean",
) -> Tensor:
r"""margin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean') -> Tensor
See :class:`~torch.nn.MarginRankingLoss` for details.
"""
if has_torch_function_variadic(input1, input2, target):
return handle_torch_function(
margin_ranking_loss,
(input1, input2, target),
input1,
input2,
target,
margin=margin,
size_average=size_average,
reduce=reduce,
reduction=reduction,
)
if size_average is not None or reduce is not None:
reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
else:
reduction_enum = _Reduction.get_enum(reduction)
if (input1.dim() != input2.dim() or input1.dim() != target.dim()):
raise RuntimeError(
(
"margin_ranking_loss : All input tensors should have same dimension but got sizes: "
"input1: {}, input2: {}, target: {} ".format(input1.size(), input2.size(), target.size())
)
)
return torch.margin_ranking_loss(input1, input2, target, margin, reduction_enum) | [
"def",
"margin_ranking_loss",
"(",
"input1",
":",
"Tensor",
",",
"input2",
":",
"Tensor",
",",
"target",
":",
"Tensor",
",",
"margin",
":",
"float",
"=",
"0",
",",
"size_average",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"reduce",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"reduction",
":",
"str",
"=",
"\"mean\"",
",",
")",
"->",
"Tensor",
":",
"if",
"has_torch_function_variadic",
"(",
"input1",
",",
"input2",
",",
"target",
")",
":",
"return",
"handle_torch_function",
"(",
"margin_ranking_loss",
",",
"(",
"input1",
",",
"input2",
",",
"target",
")",
",",
"input1",
",",
"input2",
",",
"target",
",",
"margin",
"=",
"margin",
",",
"size_average",
"=",
"size_average",
",",
"reduce",
"=",
"reduce",
",",
"reduction",
"=",
"reduction",
",",
")",
"if",
"size_average",
"is",
"not",
"None",
"or",
"reduce",
"is",
"not",
"None",
":",
"reduction_enum",
"=",
"_Reduction",
".",
"legacy_get_enum",
"(",
"size_average",
",",
"reduce",
")",
"else",
":",
"reduction_enum",
"=",
"_Reduction",
".",
"get_enum",
"(",
"reduction",
")",
"if",
"(",
"input1",
".",
"dim",
"(",
")",
"!=",
"input2",
".",
"dim",
"(",
")",
"or",
"input1",
".",
"dim",
"(",
")",
"!=",
"target",
".",
"dim",
"(",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"(",
"\"margin_ranking_loss : All input tensors should have same dimension but got sizes: \"",
"\"input1: {}, input2: {}, target: {} \"",
".",
"format",
"(",
"input1",
".",
"size",
"(",
")",
",",
"input2",
".",
"size",
"(",
")",
",",
"target",
".",
"size",
"(",
")",
")",
")",
")",
"return",
"torch",
".",
"margin_ranking_loss",
"(",
"input1",
",",
"input2",
",",
"target",
",",
"margin",
",",
"reduction_enum",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/functional.py#L3265-L3301 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/syntax.py | python | ChainedType.__init__ | (self, file_name, line, column) | Construct a Type. | Construct a Type. | [
"Construct",
"a",
"Type",
"."
] | def __init__(self, file_name, line, column):
# type: (unicode, int, int) -> None
"""Construct a Type."""
self.name = None # type: unicode
self.cpp_name = None # type: unicode
super(ChainedType, self).__init__(file_name, line, column) | [
"def",
"__init__",
"(",
"self",
",",
"file_name",
",",
"line",
",",
"column",
")",
":",
"# type: (unicode, int, int) -> None",
"self",
".",
"name",
"=",
"None",
"# type: unicode",
"self",
".",
"cpp_name",
"=",
"None",
"# type: unicode",
"super",
"(",
"ChainedType",
",",
"self",
")",
".",
"__init__",
"(",
"file_name",
",",
"line",
",",
"column",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/syntax.py#L319-L325 | ||
dmlc/decord | 96b750c7221322391969929e855b942d2fdcd06b | python/decord/audio_reader.py | python | AudioReader.shape | (self) | return (self._num_channels, self._num_samples_per_channel) | Get shape of the entire audio samples.
Returns
-------
(int, int)
The number of channels, and the number of samples in each channel. | Get shape of the entire audio samples. | [
"Get",
"shape",
"of",
"the",
"entire",
"audio",
"samples",
"."
] | def shape(self):
"""Get shape of the entire audio samples.
Returns
-------
(int, int)
The number of channels, and the number of samples in each channel.
"""
return (self._num_channels, self._num_samples_per_channel) | [
"def",
"shape",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_num_channels",
",",
"self",
".",
"_num_samples_per_channel",
")"
] | https://github.com/dmlc/decord/blob/96b750c7221322391969929e855b942d2fdcd06b/python/decord/audio_reader.py#L116-L125 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/bindings/python/llvm/object.py | python | Section.__init__ | (self, ptr) | Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module. | Construct a new section instance. | [
"Construct",
"a",
"new",
"section",
"instance",
"."
] | def __init__(self, ptr):
"""Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module.
"""
LLVMObject.__init__(self, ptr)
self.expired = False | [
"def",
"__init__",
"(",
"self",
",",
"ptr",
")",
":",
"LLVMObject",
".",
"__init__",
"(",
"self",
",",
"ptr",
")",
"self",
".",
"expired",
"=",
"False"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/bindings/python/llvm/object.py#L181-L190 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Entry.index | (self, index) | return self.tk.getint(self.tk.call(
self._w, 'index', index)) | Return position of cursor. | Return position of cursor. | [
"Return",
"position",
"of",
"cursor",
"."
] | def index(self, index):
"""Return position of cursor."""
return self.tk.getint(self.tk.call(
self._w, 'index', index)) | [
"def",
"index",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"tk",
".",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'index'",
",",
"index",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2686-L2689 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel._transform_expression | (self, expression) | return expression | Transform the expression into one that evaluates to 0 when true.
For example, 'x=y' becomes '(x)-(y)'. | Transform the expression into one that evaluates to 0 when true. | [
"Transform",
"the",
"expression",
"into",
"one",
"that",
"evaluates",
"to",
"0",
"when",
"true",
"."
] | def _transform_expression(self, expression):
"""
Transform the expression into one that evaluates to 0 when true.
For example, 'x=y' becomes '(x)-(y)'.
"""
# create transformation dictionary by precedence order
transforms = []
transforms.append(('||', 'min(abs(L), abs(R))'))
transforms.append(('&&', 'max(abs(L), abs(R))'))
transforms.append(('>=', '((L) - (R)) - abs((L) - (R))'))
transforms.append(('>', '((L) - (R)) - abs((L) - (R))'))
transforms.append(('<=', '((R) - (L)) - abs((R) - (L))'))
transforms.append(('<', '((R) - (L)) - abs((R) - (L))'))
transforms.append(('==', 'abs((L) - (R))'))
transforms.append(('=', 'abs((L) - (R))'))
# replace occurrences of each transform
for separator, transform in transforms:
while separator in expression:
# ensure parenthesis count is identical
if expression.count('(') != expression.count(')'):
self._error('Unbalances parenthesis.',
'We cannot transform the given expression '
'becuase it contains unbalanced '
'parenthesis:\n%s' % expression)
# get parenthesis depth on each character
next_depth = 0
depth = []
for c in expression:
if c == '(':
depth.append(next_depth)
next_depth += 1
elif c == ')':
next_depth -= 1
depth.append(next_depth)
else:
depth.append(next_depth)
# find extents of the inner expression
separator_index = expression.index(separator)
left_index = separator_index
right_index = separator_index + len(separator)
while left_index > 0 and (
depth[left_index - 1] > depth[separator_index] or
(depth[left_index - 1] == depth[separator_index] and
expression[left_index - 1] != ',')):
left_index -= 1
while right_index < len(expression) and (
depth[right_index] > depth[separator_index] or
(depth[right_index] == depth[separator_index] and
expression[right_index] != ',')):
right_index += 1
new_expression = expression[:left_index]
left_expression = expression[
left_index:separator_index].strip()
right_expression = expression[
separator_index + len(separator):right_index].strip()
for c in transform:
if c == 'L':
new_expression += left_expression
elif c == 'R':
new_expression += right_expression
else:
new_expression += c
new_expression += expression[right_index:]
expression = new_expression
# return the result
return expression | [
"def",
"_transform_expression",
"(",
"self",
",",
"expression",
")",
":",
"# create transformation dictionary by precedence order",
"transforms",
"=",
"[",
"]",
"transforms",
".",
"append",
"(",
"(",
"'||'",
",",
"'min(abs(L), abs(R))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'&&'",
",",
"'max(abs(L), abs(R))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'>='",
",",
"'((L) - (R)) - abs((L) - (R))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'>'",
",",
"'((L) - (R)) - abs((L) - (R))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'<='",
",",
"'((R) - (L)) - abs((R) - (L))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'<'",
",",
"'((R) - (L)) - abs((R) - (L))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'=='",
",",
"'abs((L) - (R))'",
")",
")",
"transforms",
".",
"append",
"(",
"(",
"'='",
",",
"'abs((L) - (R))'",
")",
")",
"# replace occurrences of each transform",
"for",
"separator",
",",
"transform",
"in",
"transforms",
":",
"while",
"separator",
"in",
"expression",
":",
"# ensure parenthesis count is identical",
"if",
"expression",
".",
"count",
"(",
"'('",
")",
"!=",
"expression",
".",
"count",
"(",
"')'",
")",
":",
"self",
".",
"_error",
"(",
"'Unbalances parenthesis.'",
",",
"'We cannot transform the given expression '",
"'becuase it contains unbalanced '",
"'parenthesis:\\n%s'",
"%",
"expression",
")",
"# get parenthesis depth on each character",
"next_depth",
"=",
"0",
"depth",
"=",
"[",
"]",
"for",
"c",
"in",
"expression",
":",
"if",
"c",
"==",
"'('",
":",
"depth",
".",
"append",
"(",
"next_depth",
")",
"next_depth",
"+=",
"1",
"elif",
"c",
"==",
"')'",
":",
"next_depth",
"-=",
"1",
"depth",
".",
"append",
"(",
"next_depth",
")",
"else",
":",
"depth",
".",
"append",
"(",
"next_depth",
")",
"# find extents of the inner expression",
"separator_index",
"=",
"expression",
".",
"index",
"(",
"separator",
")",
"left_index",
"=",
"separator_index",
"right_index",
"=",
"separator_index",
"+",
"len",
"(",
"separator",
")",
"while",
"left_index",
">",
"0",
"and",
"(",
"depth",
"[",
"left_index",
"-",
"1",
"]",
">",
"depth",
"[",
"separator_index",
"]",
"or",
"(",
"depth",
"[",
"left_index",
"-",
"1",
"]",
"==",
"depth",
"[",
"separator_index",
"]",
"and",
"expression",
"[",
"left_index",
"-",
"1",
"]",
"!=",
"','",
")",
")",
":",
"left_index",
"-=",
"1",
"while",
"right_index",
"<",
"len",
"(",
"expression",
")",
"and",
"(",
"depth",
"[",
"right_index",
"]",
">",
"depth",
"[",
"separator_index",
"]",
"or",
"(",
"depth",
"[",
"right_index",
"]",
"==",
"depth",
"[",
"separator_index",
"]",
"and",
"expression",
"[",
"right_index",
"]",
"!=",
"','",
")",
")",
":",
"right_index",
"+=",
"1",
"new_expression",
"=",
"expression",
"[",
":",
"left_index",
"]",
"left_expression",
"=",
"expression",
"[",
"left_index",
":",
"separator_index",
"]",
".",
"strip",
"(",
")",
"right_expression",
"=",
"expression",
"[",
"separator_index",
"+",
"len",
"(",
"separator",
")",
":",
"right_index",
"]",
".",
"strip",
"(",
")",
"for",
"c",
"in",
"transform",
":",
"if",
"c",
"==",
"'L'",
":",
"new_expression",
"+=",
"left_expression",
"elif",
"c",
"==",
"'R'",
":",
"new_expression",
"+=",
"right_expression",
"else",
":",
"new_expression",
"+=",
"c",
"new_expression",
"+=",
"expression",
"[",
"right_index",
":",
"]",
"expression",
"=",
"new_expression",
"# return the result",
"return",
"expression"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L4420-L4487 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/idna/intranges.py | python | intranges_from_list | (list_) | return tuple(ranges) | Represent a list of integers as a sequence of ranges:
((start_0, end_0), (start_1, end_1), ...), such that the original
integers are exactly those x such that start_i <= x < end_i for some i.
Ranges are encoded as single integers (start << 32 | end), not as tuples. | Represent a list of integers as a sequence of ranges:
((start_0, end_0), (start_1, end_1), ...), such that the original
integers are exactly those x such that start_i <= x < end_i for some i. | [
"Represent",
"a",
"list",
"of",
"integers",
"as",
"a",
"sequence",
"of",
"ranges",
":",
"((",
"start_0",
"end_0",
")",
"(",
"start_1",
"end_1",
")",
"...",
")",
"such",
"that",
"the",
"original",
"integers",
"are",
"exactly",
"those",
"x",
"such",
"that",
"start_i",
"<",
"=",
"x",
"<",
"end_i",
"for",
"some",
"i",
"."
] | def intranges_from_list(list_):
"""Represent a list of integers as a sequence of ranges:
((start_0, end_0), (start_1, end_1), ...), such that the original
integers are exactly those x such that start_i <= x < end_i for some i.
Ranges are encoded as single integers (start << 32 | end), not as tuples.
"""
sorted_list = sorted(list_)
ranges = []
last_write = -1
for i in range(len(sorted_list)):
if i+1 < len(sorted_list):
if sorted_list[i] == sorted_list[i+1]-1:
continue
current_range = sorted_list[last_write+1:i+1]
ranges.append(_encode_range(current_range[0], current_range[-1] + 1))
last_write = i
return tuple(ranges) | [
"def",
"intranges_from_list",
"(",
"list_",
")",
":",
"sorted_list",
"=",
"sorted",
"(",
"list_",
")",
"ranges",
"=",
"[",
"]",
"last_write",
"=",
"-",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sorted_list",
")",
")",
":",
"if",
"i",
"+",
"1",
"<",
"len",
"(",
"sorted_list",
")",
":",
"if",
"sorted_list",
"[",
"i",
"]",
"==",
"sorted_list",
"[",
"i",
"+",
"1",
"]",
"-",
"1",
":",
"continue",
"current_range",
"=",
"sorted_list",
"[",
"last_write",
"+",
"1",
":",
"i",
"+",
"1",
"]",
"ranges",
".",
"append",
"(",
"_encode_range",
"(",
"current_range",
"[",
"0",
"]",
",",
"current_range",
"[",
"-",
"1",
"]",
"+",
"1",
")",
")",
"last_write",
"=",
"i",
"return",
"tuple",
"(",
"ranges",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/idna/intranges.py#L10-L29 | |
amrayn/easyloggingpp | 8489989bb26c6371df103f6cbced3fbee1bc3c2f | tools/cpplint.py | python | _NamespaceInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Check end of namespace comments. | Check end of namespace comments. | [
"Check",
"end",
"of",
"namespace",
"comments",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace"') | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
"# Check how many lines is enclosed in this namespace. Don't issue",
"# warning for missing namespace comments if there aren't enough",
"# lines. However, do apply checks if there is already an end of",
"# namespace comment and it's incorrect.",
"#",
"# TODO(unknown): We always want to check end of namespace comments",
"# if a namespace is large, but sometimes we also want to apply the",
"# check if a short namespace contained nontrivial things (something",
"# other than forward declarations). There is currently no logic on",
"# deciding what these nontrivial things are, so this check is",
"# triggered by namespace size only, which works most of the time.",
"if",
"(",
"linenum",
"-",
"self",
".",
"starting_linenum",
"<",
"10",
"and",
"not",
"Match",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace\\b'",
",",
"line",
")",
")",
":",
"return",
"# Look for matching comment at end of namespace.",
"#",
"# Note that we accept C style \"/* */\" comments for terminating",
"# namespaces, so that code that terminate namespaces inside",
"# preprocessor macros can be cpplint clean.",
"#",
"# We also accept stuff like \"// end of namespace <name>.\" with the",
"# period at the end.",
"#",
"# Besides these, we don't accept anything else, otherwise we might",
"# get false negatives when existing comment is a substring of the",
"# expected namespace.",
"if",
"self",
".",
"name",
":",
"# Named namespace",
"if",
"not",
"Match",
"(",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace\\s+'",
"+",
"re",
".",
"escape",
"(",
"self",
".",
"name",
")",
"+",
"r'[\\*/\\.\\\\\\s]*$'",
")",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/namespace'",
",",
"5",
",",
"'Namespace should be terminated with \"// namespace %s\"'",
"%",
"self",
".",
"name",
")",
"else",
":",
"# Anonymous namespace",
"if",
"not",
"Match",
"(",
"r'};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/namespace'",
",",
"5",
",",
"'Namespace should be terminated with \"// namespace\"'",
")"
] | https://github.com/amrayn/easyloggingpp/blob/8489989bb26c6371df103f6cbced3fbee1bc3c2f/tools/cpplint.py#L1733-L1776 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | tools/python/util/get_azcopy.py | python | get_azcopy | (local_azcopy_path="azcopy") | Creates a context manager that returns a path to a particular version of
azcopy (specified in AZCOPY_VERSION). Downloads a temporary copy if needed.
:param local_azcopy_path: Path to a local azcopy to try first.
Example usage:
with get_azcopy() as azcopy_path:
subprocess.run([azcopy_path, "--version"]) | Creates a context manager that returns a path to a particular version of
azcopy (specified in AZCOPY_VERSION). Downloads a temporary copy if needed. | [
"Creates",
"a",
"context",
"manager",
"that",
"returns",
"a",
"path",
"to",
"a",
"particular",
"version",
"of",
"azcopy",
"(",
"specified",
"in",
"AZCOPY_VERSION",
")",
".",
"Downloads",
"a",
"temporary",
"copy",
"if",
"needed",
"."
] | def get_azcopy(local_azcopy_path="azcopy"):
"""
Creates a context manager that returns a path to a particular version of
azcopy (specified in AZCOPY_VERSION). Downloads a temporary copy if needed.
:param local_azcopy_path: Path to a local azcopy to try first.
Example usage:
with get_azcopy() as azcopy_path:
subprocess.run([azcopy_path, "--version"])
"""
with contextlib.ExitStack() as context_stack:
azcopy_path = shutil.which(local_azcopy_path)
if azcopy_path is None or not _check_version(azcopy_path):
temp_dir = context_stack.enter_context(
tempfile.TemporaryDirectory())
download_url = _AZCOPY_DOWNLOAD_URLS[platform.system()]
download_basename = urllib.parse.urlsplit(
download_url).path.rsplit("/", 1)[-1]
assert len(download_basename) > 0
downloaded_path = os.path.join(temp_dir, download_basename)
_log.info("Downloading azcopy from '{}'...".format(download_url))
urllib.request.urlretrieve(download_url, downloaded_path)
extracted_path = os.path.join(temp_dir, "azcopy")
shutil.unpack_archive(downloaded_path, extracted_path)
azcopy_path = _find_azcopy(extracted_path)
os.chmod(azcopy_path, stat.S_IXUSR)
yield azcopy_path | [
"def",
"get_azcopy",
"(",
"local_azcopy_path",
"=",
"\"azcopy\"",
")",
":",
"with",
"contextlib",
".",
"ExitStack",
"(",
")",
"as",
"context_stack",
":",
"azcopy_path",
"=",
"shutil",
".",
"which",
"(",
"local_azcopy_path",
")",
"if",
"azcopy_path",
"is",
"None",
"or",
"not",
"_check_version",
"(",
"azcopy_path",
")",
":",
"temp_dir",
"=",
"context_stack",
".",
"enter_context",
"(",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
")",
"download_url",
"=",
"_AZCOPY_DOWNLOAD_URLS",
"[",
"platform",
".",
"system",
"(",
")",
"]",
"download_basename",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"download_url",
")",
".",
"path",
".",
"rsplit",
"(",
"\"/\"",
",",
"1",
")",
"[",
"-",
"1",
"]",
"assert",
"len",
"(",
"download_basename",
")",
">",
"0",
"downloaded_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"download_basename",
")",
"_log",
".",
"info",
"(",
"\"Downloading azcopy from '{}'...\"",
".",
"format",
"(",
"download_url",
")",
")",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"download_url",
",",
"downloaded_path",
")",
"extracted_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"\"azcopy\"",
")",
"shutil",
".",
"unpack_archive",
"(",
"downloaded_path",
",",
"extracted_path",
")",
"azcopy_path",
"=",
"_find_azcopy",
"(",
"extracted_path",
")",
"os",
".",
"chmod",
"(",
"azcopy_path",
",",
"stat",
".",
"S_IXUSR",
")",
"yield",
"azcopy_path"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/tools/python/util/get_azcopy.py#L50-L84 | ||
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/cpplint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage-class specifier (static, extern, typedef, etc) should be '
'at the beginning of the declaration.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
explicit_constructor_match = Match(
r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*'
r'\(((?:[^()]|\([^()]*\))*)\)'
% re.escape(base_classname),
line)
if explicit_constructor_match:
is_marked_explicit = explicit_constructor_match.group(1)
if not explicit_constructor_match.group(2):
constructor_args = []
else:
constructor_args = explicit_constructor_match.group(2).split(',')
# collapse arguments so that commas in template parameter lists and function
# argument parameter lists don't split arguments in two
i = 0
while i < len(constructor_args):
constructor_arg = constructor_args[i]
while (constructor_arg.count('<') > constructor_arg.count('>') or
constructor_arg.count('(') > constructor_arg.count(')')):
constructor_arg += ',' + constructor_args[i + 1]
del constructor_args[i + 1]
constructor_args[i] = constructor_arg
i += 1
variadic_args = [arg for arg in constructor_args if '&&...' in arg]
defaulted_args = [arg for arg in constructor_args if '=' in arg]
noarg_constructor = (not constructor_args or # empty arg list
# 'void' arg specifier
(len(constructor_args) == 1 and
constructor_args[0].strip() == 'void'))
onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
not noarg_constructor) or
# all but at most one arg defaulted
(len(constructor_args) >= 1 and
not noarg_constructor and
len(defaulted_args) >= len(constructor_args) - 1) or
# variadic arguments with zero or one argument
(len(constructor_args) <= 2 and
len(variadic_args) >= 1))
initializer_list_constructor = bool(
onearg_constructor and
Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
copy_constructor = bool(
onearg_constructor and
Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), constructor_args[0].strip()))
if (not is_marked_explicit and
onearg_constructor and
not initializer_list_constructor and
not copy_constructor):
if defaulted_args or variadic_args:
error(filename, linenum, 'runtime/explicit', 5,
'Constructors callable with one argument '
'should be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 5,
'Single-parameter constructors should be marked explicit.')
elif is_marked_explicit and not onearg_constructor:
if noarg_constructor:
error(filename, linenum, 'runtime/explicit', 5,
'Zero-parameter constructors should not be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage-class specifier (static, extern, typedef, etc) should be '",
"'at the beginning of the declaration.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style.",
"explicit_constructor_match",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?(explicit\\s+)?(?:inline\\s+)?%s\\s*'",
"r'\\(((?:[^()]|\\([^()]*\\))*)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"explicit_constructor_match",
":",
"is_marked_explicit",
"=",
"explicit_constructor_match",
".",
"group",
"(",
"1",
")",
"if",
"not",
"explicit_constructor_match",
".",
"group",
"(",
"2",
")",
":",
"constructor_args",
"=",
"[",
"]",
"else",
":",
"constructor_args",
"=",
"explicit_constructor_match",
".",
"group",
"(",
"2",
")",
".",
"split",
"(",
"','",
")",
"# collapse arguments so that commas in template parameter lists and function",
"# argument parameter lists don't split arguments in two",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"constructor_args",
")",
":",
"constructor_arg",
"=",
"constructor_args",
"[",
"i",
"]",
"while",
"(",
"constructor_arg",
".",
"count",
"(",
"'<'",
")",
">",
"constructor_arg",
".",
"count",
"(",
"'>'",
")",
"or",
"constructor_arg",
".",
"count",
"(",
"'('",
")",
">",
"constructor_arg",
".",
"count",
"(",
"')'",
")",
")",
":",
"constructor_arg",
"+=",
"','",
"+",
"constructor_args",
"[",
"i",
"+",
"1",
"]",
"del",
"constructor_args",
"[",
"i",
"+",
"1",
"]",
"constructor_args",
"[",
"i",
"]",
"=",
"constructor_arg",
"i",
"+=",
"1",
"variadic_args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"constructor_args",
"if",
"'&&...'",
"in",
"arg",
"]",
"defaulted_args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"constructor_args",
"if",
"'='",
"in",
"arg",
"]",
"noarg_constructor",
"=",
"(",
"not",
"constructor_args",
"or",
"# empty arg list",
"# 'void' arg specifier",
"(",
"len",
"(",
"constructor_args",
")",
"==",
"1",
"and",
"constructor_args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"==",
"'void'",
")",
")",
"onearg_constructor",
"=",
"(",
"(",
"len",
"(",
"constructor_args",
")",
"==",
"1",
"and",
"# exactly one arg",
"not",
"noarg_constructor",
")",
"or",
"# all but at most one arg defaulted",
"(",
"len",
"(",
"constructor_args",
")",
">=",
"1",
"and",
"not",
"noarg_constructor",
"and",
"len",
"(",
"defaulted_args",
")",
">=",
"len",
"(",
"constructor_args",
")",
"-",
"1",
")",
"or",
"# variadic arguments with zero or one argument",
"(",
"len",
"(",
"constructor_args",
")",
"<=",
"2",
"and",
"len",
"(",
"variadic_args",
")",
">=",
"1",
")",
")",
"initializer_list_constructor",
"=",
"bool",
"(",
"onearg_constructor",
"and",
"Search",
"(",
"r'\\bstd\\s*::\\s*initializer_list\\b'",
",",
"constructor_args",
"[",
"0",
"]",
")",
")",
"copy_constructor",
"=",
"bool",
"(",
"onearg_constructor",
"and",
"Match",
"(",
"r'(const\\s+)?%s(\\s*<[^>]*>)?(\\s+const)?\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"constructor_args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
")",
"if",
"(",
"not",
"is_marked_explicit",
"and",
"onearg_constructor",
"and",
"not",
"initializer_list_constructor",
"and",
"not",
"copy_constructor",
")",
":",
"if",
"defaulted_args",
"or",
"variadic_args",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Constructors callable with one argument '",
"'should be marked explicit.'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-parameter constructors should be marked explicit.'",
")",
"elif",
"is_marked_explicit",
"and",
"not",
"onearg_constructor",
":",
"if",
"noarg_constructor",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Zero-parameter constructors should not be marked explicit.'",
")"
] | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L2888-L3048 | ||
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/jwt/_jwt_signature_key_manager.py | python | _JwtPublicKeyVerify.verify_and_decode_with_kid | (
self, compact: str, validator: _jwt_validator.JwtValidator,
kid: Optional[str]) | return _verified_jwt.VerifiedJwt._create(raw_jwt) | Verifies, validates and decodes a signed compact JWT token. | Verifies, validates and decodes a signed compact JWT token. | [
"Verifies",
"validates",
"and",
"decodes",
"a",
"signed",
"compact",
"JWT",
"token",
"."
] | def verify_and_decode_with_kid(
self, compact: str, validator: _jwt_validator.JwtValidator,
kid: Optional[str]) -> _verified_jwt.VerifiedJwt:
"""Verifies, validates and decodes a signed compact JWT token."""
parts = _jwt_format.split_signed_compact(compact)
unsigned_compact, json_header, json_payload, signature = parts
self._verify(signature, unsigned_compact)
header = _json_util.json_loads(json_header)
_jwt_format.validate_header(
header=header,
algorithm=self._algorithm,
tink_kid=kid,
custom_kid=self._custom_kid)
raw_jwt = _raw_jwt.raw_jwt_from_json(
_jwt_format.get_type_header(header), json_payload)
_jwt_validator.validate(validator, raw_jwt)
return _verified_jwt.VerifiedJwt._create(raw_jwt) | [
"def",
"verify_and_decode_with_kid",
"(",
"self",
",",
"compact",
":",
"str",
",",
"validator",
":",
"_jwt_validator",
".",
"JwtValidator",
",",
"kid",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"_verified_jwt",
".",
"VerifiedJwt",
":",
"parts",
"=",
"_jwt_format",
".",
"split_signed_compact",
"(",
"compact",
")",
"unsigned_compact",
",",
"json_header",
",",
"json_payload",
",",
"signature",
"=",
"parts",
"self",
".",
"_verify",
"(",
"signature",
",",
"unsigned_compact",
")",
"header",
"=",
"_json_util",
".",
"json_loads",
"(",
"json_header",
")",
"_jwt_format",
".",
"validate_header",
"(",
"header",
"=",
"header",
",",
"algorithm",
"=",
"self",
".",
"_algorithm",
",",
"tink_kid",
"=",
"kid",
",",
"custom_kid",
"=",
"self",
".",
"_custom_kid",
")",
"raw_jwt",
"=",
"_raw_jwt",
".",
"raw_jwt_from_json",
"(",
"_jwt_format",
".",
"get_type_header",
"(",
"header",
")",
",",
"json_payload",
")",
"_jwt_validator",
".",
"validate",
"(",
"validator",
",",
"raw_jwt",
")",
"return",
"_verified_jwt",
".",
"VerifiedJwt",
".",
"_create",
"(",
"raw_jwt",
")"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/jwt/_jwt_signature_key_manager.py#L111-L127 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/dsolve/linsolve.py | python | spsolve | (A, b, permc_spec=None, use_umfpack=True) | return x | Solve the sparse linear system Ax=b, where b may be a vector or a matrix.
Parameters
----------
A : ndarray or sparse matrix
The square matrix A will be converted into CSC or CSR form
b : ndarray or sparse matrix
The matrix or vector representing the right hand side of the equation.
If a vector, b.shape must be (n,) or (n, 1).
permc_spec : str, optional
How to permute the columns of the matrix for sparsity preservation.
(default: 'COLAMD')
- ``NATURAL``: natural ordering.
- ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
- ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
- ``COLAMD``: approximate minimum degree column ordering
use_umfpack : bool, optional
if True (default) then use umfpack for the solution. This is
only referenced if b is a vector and ``scikit-umfpack`` is installed.
Returns
-------
x : ndarray or sparse matrix
the solution of the sparse linear equation.
If b is a vector, then x is a vector of size A.shape[1]
If b is a matrix, then x is a matrix of size (A.shape[1], b.shape[1])
Notes
-----
For solving the matrix expression AX = B, this solver assumes the resulting
matrix X is sparse, as is often the case for very sparse inputs. If the
resulting X is dense, the construction of this sparse result will be
relatively expensive. In that case, consider converting A to a dense
matrix and using scipy.linalg.solve or its variants.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import spsolve
>>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
>>> B = csc_matrix([[2, 0], [-1, 0], [2, 0]], dtype=float)
>>> x = spsolve(A, B)
>>> np.allclose(A.dot(x).todense(), B.todense())
True | Solve the sparse linear system Ax=b, where b may be a vector or a matrix. | [
"Solve",
"the",
"sparse",
"linear",
"system",
"Ax",
"=",
"b",
"where",
"b",
"may",
"be",
"a",
"vector",
"or",
"a",
"matrix",
"."
] | def spsolve(A, b, permc_spec=None, use_umfpack=True):
"""Solve the sparse linear system Ax=b, where b may be a vector or a matrix.
Parameters
----------
A : ndarray or sparse matrix
The square matrix A will be converted into CSC or CSR form
b : ndarray or sparse matrix
The matrix or vector representing the right hand side of the equation.
If a vector, b.shape must be (n,) or (n, 1).
permc_spec : str, optional
How to permute the columns of the matrix for sparsity preservation.
(default: 'COLAMD')
- ``NATURAL``: natural ordering.
- ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
- ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
- ``COLAMD``: approximate minimum degree column ordering
use_umfpack : bool, optional
if True (default) then use umfpack for the solution. This is
only referenced if b is a vector and ``scikit-umfpack`` is installed.
Returns
-------
x : ndarray or sparse matrix
the solution of the sparse linear equation.
If b is a vector, then x is a vector of size A.shape[1]
If b is a matrix, then x is a matrix of size (A.shape[1], b.shape[1])
Notes
-----
For solving the matrix expression AX = B, this solver assumes the resulting
matrix X is sparse, as is often the case for very sparse inputs. If the
resulting X is dense, the construction of this sparse result will be
relatively expensive. In that case, consider converting A to a dense
matrix and using scipy.linalg.solve or its variants.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import spsolve
>>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
>>> B = csc_matrix([[2, 0], [-1, 0], [2, 0]], dtype=float)
>>> x = spsolve(A, B)
>>> np.allclose(A.dot(x).todense(), B.todense())
True
"""
if not (isspmatrix_csc(A) or isspmatrix_csr(A)):
A = csc_matrix(A)
warn('spsolve requires A be CSC or CSR matrix format',
SparseEfficiencyWarning)
# b is a vector only if b have shape (n,) or (n, 1)
b_is_sparse = isspmatrix(b)
if not b_is_sparse:
b = asarray(b)
b_is_vector = ((b.ndim == 1) or (b.ndim == 2 and b.shape[1] == 1))
# sum duplicates for non-canonical format
A.sum_duplicates()
A = A.asfptype() # upcast to a floating point format
result_dtype = np.promote_types(A.dtype, b.dtype)
if A.dtype != result_dtype:
A = A.astype(result_dtype)
if b.dtype != result_dtype:
b = b.astype(result_dtype)
# validate input shapes
M, N = A.shape
if (M != N):
raise ValueError("matrix must be square (has shape %s)" % ((M, N),))
if M != b.shape[0]:
raise ValueError("matrix - rhs dimension mismatch (%s - %s)"
% (A.shape, b.shape[0]))
use_umfpack = use_umfpack and useUmfpack
if b_is_vector and use_umfpack:
if b_is_sparse:
b_vec = b.toarray()
else:
b_vec = b
b_vec = asarray(b_vec, dtype=A.dtype).ravel()
if noScikit:
raise RuntimeError('Scikits.umfpack not installed.')
if A.dtype.char not in 'dD':
raise ValueError("convert matrix data to double, please, using"
" .astype(), or set linsolve.useUmfpack = False")
umf = umfpack.UmfpackContext(_get_umf_family(A))
x = umf.linsolve(umfpack.UMFPACK_A, A, b_vec,
autoTranspose=True)
else:
if b_is_vector and b_is_sparse:
b = b.toarray()
b_is_sparse = False
if not b_is_sparse:
if isspmatrix_csc(A):
flag = 1 # CSC format
else:
flag = 0 # CSR format
options = dict(ColPerm=permc_spec)
x, info = _superlu.gssv(N, A.nnz, A.data, A.indices, A.indptr,
b, flag, options=options)
if info != 0:
warn("Matrix is exactly singular", MatrixRankWarning)
x.fill(np.nan)
if b_is_vector:
x = x.ravel()
else:
# b is sparse
Afactsolve = factorized(A)
if not isspmatrix_csc(b):
warn('spsolve is more efficient when sparse b '
'is in the CSC matrix format', SparseEfficiencyWarning)
b = csc_matrix(b)
# Create a sparse output matrix by repeatedly applying
# the sparse factorization to solve columns of b.
data_segs = []
row_segs = []
col_segs = []
for j in range(b.shape[1]):
bj = b[:, j].A.ravel()
xj = Afactsolve(bj)
w = np.flatnonzero(xj)
segment_length = w.shape[0]
row_segs.append(w)
col_segs.append(np.full(segment_length, j, dtype=int))
data_segs.append(np.asarray(xj[w], dtype=A.dtype))
sparse_data = np.concatenate(data_segs)
sparse_row = np.concatenate(row_segs)
sparse_col = np.concatenate(col_segs)
x = A.__class__((sparse_data, (sparse_row, sparse_col)),
shape=b.shape, dtype=A.dtype)
return x | [
"def",
"spsolve",
"(",
"A",
",",
"b",
",",
"permc_spec",
"=",
"None",
",",
"use_umfpack",
"=",
"True",
")",
":",
"if",
"not",
"(",
"isspmatrix_csc",
"(",
"A",
")",
"or",
"isspmatrix_csr",
"(",
"A",
")",
")",
":",
"A",
"=",
"csc_matrix",
"(",
"A",
")",
"warn",
"(",
"'spsolve requires A be CSC or CSR matrix format'",
",",
"SparseEfficiencyWarning",
")",
"# b is a vector only if b have shape (n,) or (n, 1)",
"b_is_sparse",
"=",
"isspmatrix",
"(",
"b",
")",
"if",
"not",
"b_is_sparse",
":",
"b",
"=",
"asarray",
"(",
"b",
")",
"b_is_vector",
"=",
"(",
"(",
"b",
".",
"ndim",
"==",
"1",
")",
"or",
"(",
"b",
".",
"ndim",
"==",
"2",
"and",
"b",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
")",
")",
"# sum duplicates for non-canonical format",
"A",
".",
"sum_duplicates",
"(",
")",
"A",
"=",
"A",
".",
"asfptype",
"(",
")",
"# upcast to a floating point format",
"result_dtype",
"=",
"np",
".",
"promote_types",
"(",
"A",
".",
"dtype",
",",
"b",
".",
"dtype",
")",
"if",
"A",
".",
"dtype",
"!=",
"result_dtype",
":",
"A",
"=",
"A",
".",
"astype",
"(",
"result_dtype",
")",
"if",
"b",
".",
"dtype",
"!=",
"result_dtype",
":",
"b",
"=",
"b",
".",
"astype",
"(",
"result_dtype",
")",
"# validate input shapes",
"M",
",",
"N",
"=",
"A",
".",
"shape",
"if",
"(",
"M",
"!=",
"N",
")",
":",
"raise",
"ValueError",
"(",
"\"matrix must be square (has shape %s)\"",
"%",
"(",
"(",
"M",
",",
"N",
")",
",",
")",
")",
"if",
"M",
"!=",
"b",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"matrix - rhs dimension mismatch (%s - %s)\"",
"%",
"(",
"A",
".",
"shape",
",",
"b",
".",
"shape",
"[",
"0",
"]",
")",
")",
"use_umfpack",
"=",
"use_umfpack",
"and",
"useUmfpack",
"if",
"b_is_vector",
"and",
"use_umfpack",
":",
"if",
"b_is_sparse",
":",
"b_vec",
"=",
"b",
".",
"toarray",
"(",
")",
"else",
":",
"b_vec",
"=",
"b",
"b_vec",
"=",
"asarray",
"(",
"b_vec",
",",
"dtype",
"=",
"A",
".",
"dtype",
")",
".",
"ravel",
"(",
")",
"if",
"noScikit",
":",
"raise",
"RuntimeError",
"(",
"'Scikits.umfpack not installed.'",
")",
"if",
"A",
".",
"dtype",
".",
"char",
"not",
"in",
"'dD'",
":",
"raise",
"ValueError",
"(",
"\"convert matrix data to double, please, using\"",
"\" .astype(), or set linsolve.useUmfpack = False\"",
")",
"umf",
"=",
"umfpack",
".",
"UmfpackContext",
"(",
"_get_umf_family",
"(",
"A",
")",
")",
"x",
"=",
"umf",
".",
"linsolve",
"(",
"umfpack",
".",
"UMFPACK_A",
",",
"A",
",",
"b_vec",
",",
"autoTranspose",
"=",
"True",
")",
"else",
":",
"if",
"b_is_vector",
"and",
"b_is_sparse",
":",
"b",
"=",
"b",
".",
"toarray",
"(",
")",
"b_is_sparse",
"=",
"False",
"if",
"not",
"b_is_sparse",
":",
"if",
"isspmatrix_csc",
"(",
"A",
")",
":",
"flag",
"=",
"1",
"# CSC format",
"else",
":",
"flag",
"=",
"0",
"# CSR format",
"options",
"=",
"dict",
"(",
"ColPerm",
"=",
"permc_spec",
")",
"x",
",",
"info",
"=",
"_superlu",
".",
"gssv",
"(",
"N",
",",
"A",
".",
"nnz",
",",
"A",
".",
"data",
",",
"A",
".",
"indices",
",",
"A",
".",
"indptr",
",",
"b",
",",
"flag",
",",
"options",
"=",
"options",
")",
"if",
"info",
"!=",
"0",
":",
"warn",
"(",
"\"Matrix is exactly singular\"",
",",
"MatrixRankWarning",
")",
"x",
".",
"fill",
"(",
"np",
".",
"nan",
")",
"if",
"b_is_vector",
":",
"x",
"=",
"x",
".",
"ravel",
"(",
")",
"else",
":",
"# b is sparse",
"Afactsolve",
"=",
"factorized",
"(",
"A",
")",
"if",
"not",
"isspmatrix_csc",
"(",
"b",
")",
":",
"warn",
"(",
"'spsolve is more efficient when sparse b '",
"'is in the CSC matrix format'",
",",
"SparseEfficiencyWarning",
")",
"b",
"=",
"csc_matrix",
"(",
"b",
")",
"# Create a sparse output matrix by repeatedly applying",
"# the sparse factorization to solve columns of b.",
"data_segs",
"=",
"[",
"]",
"row_segs",
"=",
"[",
"]",
"col_segs",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"b",
".",
"shape",
"[",
"1",
"]",
")",
":",
"bj",
"=",
"b",
"[",
":",
",",
"j",
"]",
".",
"A",
".",
"ravel",
"(",
")",
"xj",
"=",
"Afactsolve",
"(",
"bj",
")",
"w",
"=",
"np",
".",
"flatnonzero",
"(",
"xj",
")",
"segment_length",
"=",
"w",
".",
"shape",
"[",
"0",
"]",
"row_segs",
".",
"append",
"(",
"w",
")",
"col_segs",
".",
"append",
"(",
"np",
".",
"full",
"(",
"segment_length",
",",
"j",
",",
"dtype",
"=",
"int",
")",
")",
"data_segs",
".",
"append",
"(",
"np",
".",
"asarray",
"(",
"xj",
"[",
"w",
"]",
",",
"dtype",
"=",
"A",
".",
"dtype",
")",
")",
"sparse_data",
"=",
"np",
".",
"concatenate",
"(",
"data_segs",
")",
"sparse_row",
"=",
"np",
".",
"concatenate",
"(",
"row_segs",
")",
"sparse_col",
"=",
"np",
".",
"concatenate",
"(",
"col_segs",
")",
"x",
"=",
"A",
".",
"__class__",
"(",
"(",
"sparse_data",
",",
"(",
"sparse_row",
",",
"sparse_col",
")",
")",
",",
"shape",
"=",
"b",
".",
"shape",
",",
"dtype",
"=",
"A",
".",
"dtype",
")",
"return",
"x"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/dsolve/linsolve.py#L83-L225 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/nntplib.py | python | NNTP.newgroups | (self, date, time, file=None) | return self.longcmd('NEWGROUPS ' + date + ' ' + time, file) | Process a NEWGROUPS command. Arguments:
- date: string 'yymmdd' indicating the date
- time: string 'hhmmss' indicating the time
Return:
- resp: server response if successful
- list: list of newsgroup names | Process a NEWGROUPS command. Arguments:
- date: string 'yymmdd' indicating the date
- time: string 'hhmmss' indicating the time
Return:
- resp: server response if successful
- list: list of newsgroup names | [
"Process",
"a",
"NEWGROUPS",
"command",
".",
"Arguments",
":",
"-",
"date",
":",
"string",
"yymmdd",
"indicating",
"the",
"date",
"-",
"time",
":",
"string",
"hhmmss",
"indicating",
"the",
"time",
"Return",
":",
"-",
"resp",
":",
"server",
"response",
"if",
"successful",
"-",
"list",
":",
"list",
"of",
"newsgroup",
"names"
] | def newgroups(self, date, time, file=None):
"""Process a NEWGROUPS command. Arguments:
- date: string 'yymmdd' indicating the date
- time: string 'hhmmss' indicating the time
Return:
- resp: server response if successful
- list: list of newsgroup names"""
return self.longcmd('NEWGROUPS ' + date + ' ' + time, file) | [
"def",
"newgroups",
"(",
"self",
",",
"date",
",",
"time",
",",
"file",
"=",
"None",
")",
":",
"return",
"self",
".",
"longcmd",
"(",
"'NEWGROUPS '",
"+",
"date",
"+",
"' '",
"+",
"time",
",",
"file",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/nntplib.py#L266-L274 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_presenter.py | python | BackgroundCorrectionsPresenter.handle_end_x_changed | (self) | Handles when a End X table cell is changed. | Handles when a End X table cell is changed. | [
"Handles",
"when",
"a",
"End",
"X",
"table",
"cell",
"is",
"changed",
"."
] | def handle_end_x_changed(self) -> None:
"""Handles when a End X table cell is changed."""
self._handle_start_or_end_x_changed(self._get_new_x_range_when_end_x_changed) | [
"def",
"handle_end_x_changed",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_handle_start_or_end_x_changed",
"(",
"self",
".",
"_get_new_x_range_when_end_x_changed",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_presenter.py#L101-L103 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/BaseHTTPServer.py | python | BaseHTTPRequestHandler.date_time_string | (self, timestamp=None) | return s | Return the current date and time formatted for a message header. | Return the current date and time formatted for a message header. | [
"Return",
"the",
"current",
"date",
"and",
"time",
"formatted",
"for",
"a",
"message",
"header",
"."
] | def date_time_string(self, timestamp=None):
"""Return the current date and time formatted for a message header."""
if timestamp is None:
timestamp = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s | [
"def",
"date_time_string",
"(",
"self",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"year",
",",
"month",
",",
"day",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"wd",
",",
"y",
",",
"z",
"=",
"time",
".",
"gmtime",
"(",
"timestamp",
")",
"s",
"=",
"\"%s, %02d %3s %4d %02d:%02d:%02d GMT\"",
"%",
"(",
"self",
".",
"weekdayname",
"[",
"wd",
"]",
",",
"day",
",",
"self",
".",
"monthname",
"[",
"month",
"]",
",",
"year",
",",
"hh",
",",
"mm",
",",
"ss",
")",
"return",
"s"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/BaseHTTPServer.py#L464-L473 | |
KhronosGroup/SPIRV-Tools | 940127a77d3ad795a4a1422fbeaad50c9f19f2ea | utils/generate_grammar_tables.py | python | convert_operand_kind | (operand_tuple) | return 'SPV_OPERAND_TYPE_{}'.format(
re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper()) | Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- quantifier: '', '?', or '*'
Returns:
a string of the enumerant name in spv_operand_type_t | Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar. | [
"Returns",
"the",
"corresponding",
"operand",
"type",
"used",
"in",
"spirv",
"-",
"tools",
"for",
"the",
"given",
"operand",
"kind",
"and",
"quantifier",
"used",
"in",
"the",
"JSON",
"grammar",
"."
] | def convert_operand_kind(operand_tuple):
"""Returns the corresponding operand type used in spirv-tools for the given
operand kind and quantifier used in the JSON grammar.
Arguments:
- operand_tuple: a tuple of two elements:
- operand kind: used in the JSON grammar
- quantifier: '', '?', or '*'
Returns:
a string of the enumerant name in spv_operand_type_t
"""
kind, quantifier = operand_tuple
# The following cases are where we differ between the JSON grammar and
# spirv-tools.
if kind == 'IdResultType':
kind = 'TypeId'
elif kind == 'IdResult':
kind = 'ResultId'
elif kind == 'IdMemorySemantics' or kind == 'MemorySemantics':
kind = 'MemorySemanticsId'
elif kind == 'IdScope' or kind == 'Scope':
kind = 'ScopeId'
elif kind == 'IdRef':
kind = 'Id'
elif kind == 'ImageOperands':
kind = 'Image'
elif kind == 'Dim':
kind = 'Dimensionality'
elif kind == 'ImageFormat':
kind = 'SamplerImageFormat'
elif kind == 'KernelEnqueueFlags':
kind = 'KernelEnqFlags'
elif kind == 'LiteralExtInstInteger':
kind = 'ExtensionInstructionNumber'
elif kind == 'LiteralSpecConstantOpInteger':
kind = 'SpecConstantOpNumber'
elif kind == 'LiteralContextDependentNumber':
kind = 'TypedLiteralNumber'
elif kind == 'PairLiteralIntegerIdRef':
kind = 'LiteralIntegerId'
elif kind == 'PairIdRefLiteralInteger':
kind = 'IdLiteralInteger'
elif kind == 'PairIdRefIdRef': # Used by OpPhi in the grammar
kind = 'Id'
if kind == 'FPRoundingMode':
kind = 'FpRoundingMode'
elif kind == 'FPFastMathMode':
kind = 'FpFastMathMode'
if quantifier == '?':
kind = 'Optional{}'.format(kind)
elif quantifier == '*':
kind = 'Variable{}'.format(kind)
return 'SPV_OPERAND_TYPE_{}'.format(
re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper()) | [
"def",
"convert_operand_kind",
"(",
"operand_tuple",
")",
":",
"kind",
",",
"quantifier",
"=",
"operand_tuple",
"# The following cases are where we differ between the JSON grammar and",
"# spirv-tools.",
"if",
"kind",
"==",
"'IdResultType'",
":",
"kind",
"=",
"'TypeId'",
"elif",
"kind",
"==",
"'IdResult'",
":",
"kind",
"=",
"'ResultId'",
"elif",
"kind",
"==",
"'IdMemorySemantics'",
"or",
"kind",
"==",
"'MemorySemantics'",
":",
"kind",
"=",
"'MemorySemanticsId'",
"elif",
"kind",
"==",
"'IdScope'",
"or",
"kind",
"==",
"'Scope'",
":",
"kind",
"=",
"'ScopeId'",
"elif",
"kind",
"==",
"'IdRef'",
":",
"kind",
"=",
"'Id'",
"elif",
"kind",
"==",
"'ImageOperands'",
":",
"kind",
"=",
"'Image'",
"elif",
"kind",
"==",
"'Dim'",
":",
"kind",
"=",
"'Dimensionality'",
"elif",
"kind",
"==",
"'ImageFormat'",
":",
"kind",
"=",
"'SamplerImageFormat'",
"elif",
"kind",
"==",
"'KernelEnqueueFlags'",
":",
"kind",
"=",
"'KernelEnqFlags'",
"elif",
"kind",
"==",
"'LiteralExtInstInteger'",
":",
"kind",
"=",
"'ExtensionInstructionNumber'",
"elif",
"kind",
"==",
"'LiteralSpecConstantOpInteger'",
":",
"kind",
"=",
"'SpecConstantOpNumber'",
"elif",
"kind",
"==",
"'LiteralContextDependentNumber'",
":",
"kind",
"=",
"'TypedLiteralNumber'",
"elif",
"kind",
"==",
"'PairLiteralIntegerIdRef'",
":",
"kind",
"=",
"'LiteralIntegerId'",
"elif",
"kind",
"==",
"'PairIdRefLiteralInteger'",
":",
"kind",
"=",
"'IdLiteralInteger'",
"elif",
"kind",
"==",
"'PairIdRefIdRef'",
":",
"# Used by OpPhi in the grammar",
"kind",
"=",
"'Id'",
"if",
"kind",
"==",
"'FPRoundingMode'",
":",
"kind",
"=",
"'FpRoundingMode'",
"elif",
"kind",
"==",
"'FPFastMathMode'",
":",
"kind",
"=",
"'FpFastMathMode'",
"if",
"quantifier",
"==",
"'?'",
":",
"kind",
"=",
"'Optional{}'",
".",
"format",
"(",
"kind",
")",
"elif",
"quantifier",
"==",
"'*'",
":",
"kind",
"=",
"'Variable{}'",
".",
"format",
"(",
"kind",
")",
"return",
"'SPV_OPERAND_TYPE_{}'",
".",
"format",
"(",
"re",
".",
"sub",
"(",
"r'([a-z])([A-Z])'",
",",
"r'\\1_\\2'",
",",
"kind",
")",
".",
"upper",
"(",
")",
")"
] | https://github.com/KhronosGroup/SPIRV-Tools/blob/940127a77d3ad795a4a1422fbeaad50c9f19f2ea/utils/generate_grammar_tables.py#L149-L209 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/PRESUBMIT.py | python | _CheckUnwantedDependencies | (input_api, output_api) | return results | Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning. | Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning. | [
"Runs",
"checkdeps",
"on",
"#include",
"statements",
"added",
"in",
"this",
"change",
".",
"Breaking",
"-",
"rules",
"is",
"an",
"error",
"breaking",
"!",
"rules",
"is",
"a",
"warning",
"."
] | def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results | [
"def",
"_CheckUnwantedDependencies",
"(",
"input_api",
",",
"output_api",
")",
":",
"# We need to wait until we have an input_api object and use this",
"# roundabout construct to import checkdeps because this file is",
"# eval-ed and thus doesn't have __file__.",
"original_sys_path",
"=",
"sys",
".",
"path",
"try",
":",
"sys",
".",
"path",
"=",
"sys",
".",
"path",
"+",
"[",
"input_api",
".",
"os_path",
".",
"join",
"(",
"input_api",
".",
"PresubmitLocalPath",
"(",
")",
",",
"'buildtools'",
",",
"'checkdeps'",
")",
"]",
"import",
"checkdeps",
"from",
"cpp_checker",
"import",
"CppChecker",
"from",
"rules",
"import",
"Rule",
"finally",
":",
"# Restore sys.path to what it was before.",
"sys",
".",
"path",
"=",
"original_sys_path",
"added_includes",
"=",
"[",
"]",
"for",
"f",
"in",
"input_api",
".",
"AffectedFiles",
"(",
")",
":",
"if",
"not",
"CppChecker",
".",
"IsCppFile",
"(",
"f",
".",
"LocalPath",
"(",
")",
")",
":",
"continue",
"changed_lines",
"=",
"[",
"line",
"for",
"line_num",
",",
"line",
"in",
"f",
".",
"ChangedContents",
"(",
")",
"]",
"added_includes",
".",
"append",
"(",
"[",
"f",
".",
"LocalPath",
"(",
")",
",",
"changed_lines",
"]",
")",
"deps_checker",
"=",
"checkdeps",
".",
"DepsChecker",
"(",
"input_api",
".",
"PresubmitLocalPath",
"(",
")",
")",
"error_descriptions",
"=",
"[",
"]",
"warning_descriptions",
"=",
"[",
"]",
"for",
"path",
",",
"rule_type",
",",
"rule_description",
"in",
"deps_checker",
".",
"CheckAddedCppIncludes",
"(",
"added_includes",
")",
":",
"description_with_path",
"=",
"'%s\\n %s'",
"%",
"(",
"path",
",",
"rule_description",
")",
"if",
"rule_type",
"==",
"Rule",
".",
"DISALLOW",
":",
"error_descriptions",
".",
"append",
"(",
"description_with_path",
")",
"else",
":",
"warning_descriptions",
".",
"append",
"(",
"description_with_path",
")",
"results",
"=",
"[",
"]",
"if",
"error_descriptions",
":",
"results",
".",
"append",
"(",
"output_api",
".",
"PresubmitError",
"(",
"'You added one or more #includes that violate checkdeps rules.'",
",",
"error_descriptions",
")",
")",
"if",
"warning_descriptions",
":",
"results",
".",
"append",
"(",
"output_api",
".",
"PresubmitPromptOrNotify",
"(",
"'You added one or more #includes of files that are temporarily\\n'",
"'allowed but being removed. Can you avoid introducing the\\n'",
"'#include? See relevant DEPS file(s) for details and contacts.'",
",",
"warning_descriptions",
")",
")",
"return",
"results"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/PRESUBMIT.py#L90-L140 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/linalg/linalg_impl.py | python | _matrix_exp_pade7 | (matrix) | return matrix_u, matrix_v | 7th-order Pade approximant for matrix exponential. | 7th-order Pade approximant for matrix exponential. | [
"7th",
"-",
"order",
"Pade",
"approximant",
"for",
"matrix",
"exponential",
"."
] | def _matrix_exp_pade7(matrix):
"""7th-order Pade approximant for matrix exponential."""
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0]
b = [constant_op.constant(x, matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
matrix_6 = math_ops.matmul(matrix_4, matrix_2)
tmp = matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident
return matrix_u, matrix_v | [
"def",
"_matrix_exp_pade7",
"(",
"matrix",
")",
":",
"b",
"=",
"[",
"17297280.0",
",",
"8648640.0",
",",
"1995840.0",
",",
"277200.0",
",",
"25200.0",
",",
"1512.0",
",",
"56.0",
"]",
"b",
"=",
"[",
"constant_op",
".",
"constant",
"(",
"x",
",",
"matrix",
".",
"dtype",
")",
"for",
"x",
"in",
"b",
"]",
"ident",
"=",
"linalg_ops",
".",
"eye",
"(",
"array_ops",
".",
"shape",
"(",
"matrix",
")",
"[",
"-",
"2",
"]",
",",
"batch_shape",
"=",
"array_ops",
".",
"shape",
"(",
"matrix",
")",
"[",
":",
"-",
"2",
"]",
",",
"dtype",
"=",
"matrix",
".",
"dtype",
")",
"matrix_2",
"=",
"math_ops",
".",
"matmul",
"(",
"matrix",
",",
"matrix",
")",
"matrix_4",
"=",
"math_ops",
".",
"matmul",
"(",
"matrix_2",
",",
"matrix_2",
")",
"matrix_6",
"=",
"math_ops",
".",
"matmul",
"(",
"matrix_4",
",",
"matrix_2",
")",
"tmp",
"=",
"matrix_6",
"+",
"b",
"[",
"5",
"]",
"*",
"matrix_4",
"+",
"b",
"[",
"3",
"]",
"*",
"matrix_2",
"+",
"b",
"[",
"1",
"]",
"*",
"ident",
"matrix_u",
"=",
"math_ops",
".",
"matmul",
"(",
"matrix",
",",
"tmp",
")",
"matrix_v",
"=",
"b",
"[",
"6",
"]",
"*",
"matrix_6",
"+",
"b",
"[",
"4",
"]",
"*",
"matrix_4",
"+",
"b",
"[",
"2",
"]",
"*",
"matrix_2",
"+",
"b",
"[",
"0",
"]",
"*",
"ident",
"return",
"matrix_u",
",",
"matrix_v"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/linalg/linalg_impl.py#L163-L177 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/generators.py | python | Generator.convert_multiple_sources_to_consumable_types | (self, project, prop_set, sources) | return result | Converts several files to consumable types. | Converts several files to consumable types. | [
"Converts",
"several",
"files",
"to",
"consumable",
"types",
"."
] | def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources):
""" Converts several files to consumable types.
"""
if __debug__:
from .targets import ProjectTarget
assert isinstance(project, ProjectTarget)
assert isinstance(prop_set, property_set.PropertySet)
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
if not self.source_types_:
return list(sources)
acceptable_types = set()
for t in self.source_types_:
acceptable_types.update(type.all_derived(t))
result = []
for source in sources:
if source.type() not in acceptable_types:
transformed = construct_types(
project, None,self.source_types_, prop_set, [source])
# construct_types returns [prop_set, [targets]]
for t in transformed[1]:
if t.type() in self.source_types_:
result.append(t)
if not transformed:
project.manager().logger().log(__name__, " failed to convert ", source)
else:
result.append(source)
result = sequence.unique(result, stable=True)
return result | [
"def",
"convert_multiple_sources_to_consumable_types",
"(",
"self",
",",
"project",
",",
"prop_set",
",",
"sources",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"if",
"not",
"self",
".",
"source_types_",
":",
"return",
"list",
"(",
"sources",
")",
"acceptable_types",
"=",
"set",
"(",
")",
"for",
"t",
"in",
"self",
".",
"source_types_",
":",
"acceptable_types",
".",
"update",
"(",
"type",
".",
"all_derived",
"(",
"t",
")",
")",
"result",
"=",
"[",
"]",
"for",
"source",
"in",
"sources",
":",
"if",
"source",
".",
"type",
"(",
")",
"not",
"in",
"acceptable_types",
":",
"transformed",
"=",
"construct_types",
"(",
"project",
",",
"None",
",",
"self",
".",
"source_types_",
",",
"prop_set",
",",
"[",
"source",
"]",
")",
"# construct_types returns [prop_set, [targets]]",
"for",
"t",
"in",
"transformed",
"[",
"1",
"]",
":",
"if",
"t",
".",
"type",
"(",
")",
"in",
"self",
".",
"source_types_",
":",
"result",
".",
"append",
"(",
"t",
")",
"if",
"not",
"transformed",
":",
"project",
".",
"manager",
"(",
")",
".",
"logger",
"(",
")",
".",
"log",
"(",
"__name__",
",",
"\" failed to convert \"",
",",
"source",
")",
"else",
":",
"result",
".",
"append",
"(",
"source",
")",
"result",
"=",
"sequence",
".",
"unique",
"(",
"result",
",",
"stable",
"=",
"True",
")",
"return",
"result"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/generators.py#L588-L619 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/mwcc.py | python | find_versions | () | return versions | Return a list of MWVersion objects representing installed versions | Return a list of MWVersion objects representing installed versions | [
"Return",
"a",
"list",
"of",
"MWVersion",
"objects",
"representing",
"installed",
"versions"
] | def find_versions():
"""Return a list of MWVersion objects representing installed versions"""
versions = []
### This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be implemented for other
### platforms, maybe something that calls env.WhereIs('mwcc')
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while True:
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
try:
version = SCons.Util.RegQueryValueEx(name_key, 'VERSION')
path = SCons.Util.RegQueryValueEx(name_key, 'PATH')
mwv = MWVersion(version[0], path[0], 'Win32-X86')
versions.append(mwv)
except SCons.Util.RegError:
pass
i = i + 1
except SCons.Util.RegError:
pass
return versions | [
"def",
"find_versions",
"(",
")",
":",
"versions",
"=",
"[",
"]",
"### This function finds CodeWarrior by reading from the registry on",
"### Windows. Some other method needs to be implemented for other",
"### platforms, maybe something that calls env.WhereIs('mwcc')",
"if",
"SCons",
".",
"Util",
".",
"can_read_reg",
":",
"try",
":",
"HLM",
"=",
"SCons",
".",
"Util",
".",
"HKEY_LOCAL_MACHINE",
"product",
"=",
"'SOFTWARE\\\\Metrowerks\\\\CodeWarrior\\\\Product Versions'",
"product_key",
"=",
"SCons",
".",
"Util",
".",
"RegOpenKeyEx",
"(",
"HLM",
",",
"product",
")",
"i",
"=",
"0",
"while",
"True",
":",
"name",
"=",
"product",
"+",
"'\\\\'",
"+",
"SCons",
".",
"Util",
".",
"RegEnumKey",
"(",
"product_key",
",",
"i",
")",
"name_key",
"=",
"SCons",
".",
"Util",
".",
"RegOpenKeyEx",
"(",
"HLM",
",",
"name",
")",
"try",
":",
"version",
"=",
"SCons",
".",
"Util",
".",
"RegQueryValueEx",
"(",
"name_key",
",",
"'VERSION'",
")",
"path",
"=",
"SCons",
".",
"Util",
".",
"RegQueryValueEx",
"(",
"name_key",
",",
"'PATH'",
")",
"mwv",
"=",
"MWVersion",
"(",
"version",
"[",
"0",
"]",
",",
"path",
"[",
"0",
"]",
",",
"'Win32-X86'",
")",
"versions",
".",
"append",
"(",
"mwv",
")",
"except",
"SCons",
".",
"Util",
".",
"RegError",
":",
"pass",
"i",
"=",
"i",
"+",
"1",
"except",
"SCons",
".",
"Util",
".",
"RegError",
":",
"pass",
"return",
"versions"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/mwcc.py#L87-L119 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/data/ops/dataset_ops.py | python | _UnbatchDataset.__init__ | (self, input_dataset, name=None) | See `unbatch()` for more details. | See `unbatch()` for more details. | [
"See",
"unbatch",
"()",
"for",
"more",
"details",
"."
] | def __init__(self, input_dataset, name=None):
"""See `unbatch()` for more details."""
flat_shapes = input_dataset._flat_shapes # pylint: disable=protected-access
if any(s.ndims == 0 for s in flat_shapes):
raise ValueError("Cannot unbatch an input with scalar components.")
known_batch_dim = tensor_shape.Dimension(None)
for s in flat_shapes:
try:
known_batch_dim = known_batch_dim.merge_with(s[0])
except ValueError:
raise ValueError(f"`unbatch()` is only supported for datasets of "
f"elements whose components have a matching leading "
f"dimension. Encountered both {known_batch_dim} and "
f"{s[0]}.")
self._input_dataset = input_dataset
self._structure = nest.map_structure(
lambda component_spec: component_spec._unbatch(), # pylint: disable=protected-access
get_structure(input_dataset))
self._name = name
variant_tensor = ged_ops.unbatch_dataset(
self._input_dataset._variant_tensor, # pylint: disable=protected-access
**self._common_args)
super(_UnbatchDataset, self).__init__(input_dataset, variant_tensor) | [
"def",
"__init__",
"(",
"self",
",",
"input_dataset",
",",
"name",
"=",
"None",
")",
":",
"flat_shapes",
"=",
"input_dataset",
".",
"_flat_shapes",
"# pylint: disable=protected-access",
"if",
"any",
"(",
"s",
".",
"ndims",
"==",
"0",
"for",
"s",
"in",
"flat_shapes",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot unbatch an input with scalar components.\"",
")",
"known_batch_dim",
"=",
"tensor_shape",
".",
"Dimension",
"(",
"None",
")",
"for",
"s",
"in",
"flat_shapes",
":",
"try",
":",
"known_batch_dim",
"=",
"known_batch_dim",
".",
"merge_with",
"(",
"s",
"[",
"0",
"]",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"f\"`unbatch()` is only supported for datasets of \"",
"f\"elements whose components have a matching leading \"",
"f\"dimension. Encountered both {known_batch_dim} and \"",
"f\"{s[0]}.\"",
")",
"self",
".",
"_input_dataset",
"=",
"input_dataset",
"self",
".",
"_structure",
"=",
"nest",
".",
"map_structure",
"(",
"lambda",
"component_spec",
":",
"component_spec",
".",
"_unbatch",
"(",
")",
",",
"# pylint: disable=protected-access",
"get_structure",
"(",
"input_dataset",
")",
")",
"self",
".",
"_name",
"=",
"name",
"variant_tensor",
"=",
"ged_ops",
".",
"unbatch_dataset",
"(",
"self",
".",
"_input_dataset",
".",
"_variant_tensor",
",",
"# pylint: disable=protected-access",
"*",
"*",
"self",
".",
"_common_args",
")",
"super",
"(",
"_UnbatchDataset",
",",
"self",
")",
".",
"__init__",
"(",
"input_dataset",
",",
"variant_tensor",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/ops/dataset_ops.py#L5597-L5619 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | ValidCtxt.validateRoot | (self, doc) | return ret | Try to validate a the root element basically it does the
following check as described by the XML-1.0 recommendation:
- [ VC: Root Element Type ] it doesn't try to recurse or
apply other check to the element | Try to validate a the root element basically it does the
following check as described by the XML-1.0 recommendation:
- [ VC: Root Element Type ] it doesn't try to recurse or
apply other check to the element | [
"Try",
"to",
"validate",
"a",
"the",
"root",
"element",
"basically",
"it",
"does",
"the",
"following",
"check",
"as",
"described",
"by",
"the",
"XML",
"-",
"1",
".",
"0",
"recommendation",
":",
"-",
"[",
"VC",
":",
"Root",
"Element",
"Type",
"]",
"it",
"doesn",
"t",
"try",
"to",
"recurse",
"or",
"apply",
"other",
"check",
"to",
"the",
"element"
] | def validateRoot(self, doc):
"""Try to validate a the root element basically it does the
following check as described by the XML-1.0 recommendation:
- [ VC: Root Element Type ] it doesn't try to recurse or
apply other check to the element """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlValidateRoot(self._o, doc__o)
return ret | [
"def",
"validateRoot",
"(",
"self",
",",
"doc",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateRoot",
"(",
"self",
".",
"_o",
",",
"doc__o",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7191-L7199 | |
IfcOpenShell/IfcOpenShell | 2c2954b11a9c9d581bef03240836d4567e69ad0b | src/ifcopenshell-python/ifcopenshell/ids.py | python | specification.parse | (ids_dict) | return spec | Parse xml specification to python object.
:param ids_dict:
:type ids_dict: dict | Parse xml specification to python object. | [
"Parse",
"xml",
"specification",
"to",
"python",
"object",
"."
] | def parse(ids_dict):
"""Parse xml specification to python object.
:param ids_dict:
:type ids_dict: dict
"""
def parse_rules(dict):
facet_names = list(dict.keys())
facet_properties = [v[0] if isinstance(v, list) else v for v in list(dict.values())]
classes = [meta_facet.facets.__getitem__(f) for f in facet_names]
facets = [cls(n) for cls, n in zip(classes, facet_properties)]
return facets
spec = specification()
spec.name = ids_dict["@name"]
spec.necessity = ids_dict["@necessity"]
spec.applicability = boolean_and(parse_rules(ids_dict["applicability"]))
spec.requirements = boolean_and(parse_rules(ids_dict["requirements"]))
return spec | [
"def",
"parse",
"(",
"ids_dict",
")",
":",
"def",
"parse_rules",
"(",
"dict",
")",
":",
"facet_names",
"=",
"list",
"(",
"dict",
".",
"keys",
"(",
")",
")",
"facet_properties",
"=",
"[",
"v",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
"else",
"v",
"for",
"v",
"in",
"list",
"(",
"dict",
".",
"values",
"(",
")",
")",
"]",
"classes",
"=",
"[",
"meta_facet",
".",
"facets",
".",
"__getitem__",
"(",
"f",
")",
"for",
"f",
"in",
"facet_names",
"]",
"facets",
"=",
"[",
"cls",
"(",
"n",
")",
"for",
"cls",
",",
"n",
"in",
"zip",
"(",
"classes",
",",
"facet_properties",
")",
"]",
"return",
"facets",
"spec",
"=",
"specification",
"(",
")",
"spec",
".",
"name",
"=",
"ids_dict",
"[",
"\"@name\"",
"]",
"spec",
".",
"necessity",
"=",
"ids_dict",
"[",
"\"@necessity\"",
"]",
"spec",
".",
"applicability",
"=",
"boolean_and",
"(",
"parse_rules",
"(",
"ids_dict",
"[",
"\"applicability\"",
"]",
")",
")",
"spec",
".",
"requirements",
"=",
"boolean_and",
"(",
"parse_rules",
"(",
"ids_dict",
"[",
"\"requirements\"",
"]",
")",
")",
"return",
"spec"
] | https://github.com/IfcOpenShell/IfcOpenShell/blob/2c2954b11a9c9d581bef03240836d4567e69ad0b/src/ifcopenshell-python/ifcopenshell/ids.py#L286-L305 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/core.py | python | setup | (**attrs) | return dist | The gateway to the Distutils: do everything your setup script needs
to do, in a highly flexible and user-driven way. Briefly: create a
Distribution instance; find and parse config files; parse the command
line; run each Distutils command found there, customized by the options
supplied to 'setup()' (as keyword arguments), in config files, and on
the command line.
The Distribution instance might be an instance of a class supplied via
the 'distclass' keyword argument to 'setup'; if no such class is
supplied, then the Distribution class (in dist.py) is instantiated.
All other arguments to 'setup' (except for 'cmdclass') are used to set
attributes of the Distribution instance.
The 'cmdclass' argument, if supplied, is a dictionary mapping command
names to command classes. Each command encountered on the command line
will be turned into a command class, which is in turn instantiated; any
class found in 'cmdclass' is used in place of the default, which is
(for command 'foo_bar') class 'foo_bar' in module
'distutils.command.foo_bar'. The command class must provide a
'user_options' attribute which is a list of option specifiers for
'distutils.fancy_getopt'. Any command-line options between the current
and the next command are used to set attributes of the current command
object.
When the entire command-line has been successfully parsed, calls the
'run()' method on each command object in turn. This method will be
driven entirely by the Distribution object (which each command object
has a reference to, thanks to its constructor), and the
command-specific options that became attributes of each command
object. | The gateway to the Distutils: do everything your setup script needs
to do, in a highly flexible and user-driven way. Briefly: create a
Distribution instance; find and parse config files; parse the command
line; run each Distutils command found there, customized by the options
supplied to 'setup()' (as keyword arguments), in config files, and on
the command line. | [
"The",
"gateway",
"to",
"the",
"Distutils",
":",
"do",
"everything",
"your",
"setup",
"script",
"needs",
"to",
"do",
"in",
"a",
"highly",
"flexible",
"and",
"user",
"-",
"driven",
"way",
".",
"Briefly",
":",
"create",
"a",
"Distribution",
"instance",
";",
"find",
"and",
"parse",
"config",
"files",
";",
"parse",
"the",
"command",
"line",
";",
"run",
"each",
"Distutils",
"command",
"found",
"there",
"customized",
"by",
"the",
"options",
"supplied",
"to",
"setup",
"()",
"(",
"as",
"keyword",
"arguments",
")",
"in",
"config",
"files",
"and",
"on",
"the",
"command",
"line",
"."
] | def setup (**attrs):
"""The gateway to the Distutils: do everything your setup script needs
to do, in a highly flexible and user-driven way. Briefly: create a
Distribution instance; find and parse config files; parse the command
line; run each Distutils command found there, customized by the options
supplied to 'setup()' (as keyword arguments), in config files, and on
the command line.
The Distribution instance might be an instance of a class supplied via
the 'distclass' keyword argument to 'setup'; if no such class is
supplied, then the Distribution class (in dist.py) is instantiated.
All other arguments to 'setup' (except for 'cmdclass') are used to set
attributes of the Distribution instance.
The 'cmdclass' argument, if supplied, is a dictionary mapping command
names to command classes. Each command encountered on the command line
will be turned into a command class, which is in turn instantiated; any
class found in 'cmdclass' is used in place of the default, which is
(for command 'foo_bar') class 'foo_bar' in module
'distutils.command.foo_bar'. The command class must provide a
'user_options' attribute which is a list of option specifiers for
'distutils.fancy_getopt'. Any command-line options between the current
and the next command are used to set attributes of the current command
object.
When the entire command-line has been successfully parsed, calls the
'run()' method on each command object in turn. This method will be
driven entirely by the Distribution object (which each command object
has a reference to, thanks to its constructor), and the
command-specific options that became attributes of each command
object.
"""
global _setup_stop_after, _setup_distribution
# Determine the distribution class -- either caller-supplied or
# our Distribution (see below).
klass = attrs.get('distclass')
if klass:
del attrs['distclass']
else:
klass = Distribution
if 'script_name' not in attrs:
attrs['script_name'] = os.path.basename(sys.argv[0])
if 'script_args' not in attrs:
attrs['script_args'] = sys.argv[1:]
# Create the Distribution instance, using the remaining arguments
# (ie. everything except distclass) to initialize it
try:
_setup_distribution = dist = klass(attrs)
except DistutilsSetupError as msg:
if 'name' not in attrs:
raise SystemExit("error in setup command: %s" % msg)
else:
raise SystemExit("error in %s setup command: %s" % \
(attrs['name'], msg))
if _setup_stop_after == "init":
return dist
# Find and parse the config file(s): they will override options from
# the setup script, but be overridden by the command line.
dist.parse_config_files()
if DEBUG:
print("options (after parsing config files):")
dist.dump_option_dicts()
if _setup_stop_after == "config":
return dist
# Parse the command line and override config files; any
# command-line errors are the end user's fault, so turn them into
# SystemExit to suppress tracebacks.
try:
ok = dist.parse_command_line()
except DistutilsArgError as msg:
raise SystemExit(gen_usage(dist.script_name) + "\nerror: %s" % msg)
if DEBUG:
print("options (after parsing command line):")
dist.dump_option_dicts()
if _setup_stop_after == "commandline":
return dist
# And finally, run all the commands found on the command line.
if ok:
try:
dist.run_commands()
except KeyboardInterrupt:
raise SystemExit("interrupted")
except OSError as exc:
if DEBUG:
sys.stderr.write("error: %s\n" % (exc,))
raise
else:
raise SystemExit("error: %s" % (exc,))
except (DistutilsError,
CCompilerError) as msg:
if DEBUG:
raise
else:
raise SystemExit("error: " + str(msg))
return dist | [
"def",
"setup",
"(",
"*",
"*",
"attrs",
")",
":",
"global",
"_setup_stop_after",
",",
"_setup_distribution",
"# Determine the distribution class -- either caller-supplied or",
"# our Distribution (see below).",
"klass",
"=",
"attrs",
".",
"get",
"(",
"'distclass'",
")",
"if",
"klass",
":",
"del",
"attrs",
"[",
"'distclass'",
"]",
"else",
":",
"klass",
"=",
"Distribution",
"if",
"'script_name'",
"not",
"in",
"attrs",
":",
"attrs",
"[",
"'script_name'",
"]",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"'script_args'",
"not",
"in",
"attrs",
":",
"attrs",
"[",
"'script_args'",
"]",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"# Create the Distribution instance, using the remaining arguments",
"# (ie. everything except distclass) to initialize it",
"try",
":",
"_setup_distribution",
"=",
"dist",
"=",
"klass",
"(",
"attrs",
")",
"except",
"DistutilsSetupError",
"as",
"msg",
":",
"if",
"'name'",
"not",
"in",
"attrs",
":",
"raise",
"SystemExit",
"(",
"\"error in setup command: %s\"",
"%",
"msg",
")",
"else",
":",
"raise",
"SystemExit",
"(",
"\"error in %s setup command: %s\"",
"%",
"(",
"attrs",
"[",
"'name'",
"]",
",",
"msg",
")",
")",
"if",
"_setup_stop_after",
"==",
"\"init\"",
":",
"return",
"dist",
"# Find and parse the config file(s): they will override options from",
"# the setup script, but be overridden by the command line.",
"dist",
".",
"parse_config_files",
"(",
")",
"if",
"DEBUG",
":",
"print",
"(",
"\"options (after parsing config files):\"",
")",
"dist",
".",
"dump_option_dicts",
"(",
")",
"if",
"_setup_stop_after",
"==",
"\"config\"",
":",
"return",
"dist",
"# Parse the command line and override config files; any",
"# command-line errors are the end user's fault, so turn them into",
"# SystemExit to suppress tracebacks.",
"try",
":",
"ok",
"=",
"dist",
".",
"parse_command_line",
"(",
")",
"except",
"DistutilsArgError",
"as",
"msg",
":",
"raise",
"SystemExit",
"(",
"gen_usage",
"(",
"dist",
".",
"script_name",
")",
"+",
"\"\\nerror: %s\"",
"%",
"msg",
")",
"if",
"DEBUG",
":",
"print",
"(",
"\"options (after parsing command line):\"",
")",
"dist",
".",
"dump_option_dicts",
"(",
")",
"if",
"_setup_stop_after",
"==",
"\"commandline\"",
":",
"return",
"dist",
"# And finally, run all the commands found on the command line.",
"if",
"ok",
":",
"try",
":",
"dist",
".",
"run_commands",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"SystemExit",
"(",
"\"interrupted\"",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"DEBUG",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"error: %s\\n\"",
"%",
"(",
"exc",
",",
")",
")",
"raise",
"else",
":",
"raise",
"SystemExit",
"(",
"\"error: %s\"",
"%",
"(",
"exc",
",",
")",
")",
"except",
"(",
"DistutilsError",
",",
"CCompilerError",
")",
"as",
"msg",
":",
"if",
"DEBUG",
":",
"raise",
"else",
":",
"raise",
"SystemExit",
"(",
"\"error: \"",
"+",
"str",
"(",
"msg",
")",
")",
"return",
"dist"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/core.py#L57-L165 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/browser/resources/web_dev_style/js_checker.py | python | JSChecker.ChromeSendCheck | (self, i, line) | return self.RegexCheck(i, line, r"chrome\.send\('[^']+'\s*(, \[\])\)",
'Passing an empty array to chrome.send is unnecessary.') | Checks for a particular misuse of 'chrome.send'. | Checks for a particular misuse of 'chrome.send'. | [
"Checks",
"for",
"a",
"particular",
"misuse",
"of",
"chrome",
".",
"send",
"."
] | def ChromeSendCheck(self, i, line):
"""Checks for a particular misuse of 'chrome.send'."""
return self.RegexCheck(i, line, r"chrome\.send\('[^']+'\s*(, \[\])\)",
'Passing an empty array to chrome.send is unnecessary.') | [
"def",
"ChromeSendCheck",
"(",
"self",
",",
"i",
",",
"line",
")",
":",
"return",
"self",
".",
"RegexCheck",
"(",
"i",
",",
"line",
",",
"r\"chrome\\.send\\('[^']+'\\s*(, \\[\\])\\)\"",
",",
"'Passing an empty array to chrome.send is unnecessary.'",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/browser/resources/web_dev_style/js_checker.py#L39-L42 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/FortranCommon.py | python | add_f95_to_env | (env) | Add Builders and construction variables for f95 to an Environment. | Add Builders and construction variables for f95 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f95",
"to",
"an",
"Environment",
"."
] | def add_f95_to_env(env):
"""Add Builders and construction variables for f95 to an Environment."""
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']
except KeyError:
F95PPSuffixes = []
DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes,
support_module = 1) | [
"def",
"add_f95_to_env",
"(",
"env",
")",
":",
"try",
":",
"F95Suffixes",
"=",
"env",
"[",
"'F95FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F95Suffixes",
"=",
"[",
"'.f95'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F95PPSuffixes",
"=",
"env",
"[",
"'F95PPFILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F95PPSuffixes",
"=",
"[",
"]",
"DialectAddToEnv",
"(",
"env",
",",
"\"F95\"",
",",
"F95Suffixes",
",",
"F95PPSuffixes",
",",
"support_module",
"=",
"1",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/FortranCommon.py#L220-L234 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/nearest-exit-from-entrance-in-maze.py | python | Solution2.nearestExit | (self, maze, entrance) | return -1 | :type maze: List[List[str]]
:type entrance: List[int]
:rtype: int | :type maze: List[List[str]]
:type entrance: List[int]
:rtype: int | [
":",
"type",
"maze",
":",
"List",
"[",
"List",
"[",
"str",
"]]",
":",
"type",
"entrance",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def nearestExit(self, maze, entrance):
"""
:type maze: List[List[str]]
:type entrance: List[int]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
visited = ' '
entrance = tuple(entrance)
maze[entrance[0]][entrance[1]] = visited
q = [(entrance, 0)]
while q:
new_q = []
for (r, c), step in q:
if (r, c) != entrance and \
(r in (0, len(maze)-1) or c in (0, len(maze[0])-1)):
return step
for dr, dc in directions:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(maze) and
0 <= nc < len(maze[0]) and
maze[nr][nc] == '.'):
continue
maze[nr][nc] = visited
q.append(((nr, nc), step+1))
q = new_q
return -1 | [
"def",
"nearestExit",
"(",
"self",
",",
"maze",
",",
"entrance",
")",
":",
"directions",
"=",
"[",
"(",
"0",
",",
"1",
")",
",",
"(",
"1",
",",
"0",
")",
",",
"(",
"0",
",",
"-",
"1",
")",
",",
"(",
"-",
"1",
",",
"0",
")",
"]",
"visited",
"=",
"' '",
"entrance",
"=",
"tuple",
"(",
"entrance",
")",
"maze",
"[",
"entrance",
"[",
"0",
"]",
"]",
"[",
"entrance",
"[",
"1",
"]",
"]",
"=",
"visited",
"q",
"=",
"[",
"(",
"entrance",
",",
"0",
")",
"]",
"while",
"q",
":",
"new_q",
"=",
"[",
"]",
"for",
"(",
"r",
",",
"c",
")",
",",
"step",
"in",
"q",
":",
"if",
"(",
"r",
",",
"c",
")",
"!=",
"entrance",
"and",
"(",
"r",
"in",
"(",
"0",
",",
"len",
"(",
"maze",
")",
"-",
"1",
")",
"or",
"c",
"in",
"(",
"0",
",",
"len",
"(",
"maze",
"[",
"0",
"]",
")",
"-",
"1",
")",
")",
":",
"return",
"step",
"for",
"dr",
",",
"dc",
"in",
"directions",
":",
"nr",
",",
"nc",
"=",
"r",
"+",
"dr",
",",
"c",
"+",
"dc",
"if",
"not",
"(",
"0",
"<=",
"nr",
"<",
"len",
"(",
"maze",
")",
"and",
"0",
"<=",
"nc",
"<",
"len",
"(",
"maze",
"[",
"0",
"]",
")",
"and",
"maze",
"[",
"nr",
"]",
"[",
"nc",
"]",
"==",
"'.'",
")",
":",
"continue",
"maze",
"[",
"nr",
"]",
"[",
"nc",
"]",
"=",
"visited",
"q",
".",
"append",
"(",
"(",
"(",
"nr",
",",
"nc",
")",
",",
"step",
"+",
"1",
")",
")",
"q",
"=",
"new_q",
"return",
"-",
"1"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/nearest-exit-from-entrance-in-maze.py#L46-L72 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridHitTestResult.GetColumn | (*args, **kwargs) | return _propgrid.PropertyGridHitTestResult_GetColumn(*args, **kwargs) | GetColumn(self) -> int | GetColumn(self) -> int | [
"GetColumn",
"(",
"self",
")",
"-",
">",
"int"
] | def GetColumn(*args, **kwargs):
"""GetColumn(self) -> int"""
return _propgrid.PropertyGridHitTestResult_GetColumn(*args, **kwargs) | [
"def",
"GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridHitTestResult_GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L893-L895 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.