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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py | python | VisualStudioVersion.Description | (self) | return self.description | Get the full description of the version. | Get the full description of the version. | [
"Get",
"the",
"full",
"description",
"of",
"the",
"version",
"."
] | def Description(self):
"""Get the full description of the version."""
return self.description | [
"def",
"Description",
"(",
"self",
")",
":",
"return",
"self",
".",
"description"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py#L35-L37 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/write_build_config.py | python | _ExtractMarkdownDocumentation | (input_text) | return result | Extract Markdown documentation from a list of input strings lines.
This generates a list of strings extracted from |input_text|, by looking
for '-- BEGIN_MARKDOWN --' and '-- END_MARKDOWN --' line markers. | Extract Markdown documentation from a list of input strings lines. | [
"Extract",
"Markdown",
"documentation",
"from",
"a",
"list",
"of",
"input",
"strings",
"lines",
"."
] | def _ExtractMarkdownDocumentation(input_text):
"""Extract Markdown documentation from a list of input strings lines.
This generates a list of strings extracted from |input_text|, by looking
for '-- BEGIN_MARKDOWN --' and '-- END_MARKDOWN --' line markers."""
in_markdown = False
result = []
for line in input_text.splitlines():
if in_markdown:
if '-- END_MARKDOWN --' in line:
in_markdown = False
else:
result.append(line)
else:
if '-- BEGIN_MARKDOWN --' in line:
in_markdown = True
return result | [
"def",
"_ExtractMarkdownDocumentation",
"(",
"input_text",
")",
":",
"in_markdown",
"=",
"False",
"result",
"=",
"[",
"]",
"for",
"line",
"in",
"input_text",
".",
"splitlines",
"(",
")",
":",
"if",
"in_markdown",
":",
"if",
"'-- END_MARKDOWN --'",
"in",
"line",
":",
"in_markdown",
"=",
"False",
"else",
":",
"result",
".",
"append",
"(",
"line",
")",
"else",
":",
"if",
"'-- BEGIN_MARKDOWN --'",
"in",
"line",
":",
"in_markdown",
"=",
"True",
"return",
"result"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/write_build_config.py#L606-L623 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/BaseHTTPServer.py | python | BaseHTTPRequestHandler.handle | (self) | Handle multiple requests if necessary. | Handle multiple requests if necessary. | [
"Handle",
"multiple",
"requests",
"if",
"necessary",
"."
] | def handle(self):
"""Handle multiple requests if necessary."""
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request() | [
"def",
"handle",
"(",
"self",
")",
":",
"self",
".",
"close_connection",
"=",
"1",
"self",
".",
"handle_one_request",
"(",
")",
"while",
"not",
"self",
".",
"close_connection",
":",
"self",
".",
"handle_one_request",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/BaseHTTPServer.py#L336-L342 | ||
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/state/_schemata.py | python | PipelineSchema.unwrap_datasource | (self, data, **kwargs) | return data['dataSource'] | Extract DataSource from pipeline attribute. | Extract DataSource from pipeline attribute. | [
"Extract",
"DataSource",
"from",
"pipeline",
"attribute",
"."
] | def unwrap_datasource(self, data, **kwargs):
"""
Extract DataSource from pipeline attribute.
"""
return data['dataSource'] | [
"def",
"unwrap_datasource",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"data",
"[",
"'dataSource'",
"]"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/state/_schemata.py#L283-L288 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/utils/conv_utils.py | python | convert_kernel | (kernel) | return np.copy(kernel[slices]) | Converts a Numpy kernel matrix from Theano format to TensorFlow format.
Also works reciprocally, since the transformation is its own inverse.
Arguments:
kernel: Numpy array (3D, 4D or 5D).
Returns:
The converted kernel.
Raises:
ValueError: in case of invalid kernel shape or invalid data_format. | Converts a Numpy kernel matrix from Theano format to TensorFlow format. | [
"Converts",
"a",
"Numpy",
"kernel",
"matrix",
"from",
"Theano",
"format",
"to",
"TensorFlow",
"format",
"."
] | def convert_kernel(kernel):
"""Converts a Numpy kernel matrix from Theano format to TensorFlow format.
Also works reciprocally, since the transformation is its own inverse.
Arguments:
kernel: Numpy array (3D, 4D or 5D).
Returns:
The converted kernel.
Raises:
ValueError: in case of invalid kernel shape or invalid data_format.
"""
kernel = np.asarray(kernel)
if not 3 <= kernel.ndim <= 5:
raise ValueError('Invalid kernel shape:', kernel.shape)
slices = [slice(None, None, -1) for _ in range(kernel.ndim)]
no_flip = (slice(None, None), slice(None, None))
slices[-2:] = no_flip
return np.copy(kernel[slices]) | [
"def",
"convert_kernel",
"(",
"kernel",
")",
":",
"kernel",
"=",
"np",
".",
"asarray",
"(",
"kernel",
")",
"if",
"not",
"3",
"<=",
"kernel",
".",
"ndim",
"<=",
"5",
":",
"raise",
"ValueError",
"(",
"'Invalid kernel shape:'",
",",
"kernel",
".",
"shape",
")",
"slices",
"=",
"[",
"slice",
"(",
"None",
",",
"None",
",",
"-",
"1",
")",
"for",
"_",
"in",
"range",
"(",
"kernel",
".",
"ndim",
")",
"]",
"no_flip",
"=",
"(",
"slice",
"(",
"None",
",",
"None",
")",
",",
"slice",
"(",
"None",
",",
"None",
")",
")",
"slices",
"[",
"-",
"2",
":",
"]",
"=",
"no_flip",
"return",
"np",
".",
"copy",
"(",
"kernel",
"[",
"slices",
"]",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/utils/conv_utils.py#L52-L72 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/edns.py | python | Option._cmp | (self, other) | Compare an ENDS option with another option of the same type.
Return < 0 if self < other, 0 if self == other, and > 0 if self > other. | Compare an ENDS option with another option of the same type.
Return < 0 if self < other, 0 if self == other, and > 0 if self > other. | [
"Compare",
"an",
"ENDS",
"option",
"with",
"another",
"option",
"of",
"the",
"same",
"type",
".",
"Return",
"<",
"0",
"if",
"self",
"<",
"other",
"0",
"if",
"self",
"==",
"other",
"and",
">",
"0",
"if",
"self",
">",
"other",
"."
] | def _cmp(self, other):
"""Compare an ENDS option with another option of the same type.
Return < 0 if self < other, 0 if self == other, and > 0 if self > other.
"""
raise NotImplementedError | [
"def",
"_cmp",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/edns.py#L52-L56 | ||
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 | PyObjectPtr.write_field_repr | (self, name, out, visited) | Extract the PyObject* field named "name", and write its representation
to file-like object "out" | Extract the PyObject* field named "name", and write its representation
to file-like object "out" | [
"Extract",
"the",
"PyObject",
"*",
"field",
"named",
"name",
"and",
"write",
"its",
"representation",
"to",
"file",
"-",
"like",
"object",
"out"
] | def write_field_repr(self, name, out, visited):
'''
Extract the PyObject* field named "name", and write its representation
to file-like object "out"
'''
field_obj = self.pyop_field(name)
field_obj.write_repr(out, visited) | [
"def",
"write_field_repr",
"(",
"self",
",",
"name",
",",
"out",
",",
"visited",
")",
":",
"field_obj",
"=",
"self",
".",
"pyop_field",
"(",
"name",
")",
"field_obj",
".",
"write_repr",
"(",
"out",
",",
"visited",
")"
] | 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#L232-L238 | ||
commaai/openpilot | 4416c21b1e738ab7d04147c5ae52b5135e0cdb40 | pyextra/acados_template/acados_ocp.py | python | AcadosOcpConstraints.ubx_e | (self) | return self.__ubx_e | :math:`\\bar{x}^e` - upper bounds on x at terminal shooting node N.
Type: :code:`np.ndarray`; default: :code:`np.array([])` | :math:`\\bar{x}^e` - upper bounds on x at terminal shooting node N.
Type: :code:`np.ndarray`; default: :code:`np.array([])` | [
":",
"math",
":",
"\\\\",
"bar",
"{",
"x",
"}",
"^e",
"-",
"upper",
"bounds",
"on",
"x",
"at",
"terminal",
"shooting",
"node",
"N",
".",
"Type",
":",
":",
"code",
":",
"np",
".",
"ndarray",
";",
"default",
":",
":",
"code",
":",
"np",
".",
"array",
"(",
"[]",
")"
] | def ubx_e(self):
""":math:`\\bar{x}^e` - upper bounds on x at terminal shooting node N.
Type: :code:`np.ndarray`; default: :code:`np.array([])`"""
return self.__ubx_e | [
"def",
"ubx_e",
"(",
"self",
")",
":",
"return",
"self",
".",
"__ubx_e"
] | https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L1132-L1135 | |
rdiankov/openrave | d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7 | python/databases/visibilitymodel.py | python | VisibilityModel.ShowTransform | (self, relativepose, options=None) | moves the robot links temporarily to show a transform | moves the robot links temporarily to show a transform | [
"moves",
"the",
"robot",
"links",
"temporarily",
"to",
"show",
"a",
"transform"
] | def ShowTransform(self, relativepose, options=None):
"""moves the robot links temporarily to show a transform
"""
if self.robot != self.sensorrobot:
pts = poseMult(self.sensorrobot.GetTransformPose(), InvertPose(relativepose))[4:7]
else:
pts = poseMult(self.targetlink.GetParent().GetTransformPose(), relativepose)[4:7]
h=self.env.plot3(pts,5,colors=array([0.5,0.5,1,0.2]))
try:
with RobotStateSaver(self.robot):
# disable all non-child links
for link in self.robot.GetLinks():
link.Enable(link in self.manip.GetChildLinks())
with self.GripperVisibility(self.manip):
with self.env:
if len(self.preshapes) > 0:
self.robot.SetDOFValues(self.preshapes[0],self.manip.GetGripperIndices())
if self.robot != self.sensorrobot:
# sensor is not attached to robot
assert(self.targetlink is not None)
linkrelativepose = poseMult(poseMult(self.attachedsensor.GetTransformPose(),InvertPose(relativepose)), InvertPose(self.targetlink.GetParent().GetTransformPose()))
for link in self.manip.GetChildLinks():
link.SetTransform(poseMult(linkrelativepose, link.GetTransformPose()))
else:
linkrelativepose = poseMult(InvertPose(self.attachedsensor.GetTransformPose()),self.manip.GetTransformPose())
globalCameraPose = poseMult(self.targetlink.GetParent().GetTransformPose(), relativepose)
grasppose = poseMult(globalCameraPose, linkrelativepose)
deltapose = poseMult(grasppose,InvertPose(self.manip.GetTransformPose()))
for link in self.manip.GetChildLinks():
link.SetTransform(poseMult(deltapose,link.GetTransformPose()))
visibility = self.visualprob.ComputeVisibility()
self.env.UpdatePublishedBodies()
msg='visibility=%d, press any key to continue: '%(visibility)
if options is not None and options.showimage:
pilutil=__import__('scipy.misc',fromlist=['pilutil'])
I=self.getCameraImage()
print(msg)
pilutil.imshow(I)
else:
raw_input(msg)
finally:
# have to destroy the plot handle
h = None | [
"def",
"ShowTransform",
"(",
"self",
",",
"relativepose",
",",
"options",
"=",
"None",
")",
":",
"if",
"self",
".",
"robot",
"!=",
"self",
".",
"sensorrobot",
":",
"pts",
"=",
"poseMult",
"(",
"self",
".",
"sensorrobot",
".",
"GetTransformPose",
"(",
")",
",",
"InvertPose",
"(",
"relativepose",
")",
")",
"[",
"4",
":",
"7",
"]",
"else",
":",
"pts",
"=",
"poseMult",
"(",
"self",
".",
"targetlink",
".",
"GetParent",
"(",
")",
".",
"GetTransformPose",
"(",
")",
",",
"relativepose",
")",
"[",
"4",
":",
"7",
"]",
"h",
"=",
"self",
".",
"env",
".",
"plot3",
"(",
"pts",
",",
"5",
",",
"colors",
"=",
"array",
"(",
"[",
"0.5",
",",
"0.5",
",",
"1",
",",
"0.2",
"]",
")",
")",
"try",
":",
"with",
"RobotStateSaver",
"(",
"self",
".",
"robot",
")",
":",
"# disable all non-child links",
"for",
"link",
"in",
"self",
".",
"robot",
".",
"GetLinks",
"(",
")",
":",
"link",
".",
"Enable",
"(",
"link",
"in",
"self",
".",
"manip",
".",
"GetChildLinks",
"(",
")",
")",
"with",
"self",
".",
"GripperVisibility",
"(",
"self",
".",
"manip",
")",
":",
"with",
"self",
".",
"env",
":",
"if",
"len",
"(",
"self",
".",
"preshapes",
")",
">",
"0",
":",
"self",
".",
"robot",
".",
"SetDOFValues",
"(",
"self",
".",
"preshapes",
"[",
"0",
"]",
",",
"self",
".",
"manip",
".",
"GetGripperIndices",
"(",
")",
")",
"if",
"self",
".",
"robot",
"!=",
"self",
".",
"sensorrobot",
":",
"# sensor is not attached to robot",
"assert",
"(",
"self",
".",
"targetlink",
"is",
"not",
"None",
")",
"linkrelativepose",
"=",
"poseMult",
"(",
"poseMult",
"(",
"self",
".",
"attachedsensor",
".",
"GetTransformPose",
"(",
")",
",",
"InvertPose",
"(",
"relativepose",
")",
")",
",",
"InvertPose",
"(",
"self",
".",
"targetlink",
".",
"GetParent",
"(",
")",
".",
"GetTransformPose",
"(",
")",
")",
")",
"for",
"link",
"in",
"self",
".",
"manip",
".",
"GetChildLinks",
"(",
")",
":",
"link",
".",
"SetTransform",
"(",
"poseMult",
"(",
"linkrelativepose",
",",
"link",
".",
"GetTransformPose",
"(",
")",
")",
")",
"else",
":",
"linkrelativepose",
"=",
"poseMult",
"(",
"InvertPose",
"(",
"self",
".",
"attachedsensor",
".",
"GetTransformPose",
"(",
")",
")",
",",
"self",
".",
"manip",
".",
"GetTransformPose",
"(",
")",
")",
"globalCameraPose",
"=",
"poseMult",
"(",
"self",
".",
"targetlink",
".",
"GetParent",
"(",
")",
".",
"GetTransformPose",
"(",
")",
",",
"relativepose",
")",
"grasppose",
"=",
"poseMult",
"(",
"globalCameraPose",
",",
"linkrelativepose",
")",
"deltapose",
"=",
"poseMult",
"(",
"grasppose",
",",
"InvertPose",
"(",
"self",
".",
"manip",
".",
"GetTransformPose",
"(",
")",
")",
")",
"for",
"link",
"in",
"self",
".",
"manip",
".",
"GetChildLinks",
"(",
")",
":",
"link",
".",
"SetTransform",
"(",
"poseMult",
"(",
"deltapose",
",",
"link",
".",
"GetTransformPose",
"(",
")",
")",
")",
"visibility",
"=",
"self",
".",
"visualprob",
".",
"ComputeVisibility",
"(",
")",
"self",
".",
"env",
".",
"UpdatePublishedBodies",
"(",
")",
"msg",
"=",
"'visibility=%d, press any key to continue: '",
"%",
"(",
"visibility",
")",
"if",
"options",
"is",
"not",
"None",
"and",
"options",
".",
"showimage",
":",
"pilutil",
"=",
"__import__",
"(",
"'scipy.misc'",
",",
"fromlist",
"=",
"[",
"'pilutil'",
"]",
")",
"I",
"=",
"self",
".",
"getCameraImage",
"(",
")",
"print",
"(",
"msg",
")",
"pilutil",
".",
"imshow",
"(",
"I",
")",
"else",
":",
"raw_input",
"(",
"msg",
")",
"finally",
":",
"# have to destroy the plot handle",
"h",
"=",
"None"
] | https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/databases/visibilitymodel.py#L298-L341 | ||
svn2github/webrtc | 0e4615a75ed555ec866cd5543bfea586f3385ceb | tools/refactoring/webrtc_reformat.py | python | PostfixToPrefixInForLoops | (text) | return re.sub(pattern, r'\1++\2)', text) | Converts x++ to ++x in the increment part of a for loop. | Converts x++ to ++x in the increment part of a for loop. | [
"Converts",
"x",
"++",
"to",
"++",
"x",
"in",
"the",
"increment",
"part",
"of",
"a",
"for",
"loop",
"."
] | def PostfixToPrefixInForLoops(text):
"""Converts x++ to ++x in the increment part of a for loop."""
pattern = r'(for \(.*;.*;) (\w+)\+\+\)'
return re.sub(pattern, r'\1++\2)', text) | [
"def",
"PostfixToPrefixInForLoops",
"(",
"text",
")",
":",
"pattern",
"=",
"r'(for \\(.*;.*;) (\\w+)\\+\\+\\)'",
"return",
"re",
".",
"sub",
"(",
"pattern",
",",
"r'\\1++\\2)'",
",",
"text",
")"
] | https://github.com/svn2github/webrtc/blob/0e4615a75ed555ec866cd5543bfea586f3385ceb/tools/refactoring/webrtc_reformat.py#L60-L63 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/plasma/Plasma.py | python | PtDisableControlKeyEvents | (selfKey) | Disable the control key events from calling OnControlKeyEvent | Disable the control key events from calling OnControlKeyEvent | [
"Disable",
"the",
"control",
"key",
"events",
"from",
"calling",
"OnControlKeyEvent"
] | def PtDisableControlKeyEvents(selfKey):
"""Disable the control key events from calling OnControlKeyEvent"""
pass | [
"def",
"PtDisableControlKeyEvents",
"(",
"selfKey",
")",
":",
"pass"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L206-L208 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | GLGenerator.WriteGLES2ImplementationUnitTests | (self, filename) | Writes the GLES2 helper header. | Writes the GLES2 helper header. | [
"Writes",
"the",
"GLES2",
"helper",
"header",
"."
] | def WriteGLES2ImplementationUnitTests(self, filename):
"""Writes the GLES2 helper header."""
file = CHeaderWriter(
filename,
"// This file is included by gles2_implementation.h to declare the\n"
"// GL api functions.\n")
for func in self.original_functions:
func.WriteGLES2ImplementationUnitTest(file)
file.Close() | [
"def",
"WriteGLES2ImplementationUnitTests",
"(",
"self",
",",
"filename",
")",
":",
"file",
"=",
"CHeaderWriter",
"(",
"filename",
",",
"\"// This file is included by gles2_implementation.h to declare the\\n\"",
"\"// GL api functions.\\n\"",
")",
"for",
"func",
"in",
"self",
".",
"original_functions",
":",
"func",
".",
"WriteGLES2ImplementationUnitTest",
"(",
"file",
")",
"file",
".",
"Close",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L7513-L7521 | ||
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/usdviewApi.py | python | UsdviewApi.GrabViewportShot | (self) | return self.__appController.GrabViewportShot() | Returns a QImage of the current stage view in usdview. | Returns a QImage of the current stage view in usdview. | [
"Returns",
"a",
"QImage",
"of",
"the",
"current",
"stage",
"view",
"in",
"usdview",
"."
] | def GrabViewportShot(self):
"""Returns a QImage of the current stage view in usdview."""
return self.__appController.GrabViewportShot() | [
"def",
"GrabViewportShot",
"(",
"self",
")",
":",
"return",
"self",
".",
"__appController",
".",
"GrabViewportShot",
"(",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/usdviewApi.py#L207-L210 | |
alibaba/graph-learn | 54cafee9db3054dc310a28b856be7f97c7d5aee9 | graphlearn/python/nn/tf/data/feature_handler.py | python | FeatureGroup.forward | (self, x_list) | return tf.concat(outputs, -1) | Args:
x_list: A Tensor of shape [batch_size, feature_num] or
a list of Tensors of shape [batch_size].
Returns:
The concatenated Tensor of outputs of `FeatureColumn` in
feature_column_list. | Args:
x_list: A Tensor of shape [batch_size, feature_num] or
a list of Tensors of shape [batch_size].
Returns:
The concatenated Tensor of outputs of `FeatureColumn` in
feature_column_list. | [
"Args",
":",
"x_list",
":",
"A",
"Tensor",
"of",
"shape",
"[",
"batch_size",
"feature_num",
"]",
"or",
"a",
"list",
"of",
"Tensors",
"of",
"shape",
"[",
"batch_size",
"]",
".",
"Returns",
":",
"The",
"concatenated",
"Tensor",
"of",
"outputs",
"of",
"FeatureColumn",
"in",
"feature_column_list",
"."
] | def forward(self, x_list):
"""
Args:
x_list: A Tensor of shape [batch_size, feature_num] or
a list of Tensors of shape [batch_size].
Returns:
The concatenated Tensor of outputs of `FeatureColumn` in
feature_column_list.
"""
outputs = []
if isinstance(x_list, tf.Tensor):
num = x_list.shape[-1]
x_list = tf.transpose(x_list) # [feature_num, batch_size]
else:
num = len(x_list)
if self._n != num:
raise ValueError("{} feature columns, but got {} inputs."
.format(self._n, num))
for i in range(num):
output = self._fc_list[i](x_list[i])
if isinstance(self._fc_list[i], NumericColumn):
output = tf.expand_dims(output, axis=-1)
outputs.append(output)
return tf.concat(outputs, -1) | [
"def",
"forward",
"(",
"self",
",",
"x_list",
")",
":",
"outputs",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"x_list",
",",
"tf",
".",
"Tensor",
")",
":",
"num",
"=",
"x_list",
".",
"shape",
"[",
"-",
"1",
"]",
"x_list",
"=",
"tf",
".",
"transpose",
"(",
"x_list",
")",
"# [feature_num, batch_size]",
"else",
":",
"num",
"=",
"len",
"(",
"x_list",
")",
"if",
"self",
".",
"_n",
"!=",
"num",
":",
"raise",
"ValueError",
"(",
"\"{} feature columns, but got {} inputs.\"",
".",
"format",
"(",
"self",
".",
"_n",
",",
"num",
")",
")",
"for",
"i",
"in",
"range",
"(",
"num",
")",
":",
"output",
"=",
"self",
".",
"_fc_list",
"[",
"i",
"]",
"(",
"x_list",
"[",
"i",
"]",
")",
"if",
"isinstance",
"(",
"self",
".",
"_fc_list",
"[",
"i",
"]",
",",
"NumericColumn",
")",
":",
"output",
"=",
"tf",
".",
"expand_dims",
"(",
"output",
",",
"axis",
"=",
"-",
"1",
")",
"outputs",
".",
"append",
"(",
"output",
")",
"return",
"tf",
".",
"concat",
"(",
"outputs",
",",
"-",
"1",
")"
] | https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/graphlearn/python/nn/tf/data/feature_handler.py#L45-L69 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | src/icebox/icebox_py/__init__.py | python | Vm.pause | (self) | Pause vm. | Pause vm. | [
"Pause",
"vm",
"."
] | def pause(self):
"""Pause vm."""
libicebox.pause() | [
"def",
"pause",
"(",
"self",
")",
":",
"libicebox",
".",
"pause",
"(",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/src/icebox/icebox_py/__init__.py#L654-L656 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py | python | expandtabs | (a, tabsize=8) | return _to_string_or_unicode_array(
_vec_string(a, object_, 'expandtabs', (tabsize,))) | Return a copy of each string element where all tab characters are
replaced by one or more spaces.
Calls `str.expandtabs` element-wise.
Return a copy of each string element where all tab characters are
replaced by one or more spaces, depending on the current column
and the given `tabsize`. The column number is reset to zero after
each newline occurring in the string. This doesn't understand other
non-printing characters or escape sequences.
Parameters
----------
a : array_like of str or unicode
Input array
tabsize : int, optional
Replace tabs with `tabsize` number of spaces. If not given defaults
to 8 spaces.
Returns
-------
out : ndarray
Output array of str or unicode, depending on input type
See also
--------
str.expandtabs | Return a copy of each string element where all tab characters are
replaced by one or more spaces. | [
"Return",
"a",
"copy",
"of",
"each",
"string",
"element",
"where",
"all",
"tab",
"characters",
"are",
"replaced",
"by",
"one",
"or",
"more",
"spaces",
"."
] | def expandtabs(a, tabsize=8):
"""
Return a copy of each string element where all tab characters are
replaced by one or more spaces.
Calls `str.expandtabs` element-wise.
Return a copy of each string element where all tab characters are
replaced by one or more spaces, depending on the current column
and the given `tabsize`. The column number is reset to zero after
each newline occurring in the string. This doesn't understand other
non-printing characters or escape sequences.
Parameters
----------
a : array_like of str or unicode
Input array
tabsize : int, optional
Replace tabs with `tabsize` number of spaces. If not given defaults
to 8 spaces.
Returns
-------
out : ndarray
Output array of str or unicode, depending on input type
See also
--------
str.expandtabs
"""
return _to_string_or_unicode_array(
_vec_string(a, object_, 'expandtabs', (tabsize,))) | [
"def",
"expandtabs",
"(",
"a",
",",
"tabsize",
"=",
"8",
")",
":",
"return",
"_to_string_or_unicode_array",
"(",
"_vec_string",
"(",
"a",
",",
"object_",
",",
"'expandtabs'",
",",
"(",
"tabsize",
",",
")",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py#L586-L618 | |
google/sentencepiece | 8420f2179007c398c8b70f63cb12d8aec827397c | python/src/sentencepiece/__init__.py | python | SentencePieceTrainer.Train | (arg=None, **kwargs) | return None | Train Sentencepiece model. Accept both kwargs and legacy string arg. | Train Sentencepiece model. Accept both kwargs and legacy string arg. | [
"Train",
"Sentencepiece",
"model",
".",
"Accept",
"both",
"kwargs",
"and",
"legacy",
"string",
"arg",
"."
] | def Train(arg=None, **kwargs):
"""Train Sentencepiece model. Accept both kwargs and legacy string arg."""
if arg is not None and type(arg) is str:
return SentencePieceTrainer._TrainFromString(arg)
def _encode(value):
"""Encode value to CSV.."""
if type(value) is list:
if sys.version_info[0] == 3:
f = StringIO()
else:
f = BytesIO()
writer = csv.writer(f, lineterminator='')
writer.writerow([str(v) for v in value])
return f.getvalue()
else:
return str(value)
sentence_iterator = None
model_writer = None
new_kwargs = {}
for key, value in kwargs.items():
if key in ['sentence_iterator', 'sentence_reader']:
sentence_iterator = value
elif key in ['model_writer']:
model_writer = value
else:
new_kwargs[key] = _encode(value)
if model_writer:
if sentence_iterator:
model_proto = SentencePieceTrainer._TrainFromMap4(new_kwargs,
sentence_iterator)
else:
model_proto = SentencePieceTrainer._TrainFromMap3(new_kwargs)
model_writer.write(model_proto)
else:
if sentence_iterator:
return SentencePieceTrainer._TrainFromMap2(new_kwargs, sentence_iterator)
else:
return SentencePieceTrainer._TrainFromMap(new_kwargs)
return None | [
"def",
"Train",
"(",
"arg",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"arg",
"is",
"not",
"None",
"and",
"type",
"(",
"arg",
")",
"is",
"str",
":",
"return",
"SentencePieceTrainer",
".",
"_TrainFromString",
"(",
"arg",
")",
"def",
"_encode",
"(",
"value",
")",
":",
"\"\"\"Encode value to CSV..\"\"\"",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"f",
"=",
"StringIO",
"(",
")",
"else",
":",
"f",
"=",
"BytesIO",
"(",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
",",
"lineterminator",
"=",
"''",
")",
"writer",
".",
"writerow",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]",
")",
"return",
"f",
".",
"getvalue",
"(",
")",
"else",
":",
"return",
"str",
"(",
"value",
")",
"sentence_iterator",
"=",
"None",
"model_writer",
"=",
"None",
"new_kwargs",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"[",
"'sentence_iterator'",
",",
"'sentence_reader'",
"]",
":",
"sentence_iterator",
"=",
"value",
"elif",
"key",
"in",
"[",
"'model_writer'",
"]",
":",
"model_writer",
"=",
"value",
"else",
":",
"new_kwargs",
"[",
"key",
"]",
"=",
"_encode",
"(",
"value",
")",
"if",
"model_writer",
":",
"if",
"sentence_iterator",
":",
"model_proto",
"=",
"SentencePieceTrainer",
".",
"_TrainFromMap4",
"(",
"new_kwargs",
",",
"sentence_iterator",
")",
"else",
":",
"model_proto",
"=",
"SentencePieceTrainer",
".",
"_TrainFromMap3",
"(",
"new_kwargs",
")",
"model_writer",
".",
"write",
"(",
"model_proto",
")",
"else",
":",
"if",
"sentence_iterator",
":",
"return",
"SentencePieceTrainer",
".",
"_TrainFromMap2",
"(",
"new_kwargs",
",",
"sentence_iterator",
")",
"else",
":",
"return",
"SentencePieceTrainer",
".",
"_TrainFromMap",
"(",
"new_kwargs",
")",
"return",
"None"
] | https://github.com/google/sentencepiece/blob/8420f2179007c398c8b70f63cb12d8aec827397c/python/src/sentencepiece/__init__.py#L404-L446 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/policy_templates/writers/template_writer.py | python | TemplateWriter.IsFuturePolicySupported | (self, policy) | return False | Checks if the given future policy is supported by the writer.
Args:
policy: The dictionary of the policy.
Returns:
True if the writer chooses to include the deprecated 'policy' in its
output. | Checks if the given future policy is supported by the writer. | [
"Checks",
"if",
"the",
"given",
"future",
"policy",
"is",
"supported",
"by",
"the",
"writer",
"."
] | def IsFuturePolicySupported(self, policy):
'''Checks if the given future policy is supported by the writer.
Args:
policy: The dictionary of the policy.
Returns:
True if the writer chooses to include the deprecated 'policy' in its
output.
'''
return False | [
"def",
"IsFuturePolicySupported",
"(",
"self",
",",
"policy",
")",
":",
"return",
"False"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/policy_templates/writers/template_writer.py#L45-L55 | |
PJunhyuk/people-counting-pose | 8cdaab5281847c296b305643842053d496e2e4e8 | lib/coco/PythonAPI/pycocotools/coco.py | python | COCO.loadRes | (self, resFile) | return res | Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object | Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object | [
"Load",
"result",
"file",
"and",
"return",
"a",
"result",
"api",
"object",
".",
":",
"param",
"resFile",
"(",
"str",
")",
":",
"file",
"name",
"of",
"result",
"file",
":",
"return",
":",
"res",
"(",
"obj",
")",
":",
"result",
"api",
"object"
] | def loadRes(self, resFile):
"""
Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object
"""
res = COCO()
res.dataset['images'] = [img for img in self.dataset['images']]
print('Loading and preparing results...')
tic = time.time()
if type(resFile) == str or type(resFile) == unicode:
anns = json.load(open(resFile))
elif type(resFile) == np.ndarray:
anns = self.loadNumpyAnnotations(resFile)
else:
anns = resFile
assert type(anns) == list, 'results in not an array of objects'
annsImgIds = [ann['image_id'] for ann in anns]
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \
'Results do not correspond to current coco set'
if 'caption' in anns[0]:
imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])
res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]
for id, ann in enumerate(anns):
ann['id'] = id+1
elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
bb = ann['bbox']
x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]]
if not 'segmentation' in ann:
ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
ann['area'] = bb[2]*bb[3]
ann['id'] = id+1
ann['iscrowd'] = 0
elif 'segmentation' in anns[0]:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
# now only support compressed RLE format as segmentation results
ann['area'] = maskUtils.area(ann['segmentation'])
if not 'bbox' in ann:
ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
ann['id'] = id+1
ann['iscrowd'] = 0
elif 'keypoints' in anns[0]:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
s = ann['keypoints']
x = s[0::3]
y = s[1::3]
x0,x1,y0,y1 = np.min(x), np.max(x), np.min(y), np.max(y)
ann['area'] = (x1-x0)*(y1-y0)
ann['id'] = id + 1
ann['bbox'] = [x0,y0,x1-x0,y1-y0]
print('DONE (t={:0.2f}s)'.format(time.time()- tic))
res.dataset['annotations'] = anns
res.createIndex()
return res | [
"def",
"loadRes",
"(",
"self",
",",
"resFile",
")",
":",
"res",
"=",
"COCO",
"(",
")",
"res",
".",
"dataset",
"[",
"'images'",
"]",
"=",
"[",
"img",
"for",
"img",
"in",
"self",
".",
"dataset",
"[",
"'images'",
"]",
"]",
"print",
"(",
"'Loading and preparing results...'",
")",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"if",
"type",
"(",
"resFile",
")",
"==",
"str",
"or",
"type",
"(",
"resFile",
")",
"==",
"unicode",
":",
"anns",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"resFile",
")",
")",
"elif",
"type",
"(",
"resFile",
")",
"==",
"np",
".",
"ndarray",
":",
"anns",
"=",
"self",
".",
"loadNumpyAnnotations",
"(",
"resFile",
")",
"else",
":",
"anns",
"=",
"resFile",
"assert",
"type",
"(",
"anns",
")",
"==",
"list",
",",
"'results in not an array of objects'",
"annsImgIds",
"=",
"[",
"ann",
"[",
"'image_id'",
"]",
"for",
"ann",
"in",
"anns",
"]",
"assert",
"set",
"(",
"annsImgIds",
")",
"==",
"(",
"set",
"(",
"annsImgIds",
")",
"&",
"set",
"(",
"self",
".",
"getImgIds",
"(",
")",
")",
")",
",",
"'Results do not correspond to current coco set'",
"if",
"'caption'",
"in",
"anns",
"[",
"0",
"]",
":",
"imgIds",
"=",
"set",
"(",
"[",
"img",
"[",
"'id'",
"]",
"for",
"img",
"in",
"res",
".",
"dataset",
"[",
"'images'",
"]",
"]",
")",
"&",
"set",
"(",
"[",
"ann",
"[",
"'image_id'",
"]",
"for",
"ann",
"in",
"anns",
"]",
")",
"res",
".",
"dataset",
"[",
"'images'",
"]",
"=",
"[",
"img",
"for",
"img",
"in",
"res",
".",
"dataset",
"[",
"'images'",
"]",
"if",
"img",
"[",
"'id'",
"]",
"in",
"imgIds",
"]",
"for",
"id",
",",
"ann",
"in",
"enumerate",
"(",
"anns",
")",
":",
"ann",
"[",
"'id'",
"]",
"=",
"id",
"+",
"1",
"elif",
"'bbox'",
"in",
"anns",
"[",
"0",
"]",
"and",
"not",
"anns",
"[",
"0",
"]",
"[",
"'bbox'",
"]",
"==",
"[",
"]",
":",
"res",
".",
"dataset",
"[",
"'categories'",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
")",
"for",
"id",
",",
"ann",
"in",
"enumerate",
"(",
"anns",
")",
":",
"bb",
"=",
"ann",
"[",
"'bbox'",
"]",
"x1",
",",
"x2",
",",
"y1",
",",
"y2",
"=",
"[",
"bb",
"[",
"0",
"]",
",",
"bb",
"[",
"0",
"]",
"+",
"bb",
"[",
"2",
"]",
",",
"bb",
"[",
"1",
"]",
",",
"bb",
"[",
"1",
"]",
"+",
"bb",
"[",
"3",
"]",
"]",
"if",
"not",
"'segmentation'",
"in",
"ann",
":",
"ann",
"[",
"'segmentation'",
"]",
"=",
"[",
"[",
"x1",
",",
"y1",
",",
"x1",
",",
"y2",
",",
"x2",
",",
"y2",
",",
"x2",
",",
"y1",
"]",
"]",
"ann",
"[",
"'area'",
"]",
"=",
"bb",
"[",
"2",
"]",
"*",
"bb",
"[",
"3",
"]",
"ann",
"[",
"'id'",
"]",
"=",
"id",
"+",
"1",
"ann",
"[",
"'iscrowd'",
"]",
"=",
"0",
"elif",
"'segmentation'",
"in",
"anns",
"[",
"0",
"]",
":",
"res",
".",
"dataset",
"[",
"'categories'",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
")",
"for",
"id",
",",
"ann",
"in",
"enumerate",
"(",
"anns",
")",
":",
"# now only support compressed RLE format as segmentation results",
"ann",
"[",
"'area'",
"]",
"=",
"maskUtils",
".",
"area",
"(",
"ann",
"[",
"'segmentation'",
"]",
")",
"if",
"not",
"'bbox'",
"in",
"ann",
":",
"ann",
"[",
"'bbox'",
"]",
"=",
"maskUtils",
".",
"toBbox",
"(",
"ann",
"[",
"'segmentation'",
"]",
")",
"ann",
"[",
"'id'",
"]",
"=",
"id",
"+",
"1",
"ann",
"[",
"'iscrowd'",
"]",
"=",
"0",
"elif",
"'keypoints'",
"in",
"anns",
"[",
"0",
"]",
":",
"res",
".",
"dataset",
"[",
"'categories'",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
")",
"for",
"id",
",",
"ann",
"in",
"enumerate",
"(",
"anns",
")",
":",
"s",
"=",
"ann",
"[",
"'keypoints'",
"]",
"x",
"=",
"s",
"[",
"0",
":",
":",
"3",
"]",
"y",
"=",
"s",
"[",
"1",
":",
":",
"3",
"]",
"x0",
",",
"x1",
",",
"y0",
",",
"y1",
"=",
"np",
".",
"min",
"(",
"x",
")",
",",
"np",
".",
"max",
"(",
"x",
")",
",",
"np",
".",
"min",
"(",
"y",
")",
",",
"np",
".",
"max",
"(",
"y",
")",
"ann",
"[",
"'area'",
"]",
"=",
"(",
"x1",
"-",
"x0",
")",
"*",
"(",
"y1",
"-",
"y0",
")",
"ann",
"[",
"'id'",
"]",
"=",
"id",
"+",
"1",
"ann",
"[",
"'bbox'",
"]",
"=",
"[",
"x0",
",",
"y0",
",",
"x1",
"-",
"x0",
",",
"y1",
"-",
"y0",
"]",
"print",
"(",
"'DONE (t={:0.2f}s)'",
".",
"format",
"(",
"time",
".",
"time",
"(",
")",
"-",
"tic",
")",
")",
"res",
".",
"dataset",
"[",
"'annotations'",
"]",
"=",
"anns",
"res",
".",
"createIndex",
"(",
")",
"return",
"res"
] | https://github.com/PJunhyuk/people-counting-pose/blob/8cdaab5281847c296b305643842053d496e2e4e8/lib/coco/PythonAPI/pycocotools/coco.py#L292-L351 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | FileDialog.SetPath | (*args, **kwargs) | return _windows_.FileDialog_SetPath(*args, **kwargs) | SetPath(self, String path)
Sets the path (the combined directory and filename that will be
returned when the dialog is dismissed). | SetPath(self, String path) | [
"SetPath",
"(",
"self",
"String",
"path",
")"
] | def SetPath(*args, **kwargs):
"""
SetPath(self, String path)
Sets the path (the combined directory and filename that will be
returned when the dialog is dismissed).
"""
return _windows_.FileDialog_SetPath(*args, **kwargs) | [
"def",
"SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FileDialog_SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3150-L3157 | |
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/sanitizers/sancov_merger.py | python | generate_inputs | (keep, coverage_dir, file_map, cpus) | return inputs | Generate inputs for multiprocessed merging.
Splits the sancov files into several buckets, so that each bucket can be
merged in a separate process. We have only few executables in total with
mostly lots of associated files. In the general case, with many executables
we might need to avoid splitting buckets of executables with few files.
Returns: List of args as expected by merge above. | Generate inputs for multiprocessed merging. | [
"Generate",
"inputs",
"for",
"multiprocessed",
"merging",
"."
] | def generate_inputs(keep, coverage_dir, file_map, cpus):
"""Generate inputs for multiprocessed merging.
Splits the sancov files into several buckets, so that each bucket can be
merged in a separate process. We have only few executables in total with
mostly lots of associated files. In the general case, with many executables
we might need to avoid splitting buckets of executables with few files.
Returns: List of args as expected by merge above.
"""
inputs = []
for executable, files in file_map.iteritems():
# What's the bucket size for distributing files for merging? E.g. with
# 2 cpus and 9 files we want bucket size 5.
n = max(2, int(math.ceil(len(files) / float(cpus))))
# Chop files into buckets.
buckets = [files[i:i+n] for i in range(0, len(files), n)]
# Inputs for multiprocessing. List of tuples containing:
# Keep-files option, base path, executable name, index of bucket,
# list of files.
inputs.extend([(keep, coverage_dir, executable, i, b)
for i, b in enumerate(buckets)])
return inputs | [
"def",
"generate_inputs",
"(",
"keep",
",",
"coverage_dir",
",",
"file_map",
",",
"cpus",
")",
":",
"inputs",
"=",
"[",
"]",
"for",
"executable",
",",
"files",
"in",
"file_map",
".",
"iteritems",
"(",
")",
":",
"# What's the bucket size for distributing files for merging? E.g. with",
"# 2 cpus and 9 files we want bucket size 5.",
"n",
"=",
"max",
"(",
"2",
",",
"int",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"files",
")",
"/",
"float",
"(",
"cpus",
")",
")",
")",
")",
"# Chop files into buckets.",
"buckets",
"=",
"[",
"files",
"[",
"i",
":",
"i",
"+",
"n",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"files",
")",
",",
"n",
")",
"]",
"# Inputs for multiprocessing. List of tuples containing:",
"# Keep-files option, base path, executable name, index of bucket,",
"# list of files.",
"inputs",
".",
"extend",
"(",
"[",
"(",
"keep",
",",
"coverage_dir",
",",
"executable",
",",
"i",
",",
"b",
")",
"for",
"i",
",",
"b",
"in",
"enumerate",
"(",
"buckets",
")",
"]",
")",
"return",
"inputs"
] | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/sanitizers/sancov_merger.py#L92-L116 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/zeros.py | python | _newton_quadratic | (ab, fab, d, fd, k) | return r | Apply Newton-Raphson like steps, using divided differences to approximate f'
ab is a real interval [a, b] containing a root,
fab holds the real values of f(a), f(b)
d is a real number outside [ab, b]
k is the number of steps to apply | Apply Newton-Raphson like steps, using divided differences to approximate f' | [
"Apply",
"Newton",
"-",
"Raphson",
"like",
"steps",
"using",
"divided",
"differences",
"to",
"approximate",
"f"
] | def _newton_quadratic(ab, fab, d, fd, k):
"""Apply Newton-Raphson like steps, using divided differences to approximate f'
ab is a real interval [a, b] containing a root,
fab holds the real values of f(a), f(b)
d is a real number outside [ab, b]
k is the number of steps to apply
"""
a, b = ab
fa, fb = fab
_, B, A = _compute_divided_differences([a, b, d], [fa, fb, fd],
forward=True, full=False)
# _P is the quadratic polynomial through the 3 points
def _P(x):
# Horner evaluation of fa + B * (x - a) + A * (x - a) * (x - b)
return (A * (x - b) + B) * (x - a) + fa
if A == 0:
r = a - fa / B
else:
r = (a if np.sign(A) * np.sign(fa) > 0 else b)
# Apply k Newton-Raphson steps to _P(x), starting from x=r
for i in range(k):
r1 = r - _P(r) / (B + A * (2 * r - a - b))
if not (ab[0] < r1 < ab[1]):
if (ab[0] < r < ab[1]):
return r
r = sum(ab) / 2.0
break
r = r1
return r | [
"def",
"_newton_quadratic",
"(",
"ab",
",",
"fab",
",",
"d",
",",
"fd",
",",
"k",
")",
":",
"a",
",",
"b",
"=",
"ab",
"fa",
",",
"fb",
"=",
"fab",
"_",
",",
"B",
",",
"A",
"=",
"_compute_divided_differences",
"(",
"[",
"a",
",",
"b",
",",
"d",
"]",
",",
"[",
"fa",
",",
"fb",
",",
"fd",
"]",
",",
"forward",
"=",
"True",
",",
"full",
"=",
"False",
")",
"# _P is the quadratic polynomial through the 3 points",
"def",
"_P",
"(",
"x",
")",
":",
"# Horner evaluation of fa + B * (x - a) + A * (x - a) * (x - b)",
"return",
"(",
"A",
"*",
"(",
"x",
"-",
"b",
")",
"+",
"B",
")",
"*",
"(",
"x",
"-",
"a",
")",
"+",
"fa",
"if",
"A",
"==",
"0",
":",
"r",
"=",
"a",
"-",
"fa",
"/",
"B",
"else",
":",
"r",
"=",
"(",
"a",
"if",
"np",
".",
"sign",
"(",
"A",
")",
"*",
"np",
".",
"sign",
"(",
"fa",
")",
">",
"0",
"else",
"b",
")",
"# Apply k Newton-Raphson steps to _P(x), starting from x=r",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"r1",
"=",
"r",
"-",
"_P",
"(",
"r",
")",
"/",
"(",
"B",
"+",
"A",
"*",
"(",
"2",
"*",
"r",
"-",
"a",
"-",
"b",
")",
")",
"if",
"not",
"(",
"ab",
"[",
"0",
"]",
"<",
"r1",
"<",
"ab",
"[",
"1",
"]",
")",
":",
"if",
"(",
"ab",
"[",
"0",
"]",
"<",
"r",
"<",
"ab",
"[",
"1",
"]",
")",
":",
"return",
"r",
"r",
"=",
"sum",
"(",
"ab",
")",
"/",
"2.0",
"break",
"r",
"=",
"r1",
"return",
"r"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/zeros.py#L978-L1010 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/lib/function_base.py | python | sinc | (x) | return sin(y)/y | Return the sinc function.
The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`.
Parameters
----------
x : ndarray
Array (possibly multi-dimensional) of values for which to to
calculate ``sinc(x)``.
Returns
-------
out : ndarray
``sinc(x)``, which has the same shape as the input.
Notes
-----
``sinc(0)`` is the limit value 1.
The name sinc is short for "sine cardinal" or "sinus cardinalis".
The sinc function is used in various signal processing applications,
including in anti-aliasing, in the construction of a
Lanczos resampling filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal
interpolation kernel is proportional to the sinc function.
References
----------
.. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
Resource. http://mathworld.wolfram.com/SincFunction.html
.. [2] Wikipedia, "Sinc function",
http://en.wikipedia.org/wiki/Sinc_function
Examples
--------
>>> x = np.arange(-20., 21.)/5.
>>> np.sinc(x)
array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02,
-8.90384387e-02, -5.84680802e-02, 3.89804309e-17,
6.68206631e-02, 1.16434881e-01, 1.26137788e-01,
8.50444803e-02, -3.89804309e-17, -1.03943254e-01,
-1.89206682e-01, -2.16236208e-01, -1.55914881e-01,
3.89804309e-17, 2.33872321e-01, 5.04551152e-01,
7.56826729e-01, 9.35489284e-01, 1.00000000e+00,
9.35489284e-01, 7.56826729e-01, 5.04551152e-01,
2.33872321e-01, 3.89804309e-17, -1.55914881e-01,
-2.16236208e-01, -1.89206682e-01, -1.03943254e-01,
-3.89804309e-17, 8.50444803e-02, 1.26137788e-01,
1.16434881e-01, 6.68206631e-02, 3.89804309e-17,
-5.84680802e-02, -8.90384387e-02, -8.40918587e-02,
-4.92362781e-02, -3.89804309e-17])
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, np.sinc(x))
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Sinc Function")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("X")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
It works in 2-D as well:
>>> x = np.arange(-200., 201.)/50.
>>> xx = np.outer(x, x)
>>> plt.imshow(np.sinc(xx))
<matplotlib.image.AxesImage object at 0x...> | Return the sinc function. | [
"Return",
"the",
"sinc",
"function",
"."
] | def sinc(x):
"""
Return the sinc function.
The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`.
Parameters
----------
x : ndarray
Array (possibly multi-dimensional) of values for which to to
calculate ``sinc(x)``.
Returns
-------
out : ndarray
``sinc(x)``, which has the same shape as the input.
Notes
-----
``sinc(0)`` is the limit value 1.
The name sinc is short for "sine cardinal" or "sinus cardinalis".
The sinc function is used in various signal processing applications,
including in anti-aliasing, in the construction of a
Lanczos resampling filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal
interpolation kernel is proportional to the sinc function.
References
----------
.. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
Resource. http://mathworld.wolfram.com/SincFunction.html
.. [2] Wikipedia, "Sinc function",
http://en.wikipedia.org/wiki/Sinc_function
Examples
--------
>>> x = np.arange(-20., 21.)/5.
>>> np.sinc(x)
array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02,
-8.90384387e-02, -5.84680802e-02, 3.89804309e-17,
6.68206631e-02, 1.16434881e-01, 1.26137788e-01,
8.50444803e-02, -3.89804309e-17, -1.03943254e-01,
-1.89206682e-01, -2.16236208e-01, -1.55914881e-01,
3.89804309e-17, 2.33872321e-01, 5.04551152e-01,
7.56826729e-01, 9.35489284e-01, 1.00000000e+00,
9.35489284e-01, 7.56826729e-01, 5.04551152e-01,
2.33872321e-01, 3.89804309e-17, -1.55914881e-01,
-2.16236208e-01, -1.89206682e-01, -1.03943254e-01,
-3.89804309e-17, 8.50444803e-02, 1.26137788e-01,
1.16434881e-01, 6.68206631e-02, 3.89804309e-17,
-5.84680802e-02, -8.90384387e-02, -8.40918587e-02,
-4.92362781e-02, -3.89804309e-17])
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, np.sinc(x))
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Sinc Function")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("X")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
It works in 2-D as well:
>>> x = np.arange(-200., 201.)/50.
>>> xx = np.outer(x, x)
>>> plt.imshow(np.sinc(xx))
<matplotlib.image.AxesImage object at 0x...>
"""
x = np.asanyarray(x)
y = pi* where(x == 0, 1.0e-20, x)
return sin(y)/y | [
"def",
"sinc",
"(",
"x",
")",
":",
"x",
"=",
"np",
".",
"asanyarray",
"(",
"x",
")",
"y",
"=",
"pi",
"*",
"where",
"(",
"x",
"==",
"0",
",",
"1.0e-20",
",",
"x",
")",
"return",
"sin",
"(",
"y",
")",
"/",
"y"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/function_base.py#L2755-L2832 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/masked/ipaddrctrl.py | python | IpAddrCtrl.OnDot | (self, event) | return self._OnChangeField(event) | Defines what action to take when the '.' character is typed in the
control. By default, the current field is right-justified, and the
cursor is placed in the next field. | Defines what action to take when the '.' character is typed in the
control. By default, the current field is right-justified, and the
cursor is placed in the next field. | [
"Defines",
"what",
"action",
"to",
"take",
"when",
"the",
".",
"character",
"is",
"typed",
"in",
"the",
"control",
".",
"By",
"default",
"the",
"current",
"field",
"is",
"right",
"-",
"justified",
"and",
"the",
"cursor",
"is",
"placed",
"in",
"the",
"next",
"field",
"."
] | def OnDot(self, event):
"""
Defines what action to take when the '.' character is typed in the
control. By default, the current field is right-justified, and the
cursor is placed in the next field.
"""
## dbg('IpAddrCtrl::OnDot', indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
oldvalue = self.GetValue()
edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
if not event.ShiftDown():
if pos > edit_start and pos < edit_end:
# clip data in field to the right of pos, if adjusting fields
# when not at delimeter; (assumption == they hit '.')
newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]
self._SetValue(newvalue)
self._SetInsertionPoint(pos)
## dbg(indent=0)
return self._OnChangeField(event) | [
"def",
"OnDot",
"(",
"self",
",",
"event",
")",
":",
"## dbg('IpAddrCtrl::OnDot', indent=1)",
"pos",
"=",
"self",
".",
"_adjustPos",
"(",
"self",
".",
"_GetInsertionPoint",
"(",
")",
",",
"event",
".",
"GetKeyCode",
"(",
")",
")",
"oldvalue",
"=",
"self",
".",
"GetValue",
"(",
")",
"edit_start",
",",
"edit_end",
",",
"slice",
"=",
"self",
".",
"_FindFieldExtent",
"(",
"pos",
",",
"getslice",
"=",
"True",
")",
"if",
"not",
"event",
".",
"ShiftDown",
"(",
")",
":",
"if",
"pos",
">",
"edit_start",
"and",
"pos",
"<",
"edit_end",
":",
"# clip data in field to the right of pos, if adjusting fields",
"# when not at delimeter; (assumption == they hit '.')",
"newvalue",
"=",
"oldvalue",
"[",
":",
"pos",
"]",
"+",
"' '",
"*",
"(",
"edit_end",
"-",
"pos",
")",
"+",
"oldvalue",
"[",
"edit_end",
":",
"]",
"self",
".",
"_SetValue",
"(",
"newvalue",
")",
"self",
".",
"_SetInsertionPoint",
"(",
"pos",
")",
"## dbg(indent=0)",
"return",
"self",
".",
"_OnChangeField",
"(",
"event",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/ipaddrctrl.py#L125-L143 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-thci/OpenThread.py | python | OpenThreadTHCI.__readCliLine | (self, ignoreLogs=True) | return line | Read the next line from OT CLI.d | Read the next line from OT CLI.d | [
"Read",
"the",
"next",
"line",
"from",
"OT",
"CLI",
".",
"d"
] | def __readCliLine(self, ignoreLogs=True):
"""Read the next line from OT CLI.d"""
line = self._cliReadLine()
if ignoreLogs:
while line is not None and LOGX.match(line):
line = self._cliReadLine()
return line | [
"def",
"__readCliLine",
"(",
"self",
",",
"ignoreLogs",
"=",
"True",
")",
":",
"line",
"=",
"self",
".",
"_cliReadLine",
"(",
")",
"if",
"ignoreLogs",
":",
"while",
"line",
"is",
"not",
"None",
"and",
"LOGX",
".",
"match",
"(",
"line",
")",
":",
"line",
"=",
"self",
".",
"_cliReadLine",
"(",
")",
"return",
"line"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread.py#L358-L365 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | PRESUBMIT.py | python | _CheckIncludeOrderInFile | (input_api, f, changed_linenums) | return warnings | Checks the #include order for the given file f. | Checks the #include order for the given file f. | [
"Checks",
"the",
"#include",
"order",
"for",
"the",
"given",
"file",
"f",
"."
] | def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
"""Checks the #include order for the given file f."""
system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
# Exclude the following includes from the check:
# 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a
# specific order.
# 2) <atlbase.h>, "build/build_config.h"
excluded_include_pattern = input_api.re.compile(
r'\s*#include (\<.*/.*|\<atlbase\.h\>|"build/build_config.h")')
custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
# Match the final or penultimate token if it is xxxtest so we can ignore it
# when considering the special first include.
test_file_tag_pattern = input_api.re.compile(
r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\.)')
if_pattern = input_api.re.compile(
r'\s*#\s*(if|elif|else|endif|define|undef).*')
# Some files need specialized order of includes; exclude such files from this
# check.
uncheckable_includes_pattern = input_api.re.compile(
r'\s*#include '
'("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
contents = f.NewContents()
warnings = []
line_num = 0
# Handle the special first include. If the first include file is
# some/path/file.h, the corresponding including file can be some/path/file.cc,
# some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
# etc. It's also possible that no special first include exists.
# If the included file is some/path/file_platform.h the including file could
# also be some/path/file_xxxtest_platform.h.
including_file_base_name = test_file_tag_pattern.sub(
'', input_api.os_path.basename(f.LocalPath()))
for line in contents:
line_num += 1
if system_include_pattern.match(line):
# No special first include -> process the line again along with normal
# includes.
line_num -= 1
break
match = custom_include_pattern.match(line)
if match:
match_dict = match.groupdict()
header_basename = test_file_tag_pattern.sub(
'', input_api.os_path.basename(match_dict['FILE'])).replace('.h', '')
if header_basename not in including_file_base_name:
# No special first include -> process the line again along with normal
# includes.
line_num -= 1
break
# Split into scopes: Each region between #if and #endif is its own scope.
scopes = []
current_scope = []
for line in contents[line_num:]:
line_num += 1
if uncheckable_includes_pattern.match(line):
continue
if if_pattern.match(line):
scopes.append(current_scope)
current_scope = []
elif ((system_include_pattern.match(line) or
custom_include_pattern.match(line)) and
not excluded_include_pattern.match(line)):
current_scope.append((line_num, line))
scopes.append(current_scope)
for scope in scopes:
warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
changed_linenums))
return warnings | [
"def",
"_CheckIncludeOrderInFile",
"(",
"input_api",
",",
"f",
",",
"changed_linenums",
")",
":",
"system_include_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'\\s*#include \\<.*'",
")",
"# Exclude the following includes from the check:",
"# 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a",
"# specific order.",
"# 2) <atlbase.h>, \"build/build_config.h\"",
"excluded_include_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'\\s*#include (\\<.*/.*|\\<atlbase\\.h\\>|\"build/build_config.h\")'",
")",
"custom_include_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'\\s*#include \"(?P<FILE>.*)\"'",
")",
"# Match the final or penultimate token if it is xxxtest so we can ignore it",
"# when considering the special first include.",
"test_file_tag_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\\.)'",
")",
"if_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'\\s*#\\s*(if|elif|else|endif|define|undef).*'",
")",
"# Some files need specialized order of includes; exclude such files from this",
"# check.",
"uncheckable_includes_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'\\s*#include '",
"'(\"ipc/.*macros\\.h\"|<windows\\.h>|\".*gl.*autogen.h\")\\s*'",
")",
"contents",
"=",
"f",
".",
"NewContents",
"(",
")",
"warnings",
"=",
"[",
"]",
"line_num",
"=",
"0",
"# Handle the special first include. If the first include file is",
"# some/path/file.h, the corresponding including file can be some/path/file.cc,",
"# some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h",
"# etc. It's also possible that no special first include exists.",
"# If the included file is some/path/file_platform.h the including file could",
"# also be some/path/file_xxxtest_platform.h.",
"including_file_base_name",
"=",
"test_file_tag_pattern",
".",
"sub",
"(",
"''",
",",
"input_api",
".",
"os_path",
".",
"basename",
"(",
"f",
".",
"LocalPath",
"(",
")",
")",
")",
"for",
"line",
"in",
"contents",
":",
"line_num",
"+=",
"1",
"if",
"system_include_pattern",
".",
"match",
"(",
"line",
")",
":",
"# No special first include -> process the line again along with normal",
"# includes.",
"line_num",
"-=",
"1",
"break",
"match",
"=",
"custom_include_pattern",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"match_dict",
"=",
"match",
".",
"groupdict",
"(",
")",
"header_basename",
"=",
"test_file_tag_pattern",
".",
"sub",
"(",
"''",
",",
"input_api",
".",
"os_path",
".",
"basename",
"(",
"match_dict",
"[",
"'FILE'",
"]",
")",
")",
".",
"replace",
"(",
"'.h'",
",",
"''",
")",
"if",
"header_basename",
"not",
"in",
"including_file_base_name",
":",
"# No special first include -> process the line again along with normal",
"# includes.",
"line_num",
"-=",
"1",
"break",
"# Split into scopes: Each region between #if and #endif is its own scope.",
"scopes",
"=",
"[",
"]",
"current_scope",
"=",
"[",
"]",
"for",
"line",
"in",
"contents",
"[",
"line_num",
":",
"]",
":",
"line_num",
"+=",
"1",
"if",
"uncheckable_includes_pattern",
".",
"match",
"(",
"line",
")",
":",
"continue",
"if",
"if_pattern",
".",
"match",
"(",
"line",
")",
":",
"scopes",
".",
"append",
"(",
"current_scope",
")",
"current_scope",
"=",
"[",
"]",
"elif",
"(",
"(",
"system_include_pattern",
".",
"match",
"(",
"line",
")",
"or",
"custom_include_pattern",
".",
"match",
"(",
"line",
")",
")",
"and",
"not",
"excluded_include_pattern",
".",
"match",
"(",
"line",
")",
")",
":",
"current_scope",
".",
"append",
"(",
"(",
"line_num",
",",
"line",
")",
")",
"scopes",
".",
"append",
"(",
"current_scope",
")",
"for",
"scope",
"in",
"scopes",
":",
"warnings",
".",
"extend",
"(",
"_CheckIncludeOrderForScope",
"(",
"scope",
",",
"input_api",
",",
"f",
".",
"LocalPath",
"(",
")",
",",
"changed_linenums",
")",
")",
"return",
"warnings"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/PRESUBMIT.py#L611-L685 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | win32/Lib/regutil.py | python | GetRootKey | () | Retrieves the Registry root in use by Python. | Retrieves the Registry root in use by Python. | [
"Retrieves",
"the",
"Registry",
"root",
"in",
"use",
"by",
"Python",
"."
] | def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE | [
"def",
"GetRootKey",
"(",
")",
":",
"keyname",
"=",
"BuildDefaultPythonKey",
"(",
")",
"try",
":",
"k",
"=",
"win32api",
".",
"RegOpenKey",
"(",
"win32con",
".",
"HKEY_CURRENT_USER",
",",
"keyname",
")",
"k",
".",
"close",
"(",
")",
"return",
"win32con",
".",
"HKEY_CURRENT_USER",
"except",
"win32api",
".",
"error",
":",
"return",
"win32con",
".",
"HKEY_LOCAL_MACHINE"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Lib/regutil.py#L26-L34 | ||
CaoWGG/TensorRT-YOLOv4 | 4d7c2edce99e8794a4cb4ea3540d51ce91158a36 | onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py | python | TranslationUnit.from_ast_file | (cls, filename, index=None) | return cls(ptr=ptr, index=index) | Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created. | Create a TranslationUnit instance from a saved AST file. | [
"Create",
"a",
"TranslationUnit",
"instance",
"from",
"a",
"saved",
"AST",
"file",
"."
] | def from_ast_file(cls, filename, index=None):
"""Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created.
"""
if index is None:
index = Index.create()
ptr = conf.lib.clang_createTranslationUnit(index, filename)
if not ptr:
raise TranslationUnitLoadError(filename)
return cls(ptr=ptr, index=index) | [
"def",
"from_ast_file",
"(",
"cls",
",",
"filename",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"Index",
".",
"create",
"(",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_createTranslationUnit",
"(",
"index",
",",
"filename",
")",
"if",
"not",
"ptr",
":",
"raise",
"TranslationUnitLoadError",
"(",
"filename",
")",
"return",
"cls",
"(",
"ptr",
"=",
"ptr",
",",
"index",
"=",
"index",
")"
] | https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L2541-L2560 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/selectors.py | python | BaseSelector.get_key | (self, fileobj) | Return the key associated to a registered file object.
Returns:
SelectorKey for this file object | Return the key associated to a registered file object. | [
"Return",
"the",
"key",
"associated",
"to",
"a",
"registered",
"file",
"object",
"."
] | def get_key(self, fileobj):
"""Return the key associated to a registered file object.
Returns:
SelectorKey for this file object
"""
mapping = self.get_map()
if mapping is None:
raise RuntimeError('Selector is closed')
try:
return mapping[fileobj]
except KeyError:
raise KeyError("{!r} is not registered".format(fileobj)) from None | [
"def",
"get_key",
"(",
"self",
",",
"fileobj",
")",
":",
"mapping",
"=",
"self",
".",
"get_map",
"(",
")",
"if",
"mapping",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Selector is closed'",
")",
"try",
":",
"return",
"mapping",
"[",
"fileobj",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"{!r} is not registered\"",
".",
"format",
"(",
"fileobj",
")",
")",
"from",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/selectors.py#L180-L192 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/site.py | python | setBEGINLIBPATH | () | The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path. | The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path. | [
"The",
"OS",
"/",
"2",
"EMX",
"port",
"has",
"optional",
"extension",
"modules",
"that",
"do",
"double",
"duty",
"as",
"DLLs",
"(",
"and",
"must",
"use",
"the",
".",
"DLL",
"file",
"extension",
")",
"for",
"other",
"extensions",
".",
"The",
"library",
"search",
"path",
"needs",
"to",
"be",
"amended",
"so",
"these",
"will",
"be",
"found",
"during",
"module",
"import",
".",
"Use",
"BEGINLIBPATH",
"so",
"that",
"these",
"are",
"at",
"the",
"start",
"of",
"the",
"library",
"search",
"path",
"."
] | def setBEGINLIBPATH():
"""The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path.
"""
dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
libpath = os.environ['BEGINLIBPATH'].split(';')
if libpath[-1]:
libpath.append(dllpath)
else:
libpath[-1] = dllpath
os.environ['BEGINLIBPATH'] = ';'.join(libpath) | [
"def",
"setBEGINLIBPATH",
"(",
")",
":",
"dllpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"prefix",
",",
"\"Lib\"",
",",
"\"lib-dynload\"",
")",
"libpath",
"=",
"os",
".",
"environ",
"[",
"'BEGINLIBPATH'",
"]",
".",
"split",
"(",
"';'",
")",
"if",
"libpath",
"[",
"-",
"1",
"]",
":",
"libpath",
".",
"append",
"(",
"dllpath",
")",
"else",
":",
"libpath",
"[",
"-",
"1",
"]",
"=",
"dllpath",
"os",
".",
"environ",
"[",
"'BEGINLIBPATH'",
"]",
"=",
"';'",
".",
"join",
"(",
"libpath",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/site.py#L317-L331 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/functional/elemwise.py | python | logical_xor | (x, y) | return _elwise(x, y, mode=Elemwise.Mode.XOR) | r"""Element-wise `logical xor: x ^ y`. | r"""Element-wise `logical xor: x ^ y`. | [
"r",
"Element",
"-",
"wise",
"logical",
"xor",
":",
"x",
"^",
"y",
"."
] | def logical_xor(x, y):
r"""Element-wise `logical xor: x ^ y`."""
return _elwise(x, y, mode=Elemwise.Mode.XOR) | [
"def",
"logical_xor",
"(",
"x",
",",
"y",
")",
":",
"return",
"_elwise",
"(",
"x",
",",
"y",
",",
"mode",
"=",
"Elemwise",
".",
"Mode",
".",
"XOR",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/elemwise.py#L453-L455 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Text.tag_add | (self, tagName, index1, *args) | Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
Additional pairs of indices may follow in ARGS. | Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
Additional pairs of indices may follow in ARGS. | [
"Add",
"tag",
"TAGNAME",
"to",
"all",
"characters",
"between",
"INDEX1",
"and",
"index2",
"in",
"ARGS",
".",
"Additional",
"pairs",
"of",
"indices",
"may",
"follow",
"in",
"ARGS",
"."
] | def tag_add(self, tagName, index1, *args):
"""Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
Additional pairs of indices may follow in ARGS."""
self.tk.call(
(self._w, 'tag', 'add', tagName, index1) + args) | [
"def",
"tag_add",
"(",
"self",
",",
"tagName",
",",
"index1",
",",
"*",
"args",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'tag'",
",",
"'add'",
",",
"tagName",
",",
"index1",
")",
"+",
"args",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L3342-L3346 | ||
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | apps/ngs_roi/tool_shed/roi_plot_thumbnails.py | python | main | () | return app.run() | Program entry point. | Program entry point. | [
"Program",
"entry",
"point",
"."
] | def main():
"""Program entry point."""
parser = argparse.ArgumentParser(description='Plot ROI file.')
ngs_roi.argparse.addFileArguments(parser)
ngs_roi.argparse.addPlotGridArguments(parser)
ngs_roi.argparse.addLinkArguments(parser)
args = parser.parse_args()
ngs_roi.argparse.applyFileDefaults(args)
app = PlotThumbnailsApp(args)
return app.run() | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Plot ROI file.'",
")",
"ngs_roi",
".",
"argparse",
".",
"addFileArguments",
"(",
"parser",
")",
"ngs_roi",
".",
"argparse",
".",
"addPlotGridArguments",
"(",
"parser",
")",
"ngs_roi",
".",
"argparse",
".",
"addLinkArguments",
"(",
"parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"ngs_roi",
".",
"argparse",
".",
"applyFileDefaults",
"(",
"args",
")",
"app",
"=",
"PlotThumbnailsApp",
"(",
"args",
")",
"return",
"app",
".",
"run",
"(",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/apps/ngs_roi/tool_shed/roi_plot_thumbnails.py#L179-L189 | |
ucsb-seclab/difuze | bb59a12ff87ad5ae45d9c60e349891bf80d72877 | helper_scripts/components/bear_parse_headers.py | python | BearParseHeaders.is_critical | (self) | return False | This component is not critical.
:return: False | This component is not critical.
:return: False | [
"This",
"component",
"is",
"not",
"critical",
".",
":",
"return",
":",
"False"
] | def is_critical(self):
"""
This component is not critical.
:return: False
"""
return False | [
"def",
"is_critical",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/ucsb-seclab/difuze/blob/bb59a12ff87ad5ae45d9c60e349891bf80d72877/helper_scripts/components/bear_parse_headers.py#L86-L91 | |
Cisco-Talos/moflow | ed71dfb0540d9e0d7a4c72f0881b58958d573728 | BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/cpp_message.py | python | _AddMessageMethods | (message_descriptor, cls) | Adds the methods to a protocol message class. | Adds the methods to a protocol message class. | [
"Adds",
"the",
"methods",
"to",
"a",
"protocol",
"message",
"class",
"."
] | def _AddMessageMethods(message_descriptor, cls):
"""Adds the methods to a protocol message class."""
if message_descriptor.is_extendable:
def ClearExtension(self, extension):
self.Extensions.ClearExtension(extension)
def HasExtension(self, extension):
return self.Extensions.HasExtension(extension)
def HasField(self, field_name):
return self._cmsg.HasField(field_name)
def ClearField(self, field_name):
if field_name in self._composite_fields:
del self._composite_fields[field_name]
self._cmsg.ClearField(field_name)
def Clear(self):
return self._cmsg.Clear()
def IsInitialized(self, errors=None):
if self._cmsg.IsInitialized():
return True
if errors is not None:
errors.extend(self.FindInitializationErrors());
return False
def SerializeToString(self):
if not self.IsInitialized():
raise message.EncodeError(
'Message is missing required fields: ' +
','.join(self.FindInitializationErrors()))
return self._cmsg.SerializeToString()
def SerializePartialToString(self):
return self._cmsg.SerializePartialToString()
def ParseFromString(self, serialized):
self.Clear()
self.MergeFromString(serialized)
def MergeFromString(self, serialized):
byte_size = self._cmsg.MergeFromString(serialized)
if byte_size < 0:
raise message.DecodeError('Unable to merge from string.')
return byte_size
def MergeFrom(self, msg):
if not isinstance(msg, cls):
raise TypeError(
"Parameter to MergeFrom() must be instance of same class.")
self._cmsg.MergeFrom(msg._cmsg)
def CopyFrom(self, msg):
self._cmsg.CopyFrom(msg._cmsg)
def ByteSize(self):
return self._cmsg.ByteSize()
def SetInParent(self):
return self._cmsg.SetInParent()
def ListFields(self):
all_fields = []
field_list = self._cmsg.ListFields()
fields_by_name = cls.DESCRIPTOR.fields_by_name
for is_extension, field_name in field_list:
if is_extension:
extension = cls._extensions_by_name[field_name]
all_fields.append((extension, self.Extensions[extension]))
else:
field_descriptor = fields_by_name[field_name]
all_fields.append(
(field_descriptor, getattr(self, field_name)))
all_fields.sort(key=lambda item: item[0].number)
return all_fields
def FindInitializationErrors(self):
return self._cmsg.FindInitializationErrors()
def __str__(self):
return self._cmsg.DebugString()
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, self.__class__):
return False
return self.ListFields() == other.ListFields()
def __ne__(self, other):
return not self == other
def __hash__(self):
raise TypeError('unhashable object')
def __unicode__(self):
return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
# Attach the local methods to the message class.
for key, value in locals().copy().iteritems():
if key not in ('key', 'value', '__builtins__', '__name__', '__doc__'):
setattr(cls, key, value)
# Static methods:
def RegisterExtension(extension_handle):
extension_handle.containing_type = cls.DESCRIPTOR
cls._extensions_by_name[extension_handle.full_name] = extension_handle
if _IsMessageSetExtension(extension_handle):
# MessageSet extension. Also register under type name.
cls._extensions_by_name[
extension_handle.message_type.full_name] = extension_handle
cls.RegisterExtension = staticmethod(RegisterExtension)
def FromString(string):
msg = cls()
msg.MergeFromString(string)
return msg
cls.FromString = staticmethod(FromString) | [
"def",
"_AddMessageMethods",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"if",
"message_descriptor",
".",
"is_extendable",
":",
"def",
"ClearExtension",
"(",
"self",
",",
"extension",
")",
":",
"self",
".",
"Extensions",
".",
"ClearExtension",
"(",
"extension",
")",
"def",
"HasExtension",
"(",
"self",
",",
"extension",
")",
":",
"return",
"self",
".",
"Extensions",
".",
"HasExtension",
"(",
"extension",
")",
"def",
"HasField",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"HasField",
"(",
"field_name",
")",
"def",
"ClearField",
"(",
"self",
",",
"field_name",
")",
":",
"if",
"field_name",
"in",
"self",
".",
"_composite_fields",
":",
"del",
"self",
".",
"_composite_fields",
"[",
"field_name",
"]",
"self",
".",
"_cmsg",
".",
"ClearField",
"(",
"field_name",
")",
"def",
"Clear",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"Clear",
"(",
")",
"def",
"IsInitialized",
"(",
"self",
",",
"errors",
"=",
"None",
")",
":",
"if",
"self",
".",
"_cmsg",
".",
"IsInitialized",
"(",
")",
":",
"return",
"True",
"if",
"errors",
"is",
"not",
"None",
":",
"errors",
".",
"extend",
"(",
"self",
".",
"FindInitializationErrors",
"(",
")",
")",
"return",
"False",
"def",
"SerializeToString",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"IsInitialized",
"(",
")",
":",
"raise",
"message",
".",
"EncodeError",
"(",
"'Message is missing required fields: '",
"+",
"','",
".",
"join",
"(",
"self",
".",
"FindInitializationErrors",
"(",
")",
")",
")",
"return",
"self",
".",
"_cmsg",
".",
"SerializeToString",
"(",
")",
"def",
"SerializePartialToString",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"SerializePartialToString",
"(",
")",
"def",
"ParseFromString",
"(",
"self",
",",
"serialized",
")",
":",
"self",
".",
"Clear",
"(",
")",
"self",
".",
"MergeFromString",
"(",
"serialized",
")",
"def",
"MergeFromString",
"(",
"self",
",",
"serialized",
")",
":",
"byte_size",
"=",
"self",
".",
"_cmsg",
".",
"MergeFromString",
"(",
"serialized",
")",
"if",
"byte_size",
"<",
"0",
":",
"raise",
"message",
".",
"DecodeError",
"(",
"'Unable to merge from string.'",
")",
"return",
"byte_size",
"def",
"MergeFrom",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter to MergeFrom() must be instance of same class.\"",
")",
"self",
".",
"_cmsg",
".",
"MergeFrom",
"(",
"msg",
".",
"_cmsg",
")",
"def",
"CopyFrom",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"_cmsg",
".",
"CopyFrom",
"(",
"msg",
".",
"_cmsg",
")",
"def",
"ByteSize",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"ByteSize",
"(",
")",
"def",
"SetInParent",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"SetInParent",
"(",
")",
"def",
"ListFields",
"(",
"self",
")",
":",
"all_fields",
"=",
"[",
"]",
"field_list",
"=",
"self",
".",
"_cmsg",
".",
"ListFields",
"(",
")",
"fields_by_name",
"=",
"cls",
".",
"DESCRIPTOR",
".",
"fields_by_name",
"for",
"is_extension",
",",
"field_name",
"in",
"field_list",
":",
"if",
"is_extension",
":",
"extension",
"=",
"cls",
".",
"_extensions_by_name",
"[",
"field_name",
"]",
"all_fields",
".",
"append",
"(",
"(",
"extension",
",",
"self",
".",
"Extensions",
"[",
"extension",
"]",
")",
")",
"else",
":",
"field_descriptor",
"=",
"fields_by_name",
"[",
"field_name",
"]",
"all_fields",
".",
"append",
"(",
"(",
"field_descriptor",
",",
"getattr",
"(",
"self",
",",
"field_name",
")",
")",
")",
"all_fields",
".",
"sort",
"(",
"key",
"=",
"lambda",
"item",
":",
"item",
"[",
"0",
"]",
".",
"number",
")",
"return",
"all_fields",
"def",
"FindInitializationErrors",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"FindInitializationErrors",
"(",
")",
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cmsg",
".",
"DebugString",
"(",
")",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
"is",
"other",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"False",
"return",
"self",
".",
"ListFields",
"(",
")",
"==",
"other",
".",
"ListFields",
"(",
")",
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"return",
"not",
"self",
"==",
"other",
"def",
"__hash__",
"(",
"self",
")",
":",
"raise",
"TypeError",
"(",
"'unhashable object'",
")",
"def",
"__unicode__",
"(",
"self",
")",
":",
"return",
"text_format",
".",
"MessageToString",
"(",
"self",
",",
"as_utf8",
"=",
"True",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"# Attach the local methods to the message class.",
"for",
"key",
",",
"value",
"in",
"locals",
"(",
")",
".",
"copy",
"(",
")",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'key'",
",",
"'value'",
",",
"'__builtins__'",
",",
"'__name__'",
",",
"'__doc__'",
")",
":",
"setattr",
"(",
"cls",
",",
"key",
",",
"value",
")",
"# Static methods:",
"def",
"RegisterExtension",
"(",
"extension_handle",
")",
":",
"extension_handle",
".",
"containing_type",
"=",
"cls",
".",
"DESCRIPTOR",
"cls",
".",
"_extensions_by_name",
"[",
"extension_handle",
".",
"full_name",
"]",
"=",
"extension_handle",
"if",
"_IsMessageSetExtension",
"(",
"extension_handle",
")",
":",
"# MessageSet extension. Also register under type name.",
"cls",
".",
"_extensions_by_name",
"[",
"extension_handle",
".",
"message_type",
".",
"full_name",
"]",
"=",
"extension_handle",
"cls",
".",
"RegisterExtension",
"=",
"staticmethod",
"(",
"RegisterExtension",
")",
"def",
"FromString",
"(",
"string",
")",
":",
"msg",
"=",
"cls",
"(",
")",
"msg",
".",
"MergeFromString",
"(",
"string",
")",
"return",
"msg",
"cls",
".",
"FromString",
"=",
"staticmethod",
"(",
"FromString",
")"
] | https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/cpp_message.py#L486-L607 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/logical.py | python | not_ | (a) | return _py_not(a) | Functional form of "not". | Functional form of "not". | [
"Functional",
"form",
"of",
"not",
"."
] | def not_(a):
"""Functional form of "not"."""
if tensor_util.is_tensor(a):
return _tf_not(a)
return _py_not(a) | [
"def",
"not_",
"(",
"a",
")",
":",
"if",
"tensor_util",
".",
"is_tensor",
"(",
"a",
")",
":",
"return",
"_tf_not",
"(",
"a",
")",
"return",
"_py_not",
"(",
"a",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/logical.py#L26-L30 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_base/classman.py | python | Attrsman.save_values | (self, state) | Called by the managed object during save to save the
attribute values. | Called by the managed object during save to save the
attribute values. | [
"Called",
"by",
"the",
"managed",
"object",
"during",
"save",
"to",
"save",
"the",
"attribute",
"values",
"."
] | def save_values(self, state):
"""
Called by the managed object during save to save the
attribute values.
"""
for attrconfig in self.get_configs():
attrconfig.save_value(state) | [
"def",
"save_values",
"(",
"self",
",",
"state",
")",
":",
"for",
"attrconfig",
"in",
"self",
".",
"get_configs",
"(",
")",
":",
"attrconfig",
".",
"save_value",
"(",
"state",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_base/classman.py#L2060-L2066 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/parser.py | python | CustomOptionParser.option_list_all | (self) | return res | Get a list of all options, including those in option groups. | Get a list of all options, including those in option groups. | [
"Get",
"a",
"list",
"of",
"all",
"options",
"including",
"those",
"in",
"option",
"groups",
"."
] | def option_list_all(self):
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res | [
"def",
"option_list_all",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"option_list",
"[",
":",
"]",
"for",
"i",
"in",
"self",
".",
"option_groups",
":",
"res",
".",
"extend",
"(",
"i",
".",
"option_list",
")",
"return",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/parser.py#L144-L150 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/shape_base.py | python | array_split | (ary, indices_or_sections, axis=0) | return sub_arys | Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis. For an array of length l that should be split
into n sections, it returns l % n sub-arrays of size l//n + 1
and the rest of size l//n.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
>>> x = np.arange(7.0)
>>> np.array_split(x, 3)
[array([0., 1., 2.]), array([3., 4.]), array([5., 6.])] | Split an array into multiple sub-arrays. | [
"Split",
"an",
"array",
"into",
"multiple",
"sub",
"-",
"arrays",
"."
] | def array_split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis. For an array of length l that should be split
into n sections, it returns l % n sub-arrays of size l//n + 1
and the rest of size l//n.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
>>> x = np.arange(7.0)
>>> np.array_split(x, 3)
[array([0., 1., 2.]), array([3., 4.]), array([5., 6.])]
"""
try:
Ntotal = ary.shape[axis]
except AttributeError:
Ntotal = len(ary)
try:
# handle array case.
Nsections = len(indices_or_sections) + 1
div_points = [0] + list(indices_or_sections) + [Ntotal]
except TypeError:
# indices_or_sections is a scalar, not an array.
Nsections = int(indices_or_sections)
if Nsections <= 0:
raise ValueError('number sections must be larger than 0.')
Neach_section, extras = divmod(Ntotal, Nsections)
section_sizes = ([0] +
extras * [Neach_section+1] +
(Nsections-extras) * [Neach_section])
div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum()
sub_arys = []
sary = _nx.swapaxes(ary, axis, 0)
for i in range(Nsections):
st = div_points[i]
end = div_points[i + 1]
sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
return sub_arys | [
"def",
"array_split",
"(",
"ary",
",",
"indices_or_sections",
",",
"axis",
"=",
"0",
")",
":",
"try",
":",
"Ntotal",
"=",
"ary",
".",
"shape",
"[",
"axis",
"]",
"except",
"AttributeError",
":",
"Ntotal",
"=",
"len",
"(",
"ary",
")",
"try",
":",
"# handle array case.",
"Nsections",
"=",
"len",
"(",
"indices_or_sections",
")",
"+",
"1",
"div_points",
"=",
"[",
"0",
"]",
"+",
"list",
"(",
"indices_or_sections",
")",
"+",
"[",
"Ntotal",
"]",
"except",
"TypeError",
":",
"# indices_or_sections is a scalar, not an array.",
"Nsections",
"=",
"int",
"(",
"indices_or_sections",
")",
"if",
"Nsections",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'number sections must be larger than 0.'",
")",
"Neach_section",
",",
"extras",
"=",
"divmod",
"(",
"Ntotal",
",",
"Nsections",
")",
"section_sizes",
"=",
"(",
"[",
"0",
"]",
"+",
"extras",
"*",
"[",
"Neach_section",
"+",
"1",
"]",
"+",
"(",
"Nsections",
"-",
"extras",
")",
"*",
"[",
"Neach_section",
"]",
")",
"div_points",
"=",
"_nx",
".",
"array",
"(",
"section_sizes",
",",
"dtype",
"=",
"_nx",
".",
"intp",
")",
".",
"cumsum",
"(",
")",
"sub_arys",
"=",
"[",
"]",
"sary",
"=",
"_nx",
".",
"swapaxes",
"(",
"ary",
",",
"axis",
",",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"Nsections",
")",
":",
"st",
"=",
"div_points",
"[",
"i",
"]",
"end",
"=",
"div_points",
"[",
"i",
"+",
"1",
"]",
"sub_arys",
".",
"append",
"(",
"_nx",
".",
"swapaxes",
"(",
"sary",
"[",
"st",
":",
"end",
"]",
",",
"axis",
",",
"0",
")",
")",
"return",
"sub_arys"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/shape_base.py#L738-L790 | |
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/common/Vector.py | python | Vector.is_equal_to | (self, other) | return common.misc.approximate_equal((self - other).mag_squared(), 0) | Tells if the current vector is equal to `other` vector
Args:
other (common.Vector.Vector) : The vector to be compared with
Returns:
(bool) : True if the vectors are equal
: False otherwise | Tells if the current vector is equal to `other` vector | [
"Tells",
"if",
"the",
"current",
"vector",
"is",
"equal",
"to",
"other",
"vector"
] | def is_equal_to(self, other):
"""
Tells if the current vector is equal to `other` vector
Args:
other (common.Vector.Vector) : The vector to be compared with
Returns:
(bool) : True if the vectors are equal
: False otherwise
"""
return common.misc.approximate_equal((self - other).mag_squared(), 0) | [
"def",
"is_equal_to",
"(",
"self",
",",
"other",
")",
":",
"return",
"common",
".",
"misc",
".",
"approximate_equal",
"(",
"(",
"self",
"-",
"other",
")",
".",
"mag_squared",
"(",
")",
",",
"0",
")"
] | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Vector.py#L115-L126 | |
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | SynthText_Chinese/gen_cartoon_viz.py | python | add_res_to_db | (imgname,res,db) | Add the synthetically generated text image instance
and other metadata to the dataset. | Add the synthetically generated text image instance
and other metadata to the dataset. | [
"Add",
"the",
"synthetically",
"generated",
"text",
"image",
"instance",
"and",
"other",
"metadata",
"to",
"the",
"dataset",
"."
] | def add_res_to_db(imgname,res,db):
"""
Add the synthetically generated text image instance
and other metadata to the dataset.
"""
ninstance = len(res)
for i in xrange(ninstance):
print colorize(Color.GREEN,'added into the db %s '%res[i]['txt'])
dname = "%s_%d"%(imgname, i)
db['data'].create_dataset(dname,data=res[i]['img'])
db['data'][dname].attrs['charBB'] = res[i]['charBB']
db['data'][dname].attrs['wordBB'] = res[i]['wordBB']
print 'type of res[i][\'txt\'] ',type(res[i]['txt'])
#db['data'][dname].attrs['txt'] = res[i]['txt']
db['data'][dname].attrs.create('txt', res[i]['txt'], dtype=h5py.special_dtype(vlen=unicode))
print 'type of db ',type(db['data'][dname].attrs['txt'])
print colorize(Color.GREEN,'successfully added')
print res[i]['txt']
print res[i]['img'].shape
print 'charBB',res[i]['charBB'].shape
print 'charBB',res[i]['charBB']
print 'wordBB',res[i]['wordBB'].shape
print 'wordBB',res[i]['wordBB']
'''
img = Image.fromarray(res[i]['img'])
hsv_img=np.array(rgb2hsv(img))
print 'hsv_img_shape',hsv_img.shape
print 'hsv_img',hsv_img
H=hsv_img[:,:,2]
print 'H_channel',H.shape,H
#img = Image.fromarray(db['data'][dname][:])
''' | [
"def",
"add_res_to_db",
"(",
"imgname",
",",
"res",
",",
"db",
")",
":",
"ninstance",
"=",
"len",
"(",
"res",
")",
"for",
"i",
"in",
"xrange",
"(",
"ninstance",
")",
":",
"print",
"colorize",
"(",
"Color",
".",
"GREEN",
",",
"'added into the db %s '",
"%",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
")",
"dname",
"=",
"\"%s_%d\"",
"%",
"(",
"imgname",
",",
"i",
")",
"db",
"[",
"'data'",
"]",
".",
"create_dataset",
"(",
"dname",
",",
"data",
"=",
"res",
"[",
"i",
"]",
"[",
"'img'",
"]",
")",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
"[",
"'charBB'",
"]",
"=",
"res",
"[",
"i",
"]",
"[",
"'charBB'",
"]",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
"[",
"'wordBB'",
"]",
"=",
"res",
"[",
"i",
"]",
"[",
"'wordBB'",
"]",
"print",
"'type of res[i][\\'txt\\'] '",
",",
"type",
"(",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
")",
"#db['data'][dname].attrs['txt'] = res[i]['txt']",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
".",
"create",
"(",
"'txt'",
",",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
",",
"dtype",
"=",
"h5py",
".",
"special_dtype",
"(",
"vlen",
"=",
"unicode",
")",
")",
"print",
"'type of db '",
",",
"type",
"(",
"db",
"[",
"'data'",
"]",
"[",
"dname",
"]",
".",
"attrs",
"[",
"'txt'",
"]",
")",
"print",
"colorize",
"(",
"Color",
".",
"GREEN",
",",
"'successfully added'",
")",
"print",
"res",
"[",
"i",
"]",
"[",
"'txt'",
"]",
"print",
"res",
"[",
"i",
"]",
"[",
"'img'",
"]",
".",
"shape",
"print",
"'charBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'charBB'",
"]",
".",
"shape",
"print",
"'charBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'charBB'",
"]",
"print",
"'wordBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'wordBB'",
"]",
".",
"shape",
"print",
"'wordBB'",
",",
"res",
"[",
"i",
"]",
"[",
"'wordBB'",
"]",
"'''\n img = Image.fromarray(res[i]['img'])\n hsv_img=np.array(rgb2hsv(img))\n print 'hsv_img_shape',hsv_img.shape\n print 'hsv_img',hsv_img\n H=hsv_img[:,:,2]\n print 'H_channel',H.shape,H\n #img = Image.fromarray(db['data'][dname][:])\n '''"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/gen_cartoon_viz.py#L64-L97 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTarget.BreakpointCreateFromScript | (self, class_name, extra_args, module_list, file_list, request_hardware=False) | return _lldb.SBTarget_BreakpointCreateFromScript(self, class_name, extra_args, module_list, file_list, request_hardware) | BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list, bool request_hardware=False) -> SBBreakpoint
BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list) -> SBBreakpoint
Create a breakpoint using a scripted resolver.
@param[in] class_name
This is the name of the class that implements a scripted resolver.
The class should have the following signature:
class Resolver:
def __init__(self, bkpt, extra_args):
# bkpt - the breakpoint for which this is the resolver. When
# the resolver finds an interesting address, call AddLocation
# on this breakpoint to add it.
#
# extra_args - an SBStructuredData that can be used to
# parametrize this instance. Same as the extra_args passed
# to BreakpointCreateFromScript.
def __get_depth__ (self):
# This is optional, but if defined, you should return the
# depth at which you want the callback to be called. The
# available options are:
# lldb.eSearchDepthModule
# lldb.eSearchDepthCompUnit
# The default if you don't implement this method is
# eSearchDepthModule.
def __callback__(self, sym_ctx):
# sym_ctx - an SBSymbolContext that is the cursor in the
# search through the program to resolve breakpoints.
# The sym_ctx will be filled out to the depth requested in
# __get_depth__.
# Look in this sym_ctx for new breakpoint locations,
# and if found use bkpt.AddLocation to add them.
# Note, you will only get called for modules/compile_units that
# pass the SearchFilter provided by the module_list & file_list
# passed into BreakpointCreateFromScript.
def get_short_help(self):
# Optional, but if implemented return a short string that will
# be printed at the beginning of the break list output for the
# breakpoint.
@param[in] extra_args
This is an SBStructuredData object that will get passed to the
constructor of the class in class_name. You can use this to
reuse the same class, parametrizing it with entries from this
dictionary.
@param module_list
If this is non-empty, this will be used as the module filter in the
SearchFilter created for this breakpoint.
@param file_list
If this is non-empty, this will be used as the comp unit filter in the
SearchFilter created for this breakpoint.
@return
An SBBreakpoint that will set locations based on the logic in the
resolver's search callback. | BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list, bool request_hardware=False) -> SBBreakpoint
BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list) -> SBBreakpoint | [
"BreakpointCreateFromScript",
"(",
"SBTarget",
"self",
"char",
"const",
"*",
"class_name",
"SBStructuredData",
"extra_args",
"SBFileSpecList",
"module_list",
"SBFileSpecList",
"file_list",
"bool",
"request_hardware",
"=",
"False",
")",
"-",
">",
"SBBreakpoint",
"BreakpointCreateFromScript",
"(",
"SBTarget",
"self",
"char",
"const",
"*",
"class_name",
"SBStructuredData",
"extra_args",
"SBFileSpecList",
"module_list",
"SBFileSpecList",
"file_list",
")",
"-",
">",
"SBBreakpoint"
] | def BreakpointCreateFromScript(self, class_name, extra_args, module_list, file_list, request_hardware=False):
"""
BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list, bool request_hardware=False) -> SBBreakpoint
BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list) -> SBBreakpoint
Create a breakpoint using a scripted resolver.
@param[in] class_name
This is the name of the class that implements a scripted resolver.
The class should have the following signature:
class Resolver:
def __init__(self, bkpt, extra_args):
# bkpt - the breakpoint for which this is the resolver. When
# the resolver finds an interesting address, call AddLocation
# on this breakpoint to add it.
#
# extra_args - an SBStructuredData that can be used to
# parametrize this instance. Same as the extra_args passed
# to BreakpointCreateFromScript.
def __get_depth__ (self):
# This is optional, but if defined, you should return the
# depth at which you want the callback to be called. The
# available options are:
# lldb.eSearchDepthModule
# lldb.eSearchDepthCompUnit
# The default if you don't implement this method is
# eSearchDepthModule.
def __callback__(self, sym_ctx):
# sym_ctx - an SBSymbolContext that is the cursor in the
# search through the program to resolve breakpoints.
# The sym_ctx will be filled out to the depth requested in
# __get_depth__.
# Look in this sym_ctx for new breakpoint locations,
# and if found use bkpt.AddLocation to add them.
# Note, you will only get called for modules/compile_units that
# pass the SearchFilter provided by the module_list & file_list
# passed into BreakpointCreateFromScript.
def get_short_help(self):
# Optional, but if implemented return a short string that will
# be printed at the beginning of the break list output for the
# breakpoint.
@param[in] extra_args
This is an SBStructuredData object that will get passed to the
constructor of the class in class_name. You can use this to
reuse the same class, parametrizing it with entries from this
dictionary.
@param module_list
If this is non-empty, this will be used as the module filter in the
SearchFilter created for this breakpoint.
@param file_list
If this is non-empty, this will be used as the comp unit filter in the
SearchFilter created for this breakpoint.
@return
An SBBreakpoint that will set locations based on the logic in the
resolver's search callback.
"""
return _lldb.SBTarget_BreakpointCreateFromScript(self, class_name, extra_args, module_list, file_list, request_hardware) | [
"def",
"BreakpointCreateFromScript",
"(",
"self",
",",
"class_name",
",",
"extra_args",
",",
"module_list",
",",
"file_list",
",",
"request_hardware",
"=",
"False",
")",
":",
"return",
"_lldb",
".",
"SBTarget_BreakpointCreateFromScript",
"(",
"self",
",",
"class_name",
",",
"extra_args",
",",
"module_list",
",",
"file_list",
",",
"request_hardware",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L10949-L11013 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | HyperTreeList.GetClassDefaultAttributes | (self) | return attr | Returns the default font and colours which are used by the control. This is
useful if you want to use the same font or colour in your own control as in
a standard control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the users system,
especially if it uses themes.
This static method is "overridden'' in many derived classes and so calling,
for example, :meth:`Button.GetClassDefaultAttributes` () will typically return the
values appropriate for a button which will be normally different from those
returned by, say, :meth:`ListCtrl.GetClassDefaultAttributes` ().
:note: The :class:`VisualAttributes` structure has at least the fields `font`,
`colFg` and `colBg`. All of them may be invalid if it was not possible to
determine the default control appearance or, especially for the background
colour, if the field doesn't make sense as is the case for `colBg` for the
controls with themed background. | Returns the default font and colours which are used by the control. This is
useful if you want to use the same font or colour in your own control as in
a standard control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the users system,
especially if it uses themes. | [
"Returns",
"the",
"default",
"font",
"and",
"colours",
"which",
"are",
"used",
"by",
"the",
"control",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"use",
"the",
"same",
"font",
"or",
"colour",
"in",
"your",
"own",
"control",
"as",
"in",
"a",
"standard",
"control",
"--",
"which",
"is",
"a",
"much",
"better",
"idea",
"than",
"hard",
"coding",
"specific",
"colours",
"or",
"fonts",
"which",
"might",
"look",
"completely",
"out",
"of",
"place",
"on",
"the",
"users",
"system",
"especially",
"if",
"it",
"uses",
"themes",
"."
] | def GetClassDefaultAttributes(self):
"""
Returns the default font and colours which are used by the control. This is
useful if you want to use the same font or colour in your own control as in
a standard control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the users system,
especially if it uses themes.
This static method is "overridden'' in many derived classes and so calling,
for example, :meth:`Button.GetClassDefaultAttributes` () will typically return the
values appropriate for a button which will be normally different from those
returned by, say, :meth:`ListCtrl.GetClassDefaultAttributes` ().
:note: The :class:`VisualAttributes` structure has at least the fields `font`,
`colFg` and `colBg`. All of them may be invalid if it was not possible to
determine the default control appearance or, especially for the background
colour, if the field doesn't make sense as is the case for `colBg` for the
controls with themed background.
"""
attr = wx.VisualAttributes()
attr.colFg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
attr.colBg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX)
attr.font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
return attr | [
"def",
"GetClassDefaultAttributes",
"(",
"self",
")",
":",
"attr",
"=",
"wx",
".",
"VisualAttributes",
"(",
")",
"attr",
".",
"colFg",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_WINDOWTEXT",
")",
"attr",
".",
"colBg",
"=",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_LISTBOX",
")",
"attr",
".",
"font",
"=",
"wx",
".",
"SystemSettings_GetFont",
"(",
"wx",
".",
"SYS_DEFAULT_GUI_FONT",
")",
"return",
"attr"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L4842-L4866 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/AudioEngineWwise/Tools/WwiseConfig/setup_wwise_config.py | python | get_matching_version_key | (project_version) | return version_key | Given a version string, match against all known installed versions of Wwise and return the version key.
:param project_version: Wwise project version string.
:return: A version key that closely matches the input version. | Given a version string, match against all known installed versions of Wwise and return the version key.
:param project_version: Wwise project version string.
:return: A version key that closely matches the input version. | [
"Given",
"a",
"version",
"string",
"match",
"against",
"all",
"known",
"installed",
"versions",
"of",
"Wwise",
"and",
"return",
"the",
"version",
"key",
".",
":",
"param",
"project_version",
":",
"Wwise",
"project",
"version",
"string",
".",
":",
"return",
":",
"A",
"version",
"key",
"that",
"closely",
"matches",
"the",
"input",
"version",
"."
] | def get_matching_version_key(project_version):
"""
Given a version string, match against all known installed versions of Wwise and return the version key.
:param project_version: Wwise project version string.
:return: A version key that closely matches the input version.
"""
installed_versions = [key for key in wwise_versions.keys() if 'ltx' not in key]
version_key = None
for ver in installed_versions:
if project_version[1:] in ver:
version_key = ver
break
return version_key | [
"def",
"get_matching_version_key",
"(",
"project_version",
")",
":",
"installed_versions",
"=",
"[",
"key",
"for",
"key",
"in",
"wwise_versions",
".",
"keys",
"(",
")",
"if",
"'ltx'",
"not",
"in",
"key",
"]",
"version_key",
"=",
"None",
"for",
"ver",
"in",
"installed_versions",
":",
"if",
"project_version",
"[",
"1",
":",
"]",
"in",
"ver",
":",
"version_key",
"=",
"ver",
"break",
"return",
"version_key"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/AudioEngineWwise/Tools/WwiseConfig/setup_wwise_config.py#L203-L216 | |
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/message.py | python | Message.IsInitialized | (self) | Checks if the message is initialized.
Returns:
The method returns True if the message is initialized (i.e. all of its
required fields are set). | Checks if the message is initialized. | [
"Checks",
"if",
"the",
"message",
"is",
"initialized",
"."
] | def IsInitialized(self):
"""Checks if the message is initialized.
Returns:
The method returns True if the message is initialized (i.e. all of its
required fields are set).
"""
raise NotImplementedError | [
"def",
"IsInitialized",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/message.py#L134-L141 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/RNN/rnn_quantizer/tensorflow/tf_nndct/utils/logging.py | python | _log_prefix | (level, timestamp=None, file_and_line=None) | return s | Generate a nndct logline prefix. | Generate a nndct logline prefix. | [
"Generate",
"a",
"nndct",
"logline",
"prefix",
"."
] | def _log_prefix(level, timestamp=None, file_and_line=None):
"""Generate a nndct logline prefix."""
# pylint: disable=global-variable-not-assigned
global _level_names
# pylint: enable=global-variable-not-assigned
# Record current time
now = timestamp or _time.time()
now_tuple = _time.localtime(now)
now_microsecond = int(1e6 * (now % 1.0))
(filename, line) = file_and_line or _get_file_and_line()
basename = _os.path.basename(filename)
# Severity string
severity = 'I'
if level in _level_names:
severity = _level_names[level][0]
# TODO(yuwang): Format by environment variable.
s = '%c%02d%02d %02d:%02d:%02d %s:%d]' % (
severity,
now_tuple[1], # month
now_tuple[2], # day
now_tuple[3], # hour
now_tuple[4], # min
now_tuple[5], # sec
basename,
line)
return s | [
"def",
"_log_prefix",
"(",
"level",
",",
"timestamp",
"=",
"None",
",",
"file_and_line",
"=",
"None",
")",
":",
"# pylint: disable=global-variable-not-assigned",
"global",
"_level_names",
"# pylint: enable=global-variable-not-assigned",
"# Record current time",
"now",
"=",
"timestamp",
"or",
"_time",
".",
"time",
"(",
")",
"now_tuple",
"=",
"_time",
".",
"localtime",
"(",
"now",
")",
"now_microsecond",
"=",
"int",
"(",
"1e6",
"*",
"(",
"now",
"%",
"1.0",
")",
")",
"(",
"filename",
",",
"line",
")",
"=",
"file_and_line",
"or",
"_get_file_and_line",
"(",
")",
"basename",
"=",
"_os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"# Severity string",
"severity",
"=",
"'I'",
"if",
"level",
"in",
"_level_names",
":",
"severity",
"=",
"_level_names",
"[",
"level",
"]",
"[",
"0",
"]",
"# TODO(yuwang): Format by environment variable.",
"s",
"=",
"'%c%02d%02d %02d:%02d:%02d %s:%d]'",
"%",
"(",
"severity",
",",
"now_tuple",
"[",
"1",
"]",
",",
"# month",
"now_tuple",
"[",
"2",
"]",
",",
"# day",
"now_tuple",
"[",
"3",
"]",
",",
"# hour",
"now_tuple",
"[",
"4",
"]",
",",
"# min",
"now_tuple",
"[",
"5",
"]",
",",
"# sec",
"basename",
",",
"line",
")",
"return",
"s"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/tensorflow/tf_nndct/utils/logging.py#L99-L129 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | _SwitchRefOrTensor | (data, pred, name="Switch") | Forwards `data` to an output determined by `pred`.
If `pred` is true, the `data` input is forwared to the first output.
Otherwise, the data goes to the second output.
This op handles `Tensor`s and `IndexedSlices`.
Args:
data: The tensor to be forwarded to the appropriate output.
pred: A scalar that specifies which output port will receive data.
name: A name for this operation (optional).
Returns:
`(output_false, output_false)`: If `pred` is true, data will be forwarded to
`output_true`, otherwise it goes to `output_false`.
Raises:
TypeError: if data is not a Tensor or IndexedSlices | Forwards `data` to an output determined by `pred`. | [
"Forwards",
"data",
"to",
"an",
"output",
"determined",
"by",
"pred",
"."
] | def _SwitchRefOrTensor(data, pred, name="Switch"):
"""Forwards `data` to an output determined by `pred`.
If `pred` is true, the `data` input is forwared to the first output.
Otherwise, the data goes to the second output.
This op handles `Tensor`s and `IndexedSlices`.
Args:
data: The tensor to be forwarded to the appropriate output.
pred: A scalar that specifies which output port will receive data.
name: A name for this operation (optional).
Returns:
`(output_false, output_false)`: If `pred` is true, data will be forwarded to
`output_true`, otherwise it goes to `output_false`.
Raises:
TypeError: if data is not a Tensor or IndexedSlices
"""
data = ops.convert_to_tensor_or_indexed_slices(data, name="data")
# NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below
# addresses the following scenario.
#
# Assume you execute Optimizer.apply_gradients() in a branch of a cond().
#
# 1. The update op is created inside a `with ops.colocate(var):` block
#
# 2. Some tensor `data` is captured and a switch is created in a
# `with ops.colocate_with(data):` block.
#
# with ops.colocate_with(var):
# with ops.colocate_with(data):
# op = ...
#
# var and data may be pinned to different devices, so we want to ops
# created within ops.colocate_with(data) to ignore the existing stack.
with ops.colocate_with(data, ignore_existing=True):
if isinstance(data, ops.Tensor):
if data.dtype.is_ref_dtype:
return ref_switch(data, pred, name=name)
return switch(data, pred, name=name) | [
"def",
"_SwitchRefOrTensor",
"(",
"data",
",",
"pred",
",",
"name",
"=",
"\"Switch\"",
")",
":",
"data",
"=",
"ops",
".",
"convert_to_tensor_or_indexed_slices",
"(",
"data",
",",
"name",
"=",
"\"data\"",
")",
"# NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below",
"# addresses the following scenario.",
"#",
"# Assume you execute Optimizer.apply_gradients() in a branch of a cond().",
"#",
"# 1. The update op is created inside a `with ops.colocate(var):` block",
"#",
"# 2. Some tensor `data` is captured and a switch is created in a",
"# `with ops.colocate_with(data):` block.",
"#",
"# with ops.colocate_with(var):",
"# with ops.colocate_with(data):",
"# op = ...",
"#",
"# var and data may be pinned to different devices, so we want to ops",
"# created within ops.colocate_with(data) to ignore the existing stack.",
"with",
"ops",
".",
"colocate_with",
"(",
"data",
",",
"ignore_existing",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"ops",
".",
"Tensor",
")",
":",
"if",
"data",
".",
"dtype",
".",
"is_ref_dtype",
":",
"return",
"ref_switch",
"(",
"data",
",",
"pred",
",",
"name",
"=",
"name",
")",
"return",
"switch",
"(",
"data",
",",
"pred",
",",
"name",
"=",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L285-L326 | ||
vxl/vxl | f7358571ada5a4b4823fb86976d55f8d6500ce64 | contrib/brl/bseg/boxm2/pyscripts/boxm2_uncertainty_adaptor.py | python | UncertainScene.compute_uncertainty | (self) | Store voxel uncertainty in cubic (float8) | Store voxel uncertainty in cubic (float8) | [
"Store",
"voxel",
"uncertainty",
"in",
"cubic",
"(",
"float8",
")"
] | def compute_uncertainty(self):
"""Store voxel uncertainty in cubic (float8) """
self.store_all_uncertainty_aux()
self.batch_uncertainty() | [
"def",
"compute_uncertainty",
"(",
"self",
")",
":",
"self",
".",
"store_all_uncertainty_aux",
"(",
")",
"self",
".",
"batch_uncertainty",
"(",
")"
] | https://github.com/vxl/vxl/blob/f7358571ada5a4b4823fb86976d55f8d6500ce64/contrib/brl/bseg/boxm2/pyscripts/boxm2_uncertainty_adaptor.py#L42-L45 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | Pen._SetDashes | (*args, **kwargs) | return _gdi_.Pen__SetDashes(*args, **kwargs) | _SetDashes(self, PyObject _self, PyObject pyDashes) | _SetDashes(self, PyObject _self, PyObject pyDashes) | [
"_SetDashes",
"(",
"self",
"PyObject",
"_self",
"PyObject",
"pyDashes",
")"
] | def _SetDashes(*args, **kwargs):
"""_SetDashes(self, PyObject _self, PyObject pyDashes)"""
return _gdi_.Pen__SetDashes(*args, **kwargs) | [
"def",
"_SetDashes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Pen__SetDashes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L453-L455 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | mojo/public/bindings/generators/mojom_js_generator.py | python | GetConstants | (module) | Returns a generator that enumerates all constants that can be referenced
from this module. | Returns a generator that enumerates all constants that can be referenced
from this module. | [
"Returns",
"a",
"generator",
"that",
"enumerates",
"all",
"constants",
"that",
"can",
"be",
"referenced",
"from",
"this",
"module",
"."
] | def GetConstants(module):
"""Returns a generator that enumerates all constants that can be referenced
from this module."""
class Constant:
pass
for enum in module.enums:
for field in enum.fields:
constant = Constant()
constant.namespace = module.namespace
constant.is_current_namespace = True
constant.import_item = None
constant.name = (enum.name, field.name)
yield constant
for each in module.imports:
for enum in each["module"].enums:
for field in enum.fields:
constant = Constant()
constant.namespace = each["namespace"]
constant.is_current_namespace = constant.namespace == module.namespace
constant.import_item = each
constant.name = (enum.name, field.name)
yield constant | [
"def",
"GetConstants",
"(",
"module",
")",
":",
"class",
"Constant",
":",
"pass",
"for",
"enum",
"in",
"module",
".",
"enums",
":",
"for",
"field",
"in",
"enum",
".",
"fields",
":",
"constant",
"=",
"Constant",
"(",
")",
"constant",
".",
"namespace",
"=",
"module",
".",
"namespace",
"constant",
".",
"is_current_namespace",
"=",
"True",
"constant",
".",
"import_item",
"=",
"None",
"constant",
".",
"name",
"=",
"(",
"enum",
".",
"name",
",",
"field",
".",
"name",
")",
"yield",
"constant",
"for",
"each",
"in",
"module",
".",
"imports",
":",
"for",
"enum",
"in",
"each",
"[",
"\"module\"",
"]",
".",
"enums",
":",
"for",
"field",
"in",
"enum",
".",
"fields",
":",
"constant",
"=",
"Constant",
"(",
")",
"constant",
".",
"namespace",
"=",
"each",
"[",
"\"namespace\"",
"]",
"constant",
".",
"is_current_namespace",
"=",
"constant",
".",
"namespace",
"==",
"module",
".",
"namespace",
"constant",
".",
"import_item",
"=",
"each",
"constant",
".",
"name",
"=",
"(",
"enum",
".",
"name",
",",
"field",
".",
"name",
")",
"yield",
"constant"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/mojo/public/bindings/generators/mojom_js_generator.py#L150-L173 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/inspect.py | python | iscode | (object) | return isinstance(object, types.CodeType) | Return true if the object is a code object.
Code objects provide these attributes:
co_argcount number of arguments (not including * or ** args)
co_code string of raw compiled bytecode
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
co_lnotab encoded mapping of line numbers to bytecode indices
co_name name with which this code object was defined
co_names tuple of names of local variables
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables | Return true if the object is a code object. | [
"Return",
"true",
"if",
"the",
"object",
"is",
"a",
"code",
"object",
"."
] | def iscode(object):
"""Return true if the object is a code object.
Code objects provide these attributes:
co_argcount number of arguments (not including * or ** args)
co_code string of raw compiled bytecode
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
co_lnotab encoded mapping of line numbers to bytecode indices
co_name name with which this code object was defined
co_names tuple of names of local variables
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables"""
return isinstance(object, types.CodeType) | [
"def",
"iscode",
"(",
"object",
")",
":",
"return",
"isinstance",
"(",
"object",
",",
"types",
".",
"CodeType",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/inspect.py#L209-L225 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeMemberFunction.GetDescription | (self, *args) | return _lldb.SBTypeMemberFunction_GetDescription(self, *args) | GetDescription(self, SBStream description, DescriptionLevel description_level) -> bool | GetDescription(self, SBStream description, DescriptionLevel description_level) -> bool | [
"GetDescription",
"(",
"self",
"SBStream",
"description",
"DescriptionLevel",
"description_level",
")",
"-",
">",
"bool"
] | def GetDescription(self, *args):
"""GetDescription(self, SBStream description, DescriptionLevel description_level) -> bool"""
return _lldb.SBTypeMemberFunction_GetDescription(self, *args) | [
"def",
"GetDescription",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBTypeMemberFunction_GetDescription",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L10244-L10246 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | SizerFlags.GetProportion | (*args, **kwargs) | return _core_.SizerFlags_GetProportion(*args, **kwargs) | GetProportion(self) -> int
Returns the proportion value to be used in the sizer item. | GetProportion(self) -> int | [
"GetProportion",
"(",
"self",
")",
"-",
">",
"int"
] | def GetProportion(*args, **kwargs):
"""
GetProportion(self) -> int
Returns the proportion value to be used in the sizer item.
"""
return _core_.SizerFlags_GetProportion(*args, **kwargs) | [
"def",
"GetProportion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerFlags_GetProportion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13927-L13933 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/streams.py | python | CommonTokenStream.fillBuffer | (self) | Load all tokens from the token source and put in tokens.
This is done upon first LT request because you might want to
set some token type / channel overrides before filling buffer. | Load all tokens from the token source and put in tokens.
This is done upon first LT request because you might want to
set some token type / channel overrides before filling buffer. | [
"Load",
"all",
"tokens",
"from",
"the",
"token",
"source",
"and",
"put",
"in",
"tokens",
".",
"This",
"is",
"done",
"upon",
"first",
"LT",
"request",
"because",
"you",
"might",
"want",
"to",
"set",
"some",
"token",
"type",
"/",
"channel",
"overrides",
"before",
"filling",
"buffer",
"."
] | def fillBuffer(self):
"""
Load all tokens from the token source and put in tokens.
This is done upon first LT request because you might want to
set some token type / channel overrides before filling buffer.
"""
index = 0
t = self.tokenSource.nextToken()
while t is not None and t.type != EOF:
discard = False
if self.discardSet is not None and t.type in self.discardSet:
discard = True
elif self.discardOffChannelTokens and t.channel != self.channel:
discard = True
# is there a channel override for token type?
try:
overrideChannel = self.channelOverrideMap[t.type]
except KeyError:
# no override for this type
pass
else:
if overrideChannel == self.channel:
t.channel = overrideChannel
else:
discard = True
if not discard:
t.index = index
self.tokens.append(t)
index += 1
t = self.tokenSource.nextToken()
# leave p pointing at first token on channel
self.p = 0
self.p = self.skipOffTokenChannels(self.p) | [
"def",
"fillBuffer",
"(",
"self",
")",
":",
"index",
"=",
"0",
"t",
"=",
"self",
".",
"tokenSource",
".",
"nextToken",
"(",
")",
"while",
"t",
"is",
"not",
"None",
"and",
"t",
".",
"type",
"!=",
"EOF",
":",
"discard",
"=",
"False",
"if",
"self",
".",
"discardSet",
"is",
"not",
"None",
"and",
"t",
".",
"type",
"in",
"self",
".",
"discardSet",
":",
"discard",
"=",
"True",
"elif",
"self",
".",
"discardOffChannelTokens",
"and",
"t",
".",
"channel",
"!=",
"self",
".",
"channel",
":",
"discard",
"=",
"True",
"# is there a channel override for token type?",
"try",
":",
"overrideChannel",
"=",
"self",
".",
"channelOverrideMap",
"[",
"t",
".",
"type",
"]",
"except",
"KeyError",
":",
"# no override for this type",
"pass",
"else",
":",
"if",
"overrideChannel",
"==",
"self",
".",
"channel",
":",
"t",
".",
"channel",
"=",
"overrideChannel",
"else",
":",
"discard",
"=",
"True",
"if",
"not",
"discard",
":",
"t",
".",
"index",
"=",
"index",
"self",
".",
"tokens",
".",
"append",
"(",
"t",
")",
"index",
"+=",
"1",
"t",
"=",
"self",
".",
"tokenSource",
".",
"nextToken",
"(",
")",
"# leave p pointing at first token on channel",
"self",
".",
"p",
"=",
"0",
"self",
".",
"p",
"=",
"self",
".",
"skipOffTokenChannels",
"(",
"self",
".",
"p",
")"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/streams.py#L660-L702 | ||
microsoft/Azure-Kinect-Sensor-SDK | d87ef578676c05b9a5d23c097502942753bf3777 | src/python/k4a/src/k4a/_bindings/device.py | python | Device.set_color_control | (
self,
color_ctrl_command:EColorControlCommand,
color_ctrl_mode:EColorControlMode,
color_ctrl_value:int) | return status | ! Set the Azure Kinect color sensor control value.
@param color_ctrl_command (EColorControlCommand): Color sensor control
command to set.
@param color_ctrl_mode (EColorControlMode): Color sensor control mode
to set. This mode represents whether the command is in automatic
or manual mode.
@param color_ctrl_value (int): The value to set the color sensor
control. The value is only valid if @p color_ctrl_mode is set to
EColorControlMode.MANUAL, and is otherwise ignored.
@returns EStatus.SUCCEEDED if successful, EStatus.FAILED otherwise.
@remarks
- Each control command may be set to manual or automatic. See
the definition of EColorControlCommand on how to interpret the
@p value for each command. | ! Set the Azure Kinect color sensor control value. | [
"!",
"Set",
"the",
"Azure",
"Kinect",
"color",
"sensor",
"control",
"value",
"."
] | def set_color_control(
self,
color_ctrl_command:EColorControlCommand,
color_ctrl_mode:EColorControlMode,
color_ctrl_value:int)->EStatus:
'''! Set the Azure Kinect color sensor control value.
@param color_ctrl_command (EColorControlCommand): Color sensor control
command to set.
@param color_ctrl_mode (EColorControlMode): Color sensor control mode
to set. This mode represents whether the command is in automatic
or manual mode.
@param color_ctrl_value (int): The value to set the color sensor
control. The value is only valid if @p color_ctrl_mode is set to
EColorControlMode.MANUAL, and is otherwise ignored.
@returns EStatus.SUCCEEDED if successful, EStatus.FAILED otherwise.
@remarks
- Each control command may be set to manual or automatic. See
the definition of EColorControlCommand on how to interpret the
@p value for each command.
'''
value = _ctypes.c_int32(color_ctrl_value)
command = _ctypes.c_int(color_ctrl_command.value)
mode = _ctypes.c_int(color_ctrl_mode.value)
status = k4a_device_set_color_control(
self.__device_handle,
command,
mode,
value)
return status | [
"def",
"set_color_control",
"(",
"self",
",",
"color_ctrl_command",
":",
"EColorControlCommand",
",",
"color_ctrl_mode",
":",
"EColorControlMode",
",",
"color_ctrl_value",
":",
"int",
")",
"->",
"EStatus",
":",
"value",
"=",
"_ctypes",
".",
"c_int32",
"(",
"color_ctrl_value",
")",
"command",
"=",
"_ctypes",
".",
"c_int",
"(",
"color_ctrl_command",
".",
"value",
")",
"mode",
"=",
"_ctypes",
".",
"c_int",
"(",
"color_ctrl_mode",
".",
"value",
")",
"status",
"=",
"k4a_device_set_color_control",
"(",
"self",
".",
"__device_handle",
",",
"command",
",",
"mode",
",",
"value",
")",
"return",
"status"
] | https://github.com/microsoft/Azure-Kinect-Sensor-SDK/blob/d87ef578676c05b9a5d23c097502942753bf3777/src/python/k4a/src/k4a/_bindings/device.py#L537-L573 | |
microsoft/LightGBM | 904b2d5158703c4900b68008617951dd2f9ff21b | python-package/lightgbm/basic.py | python | Dataset.create_valid | (self, data, label=None, weight=None, group=None, init_score=None, params=None) | return ret | Create validation data align with current Dataset.
Parameters
----------
data : str, pathlib.Path, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, Sequence, list of Sequence or list of numpy array
Data source of Dataset.
If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM) or a LightGBM Dataset binary file.
label : list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None)
Label of the data.
weight : list, numpy 1-D array, pandas Series or None, optional (default=None)
Weight for each instance.
group : list, numpy 1-D array, pandas Series or None, optional (default=None)
Group/query data.
Only used in the learning-to-rank task.
sum(group) = n_samples.
For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), or None, optional (default=None)
Init score for Dataset.
params : dict or None, optional (default=None)
Other parameters for validation Dataset.
Returns
-------
valid : Dataset
Validation Dataset with reference to self. | Create validation data align with current Dataset. | [
"Create",
"validation",
"data",
"align",
"with",
"current",
"Dataset",
"."
] | def create_valid(self, data, label=None, weight=None, group=None, init_score=None, params=None):
"""Create validation data align with current Dataset.
Parameters
----------
data : str, pathlib.Path, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, Sequence, list of Sequence or list of numpy array
Data source of Dataset.
If str or pathlib.Path, it represents the path to a text file (CSV, TSV, or LibSVM) or a LightGBM Dataset binary file.
label : list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None)
Label of the data.
weight : list, numpy 1-D array, pandas Series or None, optional (default=None)
Weight for each instance.
group : list, numpy 1-D array, pandas Series or None, optional (default=None)
Group/query data.
Only used in the learning-to-rank task.
sum(group) = n_samples.
For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
init_score : list, list of lists (for multi-class task), numpy array, pandas Series, pandas DataFrame (for multi-class task), or None, optional (default=None)
Init score for Dataset.
params : dict or None, optional (default=None)
Other parameters for validation Dataset.
Returns
-------
valid : Dataset
Validation Dataset with reference to self.
"""
ret = Dataset(data, label=label, reference=self,
weight=weight, group=group, init_score=init_score,
params=params, free_raw_data=self.free_raw_data)
ret._predictor = self._predictor
ret.pandas_categorical = self.pandas_categorical
return ret | [
"def",
"create_valid",
"(",
"self",
",",
"data",
",",
"label",
"=",
"None",
",",
"weight",
"=",
"None",
",",
"group",
"=",
"None",
",",
"init_score",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"ret",
"=",
"Dataset",
"(",
"data",
",",
"label",
"=",
"label",
",",
"reference",
"=",
"self",
",",
"weight",
"=",
"weight",
",",
"group",
"=",
"group",
",",
"init_score",
"=",
"init_score",
",",
"params",
"=",
"params",
",",
"free_raw_data",
"=",
"self",
".",
"free_raw_data",
")",
"ret",
".",
"_predictor",
"=",
"self",
".",
"_predictor",
"ret",
".",
"pandas_categorical",
"=",
"self",
".",
"pandas_categorical",
"return",
"ret"
] | https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/basic.py#L1809-L1842 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/summary/impl/io_wrapper.py | python | ListRecursively | (top) | Walks a directory tree, yielding (dir_path, file_paths) tuples.
For each of `top` and its subdirectories, yields a tuple containing the path
to the directory and the path to each of the contained files. Note that
unlike os.Walk()/gfile.Walk(), this does not list subdirectories and the file
paths are all absolute.
If the directory does not exist, this yields nothing.
Args:
top: A path to a directory..
Yields:
A list of (dir_path, file_paths) tuples. | Walks a directory tree, yielding (dir_path, file_paths) tuples. | [
"Walks",
"a",
"directory",
"tree",
"yielding",
"(",
"dir_path",
"file_paths",
")",
"tuples",
"."
] | def ListRecursively(top):
"""Walks a directory tree, yielding (dir_path, file_paths) tuples.
For each of `top` and its subdirectories, yields a tuple containing the path
to the directory and the path to each of the contained files. Note that
unlike os.Walk()/gfile.Walk(), this does not list subdirectories and the file
paths are all absolute.
If the directory does not exist, this yields nothing.
Args:
top: A path to a directory..
Yields:
A list of (dir_path, file_paths) tuples.
"""
if gcs.IsGCSPath(top):
for x in gcs.ListRecursively(top):
yield x
else:
for dir_path, _, filenames in gfile.Walk(top):
yield (dir_path, (os.path.join(dir_path, filename)
for filename in filenames)) | [
"def",
"ListRecursively",
"(",
"top",
")",
":",
"if",
"gcs",
".",
"IsGCSPath",
"(",
"top",
")",
":",
"for",
"x",
"in",
"gcs",
".",
"ListRecursively",
"(",
"top",
")",
":",
"yield",
"x",
"else",
":",
"for",
"dir_path",
",",
"_",
",",
"filenames",
"in",
"gfile",
".",
"Walk",
"(",
"top",
")",
":",
"yield",
"(",
"dir_path",
",",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"filename",
")",
"for",
"filename",
"in",
"filenames",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/impl/io_wrapper.py#L57-L78 | ||
chuckcho/video-caffe | fc232b3e3a90ea22dd041b9fc5c542f170581f20 | scripts/cpp_lint.py | python | PrintUsage | (message) | Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message. | Prints a brief usage string and exits, optionally with an error message. | [
"Prints",
"a",
"brief",
"usage",
"string",
"and",
"exits",
"optionally",
"with",
"an",
"error",
"message",
"."
] | def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1) | [
"def",
"PrintUsage",
"(",
"message",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"_USAGE",
")",
"if",
"message",
":",
"sys",
".",
"exit",
"(",
"'\\nFATAL ERROR: '",
"+",
"message",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/scripts/cpp_lint.py#L4763-L4773 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeCategory.GetLanguageAtIndex | (self, *args) | return _lldb.SBTypeCategory_GetLanguageAtIndex(self, *args) | GetLanguageAtIndex(self, uint32_t idx) -> LanguageType | GetLanguageAtIndex(self, uint32_t idx) -> LanguageType | [
"GetLanguageAtIndex",
"(",
"self",
"uint32_t",
"idx",
")",
"-",
">",
"LanguageType"
] | def GetLanguageAtIndex(self, *args):
"""GetLanguageAtIndex(self, uint32_t idx) -> LanguageType"""
return _lldb.SBTypeCategory_GetLanguageAtIndex(self, *args) | [
"def",
"GetLanguageAtIndex",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBTypeCategory_GetLanguageAtIndex",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L10752-L10754 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/email/charset.py | python | Charset.convert | (self, s) | Convert a string from the input_codec to the output_codec. | Convert a string from the input_codec to the output_codec. | [
"Convert",
"a",
"string",
"from",
"the",
"input_codec",
"to",
"the",
"output_codec",
"."
] | def convert(self, s):
"""Convert a string from the input_codec to the output_codec."""
if self.input_codec != self.output_codec:
return unicode(s, self.input_codec).encode(self.output_codec)
else:
return s | [
"def",
"convert",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"input_codec",
"!=",
"self",
".",
"output_codec",
":",
"return",
"unicode",
"(",
"s",
",",
"self",
".",
"input_codec",
")",
".",
"encode",
"(",
"self",
".",
"output_codec",
")",
"else",
":",
"return",
"s"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/email/charset.py#L264-L269 | ||
BestSonny/SSTD | 174d452189f6bf9cf4b6957719392008bd974069 | python/caffe/io.py | python | Transformer.set_input_scale | (self, in_, scale) | Set the scale of preprocessed inputs s.t. the blob = blob * scale.
N.B. input_scale is done AFTER mean subtraction and other preprocessing
while raw_scale is done BEFORE.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient | Set the scale of preprocessed inputs s.t. the blob = blob * scale.
N.B. input_scale is done AFTER mean subtraction and other preprocessing
while raw_scale is done BEFORE. | [
"Set",
"the",
"scale",
"of",
"preprocessed",
"inputs",
"s",
".",
"t",
".",
"the",
"blob",
"=",
"blob",
"*",
"scale",
".",
"N",
".",
"B",
".",
"input_scale",
"is",
"done",
"AFTER",
"mean",
"subtraction",
"and",
"other",
"preprocessing",
"while",
"raw_scale",
"is",
"done",
"BEFORE",
"."
] | def set_input_scale(self, in_, scale):
"""
Set the scale of preprocessed inputs s.t. the blob = blob * scale.
N.B. input_scale is done AFTER mean subtraction and other preprocessing
while raw_scale is done BEFORE.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.input_scale[in_] = scale | [
"def",
"set_input_scale",
"(",
"self",
",",
"in_",
",",
"scale",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"self",
".",
"input_scale",
"[",
"in_",
"]",
"=",
"scale"
] | https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/python/caffe/io.py#L262-L274 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | Geometry3D.setCollisionMargin | (self, margin) | return _robotsim.Geometry3D_setCollisionMargin(self, margin) | setCollisionMargin(Geometry3D self, double margin)
Sets a padding around the base geometry which affects the results of proximity
queries. | setCollisionMargin(Geometry3D self, double margin) | [
"setCollisionMargin",
"(",
"Geometry3D",
"self",
"double",
"margin",
")"
] | def setCollisionMargin(self, margin):
"""
setCollisionMargin(Geometry3D self, double margin)
Sets a padding around the base geometry which affects the results of proximity
queries.
"""
return _robotsim.Geometry3D_setCollisionMargin(self, margin) | [
"def",
"setCollisionMargin",
"(",
"self",
",",
"margin",
")",
":",
"return",
"_robotsim",
".",
"Geometry3D_setCollisionMargin",
"(",
"self",
",",
"margin",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L2223-L2233 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/fx/experimental/fx_acc/acc_ops.py | python | packed_quantized_convrelu2d_mapper | (
node: torch.fx.Node, mod: nn.Module
) | Mapping from quantized ConvReLU2d module to acc_op.relu. We use packed_quantized_conv2d_mapper to unpack all the parameters
in this mapper and pass the returned conv2d node directly to relu node. | Mapping from quantized ConvReLU2d module to acc_op.relu. We use packed_quantized_conv2d_mapper to unpack all the parameters
in this mapper and pass the returned conv2d node directly to relu node. | [
"Mapping",
"from",
"quantized",
"ConvReLU2d",
"module",
"to",
"acc_op",
".",
"relu",
".",
"We",
"use",
"packed_quantized_conv2d_mapper",
"to",
"unpack",
"all",
"the",
"parameters",
"in",
"this",
"mapper",
"and",
"pass",
"the",
"returned",
"conv2d",
"node",
"directly",
"to",
"relu",
"node",
"."
] | def packed_quantized_convrelu2d_mapper(
node: torch.fx.Node, mod: nn.Module
) -> torch.fx.Node:
"""
Mapping from quantized ConvReLU2d module to acc_op.relu. We use packed_quantized_conv2d_mapper to unpack all the parameters
in this mapper and pass the returned conv2d node directly to relu node.
"""
with node.graph.inserting_before(node):
# conv2d op
conv2d_node = packed_quantized_conv2d_mapper(node, mod)
# relu op
relu_node = node.graph.call_function(
relu, kwargs={"input": conv2d_node, "inplace": False}
)
relu_node.meta = node.meta
return relu_node | [
"def",
"packed_quantized_convrelu2d_mapper",
"(",
"node",
":",
"torch",
".",
"fx",
".",
"Node",
",",
"mod",
":",
"nn",
".",
"Module",
")",
"->",
"torch",
".",
"fx",
".",
"Node",
":",
"with",
"node",
".",
"graph",
".",
"inserting_before",
"(",
"node",
")",
":",
"# conv2d op",
"conv2d_node",
"=",
"packed_quantized_conv2d_mapper",
"(",
"node",
",",
"mod",
")",
"# relu op",
"relu_node",
"=",
"node",
".",
"graph",
".",
"call_function",
"(",
"relu",
",",
"kwargs",
"=",
"{",
"\"input\"",
":",
"conv2d_node",
",",
"\"inplace\"",
":",
"False",
"}",
")",
"relu_node",
".",
"meta",
"=",
"node",
".",
"meta",
"return",
"relu_node"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/fx_acc/acc_ops.py#L1883-L1900 | ||
NVlabs/fermat | 06e8c03ac59ab440cbb13897f90631ef1861e769 | contrib/assimp-4.1.0/port/PyAssimp/scripts/transformations.py | python | superimposition_matrix | (v0, v1, scaling=False, usesvd=True) | return M | Return matrix to transform given vector set into second vector set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors.
If usesvd is True, the weighted sum of squared deviations (RMSD) is
minimized according to the algorithm by W. Kabsch [8]. Otherwise the
quaternion based algorithm by B. Horn [9] is used (slower when using
this Python implementation).
The returned matrix performs rotation, translation and uniform scaling
(if specified).
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1))
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0
>>> v0[3] = 1.0
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scaling=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3), dtype=numpy.float64)
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True | Return matrix to transform given vector set into second vector set. | [
"Return",
"matrix",
"to",
"transform",
"given",
"vector",
"set",
"into",
"second",
"vector",
"set",
"."
] | def superimposition_matrix(v0, v1, scaling=False, usesvd=True):
"""Return matrix to transform given vector set into second vector set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors.
If usesvd is True, the weighted sum of squared deviations (RMSD) is
minimized according to the algorithm by W. Kabsch [8]. Otherwise the
quaternion based algorithm by B. Horn [9] is used (slower when using
this Python implementation).
The returned matrix performs rotation, translation and uniform scaling
(if specified).
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1))
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0
>>> v0[3] = 1.0
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scaling=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3), dtype=numpy.float64)
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3]
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3]
if v0.shape != v1.shape or v0.shape[1] < 3:
raise ValueError("Vector sets are of wrong shape or type.")
# move centroids to origin
t0 = numpy.mean(v0, axis=1)
t1 = numpy.mean(v1, axis=1)
v0 = v0 - t0.reshape(3, 1)
v1 = v1 - t1.reshape(3, 1)
if usesvd:
# Singular Value Decomposition of covariance matrix
u, s, vh = numpy.linalg.svd(numpy.dot(v1, v0.T))
# rotation matrix from SVD orthonormal bases
R = numpy.dot(u, vh)
if numpy.linalg.det(R) < 0.0:
# R does not constitute right handed system
R -= numpy.outer(u[:, 2], vh[2, :]*2.0)
s[-1] *= -1.0
# homogeneous transformation matrix
M = numpy.identity(4)
M[:3, :3] = R
else:
# compute symmetric matrix N
xx, yy, zz = numpy.sum(v0 * v1, axis=1)
xy, yz, zx = numpy.sum(v0 * numpy.roll(v1, -1, axis=0), axis=1)
xz, yx, zy = numpy.sum(v0 * numpy.roll(v1, -2, axis=0), axis=1)
N = ((xx+yy+zz, yz-zy, zx-xz, xy-yx),
(yz-zy, xx-yy-zz, xy+yx, zx+xz),
(zx-xz, xy+yx, -xx+yy-zz, yz+zy),
(xy-yx, zx+xz, yz+zy, -xx-yy+zz))
# quaternion: eigenvector corresponding to most positive eigenvalue
l, V = numpy.linalg.eig(N)
q = V[:, numpy.argmax(l)]
q /= vector_norm(q) # unit quaternion
q = numpy.roll(q, -1) # move w component to end
# homogeneous transformation matrix
M = quaternion_matrix(q)
# scale: ratio of rms deviations from centroid
if scaling:
v0 *= v0
v1 *= v1
M[:3, :3] *= math.sqrt(numpy.sum(v1) / numpy.sum(v0))
# translation
M[:3, 3] = t1
T = numpy.identity(4)
T[:3, 3] = -t0
M = numpy.dot(M, T)
return M | [
"def",
"superimposition_matrix",
"(",
"v0",
",",
"v1",
",",
"scaling",
"=",
"False",
",",
"usesvd",
"=",
"True",
")",
":",
"v0",
"=",
"numpy",
".",
"array",
"(",
"v0",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"[",
":",
"3",
"]",
"v1",
"=",
"numpy",
".",
"array",
"(",
"v1",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"[",
":",
"3",
"]",
"if",
"v0",
".",
"shape",
"!=",
"v1",
".",
"shape",
"or",
"v0",
".",
"shape",
"[",
"1",
"]",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"\"Vector sets are of wrong shape or type.\"",
")",
"# move centroids to origin",
"t0",
"=",
"numpy",
".",
"mean",
"(",
"v0",
",",
"axis",
"=",
"1",
")",
"t1",
"=",
"numpy",
".",
"mean",
"(",
"v1",
",",
"axis",
"=",
"1",
")",
"v0",
"=",
"v0",
"-",
"t0",
".",
"reshape",
"(",
"3",
",",
"1",
")",
"v1",
"=",
"v1",
"-",
"t1",
".",
"reshape",
"(",
"3",
",",
"1",
")",
"if",
"usesvd",
":",
"# Singular Value Decomposition of covariance matrix",
"u",
",",
"s",
",",
"vh",
"=",
"numpy",
".",
"linalg",
".",
"svd",
"(",
"numpy",
".",
"dot",
"(",
"v1",
",",
"v0",
".",
"T",
")",
")",
"# rotation matrix from SVD orthonormal bases",
"R",
"=",
"numpy",
".",
"dot",
"(",
"u",
",",
"vh",
")",
"if",
"numpy",
".",
"linalg",
".",
"det",
"(",
"R",
")",
"<",
"0.0",
":",
"# R does not constitute right handed system",
"R",
"-=",
"numpy",
".",
"outer",
"(",
"u",
"[",
":",
",",
"2",
"]",
",",
"vh",
"[",
"2",
",",
":",
"]",
"*",
"2.0",
")",
"s",
"[",
"-",
"1",
"]",
"*=",
"-",
"1.0",
"# homogeneous transformation matrix",
"M",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"M",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"R",
"else",
":",
"# compute symmetric matrix N",
"xx",
",",
"yy",
",",
"zz",
"=",
"numpy",
".",
"sum",
"(",
"v0",
"*",
"v1",
",",
"axis",
"=",
"1",
")",
"xy",
",",
"yz",
",",
"zx",
"=",
"numpy",
".",
"sum",
"(",
"v0",
"*",
"numpy",
".",
"roll",
"(",
"v1",
",",
"-",
"1",
",",
"axis",
"=",
"0",
")",
",",
"axis",
"=",
"1",
")",
"xz",
",",
"yx",
",",
"zy",
"=",
"numpy",
".",
"sum",
"(",
"v0",
"*",
"numpy",
".",
"roll",
"(",
"v1",
",",
"-",
"2",
",",
"axis",
"=",
"0",
")",
",",
"axis",
"=",
"1",
")",
"N",
"=",
"(",
"(",
"xx",
"+",
"yy",
"+",
"zz",
",",
"yz",
"-",
"zy",
",",
"zx",
"-",
"xz",
",",
"xy",
"-",
"yx",
")",
",",
"(",
"yz",
"-",
"zy",
",",
"xx",
"-",
"yy",
"-",
"zz",
",",
"xy",
"+",
"yx",
",",
"zx",
"+",
"xz",
")",
",",
"(",
"zx",
"-",
"xz",
",",
"xy",
"+",
"yx",
",",
"-",
"xx",
"+",
"yy",
"-",
"zz",
",",
"yz",
"+",
"zy",
")",
",",
"(",
"xy",
"-",
"yx",
",",
"zx",
"+",
"xz",
",",
"yz",
"+",
"zy",
",",
"-",
"xx",
"-",
"yy",
"+",
"zz",
")",
")",
"# quaternion: eigenvector corresponding to most positive eigenvalue",
"l",
",",
"V",
"=",
"numpy",
".",
"linalg",
".",
"eig",
"(",
"N",
")",
"q",
"=",
"V",
"[",
":",
",",
"numpy",
".",
"argmax",
"(",
"l",
")",
"]",
"q",
"/=",
"vector_norm",
"(",
"q",
")",
"# unit quaternion",
"q",
"=",
"numpy",
".",
"roll",
"(",
"q",
",",
"-",
"1",
")",
"# move w component to end",
"# homogeneous transformation matrix",
"M",
"=",
"quaternion_matrix",
"(",
"q",
")",
"# scale: ratio of rms deviations from centroid",
"if",
"scaling",
":",
"v0",
"*=",
"v0",
"v1",
"*=",
"v1",
"M",
"[",
":",
"3",
",",
":",
"3",
"]",
"*=",
"math",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"v1",
")",
"/",
"numpy",
".",
"sum",
"(",
"v0",
")",
")",
"# translation",
"M",
"[",
":",
"3",
",",
"3",
"]",
"=",
"t1",
"T",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"T",
"[",
":",
"3",
",",
"3",
"]",
"=",
"-",
"t0",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"T",
")",
"return",
"M"
] | https://github.com/NVlabs/fermat/blob/06e8c03ac59ab440cbb13897f90631ef1861e769/contrib/assimp-4.1.0/port/PyAssimp/scripts/transformations.py#L866-L965 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | TypeHandler.WriteImmediateServiceUnitTest | (self, func, file) | Writes the service unit test for an immediate command. | Writes the service unit test for an immediate command. | [
"Writes",
"the",
"service",
"unit",
"test",
"for",
"an",
"immediate",
"command",
"."
] | def WriteImmediateServiceUnitTest(self, func, file):
"""Writes the service unit test for an immediate command."""
file.Write("// TODO(gman): %s\n" % func.name) | [
"def",
"WriteImmediateServiceUnitTest",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"file",
".",
"Write",
"(",
"\"// TODO(gman): %s\\n\"",
"%",
"func",
".",
"name",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L2999-L3001 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py | python | Pdb.do_whatis | (self, arg) | whatis arg
Print the type of the argument. | whatis arg
Print the type of the argument. | [
"whatis",
"arg",
"Print",
"the",
"type",
"of",
"the",
"argument",
"."
] | def do_whatis(self, arg):
"""whatis arg
Print the type of the argument.
"""
try:
value = self._getval(arg)
except:
# _getval() already printed the error
return
code = None
# Is it a function?
try:
code = value.__code__
except Exception:
pass
if code:
self.message('Function %s' % code.co_name)
return
# Is it an instance method?
try:
code = value.__func__.__code__
except Exception:
pass
if code:
self.message('Method %s' % code.co_name)
return
# Is it a class?
if value.__class__ is type:
self.message('Class %s.%s' % (value.__module__, value.__qualname__))
return
# None of the above...
self.message(type(value)) | [
"def",
"do_whatis",
"(",
"self",
",",
"arg",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_getval",
"(",
"arg",
")",
"except",
":",
"# _getval() already printed the error",
"return",
"code",
"=",
"None",
"# Is it a function?",
"try",
":",
"code",
"=",
"value",
".",
"__code__",
"except",
"Exception",
":",
"pass",
"if",
"code",
":",
"self",
".",
"message",
"(",
"'Function %s'",
"%",
"code",
".",
"co_name",
")",
"return",
"# Is it an instance method?",
"try",
":",
"code",
"=",
"value",
".",
"__func__",
".",
"__code__",
"except",
"Exception",
":",
"pass",
"if",
"code",
":",
"self",
".",
"message",
"(",
"'Method %s'",
"%",
"code",
".",
"co_name",
")",
"return",
"# Is it a class?",
"if",
"value",
".",
"__class__",
"is",
"type",
":",
"self",
".",
"message",
"(",
"'Class %s.%s'",
"%",
"(",
"value",
".",
"__module__",
",",
"value",
".",
"__qualname__",
")",
")",
"return",
"# None of the above...",
"self",
".",
"message",
"(",
"type",
"(",
"value",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py#L1299-L1330 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset8/ops.py | python | multiclass_nms | (
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
iou_threshold: float = 0.0,
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True
) | return _get_node_factory_opset8().create("MulticlassNms", inputs, attributes) | Return a node which performs MulticlassNms.
@param boxes: Tensor with box coordinates.
@param scores: Tensor with box scores.
@param sort_result_type: Specifies order of output elements, possible values:
'class': sort selected boxes by class id (ascending)
'score': sort selected boxes by score (descending)
'none': do not guarantee the order.
@param sort_result_across_batch: Specifies whenever it is necessary to sort selected boxes
across batches or not
@param output_type: Specifies the output tensor type, possible values:
'i64', 'i32'
@param iou_threshold: Specifies intersection over union threshold
@param score_threshold: Specifies minimum score to consider box for the processing
@param nms_top_k: Specifies maximum number of boxes to be selected per class, -1 meaning
to keep all boxes
@param keep_top_k: Specifies maximum number of boxes to be selected per batch element, -1
meaning to keep all boxes
@param background_class: Specifies the background class id, -1 meaning to keep all classes
@param nms_eta: Specifies eta parameter for adpative NMS, in close range [0, 1.0]
@param normalized: Specifies whether boxes are normalized or not
@return: The new node which performs MuticlassNms | Return a node which performs MulticlassNms. | [
"Return",
"a",
"node",
"which",
"performs",
"MulticlassNms",
"."
] | def multiclass_nms(
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
iou_threshold: float = 0.0,
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True
) -> Node:
"""Return a node which performs MulticlassNms.
@param boxes: Tensor with box coordinates.
@param scores: Tensor with box scores.
@param sort_result_type: Specifies order of output elements, possible values:
'class': sort selected boxes by class id (ascending)
'score': sort selected boxes by score (descending)
'none': do not guarantee the order.
@param sort_result_across_batch: Specifies whenever it is necessary to sort selected boxes
across batches or not
@param output_type: Specifies the output tensor type, possible values:
'i64', 'i32'
@param iou_threshold: Specifies intersection over union threshold
@param score_threshold: Specifies minimum score to consider box for the processing
@param nms_top_k: Specifies maximum number of boxes to be selected per class, -1 meaning
to keep all boxes
@param keep_top_k: Specifies maximum number of boxes to be selected per batch element, -1
meaning to keep all boxes
@param background_class: Specifies the background class id, -1 meaning to keep all classes
@param nms_eta: Specifies eta parameter for adpative NMS, in close range [0, 1.0]
@param normalized: Specifies whether boxes are normalized or not
@return: The new node which performs MuticlassNms
"""
inputs = as_nodes(boxes, scores)
attributes = {
"sort_result_type": sort_result_type,
"sort_result_across_batch": sort_result_across_batch,
"output_type": output_type,
"iou_threshold": iou_threshold,
"score_threshold": score_threshold,
"nms_top_k": nms_top_k,
"keep_top_k": keep_top_k,
"background_class": background_class,
"nms_eta": nms_eta,
"normalized": normalized
}
return _get_node_factory_opset8().create("MulticlassNms", inputs, attributes) | [
"def",
"multiclass_nms",
"(",
"boxes",
":",
"NodeInput",
",",
"scores",
":",
"NodeInput",
",",
"sort_result_type",
":",
"str",
"=",
"\"none\"",
",",
"sort_result_across_batch",
":",
"bool",
"=",
"False",
",",
"output_type",
":",
"str",
"=",
"\"i64\"",
",",
"iou_threshold",
":",
"float",
"=",
"0.0",
",",
"score_threshold",
":",
"float",
"=",
"0.0",
",",
"nms_top_k",
":",
"int",
"=",
"-",
"1",
",",
"keep_top_k",
":",
"int",
"=",
"-",
"1",
",",
"background_class",
":",
"int",
"=",
"-",
"1",
",",
"nms_eta",
":",
"float",
"=",
"1.0",
",",
"normalized",
":",
"bool",
"=",
"True",
")",
"->",
"Node",
":",
"inputs",
"=",
"as_nodes",
"(",
"boxes",
",",
"scores",
")",
"attributes",
"=",
"{",
"\"sort_result_type\"",
":",
"sort_result_type",
",",
"\"sort_result_across_batch\"",
":",
"sort_result_across_batch",
",",
"\"output_type\"",
":",
"output_type",
",",
"\"iou_threshold\"",
":",
"iou_threshold",
",",
"\"score_threshold\"",
":",
"score_threshold",
",",
"\"nms_top_k\"",
":",
"nms_top_k",
",",
"\"keep_top_k\"",
":",
"keep_top_k",
",",
"\"background_class\"",
":",
"background_class",
",",
"\"nms_eta\"",
":",
"nms_eta",
",",
"\"normalized\"",
":",
"normalized",
"}",
"return",
"_get_node_factory_opset8",
"(",
")",
".",
"create",
"(",
"\"MulticlassNms\"",
",",
"inputs",
",",
"attributes",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset8/ops.py#L130-L182 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py | python | Doxypy.appendCommentLine | (self, match) | Appends a comment line.
The comment delimiter is removed from multiline start and ends as
well as singleline comments. | Appends a comment line. | [
"Appends",
"a",
"comment",
"line",
"."
] | def appendCommentLine(self, match):
"""Appends a comment line.
The comment delimiter is removed from multiline start and ends as
well as singleline comments.
"""
if args.debug:
print("# CALLBACK: appendCommentLine", file=sys.stderr)
(from_state, to_state, condition, callback) = self.fsm.current_transition
# single line comment
if (from_state == "DEFCLASS" and to_state == "DEFCLASS_BODY") \
or (from_state == "FILEHEAD" and to_state == "FILEHEAD"):
# remove comment delimiter from begin and end of the line
activeCommentDelim = match.group(1)
line = self.fsm.current_input
self.comment.append(line[line.find(
activeCommentDelim) + len(activeCommentDelim):line.rfind(activeCommentDelim)])
if (to_state == "DEFCLASS_BODY"):
self.__closeComment()
self.defclass = []
# multiline start
elif from_state == "DEFCLASS" or from_state == "FILEHEAD":
# remove comment delimiter from begin of the line
activeCommentDelim = match.group(1)
line = self.fsm.current_input
self.comment.append(
line[line.find(activeCommentDelim) + len(activeCommentDelim):])
# multiline end
elif to_state == "DEFCLASS_BODY" or to_state == "FILEHEAD":
# remove comment delimiter from end of the line
activeCommentDelim = match.group(1)
line = self.fsm.current_input
self.comment.append(line[0:line.rfind(activeCommentDelim)])
if (to_state == "DEFCLASS_BODY"):
self.__closeComment()
self.defclass = []
# in multiline comment
else:
# just append the comment line
self.comment.append(self.fsm.current_input) | [
"def",
"appendCommentLine",
"(",
"self",
",",
"match",
")",
":",
"if",
"args",
".",
"debug",
":",
"print",
"(",
"\"# CALLBACK: appendCommentLine\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"(",
"from_state",
",",
"to_state",
",",
"condition",
",",
"callback",
")",
"=",
"self",
".",
"fsm",
".",
"current_transition",
"# single line comment",
"if",
"(",
"from_state",
"==",
"\"DEFCLASS\"",
"and",
"to_state",
"==",
"\"DEFCLASS_BODY\"",
")",
"or",
"(",
"from_state",
"==",
"\"FILEHEAD\"",
"and",
"to_state",
"==",
"\"FILEHEAD\"",
")",
":",
"# remove comment delimiter from begin and end of the line",
"activeCommentDelim",
"=",
"match",
".",
"group",
"(",
"1",
")",
"line",
"=",
"self",
".",
"fsm",
".",
"current_input",
"self",
".",
"comment",
".",
"append",
"(",
"line",
"[",
"line",
".",
"find",
"(",
"activeCommentDelim",
")",
"+",
"len",
"(",
"activeCommentDelim",
")",
":",
"line",
".",
"rfind",
"(",
"activeCommentDelim",
")",
"]",
")",
"if",
"(",
"to_state",
"==",
"\"DEFCLASS_BODY\"",
")",
":",
"self",
".",
"__closeComment",
"(",
")",
"self",
".",
"defclass",
"=",
"[",
"]",
"# multiline start",
"elif",
"from_state",
"==",
"\"DEFCLASS\"",
"or",
"from_state",
"==",
"\"FILEHEAD\"",
":",
"# remove comment delimiter from begin of the line",
"activeCommentDelim",
"=",
"match",
".",
"group",
"(",
"1",
")",
"line",
"=",
"self",
".",
"fsm",
".",
"current_input",
"self",
".",
"comment",
".",
"append",
"(",
"line",
"[",
"line",
".",
"find",
"(",
"activeCommentDelim",
")",
"+",
"len",
"(",
"activeCommentDelim",
")",
":",
"]",
")",
"# multiline end",
"elif",
"to_state",
"==",
"\"DEFCLASS_BODY\"",
"or",
"to_state",
"==",
"\"FILEHEAD\"",
":",
"# remove comment delimiter from end of the line",
"activeCommentDelim",
"=",
"match",
".",
"group",
"(",
"1",
")",
"line",
"=",
"self",
".",
"fsm",
".",
"current_input",
"self",
".",
"comment",
".",
"append",
"(",
"line",
"[",
"0",
":",
"line",
".",
"rfind",
"(",
"activeCommentDelim",
")",
"]",
")",
"if",
"(",
"to_state",
"==",
"\"DEFCLASS_BODY\"",
")",
":",
"self",
".",
"__closeComment",
"(",
")",
"self",
".",
"defclass",
"=",
"[",
"]",
"# in multiline comment",
"else",
":",
"# just append the comment line",
"self",
".",
"comment",
".",
"append",
"(",
"self",
".",
"fsm",
".",
"current_input",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py#L304-L345 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/perf/metrics/histogram_util.py | python | SubtractHistogram | (histogram_json, start_histogram_json) | return json.dumps(histogram) | Subtracts a previous histogram from a histogram.
Both parameters and the returned result are json serializations. | Subtracts a previous histogram from a histogram. | [
"Subtracts",
"a",
"previous",
"histogram",
"from",
"a",
"histogram",
"."
] | def SubtractHistogram(histogram_json, start_histogram_json):
"""Subtracts a previous histogram from a histogram.
Both parameters and the returned result are json serializations.
"""
start_histogram = json.loads(start_histogram_json)
# It's ok if the start histogram is empty (we had no data, maybe even no
# histogram at all, at the start of the test).
if 'buckets' not in start_histogram:
return histogram_json
histogram = json.loads(histogram_json)
if ('pid' in start_histogram and 'pid' in histogram
and start_histogram['pid'] != histogram['pid']):
raise Exception(
'Trying to compare histograms from different processes (%d and %d)'
% (start_histogram['pid'], histogram['pid']))
start_histogram_buckets = dict()
for b in start_histogram['buckets']:
start_histogram_buckets[b['low']] = b['count']
new_buckets = []
for b in histogram['buckets']:
new_bucket = b
low = b['low']
if low in start_histogram_buckets:
new_bucket['count'] = b['count'] - start_histogram_buckets[low]
if new_bucket['count'] < 0:
logging.error('Histogram subtraction error, starting histogram most '
'probably invalid.')
if new_bucket['count']:
new_buckets.append(new_bucket)
histogram['buckets'] = new_buckets
histogram['count'] -= start_histogram['count']
return json.dumps(histogram) | [
"def",
"SubtractHistogram",
"(",
"histogram_json",
",",
"start_histogram_json",
")",
":",
"start_histogram",
"=",
"json",
".",
"loads",
"(",
"start_histogram_json",
")",
"# It's ok if the start histogram is empty (we had no data, maybe even no",
"# histogram at all, at the start of the test).",
"if",
"'buckets'",
"not",
"in",
"start_histogram",
":",
"return",
"histogram_json",
"histogram",
"=",
"json",
".",
"loads",
"(",
"histogram_json",
")",
"if",
"(",
"'pid'",
"in",
"start_histogram",
"and",
"'pid'",
"in",
"histogram",
"and",
"start_histogram",
"[",
"'pid'",
"]",
"!=",
"histogram",
"[",
"'pid'",
"]",
")",
":",
"raise",
"Exception",
"(",
"'Trying to compare histograms from different processes (%d and %d)'",
"%",
"(",
"start_histogram",
"[",
"'pid'",
"]",
",",
"histogram",
"[",
"'pid'",
"]",
")",
")",
"start_histogram_buckets",
"=",
"dict",
"(",
")",
"for",
"b",
"in",
"start_histogram",
"[",
"'buckets'",
"]",
":",
"start_histogram_buckets",
"[",
"b",
"[",
"'low'",
"]",
"]",
"=",
"b",
"[",
"'count'",
"]",
"new_buckets",
"=",
"[",
"]",
"for",
"b",
"in",
"histogram",
"[",
"'buckets'",
"]",
":",
"new_bucket",
"=",
"b",
"low",
"=",
"b",
"[",
"'low'",
"]",
"if",
"low",
"in",
"start_histogram_buckets",
":",
"new_bucket",
"[",
"'count'",
"]",
"=",
"b",
"[",
"'count'",
"]",
"-",
"start_histogram_buckets",
"[",
"low",
"]",
"if",
"new_bucket",
"[",
"'count'",
"]",
"<",
"0",
":",
"logging",
".",
"error",
"(",
"'Histogram subtraction error, starting histogram most '",
"'probably invalid.'",
")",
"if",
"new_bucket",
"[",
"'count'",
"]",
":",
"new_buckets",
".",
"append",
"(",
"new_bucket",
")",
"histogram",
"[",
"'buckets'",
"]",
"=",
"new_buckets",
"histogram",
"[",
"'count'",
"]",
"-=",
"start_histogram",
"[",
"'count'",
"]",
"return",
"json",
".",
"dumps",
"(",
"histogram",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/metrics/histogram_util.py#L23-L59 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Source/bindings/scripts/v8_types.py | python | v8_set_return_value | (idl_type, cpp_value, extended_attributes=None, script_wrappable='', release=False, for_main_world=False, is_static=False) | return statement | Returns a statement that converts a C++ value to a V8 value and sets it as a return value. | Returns a statement that converts a C++ value to a V8 value and sets it as a return value. | [
"Returns",
"a",
"statement",
"that",
"converts",
"a",
"C",
"++",
"value",
"to",
"a",
"V8",
"value",
"and",
"sets",
"it",
"as",
"a",
"return",
"value",
"."
] | def v8_set_return_value(idl_type, cpp_value, extended_attributes=None, script_wrappable='', release=False, for_main_world=False, is_static=False):
"""Returns a statement that converts a C++ value to a V8 value and sets it as a return value.
"""
def dom_wrapper_conversion_type():
if is_static:
return 'DOMWrapperStatic'
if not script_wrappable:
return 'DOMWrapperDefault'
if for_main_world:
return 'DOMWrapperForMainWorld'
return 'DOMWrapperFast'
idl_type, cpp_value = preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes)
this_v8_conversion_type = idl_type.v8_conversion_type(extended_attributes)
# SetReturn-specific overrides
if this_v8_conversion_type in ['Date', 'EventHandler', 'ScriptValue', 'SerializedScriptValue', 'array']:
# Convert value to V8 and then use general v8SetReturnValue
cpp_value = idl_type.cpp_value_to_v8_value(cpp_value, extended_attributes=extended_attributes)
if this_v8_conversion_type == 'DOMWrapper':
this_v8_conversion_type = dom_wrapper_conversion_type()
if is_static and this_v8_conversion_type in ('Dictionary', 'NullableDictionary', 'DictionaryOrUnion'):
this_v8_conversion_type += 'Static'
format_string = V8_SET_RETURN_VALUE[this_v8_conversion_type]
# FIXME: oilpan: Remove .release() once we remove all RefPtrs from generated code.
if release:
cpp_value = '%s.release()' % cpp_value
statement = format_string.format(cpp_value=cpp_value, script_wrappable=script_wrappable)
return statement | [
"def",
"v8_set_return_value",
"(",
"idl_type",
",",
"cpp_value",
",",
"extended_attributes",
"=",
"None",
",",
"script_wrappable",
"=",
"''",
",",
"release",
"=",
"False",
",",
"for_main_world",
"=",
"False",
",",
"is_static",
"=",
"False",
")",
":",
"def",
"dom_wrapper_conversion_type",
"(",
")",
":",
"if",
"is_static",
":",
"return",
"'DOMWrapperStatic'",
"if",
"not",
"script_wrappable",
":",
"return",
"'DOMWrapperDefault'",
"if",
"for_main_world",
":",
"return",
"'DOMWrapperForMainWorld'",
"return",
"'DOMWrapperFast'",
"idl_type",
",",
"cpp_value",
"=",
"preprocess_idl_type_and_value",
"(",
"idl_type",
",",
"cpp_value",
",",
"extended_attributes",
")",
"this_v8_conversion_type",
"=",
"idl_type",
".",
"v8_conversion_type",
"(",
"extended_attributes",
")",
"# SetReturn-specific overrides",
"if",
"this_v8_conversion_type",
"in",
"[",
"'Date'",
",",
"'EventHandler'",
",",
"'ScriptValue'",
",",
"'SerializedScriptValue'",
",",
"'array'",
"]",
":",
"# Convert value to V8 and then use general v8SetReturnValue",
"cpp_value",
"=",
"idl_type",
".",
"cpp_value_to_v8_value",
"(",
"cpp_value",
",",
"extended_attributes",
"=",
"extended_attributes",
")",
"if",
"this_v8_conversion_type",
"==",
"'DOMWrapper'",
":",
"this_v8_conversion_type",
"=",
"dom_wrapper_conversion_type",
"(",
")",
"if",
"is_static",
"and",
"this_v8_conversion_type",
"in",
"(",
"'Dictionary'",
",",
"'NullableDictionary'",
",",
"'DictionaryOrUnion'",
")",
":",
"this_v8_conversion_type",
"+=",
"'Static'",
"format_string",
"=",
"V8_SET_RETURN_VALUE",
"[",
"this_v8_conversion_type",
"]",
"# FIXME: oilpan: Remove .release() once we remove all RefPtrs from generated code.",
"if",
"release",
":",
"cpp_value",
"=",
"'%s.release()'",
"%",
"cpp_value",
"statement",
"=",
"format_string",
".",
"format",
"(",
"cpp_value",
"=",
"cpp_value",
",",
"script_wrappable",
"=",
"script_wrappable",
")",
"return",
"statement"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/v8_types.py#L820-L849 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | PseudoDC.DrawArc | (*args, **kwargs) | return _gdi_.PseudoDC_DrawArc(*args, **kwargs) | DrawArc(self, int x1, int y1, int x2, int y2, int xc, int yc)
Draws an arc of a circle, centred on the *center* point (xc, yc), from
the first point to the second. The current pen is used for the outline
and the current brush for filling the shape.
The arc is drawn in an anticlockwise direction from the start point to
the end point. | DrawArc(self, int x1, int y1, int x2, int y2, int xc, int yc) | [
"DrawArc",
"(",
"self",
"int",
"x1",
"int",
"y1",
"int",
"x2",
"int",
"y2",
"int",
"xc",
"int",
"yc",
")"
] | def DrawArc(*args, **kwargs):
"""
DrawArc(self, int x1, int y1, int x2, int y2, int xc, int yc)
Draws an arc of a circle, centred on the *center* point (xc, yc), from
the first point to the second. The current pen is used for the outline
and the current brush for filling the shape.
The arc is drawn in an anticlockwise direction from the start point to
the end point.
"""
return _gdi_.PseudoDC_DrawArc(*args, **kwargs) | [
"def",
"DrawArc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"PseudoDC_DrawArc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L7822-L7833 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/bindings/python/clang/cindex.py | python | Cursor.is_move_constructor | (self) | return conf.lib.clang_CXXConstructor_isMoveConstructor(self) | Returns True if the cursor refers to a C++ move constructor. | Returns True if the cursor refers to a C++ move constructor. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"move",
"constructor",
"."
] | def is_move_constructor(self):
"""Returns True if the cursor refers to a C++ move constructor.
"""
return conf.lib.clang_CXXConstructor_isMoveConstructor(self) | [
"def",
"is_move_constructor",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXConstructor_isMoveConstructor",
"(",
"self",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/bindings/python/clang/cindex.py#L1462-L1465 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | CheckSpacingForFunctionCall | (filename, clean_lines, linenum, error) | Checks for the correctness of various spacing around function calls.
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. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
not Search(r'\bcase\s+\(', fncall)):
# TODO(unknown): Space after an operator function seem to be a common
# error, silence those for now by restricting them to highest verbosity.
if Search(r'\boperator_*\b', line):
error(filename, linenum, 'whitespace/parens', 0,
'Extra space before ( in function call')
else:
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside such an expression for a",
"# function call, to which we can apply more strict standards.",
"fncall",
"=",
"line",
"# if there's no control flow construct, look at whole line",
"for",
"pattern",
"in",
"(",
"r'\\bif\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bfor\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'",
",",
"r'\\bswitch\\s*\\((.*)\\)\\s*{'",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"match",
":",
"fncall",
"=",
"match",
".",
"group",
"(",
"1",
")",
"# look inside the parens for function calls",
"break",
"# Except in if/for/while/switch, there should never be space",
"# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception",
"# for nested parens ( (a+b) + c ). Likewise, there should never be",
"# a space before a ( when it's a function argument. I assume it's a",
"# function argument when the char before the whitespace is legal in",
"# a function name (alnum + _) and we're not starting a macro. Also ignore",
"# pointers and references to arrays and functions coz they're too tricky:",
"# we use a very simple way to recognize these:",
"# \" (something)(maybe-something)\" or",
"# \" (something)(maybe-something,\" or",
"# \" (something)[something]\"",
"# Note that we assume the contents of [] to be short enough that",
"# they'll never need to wrap.",
"if",
"(",
"# Ignore control structures.",
"not",
"Search",
"(",
"r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to functions.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\([^)]*(\\)|,$)'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to arrays.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\[[^\\]]+\\]'",
",",
"fncall",
")",
")",
":",
"if",
"Search",
"(",
"r'\\w\\s*\\(\\s(?!\\s*\\\\$)'",
",",
"fncall",
")",
":",
"# a ( used for a fn call",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space after ( in function call'",
")",
"elif",
"Search",
"(",
"r'\\(\\s+(?!(\\s*\\\\)|\\()'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space after ('",
")",
"if",
"(",
"Search",
"(",
"r'\\w\\s+\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'_{0,2}asm_{0,2}\\s+_{0,2}volatile_{0,2}\\s+\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'#\\s*define|typedef|using\\s+\\w+\\s*='",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'\\bcase\\s+\\('",
",",
"fncall",
")",
")",
":",
"# TODO(unknown): Space after an operator function seem to be a common",
"# error, silence those for now by restricting them to highest verbosity.",
"if",
"Search",
"(",
"r'\\boperator_*\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"0",
",",
"'Extra space before ( in function call'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space before ( in function call'",
")",
"# If the ) is followed only by a newline or a { + newline, assume it's",
"# part of a control statement (if/while/etc), and don't complain",
"if",
"Search",
"(",
"r'[^)]\\s+\\)\\s*[^{\\s]'",
",",
"fncall",
")",
":",
"# If the closing parenthesis is preceded by only whitespaces,",
"# try to give a more descriptive error message.",
"if",
"Search",
"(",
"r'^\\s+\\)'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Closing ) should be moved to the previous line'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space before )'",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L2940-L3014 | ||
NVIDIA/MDL-SDK | aa9642b2546ad7b6236b5627385d882c2ed83c5d | src/mdl/jit/llvm/dist/bindings/python/llvm/object.py | python | Section.size | (self) | return lib.LLVMGetSectionSize(self) | The size of the section, in long bytes. | The size of the section, in long bytes. | [
"The",
"size",
"of",
"the",
"section",
"in",
"long",
"bytes",
"."
] | def size(self):
"""The size of the section, in long bytes."""
if self.expired:
raise Exception('Section instance has expired.')
return lib.LLVMGetSectionSize(self) | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Section instance has expired.'",
")",
"return",
"lib",
".",
"LLVMGetSectionSize",
"(",
"self",
")"
] | https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/bindings/python/llvm/object.py#L205-L210 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/addins/calc.py | python | CalcAddin.loopName | (self, param) | return param.name() | Return the name of the given parameter as required for loop code - in
this case no conversion is performed. | Return the name of the given parameter as required for loop code - in
this case no conversion is performed. | [
"Return",
"the",
"name",
"of",
"the",
"given",
"parameter",
"as",
"required",
"for",
"loop",
"code",
"-",
"in",
"this",
"case",
"no",
"conversion",
"is",
"performed",
"."
] | def loopName(self, param):
"""Return the name of the given parameter as required for loop code - in
this case no conversion is performed."""
return param.name() | [
"def",
"loopName",
"(",
"self",
",",
"param",
")",
":",
"return",
"param",
".",
"name",
"(",
")"
] | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/calc.py#L246-L249 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py | python | BaseWidget.destroy | (self) | Destroy this and all descendants widgets. | Destroy this and all descendants widgets. | [
"Destroy",
"this",
"and",
"all",
"descendants",
"widgets",
"."
] | def destroy(self):
"""Destroy this and all descendants widgets."""
for c in list(self.children.values()): c.destroy()
self.tk.call('destroy', self._w)
if self._name in self.master.children:
del self.master.children[self._name]
Misc.destroy(self) | [
"def",
"destroy",
"(",
"self",
")",
":",
"for",
"c",
"in",
"list",
"(",
"self",
".",
"children",
".",
"values",
"(",
")",
")",
":",
"c",
".",
"destroy",
"(",
")",
"self",
".",
"tk",
".",
"call",
"(",
"'destroy'",
",",
"self",
".",
"_w",
")",
"if",
"self",
".",
"_name",
"in",
"self",
".",
"master",
".",
"children",
":",
"del",
"self",
".",
"master",
".",
"children",
"[",
"self",
".",
"_name",
"]",
"Misc",
".",
"destroy",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L2302-L2308 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py | python | _GenerateMSBuildFiltersFile | (filters_path, source_files,
extension_to_rule_name) | Generate the filters file.
This file is used by Visual Studio to organize the presentation of source
files into folders.
Arguments:
filters_path: The path of the file to be created.
source_files: The hierarchical structure of all the sources.
extension_to_rule_name: A dictionary mapping file extensions to rules. | Generate the filters file. | [
"Generate",
"the",
"filters",
"file",
"."
] | def _GenerateMSBuildFiltersFile(filters_path, source_files,
extension_to_rule_name):
"""Generate the filters file.
This file is used by Visual Studio to organize the presentation of source
files into folders.
Arguments:
filters_path: The path of the file to be created.
source_files: The hierarchical structure of all the sources.
extension_to_rule_name: A dictionary mapping file extensions to rules.
"""
filter_group = []
source_group = []
_AppendFiltersForMSBuild('', source_files, extension_to_rule_name,
filter_group, source_group)
if filter_group:
content = ['Project',
{'ToolsVersion': '4.0',
'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'
},
['ItemGroup'] + filter_group,
['ItemGroup'] + source_group
]
easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True)
elif os.path.exists(filters_path):
# We don't need this filter anymore. Delete the old filter file.
os.unlink(filters_path) | [
"def",
"_GenerateMSBuildFiltersFile",
"(",
"filters_path",
",",
"source_files",
",",
"extension_to_rule_name",
")",
":",
"filter_group",
"=",
"[",
"]",
"source_group",
"=",
"[",
"]",
"_AppendFiltersForMSBuild",
"(",
"''",
",",
"source_files",
",",
"extension_to_rule_name",
",",
"filter_group",
",",
"source_group",
")",
"if",
"filter_group",
":",
"content",
"=",
"[",
"'Project'",
",",
"{",
"'ToolsVersion'",
":",
"'4.0'",
",",
"'xmlns'",
":",
"'http://schemas.microsoft.com/developer/msbuild/2003'",
"}",
",",
"[",
"'ItemGroup'",
"]",
"+",
"filter_group",
",",
"[",
"'ItemGroup'",
"]",
"+",
"source_group",
"]",
"easy_xml",
".",
"WriteXmlIfChanged",
"(",
"content",
",",
"filters_path",
",",
"pretty",
"=",
"True",
",",
"win32",
"=",
"True",
")",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"filters_path",
")",
":",
"# We don't need this filter anymore. Delete the old filter file.",
"os",
".",
"unlink",
"(",
"filters_path",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L1880-L1907 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/candidate_sampling_ops.py | python | compute_accidental_hits | (true_classes, sampled_candidates, num_true,
seed=None, name=None) | return gen_candidate_sampling_ops._compute_accidental_hits(
true_classes, sampled_candidates, num_true, seed=seed1, seed2=seed2,
name=name) | Compute the position ids in `sampled_candidates` matching `true_classes`.
In Candidate Sampling, this operation facilitates virtually removing
sampled classes which happen to match target classes. This is done
in Sampled Softmax and Sampled Logistic.
See our [Candidate Sampling Algorithms
Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf).
We presuppose that the `sampled_candidates` are unique.
We call it an 'accidental hit' when one of the target classes
matches one of the sampled classes. This operation reports
accidental hits as triples `(index, id, weight)`, where `index`
represents the row number in `true_classes`, `id` represents the
position in `sampled_candidates`, and weight is `-FLOAT_MAX`.
The result of this op should be passed through a `sparse_to_dense`
operation, then added to the logits of the sampled classes. This
removes the contradictory effect of accidentally sampling the true
target classes as noise classes for the same example.
Args:
true_classes: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
sampled_candidates: A tensor of type `int64` and shape `[num_sampled]`.
The sampled_candidates output of CandidateSampler.
num_true: An `int`. The number of target classes per training example.
seed: An `int`. An operation-specific seed. Default is 0.
name: A name for the operation (optional).
Returns:
indices: A `Tensor` of type `int32` and shape `[num_accidental_hits]`.
Values indicate rows in `true_classes`.
ids: A `Tensor` of type `int64` and shape `[num_accidental_hits]`.
Values indicate positions in `sampled_candidates`.
weights: A `Tensor` of type `float` and shape `[num_accidental_hits]`.
Each value is `-FLOAT_MAX`. | Compute the position ids in `sampled_candidates` matching `true_classes`. | [
"Compute",
"the",
"position",
"ids",
"in",
"sampled_candidates",
"matching",
"true_classes",
"."
] | def compute_accidental_hits(true_classes, sampled_candidates, num_true,
seed=None, name=None):
"""Compute the position ids in `sampled_candidates` matching `true_classes`.
In Candidate Sampling, this operation facilitates virtually removing
sampled classes which happen to match target classes. This is done
in Sampled Softmax and Sampled Logistic.
See our [Candidate Sampling Algorithms
Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf).
We presuppose that the `sampled_candidates` are unique.
We call it an 'accidental hit' when one of the target classes
matches one of the sampled classes. This operation reports
accidental hits as triples `(index, id, weight)`, where `index`
represents the row number in `true_classes`, `id` represents the
position in `sampled_candidates`, and weight is `-FLOAT_MAX`.
The result of this op should be passed through a `sparse_to_dense`
operation, then added to the logits of the sampled classes. This
removes the contradictory effect of accidentally sampling the true
target classes as noise classes for the same example.
Args:
true_classes: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
sampled_candidates: A tensor of type `int64` and shape `[num_sampled]`.
The sampled_candidates output of CandidateSampler.
num_true: An `int`. The number of target classes per training example.
seed: An `int`. An operation-specific seed. Default is 0.
name: A name for the operation (optional).
Returns:
indices: A `Tensor` of type `int32` and shape `[num_accidental_hits]`.
Values indicate rows in `true_classes`.
ids: A `Tensor` of type `int64` and shape `[num_accidental_hits]`.
Values indicate positions in `sampled_candidates`.
weights: A `Tensor` of type `float` and shape `[num_accidental_hits]`.
Each value is `-FLOAT_MAX`.
"""
seed1, seed2 = random_seed.get_seed(seed)
return gen_candidate_sampling_ops._compute_accidental_hits(
true_classes, sampled_candidates, num_true, seed=seed1, seed2=seed2,
name=name) | [
"def",
"compute_accidental_hits",
"(",
"true_classes",
",",
"sampled_candidates",
",",
"num_true",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"seed1",
",",
"seed2",
"=",
"random_seed",
".",
"get_seed",
"(",
"seed",
")",
"return",
"gen_candidate_sampling_ops",
".",
"_compute_accidental_hits",
"(",
"true_classes",
",",
"sampled_candidates",
",",
"num_true",
",",
"seed",
"=",
"seed1",
",",
"seed2",
"=",
"seed2",
",",
"name",
"=",
"name",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/candidate_sampling_ops.py#L323-L368 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_vdvt_update.py | python | OperatorPDSqrtVDVTUpdate.__init__ | (self,
operator,
v,
diag=None,
verify_pd=True,
verify_shapes=True,
name='OperatorPDSqrtVDVTUpdate') | Initialize an `OperatorPDSqrtVDVTUpdate`.
Args:
operator: Subclass of `OperatorPDBase`. Represents the (batch) positive
definite matrix `M` in `R^{k x k}`.
v: `Tensor` defining batch matrix of same `dtype` and `batch_shape` as
`operator`, and last two dimensions of shape `(k, r)`.
diag: Optional `Tensor` defining batch vector of same `dtype` and
`batch_shape` as `operator`, and last dimension of size `r`. If `None`,
the update becomes `VV^T` rather than `VDV^T`.
verify_pd: `Boolean`. If `True`, add asserts that `diag > 0`, which,
along with the positive definiteness of `operator`, is sufficient to
make the resulting operator positive definite.
verify_shapes: `Boolean`. If `True`, check that `operator`, `v`, and
`diag` have compatible shapes.
name: A name to prepend to `Op` names. | Initialize an `OperatorPDSqrtVDVTUpdate`. | [
"Initialize",
"an",
"OperatorPDSqrtVDVTUpdate",
"."
] | def __init__(self,
operator,
v,
diag=None,
verify_pd=True,
verify_shapes=True,
name='OperatorPDSqrtVDVTUpdate'):
"""Initialize an `OperatorPDSqrtVDVTUpdate`.
Args:
operator: Subclass of `OperatorPDBase`. Represents the (batch) positive
definite matrix `M` in `R^{k x k}`.
v: `Tensor` defining batch matrix of same `dtype` and `batch_shape` as
`operator`, and last two dimensions of shape `(k, r)`.
diag: Optional `Tensor` defining batch vector of same `dtype` and
`batch_shape` as `operator`, and last dimension of size `r`. If `None`,
the update becomes `VV^T` rather than `VDV^T`.
verify_pd: `Boolean`. If `True`, add asserts that `diag > 0`, which,
along with the positive definiteness of `operator`, is sufficient to
make the resulting operator positive definite.
verify_shapes: `Boolean`. If `True`, check that `operator`, `v`, and
`diag` have compatible shapes.
name: A name to prepend to `Op` names.
"""
if not isinstance(operator, operator_pd.OperatorPDBase):
raise TypeError('operator was not instance of OperatorPDBase.')
with ops.name_scope(name):
with ops.op_scope(operator.inputs + [v, diag], 'init'):
self._operator = operator
self._v = ops.convert_to_tensor(v, name='v')
self._verify_pd = verify_pd
self._verify_shapes = verify_shapes
self._name = name
# This operator will be PD so long as the diag is PSD, but Woodbury
# and determinant lemmas require diag to be PD. So require diag PD
# whenever we ask to "verify_pd".
if diag is not None:
self._diag = ops.convert_to_tensor(diag, name='diag')
self._diag_operator = operator_pd_diag.OperatorPDDiag(
diag, verify_pd=self.verify_pd)
# No need to verify that the inverse of a PD is PD.
self._diag_inv_operator = operator_pd_diag.OperatorPDDiag(
1 / self._diag, verify_pd=False)
else:
self._diag = None
self._diag_operator = self._get_identity_operator(self._v)
self._diag_inv_operator = self._diag_operator
self._check_types(operator, self._v, self._diag)
# Always check static.
checked = self._check_shapes_static(operator, self._v, self._diag)
if not checked and self._verify_shapes:
self._v, self._diag = self._check_shapes_dynamic(
operator, self._v, self._diag) | [
"def",
"__init__",
"(",
"self",
",",
"operator",
",",
"v",
",",
"diag",
"=",
"None",
",",
"verify_pd",
"=",
"True",
",",
"verify_shapes",
"=",
"True",
",",
"name",
"=",
"'OperatorPDSqrtVDVTUpdate'",
")",
":",
"if",
"not",
"isinstance",
"(",
"operator",
",",
"operator_pd",
".",
"OperatorPDBase",
")",
":",
"raise",
"TypeError",
"(",
"'operator was not instance of OperatorPDBase.'",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"operator",
".",
"inputs",
"+",
"[",
"v",
",",
"diag",
"]",
",",
"'init'",
")",
":",
"self",
".",
"_operator",
"=",
"operator",
"self",
".",
"_v",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"v",
",",
"name",
"=",
"'v'",
")",
"self",
".",
"_verify_pd",
"=",
"verify_pd",
"self",
".",
"_verify_shapes",
"=",
"verify_shapes",
"self",
".",
"_name",
"=",
"name",
"# This operator will be PD so long as the diag is PSD, but Woodbury",
"# and determinant lemmas require diag to be PD. So require diag PD",
"# whenever we ask to \"verify_pd\".",
"if",
"diag",
"is",
"not",
"None",
":",
"self",
".",
"_diag",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"diag",
",",
"name",
"=",
"'diag'",
")",
"self",
".",
"_diag_operator",
"=",
"operator_pd_diag",
".",
"OperatorPDDiag",
"(",
"diag",
",",
"verify_pd",
"=",
"self",
".",
"verify_pd",
")",
"# No need to verify that the inverse of a PD is PD.",
"self",
".",
"_diag_inv_operator",
"=",
"operator_pd_diag",
".",
"OperatorPDDiag",
"(",
"1",
"/",
"self",
".",
"_diag",
",",
"verify_pd",
"=",
"False",
")",
"else",
":",
"self",
".",
"_diag",
"=",
"None",
"self",
".",
"_diag_operator",
"=",
"self",
".",
"_get_identity_operator",
"(",
"self",
".",
"_v",
")",
"self",
".",
"_diag_inv_operator",
"=",
"self",
".",
"_diag_operator",
"self",
".",
"_check_types",
"(",
"operator",
",",
"self",
".",
"_v",
",",
"self",
".",
"_diag",
")",
"# Always check static.",
"checked",
"=",
"self",
".",
"_check_shapes_static",
"(",
"operator",
",",
"self",
".",
"_v",
",",
"self",
".",
"_diag",
")",
"if",
"not",
"checked",
"and",
"self",
".",
"_verify_shapes",
":",
"self",
".",
"_v",
",",
"self",
".",
"_diag",
"=",
"self",
".",
"_check_shapes_dynamic",
"(",
"operator",
",",
"self",
".",
"_v",
",",
"self",
".",
"_diag",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_vdvt_update.py#L79-L135 | ||
kitao/pyxel | f58bd6fe84153219a1e5edc506ae9606614883dc | pyxel/examples/07_snake.py | python | define_sound_and_music | () | Define sound and music. | Define sound and music. | [
"Define",
"sound",
"and",
"music",
"."
] | def define_sound_and_music():
"""Define sound and music."""
# Sound effects
pyxel.sound(0).set(
notes="c3e3g3c4c4", tones="s", volumes="4", effects=("n" * 4 + "f"), speed=7
)
pyxel.sound(1).set(
notes="f3 b2 f2 b1 f1 f1 f1 f1",
tones="p",
volumes=("4" * 4 + "4321"),
effects=("n" * 7 + "f"),
speed=9,
)
melody1 = (
"c3 c3 c3 d3 e3 r e3 r"
+ ("r" * 8)
+ "e3 e3 e3 f3 d3 r c3 r"
+ ("r" * 8)
+ "c3 c3 c3 d3 e3 r e3 r"
+ ("r" * 8)
+ "b2 b2 b2 f3 d3 r c3 r"
+ ("r" * 8)
)
melody2 = (
"rrrr e3e3e3e3 d3d3c3c3 b2b2c3c3"
+ "a2a2a2a2 c3c3c3c3 d3d3d3d3 e3e3e3e3"
+ "rrrr e3e3e3e3 d3d3c3c3 b2b2c3c3"
+ "a2a2a2a2 g2g2g2g2 c3c3c3c3 g2g2a2a2"
+ "rrrr e3e3e3e3 d3d3c3c3 b2b2c3c3"
+ "a2a2a2a2 c3c3c3c3 d3d3d3d3 e3e3e3e3"
+ "f3f3f3a3 a3a3a3a3 g3g3g3b3 b3b3b3b3"
+ "b3b3b3b4 rrrr e3d3c3g3 a2g2e2d2"
)
# Music
pyxel.sound(2).set(
notes=melody1 * 2 + melody2 * 2,
tones="s",
volumes=("3"),
effects=("nnnsffff"),
speed=20,
)
harmony1 = (
"a1 a1 a1 b1 f1 f1 c2 c2"
"c2 c2 c2 c2 g1 g1 b1 b1" * 3
+ "f1 f1 f1 f1 f1 f1 f1 f1 g1 g1 g1 g1 g1 g1 g1 g1"
)
harmony2 = (
("f1" * 8 + "g1" * 8 + "a1" * 8 + ("c2" * 7 + "d2")) * 3 + "f1" * 16 + "g1" * 16
)
pyxel.sound(3).set(
notes=harmony1 * 2 + harmony2 * 2, tones="t", volumes="5", effects="f", speed=20
)
pyxel.sound(4).set(
notes=("f0 r a4 r f0 f0 a4 r" "f0 r a4 r f0 f0 a4 f0"),
tones="n",
volumes="6622 6622 6622 6426",
effects="f",
speed=20,
)
pyxel.music(0).set([], [2], [3], [4]) | [
"def",
"define_sound_and_music",
"(",
")",
":",
"# Sound effects",
"pyxel",
".",
"sound",
"(",
"0",
")",
".",
"set",
"(",
"notes",
"=",
"\"c3e3g3c4c4\"",
",",
"tones",
"=",
"\"s\"",
",",
"volumes",
"=",
"\"4\"",
",",
"effects",
"=",
"(",
"\"n\"",
"*",
"4",
"+",
"\"f\"",
")",
",",
"speed",
"=",
"7",
")",
"pyxel",
".",
"sound",
"(",
"1",
")",
".",
"set",
"(",
"notes",
"=",
"\"f3 b2 f2 b1 f1 f1 f1 f1\"",
",",
"tones",
"=",
"\"p\"",
",",
"volumes",
"=",
"(",
"\"4\"",
"*",
"4",
"+",
"\"4321\"",
")",
",",
"effects",
"=",
"(",
"\"n\"",
"*",
"7",
"+",
"\"f\"",
")",
",",
"speed",
"=",
"9",
",",
")",
"melody1",
"=",
"(",
"\"c3 c3 c3 d3 e3 r e3 r\"",
"+",
"(",
"\"r\"",
"*",
"8",
")",
"+",
"\"e3 e3 e3 f3 d3 r c3 r\"",
"+",
"(",
"\"r\"",
"*",
"8",
")",
"+",
"\"c3 c3 c3 d3 e3 r e3 r\"",
"+",
"(",
"\"r\"",
"*",
"8",
")",
"+",
"\"b2 b2 b2 f3 d3 r c3 r\"",
"+",
"(",
"\"r\"",
"*",
"8",
")",
")",
"melody2",
"=",
"(",
"\"rrrr e3e3e3e3 d3d3c3c3 b2b2c3c3\"",
"+",
"\"a2a2a2a2 c3c3c3c3 d3d3d3d3 e3e3e3e3\"",
"+",
"\"rrrr e3e3e3e3 d3d3c3c3 b2b2c3c3\"",
"+",
"\"a2a2a2a2 g2g2g2g2 c3c3c3c3 g2g2a2a2\"",
"+",
"\"rrrr e3e3e3e3 d3d3c3c3 b2b2c3c3\"",
"+",
"\"a2a2a2a2 c3c3c3c3 d3d3d3d3 e3e3e3e3\"",
"+",
"\"f3f3f3a3 a3a3a3a3 g3g3g3b3 b3b3b3b3\"",
"+",
"\"b3b3b3b4 rrrr e3d3c3g3 a2g2e2d2\"",
")",
"# Music",
"pyxel",
".",
"sound",
"(",
"2",
")",
".",
"set",
"(",
"notes",
"=",
"melody1",
"*",
"2",
"+",
"melody2",
"*",
"2",
",",
"tones",
"=",
"\"s\"",
",",
"volumes",
"=",
"(",
"\"3\"",
")",
",",
"effects",
"=",
"(",
"\"nnnsffff\"",
")",
",",
"speed",
"=",
"20",
",",
")",
"harmony1",
"=",
"(",
"\"a1 a1 a1 b1 f1 f1 c2 c2\"",
"\"c2 c2 c2 c2 g1 g1 b1 b1\"",
"*",
"3",
"+",
"\"f1 f1 f1 f1 f1 f1 f1 f1 g1 g1 g1 g1 g1 g1 g1 g1\"",
")",
"harmony2",
"=",
"(",
"(",
"\"f1\"",
"*",
"8",
"+",
"\"g1\"",
"*",
"8",
"+",
"\"a1\"",
"*",
"8",
"+",
"(",
"\"c2\"",
"*",
"7",
"+",
"\"d2\"",
")",
")",
"*",
"3",
"+",
"\"f1\"",
"*",
"16",
"+",
"\"g1\"",
"*",
"16",
")",
"pyxel",
".",
"sound",
"(",
"3",
")",
".",
"set",
"(",
"notes",
"=",
"harmony1",
"*",
"2",
"+",
"harmony2",
"*",
"2",
",",
"tones",
"=",
"\"t\"",
",",
"volumes",
"=",
"\"5\"",
",",
"effects",
"=",
"\"f\"",
",",
"speed",
"=",
"20",
")",
"pyxel",
".",
"sound",
"(",
"4",
")",
".",
"set",
"(",
"notes",
"=",
"(",
"\"f0 r a4 r f0 f0 a4 r\"",
"\"f0 r a4 r f0 f0 a4 f0\"",
")",
",",
"tones",
"=",
"\"n\"",
",",
"volumes",
"=",
"\"6622 6622 6622 6426\"",
",",
"effects",
"=",
"\"f\"",
",",
"speed",
"=",
"20",
",",
")",
"pyxel",
".",
"music",
"(",
"0",
")",
".",
"set",
"(",
"[",
"]",
",",
"[",
"2",
"]",
",",
"[",
"3",
"]",
",",
"[",
"4",
"]",
")"
] | https://github.com/kitao/pyxel/blob/f58bd6fe84153219a1e5edc506ae9606614883dc/pyxel/examples/07_snake.py#L217-L283 | ||
wujian16/Cornell-MOE | df299d1be882d2af9796d7a68b3f9505cac7a53e | moe/optimal_learning/python/interfaces/covariance_interface.py | python | CovarianceInterface.grad_covariance | (self, point_one, point_two) | r"""Compute the gradient of self.covariance(point_one, point_two) with respect to the FIRST argument, point_one.
.. Note:: comments are copied from the matching method comments of CovarianceInterface in gpp_covariance.hpp
and comments are copied to the matching method comments of
:mod:`moe.optimal_learning.python.python_version.covariance.SquareExponential`.
This distinction is important for maintaining the desired symmetry. ``Cov(x, y) = Cov(y, x)``.
Additionally, ``\pderiv{Cov(x, y)}{x} = \pderiv{Cov(y, x)}{x}``.
However, in general, ``\pderiv{Cov(x, y)}{x} != \pderiv{Cov(y, x)}{y}`` (NOT equal! These may differ by a negative sign)
Hence to avoid separate implementations for differentiating against first vs second argument, this function only handles
differentiation against the first argument. If you need ``\pderiv{Cov(y, x)}{x}``, just swap points x and y.
:param point_one: first input, the point ``x``
:type point_one: array of float64 with shape (dim)
:param point_two: second input, the point ``y``
:type point_two: array of float64 with shape (dim)
:return: grad_cov: i-th entry is ``\pderiv{cov(x_1, x_2)}{x_i}``
:rtype: array of float64 with shape (dim) | r"""Compute the gradient of self.covariance(point_one, point_two) with respect to the FIRST argument, point_one. | [
"r",
"Compute",
"the",
"gradient",
"of",
"self",
".",
"covariance",
"(",
"point_one",
"point_two",
")",
"with",
"respect",
"to",
"the",
"FIRST",
"argument",
"point_one",
"."
] | def grad_covariance(self, point_one, point_two):
r"""Compute the gradient of self.covariance(point_one, point_two) with respect to the FIRST argument, point_one.
.. Note:: comments are copied from the matching method comments of CovarianceInterface in gpp_covariance.hpp
and comments are copied to the matching method comments of
:mod:`moe.optimal_learning.python.python_version.covariance.SquareExponential`.
This distinction is important for maintaining the desired symmetry. ``Cov(x, y) = Cov(y, x)``.
Additionally, ``\pderiv{Cov(x, y)}{x} = \pderiv{Cov(y, x)}{x}``.
However, in general, ``\pderiv{Cov(x, y)}{x} != \pderiv{Cov(y, x)}{y}`` (NOT equal! These may differ by a negative sign)
Hence to avoid separate implementations for differentiating against first vs second argument, this function only handles
differentiation against the first argument. If you need ``\pderiv{Cov(y, x)}{x}``, just swap points x and y.
:param point_one: first input, the point ``x``
:type point_one: array of float64 with shape (dim)
:param point_two: second input, the point ``y``
:type point_two: array of float64 with shape (dim)
:return: grad_cov: i-th entry is ``\pderiv{cov(x_1, x_2)}{x_i}``
:rtype: array of float64 with shape (dim)
"""
pass | [
"def",
"grad_covariance",
"(",
"self",
",",
"point_one",
",",
"point_two",
")",
":",
"pass"
] | https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/interfaces/covariance_interface.py#L95-L117 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/SConsign.py | python | DirFile.write | (self, sync=1) | Write the .sconsign file to disk.
Try to write to a temporary file first, and rename it if we
succeed. If we can't write to the temporary file, it's
probably because the directory isn't writable (and if so,
how did we build anything in this directory, anyway?), so
try to write directly to the .sconsign file as a backup.
If we can't rename, try to copy the temporary contents back
to the .sconsign file. Either way, always try to remove
the temporary file at the end. | Write the .sconsign file to disk. | [
"Write",
"the",
".",
"sconsign",
"file",
"to",
"disk",
"."
] | def write(self, sync=1):
"""
Write the .sconsign file to disk.
Try to write to a temporary file first, and rename it if we
succeed. If we can't write to the temporary file, it's
probably because the directory isn't writable (and if so,
how did we build anything in this directory, anyway?), so
try to write directly to the .sconsign file as a backup.
If we can't rename, try to copy the temporary contents back
to the .sconsign file. Either way, always try to remove
the temporary file at the end.
"""
if not self.dirty:
return
self.merge()
temp = os.path.join(self.dir.get_internal_path(), '.scons%d' % os.getpid())
try:
file = open(temp, 'wb')
fname = temp
except IOError:
try:
file = open(self.sconsign, 'wb')
fname = self.sconsign
except IOError:
return
for key, entry in self.entries.items():
entry.convert_to_sconsign()
pickle.dump(self.entries, file, 1)
file.close()
if fname != self.sconsign:
try:
mode = os.stat(self.sconsign)[0]
os.chmod(self.sconsign, 0666)
os.unlink(self.sconsign)
except (IOError, OSError):
# Try to carry on in the face of either OSError
# (things like permission issues) or IOError (disk
# or network issues). If there's a really dangerous
# issue, it should get re-raised by the calls below.
pass
try:
os.rename(fname, self.sconsign)
except OSError:
# An OSError failure to rename may indicate something
# like the directory has no write permission, but
# the .sconsign file itself might still be writable,
# so try writing on top of it directly. An IOError
# here, or in any of the following calls, would get
# raised, indicating something like a potentially
# serious disk or network issue.
open(self.sconsign, 'wb').write(open(fname, 'rb').read())
os.chmod(self.sconsign, mode)
try:
os.unlink(temp)
except (IOError, OSError):
pass | [
"def",
"write",
"(",
"self",
",",
"sync",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"dirty",
":",
"return",
"self",
".",
"merge",
"(",
")",
"temp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dir",
".",
"get_internal_path",
"(",
")",
",",
"'.scons%d'",
"%",
"os",
".",
"getpid",
"(",
")",
")",
"try",
":",
"file",
"=",
"open",
"(",
"temp",
",",
"'wb'",
")",
"fname",
"=",
"temp",
"except",
"IOError",
":",
"try",
":",
"file",
"=",
"open",
"(",
"self",
".",
"sconsign",
",",
"'wb'",
")",
"fname",
"=",
"self",
".",
"sconsign",
"except",
"IOError",
":",
"return",
"for",
"key",
",",
"entry",
"in",
"self",
".",
"entries",
".",
"items",
"(",
")",
":",
"entry",
".",
"convert_to_sconsign",
"(",
")",
"pickle",
".",
"dump",
"(",
"self",
".",
"entries",
",",
"file",
",",
"1",
")",
"file",
".",
"close",
"(",
")",
"if",
"fname",
"!=",
"self",
".",
"sconsign",
":",
"try",
":",
"mode",
"=",
"os",
".",
"stat",
"(",
"self",
".",
"sconsign",
")",
"[",
"0",
"]",
"os",
".",
"chmod",
"(",
"self",
".",
"sconsign",
",",
"0666",
")",
"os",
".",
"unlink",
"(",
"self",
".",
"sconsign",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"# Try to carry on in the face of either OSError",
"# (things like permission issues) or IOError (disk",
"# or network issues). If there's a really dangerous",
"# issue, it should get re-raised by the calls below.",
"pass",
"try",
":",
"os",
".",
"rename",
"(",
"fname",
",",
"self",
".",
"sconsign",
")",
"except",
"OSError",
":",
"# An OSError failure to rename may indicate something",
"# like the directory has no write permission, but",
"# the .sconsign file itself might still be writable,",
"# so try writing on top of it directly. An IOError",
"# here, or in any of the following calls, would get",
"# raised, indicating something like a potentially",
"# serious disk or network issue.",
"open",
"(",
"self",
".",
"sconsign",
",",
"'wb'",
")",
".",
"write",
"(",
"open",
"(",
"fname",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
"os",
".",
"chmod",
"(",
"self",
".",
"sconsign",
",",
"mode",
")",
"try",
":",
"os",
".",
"unlink",
"(",
"temp",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"pass"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/SConsign.py#L332-L390 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/base.py | python | load_csv_with_header | (filename,
target_dtype,
features_dtype,
target_column=-1) | return Dataset(data=data, target=target) | Load dataset from CSV file with a header row. | Load dataset from CSV file with a header row. | [
"Load",
"dataset",
"from",
"CSV",
"file",
"with",
"a",
"header",
"row",
"."
] | def load_csv_with_header(filename,
target_dtype,
features_dtype,
target_column=-1):
"""Load dataset from CSV file with a header row."""
with gfile.Open(filename) as csv_file:
data_file = csv.reader(csv_file)
header = next(data_file)
n_samples = int(header[0])
n_features = int(header[1])
data = np.zeros((n_samples, n_features))
target = np.zeros((n_samples,), dtype=target_dtype)
for i, row in enumerate(data_file):
target[i] = np.asarray(row.pop(target_column), dtype=target_dtype)
data[i] = np.asarray(row, dtype=features_dtype)
return Dataset(data=data, target=target) | [
"def",
"load_csv_with_header",
"(",
"filename",
",",
"target_dtype",
",",
"features_dtype",
",",
"target_column",
"=",
"-",
"1",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"csv_file",
":",
"data_file",
"=",
"csv",
".",
"reader",
"(",
"csv_file",
")",
"header",
"=",
"next",
"(",
"data_file",
")",
"n_samples",
"=",
"int",
"(",
"header",
"[",
"0",
"]",
")",
"n_features",
"=",
"int",
"(",
"header",
"[",
"1",
"]",
")",
"data",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"n_features",
")",
")",
"target",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
")",
",",
"dtype",
"=",
"target_dtype",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"data_file",
")",
":",
"target",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"row",
".",
"pop",
"(",
"target_column",
")",
",",
"dtype",
"=",
"target_dtype",
")",
"data",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"row",
",",
"dtype",
"=",
"features_dtype",
")",
"return",
"Dataset",
"(",
"data",
"=",
"data",
",",
"target",
"=",
"target",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/base.py#L53-L69 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/io_ops.py | python | _RestoreShape | (op) | return [tensor_shape.unknown_shape()] | Shape function for Restore op. | Shape function for Restore op. | [
"Shape",
"function",
"for",
"Restore",
"op",
"."
] | def _RestoreShape(op):
"""Shape function for Restore op."""
# Validate input shapes.
unused_file_pattern = op.inputs[0].get_shape().merge_with(
tensor_shape.scalar())
unused_tensor_name = op.inputs[1].get_shape().merge_with(
tensor_shape.scalar())
return [tensor_shape.unknown_shape()] | [
"def",
"_RestoreShape",
"(",
"op",
")",
":",
"# Validate input shapes.",
"unused_file_pattern",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"unused_tensor_name",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"return",
"[",
"tensor_shape",
".",
"unknown_shape",
"(",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L207-L214 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/paginate.py | python | TokenEncoder._encode | (self, data, path) | Encode bytes in given data, keeping track of the path traversed. | Encode bytes in given data, keeping track of the path traversed. | [
"Encode",
"bytes",
"in",
"given",
"data",
"keeping",
"track",
"of",
"the",
"path",
"traversed",
"."
] | def _encode(self, data, path):
"""Encode bytes in given data, keeping track of the path traversed."""
if isinstance(data, dict):
return self._encode_dict(data, path)
elif isinstance(data, list):
return self._encode_list(data, path)
elif isinstance(data, six.binary_type):
return self._encode_bytes(data, path)
else:
return data, [] | [
"def",
"_encode",
"(",
"self",
",",
"data",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"self",
".",
"_encode_dict",
"(",
"data",
",",
"path",
")",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"self",
".",
"_encode_list",
"(",
"data",
",",
"path",
")",
"elif",
"isinstance",
"(",
"data",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"self",
".",
"_encode_bytes",
"(",
"data",
",",
"path",
")",
"else",
":",
"return",
"data",
",",
"[",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/paginate.py#L70-L79 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/results_tab_widget/results_tab_model.py | python | ResultsTabModel.create_results_table | (self, log_selection, results_selection) | return results_table | Create a TableWorkspace with the fit results and logs combined. The format is
a single row per workspace with columns:
|workspace_name|selected_log_1|selected_log_2|...|param1_|param1_err|param2|param2_err|...|
Any time-series log values are averaged.
The workspace is added to the ADS with the name given by results_table_name
:param log_selection: The current selection of logs as a list
It is assumed this is ordered as it should be displayed. It can be empty.
:param results_selection: The current selection of result workspaces as a list of 2-tuple
[(workspace, fit_position),...]
It is assumed this is not empty and ordered as it should be displayed. | Create a TableWorkspace with the fit results and logs combined. The format is
a single row per workspace with columns:
|workspace_name|selected_log_1|selected_log_2|...|param1_|param1_err|param2|param2_err|...|
Any time-series log values are averaged.
The workspace is added to the ADS with the name given by results_table_name | [
"Create",
"a",
"TableWorkspace",
"with",
"the",
"fit",
"results",
"and",
"logs",
"combined",
".",
"The",
"format",
"is",
"a",
"single",
"row",
"per",
"workspace",
"with",
"columns",
":",
"|workspace_name|selected_log_1|selected_log_2|",
"...",
"|param1_|param1_err|param2|param2_err|",
"...",
"|",
"Any",
"time",
"-",
"series",
"log",
"values",
"are",
"averaged",
".",
"The",
"workspace",
"is",
"added",
"to",
"the",
"ADS",
"with",
"the",
"name",
"given",
"by",
"results_table_name"
] | def create_results_table(self, log_selection, results_selection):
"""Create a TableWorkspace with the fit results and logs combined. The format is
a single row per workspace with columns:
|workspace_name|selected_log_1|selected_log_2|...|param1_|param1_err|param2|param2_err|...|
Any time-series log values are averaged.
The workspace is added to the ADS with the name given by results_table_name
:param log_selection: The current selection of logs as a list
It is assumed this is ordered as it should be displayed. It can be empty.
:param results_selection: The current selection of result workspaces as a list of 2-tuple
[(workspace, fit_position),...]
It is assumed this is not empty and ordered as it should be displayed.
"""
self._raise_error_on_incompatible_selection(log_selection,
results_selection)
all_fits = self._fit_context.all_latest_fits()
results_table = self._create_empty_results_table(
log_selection, results_selection, all_fits)
for _, position in results_selection:
fit = all_fits[position]
fit_parameters = fit.parameters
row_dict = {
WORKSPACE_NAME_COL: fit_parameters.parameter_workspace_name
}
row_dict = self._add_logs_to_table(row_dict, fit, log_selection)
results_table.addRow(self._add_parameters_to_table(row_dict, fit_parameters))
ads.Instance().addOrReplace(self.results_table_name(), results_table)
self._results_context.add_result_table(self.results_table_name())
return results_table | [
"def",
"create_results_table",
"(",
"self",
",",
"log_selection",
",",
"results_selection",
")",
":",
"self",
".",
"_raise_error_on_incompatible_selection",
"(",
"log_selection",
",",
"results_selection",
")",
"all_fits",
"=",
"self",
".",
"_fit_context",
".",
"all_latest_fits",
"(",
")",
"results_table",
"=",
"self",
".",
"_create_empty_results_table",
"(",
"log_selection",
",",
"results_selection",
",",
"all_fits",
")",
"for",
"_",
",",
"position",
"in",
"results_selection",
":",
"fit",
"=",
"all_fits",
"[",
"position",
"]",
"fit_parameters",
"=",
"fit",
".",
"parameters",
"row_dict",
"=",
"{",
"WORKSPACE_NAME_COL",
":",
"fit_parameters",
".",
"parameter_workspace_name",
"}",
"row_dict",
"=",
"self",
".",
"_add_logs_to_table",
"(",
"row_dict",
",",
"fit",
",",
"log_selection",
")",
"results_table",
".",
"addRow",
"(",
"self",
".",
"_add_parameters_to_table",
"(",
"row_dict",
",",
"fit_parameters",
")",
")",
"ads",
".",
"Instance",
"(",
")",
".",
"addOrReplace",
"(",
"self",
".",
"results_table_name",
"(",
")",
",",
"results_table",
")",
"self",
".",
"_results_context",
".",
"add_result_table",
"(",
"self",
".",
"results_table_name",
"(",
")",
")",
"return",
"results_table"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/results_tab_widget/results_tab_model.py#L124-L153 | |
mapsme/omim | 1892903b63f2c85b16ed4966d21fe76aba06b9ba | tools/python/maps_generator/maps_generator.py | python | generate_maps | (env: Env, from_stage: Optional[AnyStr] = None) | Runs maps generation. | Runs maps generation. | [
"Runs",
"maps",
"generation",
"."
] | def generate_maps(env: Env, from_stage: Optional[AnyStr] = None):
""""Runs maps generation."""
stages = (
sd.StageDownloadAndConvertPlanet(),
sd.StageUpdatePlanet(),
sd.StageCoastline(),
sd.StagePreprocess(),
sd.StageFeatures(),
sd.StageDownloadDescriptions(),
sd.StageMwm(),
sd.StageCountriesTxt(),
sd.StageExternalResources(),
sd.StageLocalAds(),
sd.StageStatistics(),
sd.StageCleanup(),
)
run_generation(env, stages, from_stage) | [
"def",
"generate_maps",
"(",
"env",
":",
"Env",
",",
"from_stage",
":",
"Optional",
"[",
"AnyStr",
"]",
"=",
"None",
")",
":",
"stages",
"=",
"(",
"sd",
".",
"StageDownloadAndConvertPlanet",
"(",
")",
",",
"sd",
".",
"StageUpdatePlanet",
"(",
")",
",",
"sd",
".",
"StageCoastline",
"(",
")",
",",
"sd",
".",
"StagePreprocess",
"(",
")",
",",
"sd",
".",
"StageFeatures",
"(",
")",
",",
"sd",
".",
"StageDownloadDescriptions",
"(",
")",
",",
"sd",
".",
"StageMwm",
"(",
")",
",",
"sd",
".",
"StageCountriesTxt",
"(",
")",
",",
"sd",
".",
"StageExternalResources",
"(",
")",
",",
"sd",
".",
"StageLocalAds",
"(",
")",
",",
"sd",
".",
"StageStatistics",
"(",
")",
",",
"sd",
".",
"StageCleanup",
"(",
")",
",",
")",
"run_generation",
"(",
"env",
",",
"stages",
",",
"from_stage",
")"
] | https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/tools/python/maps_generator/maps_generator.py#L27-L44 | ||
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/constant.py | python | Constant._sessions | (self) | return self.__sessions | Return session(s) this object is related to. For internal use. | Return session(s) this object is related to. For internal use. | [
"Return",
"session",
"(",
"s",
")",
"this",
"object",
"is",
"related",
"to",
".",
"For",
"internal",
"use",
"."
] | def _sessions(self):
"""Return session(s) this object is related to. For internal use."""
return self.__sessions | [
"def",
"_sessions",
"(",
"self",
")",
":",
"return",
"self",
".",
"__sessions"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/constant.py#L167-L169 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | components/policy/tools/make_policy_zip.py | python | main | (argv) | Pack a list of files into a zip archive.
Args:
zip_path: The file name of the zip archive.
base_dir: Base path of input files.
locales: The list of locales that are used to generate the list of file
names using INPUT_FILES. | Pack a list of files into a zip archive. | [
"Pack",
"a",
"list",
"of",
"files",
"into",
"a",
"zip",
"archive",
"."
] | def main(argv):
"""Pack a list of files into a zip archive.
Args:
zip_path: The file name of the zip archive.
base_dir: Base path of input files.
locales: The list of locales that are used to generate the list of file
names using INPUT_FILES.
"""
parser = optparse.OptionParser()
parser.add_option("--output", dest="output")
parser.add_option("--basedir", dest="basedir")
parser.add_option("--grit_info", dest="grit_info")
parser.add_option("--grd_input", dest="grd_input")
parser.add_option("--grd_strip_path_prefix", dest="grd_strip_path_prefix")
parser.add_option("--extra_input", action="append", dest="extra_input",
default=[])
parser.add_option("-D", action="append", dest="grit_defines", default=[])
parser.add_option("-E", action="append", dest="grit_build_env", default=[])
options, args = parser.parse_args(argv[1:])
if (options.basedir[-1] != '/'):
options.basedir += '/'
grit_defines = {}
for define in options.grit_defines:
grit_defines[define] = 1
file_list = options.extra_input
file_list += get_grd_outputs(options.grit_info, grit_defines,
options.grd_input, options.grd_strip_path_prefix)
zip_file = zipfile.ZipFile(options.output, 'w', zipfile.ZIP_DEFLATED)
try:
return add_files_to_zip(zip_file, options.basedir, file_list)
finally:
zip_file.close() | [
"def",
"main",
"(",
"argv",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"\"--output\"",
",",
"dest",
"=",
"\"output\"",
")",
"parser",
".",
"add_option",
"(",
"\"--basedir\"",
",",
"dest",
"=",
"\"basedir\"",
")",
"parser",
".",
"add_option",
"(",
"\"--grit_info\"",
",",
"dest",
"=",
"\"grit_info\"",
")",
"parser",
".",
"add_option",
"(",
"\"--grd_input\"",
",",
"dest",
"=",
"\"grd_input\"",
")",
"parser",
".",
"add_option",
"(",
"\"--grd_strip_path_prefix\"",
",",
"dest",
"=",
"\"grd_strip_path_prefix\"",
")",
"parser",
".",
"add_option",
"(",
"\"--extra_input\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"extra_input\"",
",",
"default",
"=",
"[",
"]",
")",
"parser",
".",
"add_option",
"(",
"\"-D\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"grit_defines\"",
",",
"default",
"=",
"[",
"]",
")",
"parser",
".",
"add_option",
"(",
"\"-E\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"grit_build_env\"",
",",
"default",
"=",
"[",
"]",
")",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"(",
"options",
".",
"basedir",
"[",
"-",
"1",
"]",
"!=",
"'/'",
")",
":",
"options",
".",
"basedir",
"+=",
"'/'",
"grit_defines",
"=",
"{",
"}",
"for",
"define",
"in",
"options",
".",
"grit_defines",
":",
"grit_defines",
"[",
"define",
"]",
"=",
"1",
"file_list",
"=",
"options",
".",
"extra_input",
"file_list",
"+=",
"get_grd_outputs",
"(",
"options",
".",
"grit_info",
",",
"grit_defines",
",",
"options",
".",
"grd_input",
",",
"options",
".",
"grd_strip_path_prefix",
")",
"zip_file",
"=",
"zipfile",
".",
"ZipFile",
"(",
"options",
".",
"output",
",",
"'w'",
",",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"try",
":",
"return",
"add_files_to_zip",
"(",
"zip_file",
",",
"options",
".",
"basedir",
",",
"file_list",
")",
"finally",
":",
"zip_file",
".",
"close",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/components/policy/tools/make_policy_zip.py#L45-L79 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | GradLoopState.forward_index | (self) | return self._forward_index | The loop index of forward loop. | The loop index of forward loop. | [
"The",
"loop",
"index",
"of",
"forward",
"loop",
"."
] | def forward_index(self):
"""The loop index of forward loop."""
return self._forward_index | [
"def",
"forward_index",
"(",
"self",
")",
":",
"return",
"self",
".",
"_forward_index"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L571-L573 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewTreeStoreNodeList.__contains__ | (*args, **kwargs) | return _dataview.DataViewTreeStoreNodeList___contains__(*args, **kwargs) | __contains__(self, DataViewTreeStoreNode obj) -> bool | __contains__(self, DataViewTreeStoreNode obj) -> bool | [
"__contains__",
"(",
"self",
"DataViewTreeStoreNode",
"obj",
")",
"-",
">",
"bool"
] | def __contains__(*args, **kwargs):
"""__contains__(self, DataViewTreeStoreNode obj) -> bool"""
return _dataview.DataViewTreeStoreNodeList___contains__(*args, **kwargs) | [
"def",
"__contains__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewTreeStoreNodeList___contains__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L2297-L2299 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/indexes/base.py | python | Index._maybe_disallow_fill | (self, allow_fill: bool, fill_value, indices) | return allow_fill | We only use pandas-style take when allow_fill is True _and_
fill_value is not None. | We only use pandas-style take when allow_fill is True _and_
fill_value is not None. | [
"We",
"only",
"use",
"pandas",
"-",
"style",
"take",
"when",
"allow_fill",
"is",
"True",
"_and_",
"fill_value",
"is",
"not",
"None",
"."
] | def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool:
"""
We only use pandas-style take when allow_fill is True _and_
fill_value is not None.
"""
if allow_fill and fill_value is not None:
# only fill if we are passing a non-None fill_value
if self._can_hold_na:
if (indices < -1).any():
raise ValueError(
"When allow_fill=True and fill_value is not None, "
"all indices must be >= -1"
)
else:
cls_name = type(self).__name__
raise ValueError(
f"Unable to fill values because {cls_name} cannot contain NA"
)
else:
allow_fill = False
return allow_fill | [
"def",
"_maybe_disallow_fill",
"(",
"self",
",",
"allow_fill",
":",
"bool",
",",
"fill_value",
",",
"indices",
")",
"->",
"bool",
":",
"if",
"allow_fill",
"and",
"fill_value",
"is",
"not",
"None",
":",
"# only fill if we are passing a non-None fill_value",
"if",
"self",
".",
"_can_hold_na",
":",
"if",
"(",
"indices",
"<",
"-",
"1",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"When allow_fill=True and fill_value is not None, \"",
"\"all indices must be >= -1\"",
")",
"else",
":",
"cls_name",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"raise",
"ValueError",
"(",
"f\"Unable to fill values because {cls_name} cannot contain NA\"",
")",
"else",
":",
"allow_fill",
"=",
"False",
"return",
"allow_fill"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L967-L987 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/getopt.py | python | gnu_getopt | (args, shortopts, longopts = []) | return opts, prog_args | getopt(args, options[, long_options]) -> opts, args
This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing options as soon as a non-option argument is
encountered.
If the first character of the option string is `+', or if the
environment variable POSIXLY_CORRECT is set, then option
processing stops as soon as a non-option argument is encountered. | getopt(args, options[, long_options]) -> opts, args | [
"getopt",
"(",
"args",
"options",
"[",
"long_options",
"]",
")",
"-",
">",
"opts",
"args"
] | def gnu_getopt(args, shortopts, longopts = []):
"""getopt(args, options[, long_options]) -> opts, args
This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing options as soon as a non-option argument is
encountered.
If the first character of the option string is `+', or if the
environment variable POSIXLY_CORRECT is set, then option
processing stops as soon as a non-option argument is encountered.
"""
opts = []
prog_args = []
if isinstance(longopts, str):
longopts = [longopts]
else:
longopts = list(longopts)
# Allow options after non-option arguments?
if shortopts.startswith('+'):
shortopts = shortopts[1:]
all_options_first = True
elif os.environ.get("POSIXLY_CORRECT"):
all_options_first = True
else:
all_options_first = False
while args:
if args[0] == '--':
prog_args += args[1:]
break
if args[0][:2] == '--':
opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
elif args[0][:1] == '-' and args[0] != '-':
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
else:
if all_options_first:
prog_args += args
break
else:
prog_args.append(args[0])
args = args[1:]
return opts, prog_args | [
"def",
"gnu_getopt",
"(",
"args",
",",
"shortopts",
",",
"longopts",
"=",
"[",
"]",
")",
":",
"opts",
"=",
"[",
"]",
"prog_args",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"longopts",
",",
"str",
")",
":",
"longopts",
"=",
"[",
"longopts",
"]",
"else",
":",
"longopts",
"=",
"list",
"(",
"longopts",
")",
"# Allow options after non-option arguments?",
"if",
"shortopts",
".",
"startswith",
"(",
"'+'",
")",
":",
"shortopts",
"=",
"shortopts",
"[",
"1",
":",
"]",
"all_options_first",
"=",
"True",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"\"POSIXLY_CORRECT\"",
")",
":",
"all_options_first",
"=",
"True",
"else",
":",
"all_options_first",
"=",
"False",
"while",
"args",
":",
"if",
"args",
"[",
"0",
"]",
"==",
"'--'",
":",
"prog_args",
"+=",
"args",
"[",
"1",
":",
"]",
"break",
"if",
"args",
"[",
"0",
"]",
"[",
":",
"2",
"]",
"==",
"'--'",
":",
"opts",
",",
"args",
"=",
"do_longs",
"(",
"opts",
",",
"args",
"[",
"0",
"]",
"[",
"2",
":",
"]",
",",
"longopts",
",",
"args",
"[",
"1",
":",
"]",
")",
"elif",
"args",
"[",
"0",
"]",
"[",
":",
"1",
"]",
"==",
"'-'",
"and",
"args",
"[",
"0",
"]",
"!=",
"'-'",
":",
"opts",
",",
"args",
"=",
"do_shorts",
"(",
"opts",
",",
"args",
"[",
"0",
"]",
"[",
"1",
":",
"]",
",",
"shortopts",
",",
"args",
"[",
"1",
":",
"]",
")",
"else",
":",
"if",
"all_options_first",
":",
"prog_args",
"+=",
"args",
"break",
"else",
":",
"prog_args",
".",
"append",
"(",
"args",
"[",
"0",
"]",
")",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"return",
"opts",
",",
"prog_args"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/getopt.py#L94-L142 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/graph_editor/subgraph.py | python | _check_graph | (sgv, graph) | return sgv | Check if sgv belongs to the given graph.
Args:
sgv: a SubGraphView.
graph: a graph or None.
Returns:
The SubGraphView sgv.
Raises:
TypeError: if sgv is not a SubGraphView or if graph is not None and not
a tf.Graph.
ValueError: if the graph of sgv and the given graph are not None and
different. | Check if sgv belongs to the given graph. | [
"Check",
"if",
"sgv",
"belongs",
"to",
"the",
"given",
"graph",
"."
] | def _check_graph(sgv, graph):
"""Check if sgv belongs to the given graph.
Args:
sgv: a SubGraphView.
graph: a graph or None.
Returns:
The SubGraphView sgv.
Raises:
TypeError: if sgv is not a SubGraphView or if graph is not None and not
a tf.Graph.
ValueError: if the graph of sgv and the given graph are not None and
different.
"""
if not isinstance(sgv, SubGraphView):
raise TypeError("Expected a SubGraphView, got: {}".format(type(graph)))
if graph is None or not sgv.graph:
return sgv
if not isinstance(graph, tf_ops.Graph):
raise TypeError("Expected a tf.Graph, got: {}".format(type(graph)))
if sgv.graph is not graph:
raise ValueError("Graph mismatch.")
return sgv | [
"def",
"_check_graph",
"(",
"sgv",
",",
"graph",
")",
":",
"if",
"not",
"isinstance",
"(",
"sgv",
",",
"SubGraphView",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a SubGraphView, got: {}\"",
".",
"format",
"(",
"type",
"(",
"graph",
")",
")",
")",
"if",
"graph",
"is",
"None",
"or",
"not",
"sgv",
".",
"graph",
":",
"return",
"sgv",
"if",
"not",
"isinstance",
"(",
"graph",
",",
"tf_ops",
".",
"Graph",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a tf.Graph, got: {}\"",
".",
"format",
"(",
"type",
"(",
"graph",
")",
")",
")",
"if",
"sgv",
".",
"graph",
"is",
"not",
"graph",
":",
"raise",
"ValueError",
"(",
"\"Graph mismatch.\"",
")",
"return",
"sgv"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/subgraph.py#L604-L626 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py | python | rebin_to_smallest | (*workspaces) | return rebinned_workspaces | Rebins the specified list to the workspace with the smallest
x-range in the list.
:param workspaces: The list of workspaces to rebin to the smallest.
:return: The rebinned list of workspaces. | Rebins the specified list to the workspace with the smallest
x-range in the list. | [
"Rebins",
"the",
"specified",
"list",
"to",
"the",
"workspace",
"with",
"the",
"smallest",
"x",
"-",
"range",
"in",
"the",
"list",
"."
] | def rebin_to_smallest(*workspaces):
"""
Rebins the specified list to the workspace with the smallest
x-range in the list.
:param workspaces: The list of workspaces to rebin to the smallest.
:return: The rebinned list of workspaces.
"""
if len(workspaces) == 1:
return workspaces
smallest_idx, smallest_ws = \
min(enumerate(workspaces), key=lambda x: x[1].blocksize())
rebinned_workspaces = []
for idx, workspace in enumerate(workspaces):
# Check whether this is the workspace with the smallest x-range.
# No reason to rebin workspace to match itself.
# NOTE: In the future this may append workspace.clone() - this will
# occur in the circumstance that the input files do not want to be
# removed from the ADS.
if idx == smallest_idx:
rebinned_workspaces.append(workspace)
else:
rebinned_workspaces.append(RebinToWorkspace(WorkspaceToRebin=workspace,
WorkspaceToMatch=smallest_ws,
OutputWorkspace="rebinned",
StoreInADS=False, EnableLogging=False))
return rebinned_workspaces | [
"def",
"rebin_to_smallest",
"(",
"*",
"workspaces",
")",
":",
"if",
"len",
"(",
"workspaces",
")",
"==",
"1",
":",
"return",
"workspaces",
"smallest_idx",
",",
"smallest_ws",
"=",
"min",
"(",
"enumerate",
"(",
"workspaces",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
".",
"blocksize",
"(",
")",
")",
"rebinned_workspaces",
"=",
"[",
"]",
"for",
"idx",
",",
"workspace",
"in",
"enumerate",
"(",
"workspaces",
")",
":",
"# Check whether this is the workspace with the smallest x-range.",
"# No reason to rebin workspace to match itself.",
"# NOTE: In the future this may append workspace.clone() - this will",
"# occur in the circumstance that the input files do not want to be",
"# removed from the ADS.",
"if",
"idx",
"==",
"smallest_idx",
":",
"rebinned_workspaces",
".",
"append",
"(",
"workspace",
")",
"else",
":",
"rebinned_workspaces",
".",
"append",
"(",
"RebinToWorkspace",
"(",
"WorkspaceToRebin",
"=",
"workspace",
",",
"WorkspaceToMatch",
"=",
"smallest_ws",
",",
"OutputWorkspace",
"=",
"\"rebinned\"",
",",
"StoreInADS",
"=",
"False",
",",
"EnableLogging",
"=",
"False",
")",
")",
"return",
"rebinned_workspaces"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py#L304-L334 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | examples/python/mach_o.py | python | TerminalColors.black | (self, fg=True) | return '' | Set the foreground or background color to black.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | Set the foreground or background color to black.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | [
"Set",
"the",
"foreground",
"or",
"background",
"color",
"to",
"black",
".",
"The",
"foreground",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"True",
".",
"The",
"background",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"False",
"."
] | def black(self, fg=True):
'''Set the foreground or background color to black.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[30m"
else:
return "\x1b[40m"
return '' | [
"def",
"black",
"(",
"self",
",",
"fg",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"fg",
":",
"return",
"\"\\x1b[30m\"",
"else",
":",
"return",
"\"\\x1b[40m\"",
"return",
"''"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/examples/python/mach_o.py#L271-L279 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.StyleGetHotSpot | (*args, **kwargs) | return _stc.StyledTextCtrl_StyleGetHotSpot(*args, **kwargs) | StyleGetHotSpot(self, int style) -> bool
Get is a style a hotspot or not. | StyleGetHotSpot(self, int style) -> bool | [
"StyleGetHotSpot",
"(",
"self",
"int",
"style",
")",
"-",
">",
"bool"
] | def StyleGetHotSpot(*args, **kwargs):
"""
StyleGetHotSpot(self, int style) -> bool
Get is a style a hotspot or not.
"""
return _stc.StyledTextCtrl_StyleGetHotSpot(*args, **kwargs) | [
"def",
"StyleGetHotSpot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_StyleGetHotSpot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2683-L2689 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/date_converters.py | python | parse_date_time | (date_col, time_col) | return parsing.try_parse_date_and_time(date_col, time_col) | Parse columns with dates and times into a single datetime column.
.. deprecated:: 1.2 | Parse columns with dates and times into a single datetime column. | [
"Parse",
"columns",
"with",
"dates",
"and",
"times",
"into",
"a",
"single",
"datetime",
"column",
"."
] | def parse_date_time(date_col, time_col):
"""
Parse columns with dates and times into a single datetime column.
.. deprecated:: 1.2
"""
warnings.warn(
"""
Use pd.to_datetime(date_col + " " + time_col) instead to get a Pandas Series.
Use pd.to_datetime(date_col + " " + time_col).to_pydatetime() instead to get a Numpy array.
""", # noqa: E501
FutureWarning,
stacklevel=2,
)
date_col = _maybe_cast(date_col)
time_col = _maybe_cast(time_col)
return parsing.try_parse_date_and_time(date_col, time_col) | [
"def",
"parse_date_time",
"(",
"date_col",
",",
"time_col",
")",
":",
"warnings",
".",
"warn",
"(",
"\"\"\"\n Use pd.to_datetime(date_col + \" \" + time_col) instead to get a Pandas Series.\n Use pd.to_datetime(date_col + \" \" + time_col).to_pydatetime() instead to get a Numpy array.\n\"\"\"",
",",
"# noqa: E501",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"date_col",
"=",
"_maybe_cast",
"(",
"date_col",
")",
"time_col",
"=",
"_maybe_cast",
"(",
"time_col",
")",
"return",
"parsing",
".",
"try_parse_date_and_time",
"(",
"date_col",
",",
"time_col",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/date_converters.py#L9-L25 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/third_party/six/six.py | python | _SixMetaPathImporter.is_package | (self, fullname) | return hasattr(self.__get_module(fullname), "__path__") | Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451) | Return true, if the named module is a package. | [
"Return",
"true",
"if",
"the",
"named",
"module",
"is",
"a",
"package",
"."
] | def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__") | [
"def",
"is_package",
"(",
"self",
",",
"fullname",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"__get_module",
"(",
"fullname",
")",
",",
"\"__path__\"",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/third_party/six/six.py#L209-L216 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextParagraphLayoutBox.GetStyle | (*args, **kwargs) | return _richtext.RichTextParagraphLayoutBox_GetStyle(*args, **kwargs) | GetStyle(self, long position, RichTextAttr style) -> bool | GetStyle(self, long position, RichTextAttr style) -> bool | [
"GetStyle",
"(",
"self",
"long",
"position",
"RichTextAttr",
"style",
")",
"-",
">",
"bool"
] | def GetStyle(*args, **kwargs):
"""GetStyle(self, long position, RichTextAttr style) -> bool"""
return _richtext.RichTextParagraphLayoutBox_GetStyle(*args, **kwargs) | [
"def",
"GetStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraphLayoutBox_GetStyle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1732-L1734 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.