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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/training_v1.py | python | Model._prepare_sample_weights | (self, sample_weights=None) | Sets sample weight attribute on the model. | Sets sample weight attribute on the model. | [
"Sets",
"sample",
"weight",
"attribute",
"on",
"the",
"model",
"."
] | def _prepare_sample_weights(self, sample_weights=None):
"""Sets sample weight attribute on the model."""
# List with the same length as model outputs.
if sample_weights is not None:
if len(sample_weights) != len(self._training_endpoints):
raise ValueError('Provided sample weights must have same length as the '
'number of outputs. Expected: {}, got: {}.'.format(
len(self._training_endpoints),
len(sample_weights)))
else:
sample_weights = [None] * len(self._training_endpoints)
for endpoint, weight in zip(self._training_endpoints, sample_weights):
endpoint.populate_sample_weight(weight, endpoint.sample_weight_mode) | [
"def",
"_prepare_sample_weights",
"(",
"self",
",",
"sample_weights",
"=",
"None",
")",
":",
"# List with the same length as model outputs.",
"if",
"sample_weights",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"sample_weights",
")",
"!=",
"len",
"(",
"self",
".",
"_training_endpoints",
")",
":",
"raise",
"ValueError",
"(",
"'Provided sample weights must have same length as the '",
"'number of outputs. Expected: {}, got: {}.'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_training_endpoints",
")",
",",
"len",
"(",
"sample_weights",
")",
")",
")",
"else",
":",
"sample_weights",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"self",
".",
"_training_endpoints",
")",
"for",
"endpoint",
",",
"weight",
"in",
"zip",
"(",
"self",
".",
"_training_endpoints",
",",
"sample_weights",
")",
":",
"endpoint",
".",
"populate_sample_weight",
"(",
"weight",
",",
"endpoint",
".",
"sample_weight_mode",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_v1.py#L1774-L1786 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/environment.py | python | Environment.call_test | (self, name, value, args=None, kwargs=None) | return func(value, *(args or ()), **(kwargs or {})) | Invokes a test on a value the same way the compiler does it.
.. versionadded:: 2.7 | Invokes a test on a value the same way the compiler does it. | [
"Invokes",
"a",
"test",
"on",
"a",
"value",
"the",
"same",
"way",
"the",
"compiler",
"does",
"it",
"."
] | def call_test(self, name, value, args=None, kwargs=None):
"""Invokes a test on a value the same way the compiler does it.
.. versionadded:: 2.7
"""
func = self.tests.get(name)
if func is None:
fail_for_missing_callable('no test named %r', name)
return func(value, *(args or ()), **(kwargs or {})) | [
"def",
"call_test",
"(",
"self",
",",
"name",
",",
"value",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"func",
"=",
"self",
".",
"tests",
".",
"get",
"(",
"name",
")",
"if",
"func",
"is",
"None",
":",
"fail_for_missing_callable",
"(",
"'no test named %r'",
",",
"name",
")",
"return",
"func",
"(",
"value",
",",
"*",
"(",
"args",
"or",
"(",
")",
")",
",",
"*",
"*",
"(",
"kwargs",
"or",
"{",
"}",
")",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/environment.py#L469-L477 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | getdata | (a, subok=True) | return data | Return the data of a masked array as an ndarray.
Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
else return `a` as a ndarray or subclass (depending on `subok`) if not.
Parameters
----------
a : array_like
Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a `pure` ndarray (False) or to
return a subclass of ndarray if appropriate (True, default).
See Also
--------
getmask : Return the mask of a masked array, or nomask.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=2)
>>> ma.getdata(a)
array([[1, 2],
[3, 4]])
Equivalently use the ``MaskedArray`` `data` attribute.
>>> a.data
array([[1, 2],
[3, 4]]) | Return the data of a masked array as an ndarray. | [
"Return",
"the",
"data",
"of",
"a",
"masked",
"array",
"as",
"an",
"ndarray",
"."
] | def getdata(a, subok=True):
"""
Return the data of a masked array as an ndarray.
Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
else return `a` as a ndarray or subclass (depending on `subok`) if not.
Parameters
----------
a : array_like
Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a `pure` ndarray (False) or to
return a subclass of ndarray if appropriate (True, default).
See Also
--------
getmask : Return the mask of a masked array, or nomask.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=2)
>>> ma.getdata(a)
array([[1, 2],
[3, 4]])
Equivalently use the ``MaskedArray`` `data` attribute.
>>> a.data
array([[1, 2],
[3, 4]])
"""
try:
data = a._data
except AttributeError:
data = np.array(a, copy=False, subok=subok)
if not subok:
return data.view(ndarray)
return data | [
"def",
"getdata",
"(",
"a",
",",
"subok",
"=",
"True",
")",
":",
"try",
":",
"data",
"=",
"a",
".",
"_data",
"except",
"AttributeError",
":",
"data",
"=",
"np",
".",
"array",
"(",
"a",
",",
"copy",
"=",
"False",
",",
"subok",
"=",
"subok",
")",
"if",
"not",
"subok",
":",
"return",
"data",
".",
"view",
"(",
"ndarray",
")",
"return",
"data"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L677-L725 | |
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/descriptor_pool.py | python | DescriptorPool.FindFileContainingSymbol | (self, symbol) | return self._ConvertFileProtoToFileDescriptor(file_proto) | Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file can not be found in the pool. | Gets the FileDescriptor for the file containing the specified symbol. | [
"Gets",
"the",
"FileDescriptor",
"for",
"the",
"file",
"containing",
"the",
"specified",
"symbol",
"."
] | def FindFileContainingSymbol(self, symbol):
"""Gets the FileDescriptor for the file containing the specified symbol.
Args:
symbol: The name of the symbol to search for.
Returns:
A FileDescriptor that contains the specified symbol.
Raises:
KeyError: if the file can not be found in the pool.
"""
symbol = _NormalizeFullyQualifiedName(symbol)
try:
return self._descriptors[symbol].file
except KeyError:
pass
try:
return self._enum_descriptors[symbol].file
except KeyError:
pass
try:
file_proto = self._internal_db.FindFileContainingSymbol(symbol)
except KeyError:
_, error, _ = sys.exc_info() #PY25 compatible for GAE.
if self._descriptor_db:
file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
else:
raise error
if not file_proto:
raise KeyError('Cannot find a file containing %s' % symbol)
return self._ConvertFileProtoToFileDescriptor(file_proto) | [
"def",
"FindFileContainingSymbol",
"(",
"self",
",",
"symbol",
")",
":",
"symbol",
"=",
"_NormalizeFullyQualifiedName",
"(",
"symbol",
")",
"try",
":",
"return",
"self",
".",
"_descriptors",
"[",
"symbol",
"]",
".",
"file",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"_enum_descriptors",
"[",
"symbol",
"]",
".",
"file",
"except",
"KeyError",
":",
"pass",
"try",
":",
"file_proto",
"=",
"self",
".",
"_internal_db",
".",
"FindFileContainingSymbol",
"(",
"symbol",
")",
"except",
"KeyError",
":",
"_",
",",
"error",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"#PY25 compatible for GAE.",
"if",
"self",
".",
"_descriptor_db",
":",
"file_proto",
"=",
"self",
".",
"_descriptor_db",
".",
"FindFileContainingSymbol",
"(",
"symbol",
")",
"else",
":",
"raise",
"error",
"if",
"not",
"file_proto",
":",
"raise",
"KeyError",
"(",
"'Cannot find a file containing %s'",
"%",
"symbol",
")",
"return",
"self",
".",
"_ConvertFileProtoToFileDescriptor",
"(",
"file_proto",
")"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/descriptor_pool.py#L188-L222 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_CLOCK_INFO.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeInt64(self.clock)
buf.writeInt(self.resetCount)
buf.writeInt(self.restartCount)
buf.writeByte(self.safe) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeInt64",
"(",
"self",
".",
"clock",
")",
"buf",
".",
"writeInt",
"(",
"self",
".",
"resetCount",
")",
"buf",
".",
"writeInt",
"(",
"self",
".",
"restartCount",
")",
"buf",
".",
"writeByte",
"(",
"self",
".",
"safe",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4996-L5001 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py | python | Flag._WriteCustomInfoInXMLFormat | (self, outfile, indent) | Writes extra info about this flag, in XML format.
"Extra" means "not already printed by WriteInfoInXMLFormat above."
Args:
outfile: File object we write to.
indent: A string that is prepended to each generated line. | Writes extra info about this flag, in XML format. | [
"Writes",
"extra",
"info",
"about",
"this",
"flag",
"in",
"XML",
"format",
"."
] | def _WriteCustomInfoInXMLFormat(self, outfile, indent):
"""Writes extra info about this flag, in XML format.
"Extra" means "not already printed by WriteInfoInXMLFormat above."
Args:
outfile: File object we write to.
indent: A string that is prepended to each generated line.
"""
# Usually, the parser knows the extra details about the flag, so
# we just forward the call to it.
self.parser.WriteCustomInfoInXMLFormat(outfile, indent) | [
"def",
"_WriteCustomInfoInXMLFormat",
"(",
"self",
",",
"outfile",
",",
"indent",
")",
":",
"# Usually, the parser knows the extra details about the flag, so",
"# we just forward the call to it.",
"self",
".",
"parser",
".",
"WriteCustomInfoInXMLFormat",
"(",
"outfile",
",",
"indent",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py#L1978-L1989 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/ext.py | python | Extension.parse | (self, parser) | If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes. | If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes. | [
"If",
"any",
"of",
"the",
":",
"attr",
":",
"tags",
"matched",
"this",
"method",
"is",
"called",
"with",
"the",
"parser",
"as",
"first",
"argument",
".",
"The",
"token",
"the",
"parser",
"stream",
"is",
"pointing",
"at",
"is",
"the",
"name",
"token",
"that",
"matched",
".",
"This",
"method",
"has",
"to",
"return",
"one",
"or",
"a",
"list",
"of",
"multiple",
"nodes",
"."
] | def parse(self, parser):
"""If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes.
"""
raise NotImplementedError() | [
"def",
"parse",
"(",
"self",
",",
"parser",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/ext.py#L99-L105 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.EndParagraphSpacing | (*args, **kwargs) | return _richtext.RichTextCtrl_EndParagraphSpacing(*args, **kwargs) | EndParagraphSpacing(self) -> bool
End paragraph spacing | EndParagraphSpacing(self) -> bool | [
"EndParagraphSpacing",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndParagraphSpacing(*args, **kwargs):
"""
EndParagraphSpacing(self) -> bool
End paragraph spacing
"""
return _richtext.RichTextCtrl_EndParagraphSpacing(*args, **kwargs) | [
"def",
"EndParagraphSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_EndParagraphSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3491-L3497 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Window.SetClientSize | (*args, **kwargs) | return _core_.Window_SetClientSize(*args, **kwargs) | SetClientSize(self, Size size)
This sets the size of the window client area in pixels. Using this
function to size a window tends to be more device-independent than
wx.Window.SetSize, since the application need not worry about what
dimensions the border or title bar have when trying to fit the window
around panel items, for example. | SetClientSize(self, Size size) | [
"SetClientSize",
"(",
"self",
"Size",
"size",
")"
] | def SetClientSize(*args, **kwargs):
"""
SetClientSize(self, Size size)
This sets the size of the window client area in pixels. Using this
function to size a window tends to be more device-independent than
wx.Window.SetSize, since the application need not worry about what
dimensions the border or title bar have when trying to fit the window
around panel items, for example.
"""
return _core_.Window_SetClientSize(*args, **kwargs) | [
"def",
"SetClientSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetClientSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L9418-L9428 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/common.py | python | ExceptionAppend | (e, msg) | Append a message to the given exception's message. | Append a message to the given exception's message. | [
"Append",
"a",
"message",
"to",
"the",
"given",
"exception",
"s",
"message",
"."
] | def ExceptionAppend(e, msg):
"""Append a message to the given exception's message."""
if not e.args:
e.args = (msg,)
elif len(e.args) == 1:
e.args = (str(e.args[0]) + ' ' + msg,)
else:
e.args = (str(e.args[0]) + ' ' + msg,) + e.args[1:] | [
"def",
"ExceptionAppend",
"(",
"e",
",",
"msg",
")",
":",
"if",
"not",
"e",
".",
"args",
":",
"e",
".",
"args",
"=",
"(",
"msg",
",",
")",
"elif",
"len",
"(",
"e",
".",
"args",
")",
"==",
"1",
":",
"e",
".",
"args",
"=",
"(",
"str",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
"+",
"' '",
"+",
"msg",
",",
")",
"else",
":",
"e",
".",
"args",
"=",
"(",
"str",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
"+",
"' '",
"+",
"msg",
",",
")",
"+",
"e",
".",
"args",
"[",
"1",
":",
"]"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/common.py#L38-L45 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/plot.py | python | PolyMarker.getSymExtent | (self, printerScale) | return (s, s) | Width and Height of Marker | Width and Height of Marker | [
"Width",
"and",
"Height",
"of",
"Marker"
] | def getSymExtent(self, printerScale):
"""Width and Height of Marker"""
s = 5 * self.attributes['size'] * printerScale * self._pointSize[0]
return (s, s) | [
"def",
"getSymExtent",
"(",
"self",
",",
"printerScale",
")",
":",
"s",
"=",
"5",
"*",
"self",
".",
"attributes",
"[",
"'size'",
"]",
"*",
"printerScale",
"*",
"self",
".",
"_pointSize",
"[",
"0",
"]",
"return",
"(",
"s",
",",
"s",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L383-L386 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/Maya_AnimationRiggingTools/ARTv1/MayaTools/General/Scripts/Modules/facial/face.py | python | FaceMask.snapMovers | (self, axis, mesh, debug=1) | for this system, in the tool UI itself that snaps the movers, I always bidirectionally cast against Y | [] | def snapMovers(self, axis, mesh, debug=1):
'''
for this system, in the tool UI itself that snaps the movers, I always bidirectionally cast against Y
'''
try:
cmds.undoInfo(openChunk=True)
#iterate through the *active* facial joint movers and snap them to the surface
if debug: print 'activeJointMovers:', self.faceModule.activeJointMovers
for mover in self.faceModule.activeJointMovers:
if debug: print 'snapping', mover
#do not snap manually placed movers
if not cmds.getAttr(mover + '.alignmentType'):
#set the axis vector
axisVector = None
if axis == 'x': axisVector = utils.getAxisWorldVectors(mover)[0]
elif axis == 'y': axisVector = utils.getAxisWorldVectors(mover)[1]
elif axis == 'z': axisVector = utils.getAxisWorldVectors(mover)[2]
pos = cmds.xform(mover, q=1, rp=1, ws=1)
#raycast in and out and find the closest hit of the facial surface
pos1 = utils.rayMeshIntersect(mesh, pos, axisVector)
pos2 = utils.rayMeshIntersect(mesh, pos, -axisVector)
dist1 = utils.square_distance(pos, pos1)
dist2 = utils.square_distance(pos, pos2)
newPos = None
if dist1 <= dist2:
newPos = pos1
else:
newPos = pos2
cmds.xform(mover, t=newPos, ws=1)
if debug: print mover, 'snapped.'
except Exception as e:
print e
finally:
cmds.undoInfo(closeChunk=True) | [
"def",
"snapMovers",
"(",
"self",
",",
"axis",
",",
"mesh",
",",
"debug",
"=",
"1",
")",
":",
"try",
":",
"cmds",
".",
"undoInfo",
"(",
"openChunk",
"=",
"True",
")",
"#iterate through the *active* facial joint movers and snap them to the surface",
"if",
"debug",
":",
"print",
"'activeJointMovers:'",
",",
"self",
".",
"faceModule",
".",
"activeJointMovers",
"for",
"mover",
"in",
"self",
".",
"faceModule",
".",
"activeJointMovers",
":",
"if",
"debug",
":",
"print",
"'snapping'",
",",
"mover",
"#do not snap manually placed movers",
"if",
"not",
"cmds",
".",
"getAttr",
"(",
"mover",
"+",
"'.alignmentType'",
")",
":",
"#set the axis vector",
"axisVector",
"=",
"None",
"if",
"axis",
"==",
"'x'",
":",
"axisVector",
"=",
"utils",
".",
"getAxisWorldVectors",
"(",
"mover",
")",
"[",
"0",
"]",
"elif",
"axis",
"==",
"'y'",
":",
"axisVector",
"=",
"utils",
".",
"getAxisWorldVectors",
"(",
"mover",
")",
"[",
"1",
"]",
"elif",
"axis",
"==",
"'z'",
":",
"axisVector",
"=",
"utils",
".",
"getAxisWorldVectors",
"(",
"mover",
")",
"[",
"2",
"]",
"pos",
"=",
"cmds",
".",
"xform",
"(",
"mover",
",",
"q",
"=",
"1",
",",
"rp",
"=",
"1",
",",
"ws",
"=",
"1",
")",
"#raycast in and out and find the closest hit of the facial surface",
"pos1",
"=",
"utils",
".",
"rayMeshIntersect",
"(",
"mesh",
",",
"pos",
",",
"axisVector",
")",
"pos2",
"=",
"utils",
".",
"rayMeshIntersect",
"(",
"mesh",
",",
"pos",
",",
"-",
"axisVector",
")",
"dist1",
"=",
"utils",
".",
"square_distance",
"(",
"pos",
",",
"pos1",
")",
"dist2",
"=",
"utils",
".",
"square_distance",
"(",
"pos",
",",
"pos2",
")",
"newPos",
"=",
"None",
"if",
"dist1",
"<=",
"dist2",
":",
"newPos",
"=",
"pos1",
"else",
":",
"newPos",
"=",
"pos2",
"cmds",
".",
"xform",
"(",
"mover",
",",
"t",
"=",
"newPos",
",",
"ws",
"=",
"1",
")",
"if",
"debug",
":",
"print",
"mover",
",",
"'snapped.'",
"except",
"Exception",
"as",
"e",
":",
"print",
"e",
"finally",
":",
"cmds",
".",
"undoInfo",
"(",
"closeChunk",
"=",
"True",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/Maya_AnimationRiggingTools/ARTv1/MayaTools/General/Scripts/Modules/facial/face.py#L197-L271 | |||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | SizerFlags.DoubleBorder | (*args, **kwargs) | return _core_.SizerFlags_DoubleBorder(*args, **kwargs) | DoubleBorder(self, int direction=ALL) -> SizerFlags
Sets the border in the given direction to twice the default border
size. | DoubleBorder(self, int direction=ALL) -> SizerFlags | [
"DoubleBorder",
"(",
"self",
"int",
"direction",
"=",
"ALL",
")",
"-",
">",
"SizerFlags"
] | def DoubleBorder(*args, **kwargs):
"""
DoubleBorder(self, int direction=ALL) -> SizerFlags
Sets the border in the given direction to twice the default border
size.
"""
return _core_.SizerFlags_DoubleBorder(*args, **kwargs) | [
"def",
"DoubleBorder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerFlags_DoubleBorder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13880-L13887 | |
sit/dht | bab0bd7d81b0f04d1777ce30d21744bf481e77b3 | tools/RPC.py | python | Server.__init__ | (self, module, PROG, VERS, port, handlers, name=None) | If name is not None, Server prints debug messages
prefixed by name. | If name is not None, Server prints debug messages
prefixed by name. | [
"If",
"name",
"is",
"not",
"None",
"Server",
"prints",
"debug",
"messages",
"prefixed",
"by",
"name",
"."
] | def __init__(self, module, PROG, VERS, port, handlers, name=None):
"""If name is not None, Server prints debug messages
prefixed by name."""
assert module is not None
assert 'programs' in dir(module)
assert PROG in module.programs
assert VERS in module.programs[PROG]
for proc in handlers:
assert proc in module.programs[PROG][VERS]
import SocketServer
class StreamHandler(SocketServer.StreamRequestHandler):
def dispatch(self, request):
xid, prog, vers, proc, cred, verf, u = unpack_call(
request, myprog=PROG, myvers=VERS)
if proc in handlers:
if name:
print name + ": Got proc", proc
arg = module.programs[PROG][VERS][proc].unpack_arg(u)
res = handlers[proc](xid, cred, verf, arg)
p = pack_reply(xid, MSG_ACCEPTED, NULL_AUTH, SUCCESS)
module.programs[PROG][VERS][proc].pack_res(p, res)
return p.get_buffer()
else:
# no such procedure
if name:
print name + ": Got unknown proc", proc
return pack_reply(xid, MSG_ACCEPTED, NULL_AUTH,
PROC_UNAVAIL).get_buffer()
def handle(self):
rfile = self.request.makefile('rb', -1)
wfile = self.request.makefile('wb', -1)
if name:
print name + ": Got connection from", self.client_address
while 1:
try:
request = readfrags(rfile.read)
reply = self.dispatch(request)
writefrags(reply, wfile.write)
wfile.flush()
except EOFError:
return
except UnpackException, e:
if name:
print name + ":", e
return
except ReplyException, e:
if name:
print name + ":", e
writefrags(e.reply, wfile.write)
wfile.flush()
except:
if name:
print name + ": Unexpected error:"
print_exc()
return # avoid killing the server
self.handler = StreamHandler
self.port = port | [
"def",
"__init__",
"(",
"self",
",",
"module",
",",
"PROG",
",",
"VERS",
",",
"port",
",",
"handlers",
",",
"name",
"=",
"None",
")",
":",
"assert",
"module",
"is",
"not",
"None",
"assert",
"'programs'",
"in",
"dir",
"(",
"module",
")",
"assert",
"PROG",
"in",
"module",
".",
"programs",
"assert",
"VERS",
"in",
"module",
".",
"programs",
"[",
"PROG",
"]",
"for",
"proc",
"in",
"handlers",
":",
"assert",
"proc",
"in",
"module",
".",
"programs",
"[",
"PROG",
"]",
"[",
"VERS",
"]",
"import",
"SocketServer",
"class",
"StreamHandler",
"(",
"SocketServer",
".",
"StreamRequestHandler",
")",
":",
"def",
"dispatch",
"(",
"self",
",",
"request",
")",
":",
"xid",
",",
"prog",
",",
"vers",
",",
"proc",
",",
"cred",
",",
"verf",
",",
"u",
"=",
"unpack_call",
"(",
"request",
",",
"myprog",
"=",
"PROG",
",",
"myvers",
"=",
"VERS",
")",
"if",
"proc",
"in",
"handlers",
":",
"if",
"name",
":",
"print",
"name",
"+",
"\": Got proc\"",
",",
"proc",
"arg",
"=",
"module",
".",
"programs",
"[",
"PROG",
"]",
"[",
"VERS",
"]",
"[",
"proc",
"]",
".",
"unpack_arg",
"(",
"u",
")",
"res",
"=",
"handlers",
"[",
"proc",
"]",
"(",
"xid",
",",
"cred",
",",
"verf",
",",
"arg",
")",
"p",
"=",
"pack_reply",
"(",
"xid",
",",
"MSG_ACCEPTED",
",",
"NULL_AUTH",
",",
"SUCCESS",
")",
"module",
".",
"programs",
"[",
"PROG",
"]",
"[",
"VERS",
"]",
"[",
"proc",
"]",
".",
"pack_res",
"(",
"p",
",",
"res",
")",
"return",
"p",
".",
"get_buffer",
"(",
")",
"else",
":",
"# no such procedure",
"if",
"name",
":",
"print",
"name",
"+",
"\": Got unknown proc\"",
",",
"proc",
"return",
"pack_reply",
"(",
"xid",
",",
"MSG_ACCEPTED",
",",
"NULL_AUTH",
",",
"PROC_UNAVAIL",
")",
".",
"get_buffer",
"(",
")",
"def",
"handle",
"(",
"self",
")",
":",
"rfile",
"=",
"self",
".",
"request",
".",
"makefile",
"(",
"'rb'",
",",
"-",
"1",
")",
"wfile",
"=",
"self",
".",
"request",
".",
"makefile",
"(",
"'wb'",
",",
"-",
"1",
")",
"if",
"name",
":",
"print",
"name",
"+",
"\": Got connection from\"",
",",
"self",
".",
"client_address",
"while",
"1",
":",
"try",
":",
"request",
"=",
"readfrags",
"(",
"rfile",
".",
"read",
")",
"reply",
"=",
"self",
".",
"dispatch",
"(",
"request",
")",
"writefrags",
"(",
"reply",
",",
"wfile",
".",
"write",
")",
"wfile",
".",
"flush",
"(",
")",
"except",
"EOFError",
":",
"return",
"except",
"UnpackException",
",",
"e",
":",
"if",
"name",
":",
"print",
"name",
"+",
"\":\"",
",",
"e",
"return",
"except",
"ReplyException",
",",
"e",
":",
"if",
"name",
":",
"print",
"name",
"+",
"\":\"",
",",
"e",
"writefrags",
"(",
"e",
".",
"reply",
",",
"wfile",
".",
"write",
")",
"wfile",
".",
"flush",
"(",
")",
"except",
":",
"if",
"name",
":",
"print",
"name",
"+",
"\": Unexpected error:\"",
"print_exc",
"(",
")",
"return",
"# avoid killing the server",
"self",
".",
"handler",
"=",
"StreamHandler",
"self",
".",
"port",
"=",
"port"
] | https://github.com/sit/dht/blob/bab0bd7d81b0f04d1777ce30d21744bf481e77b3/tools/RPC.py#L297-L353 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/_common.py | python | _validate_fromutc_inputs | (f) | return fromutc | The CPython version of ``fromutc`` checks that the input is a ``datetime``
object and that ``self`` is attached as its ``tzinfo``. | The CPython version of ``fromutc`` checks that the input is a ``datetime``
object and that ``self`` is attached as its ``tzinfo``. | [
"The",
"CPython",
"version",
"of",
"fromutc",
"checks",
"that",
"the",
"input",
"is",
"a",
"datetime",
"object",
"and",
"that",
"self",
"is",
"attached",
"as",
"its",
"tzinfo",
"."
] | def _validate_fromutc_inputs(f):
"""
The CPython version of ``fromutc`` checks that the input is a ``datetime``
object and that ``self`` is attached as its ``tzinfo``.
"""
@wraps(f)
def fromutc(self, dt):
if not isinstance(dt, datetime):
raise TypeError("fromutc() requires a datetime argument")
if dt.tzinfo is not self:
raise ValueError("dt.tzinfo is not self")
return f(self, dt)
return fromutc | [
"def",
"_validate_fromutc_inputs",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"fromutc",
"(",
"self",
",",
"dt",
")",
":",
"if",
"not",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"fromutc() requires a datetime argument\"",
")",
"if",
"dt",
".",
"tzinfo",
"is",
"not",
"self",
":",
"raise",
"ValueError",
"(",
"\"dt.tzinfo is not self\"",
")",
"return",
"f",
"(",
"self",
",",
"dt",
")",
"return",
"fromutc"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/dateutil/tz/_common.py#L98-L112 | |
syoyo/tinygltf | e7f1ff5c59d3ca2489923beb239bdf93d863498f | deps/cpplint.py | python | PrintCategories | () | Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter. | Prints a list of all the error-categories used by error messages. | [
"Prints",
"a",
"list",
"of",
"all",
"the",
"error",
"-",
"categories",
"used",
"by",
"error",
"messages",
"."
] | def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0) | [
"def",
"PrintCategories",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"''",
".",
"join",
"(",
"' %s\\n'",
"%",
"cat",
"for",
"cat",
"in",
"_ERROR_CATEGORIES",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L6225-L6231 | ||
quantumlib/qsim | 8f7f94020c56ad6a8645313743d9985f7ea77808 | qsimcirq/qsim_simulator.py | python | QSimSimulator.simulate_moment_expectation_values | (
self,
program: cirq.Circuit,
indexed_observables: Union[
Dict[int, Union[cirq.PauliSumLike, List[cirq.PauliSumLike]]],
cirq.PauliSumLike,
List[cirq.PauliSumLike],
],
param_resolver: cirq.ParamResolver,
qubit_order: cirq.QubitOrderOrList = cirq.QubitOrder.DEFAULT,
initial_state: Any = None,
) | Calculates expectation values at each moment of a circuit.
Args:
program: The circuit to simulate.
indexed_observables: A map of moment indices to an observable
or list of observables to calculate after that moment. As a
convenience, users can instead pass in a single observable
or observable list to calculate after ALL moments.
param_resolver: Parameters to run with the program.
qubit_order: Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.
initial_state: The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.
permit_terminal_measurements: If the provided circuit ends with
measurement(s), this method will generate an error unless this
is set to True. This is meant to prevent measurements from
ruining expectation value calculations.
Returns:
A list of expectation values for each moment m in the circuit,
where value `n` corresponds to `indexed_observables[m][n]`.
Raises:
ValueError if 'program' has terminal measurement(s) and
'permit_terminal_measurements' is False. (Note: We cannot test this
until Cirq's `are_any_measurements_terminal` is released.) | Calculates expectation values at each moment of a circuit. | [
"Calculates",
"expectation",
"values",
"at",
"each",
"moment",
"of",
"a",
"circuit",
"."
] | def simulate_moment_expectation_values(
self,
program: cirq.Circuit,
indexed_observables: Union[
Dict[int, Union[cirq.PauliSumLike, List[cirq.PauliSumLike]]],
cirq.PauliSumLike,
List[cirq.PauliSumLike],
],
param_resolver: cirq.ParamResolver,
qubit_order: cirq.QubitOrderOrList = cirq.QubitOrder.DEFAULT,
initial_state: Any = None,
) -> List[List[float]]:
"""Calculates expectation values at each moment of a circuit.
Args:
program: The circuit to simulate.
indexed_observables: A map of moment indices to an observable
or list of observables to calculate after that moment. As a
convenience, users can instead pass in a single observable
or observable list to calculate after ALL moments.
param_resolver: Parameters to run with the program.
qubit_order: Determines the canonical ordering of the qubits. This
is often used in specifying the initial state, i.e. the
ordering of the computational basis states.
initial_state: The initial state for the simulation. The form of
this state depends on the simulation implementation. See
documentation of the implementing class for details.
permit_terminal_measurements: If the provided circuit ends with
measurement(s), this method will generate an error unless this
is set to True. This is meant to prevent measurements from
ruining expectation value calculations.
Returns:
A list of expectation values for each moment m in the circuit,
where value `n` corresponds to `indexed_observables[m][n]`.
Raises:
ValueError if 'program' has terminal measurement(s) and
'permit_terminal_measurements' is False. (Note: We cannot test this
until Cirq's `are_any_measurements_terminal` is released.)
"""
if not isinstance(indexed_observables, Dict):
if not isinstance(indexed_observables, List):
indexed_observables = [
(i, [indexed_observables]) for i, _ in enumerate(program)
]
else:
indexed_observables = [
(i, indexed_observables) for i, _ in enumerate(program)
]
else:
indexed_observables = [
(i, obs) if isinstance(obs, List) else (i, [obs])
for i, obs in indexed_observables.items()
]
indexed_observables.sort(key=lambda x: x[0])
psum_pairs = [
(i, [cirq.PauliSum.wrap(pslike) for pslike in obs_list])
for i, obs_list in indexed_observables
]
all_qubits = program.all_qubits()
cirq_order = cirq.QubitOrder.as_qubit_order(qubit_order).order_for(all_qubits)
qsim_order = list(reversed(cirq_order))
num_qubits = len(qsim_order)
qubit_map = {qubit: index for index, qubit in enumerate(qsim_order)}
opsums_and_qcount_map = {}
for i, psumlist in psum_pairs:
opsums_and_qcount_map[i] = []
for psum in psumlist:
opsum = []
opsum_qubits = set()
for pstr in psum:
opstring = qsim.OpString()
opstring.weight = pstr.coefficient
for q, pauli in pstr.items():
op = pauli.on(q)
opsum_qubits.add(q)
qsimc.add_op_to_opstring(op, qubit_map, opstring)
opsum.append(opstring)
opsums_and_qcount_map[i].append((opsum, len(opsum_qubits)))
if initial_state is None:
initial_state = 0
if not isinstance(initial_state, (int, np.ndarray)):
raise TypeError("initial_state must be an int or state vector.")
# Add noise to the circuit if a noise model was provided.
program = qsimc.QSimCircuit(
self.noise.noisy_moments(program, sorted(all_qubits))
if self.noise is not cirq.NO_NOISE
else program,
device=program.device,
)
options = {}
options.update(self.qsim_options)
param_resolver = cirq.to_resolvers(param_resolver)
if isinstance(initial_state, np.ndarray):
if initial_state.dtype != np.complex64:
raise TypeError(f"initial_state vector must have dtype np.complex64.")
input_vector = initial_state.view(np.float32)
if len(input_vector) != 2 ** num_qubits * 2:
raise ValueError(
f"initial_state vector size must match number of qubits."
f"Expected: {2**num_qubits * 2} Received: {len(input_vector)}"
)
is_noisy = _needs_trajectories(program)
if is_noisy:
translator_fn_name = "translate_cirq_to_qtrajectory"
ev_simulator_fn = (
self._sim_module.qtrajectory_simulate_moment_expectation_values
)
else:
translator_fn_name = "translate_cirq_to_qsim"
ev_simulator_fn = self._sim_module.qsim_simulate_moment_expectation_values
solved_circuit = cirq.resolve_parameters(program, param_resolver)
options["c"], opsum_reindex = self._translate_circuit(
solved_circuit,
translator_fn_name,
cirq_order,
)
opsums_and_qubit_counts = []
for m, opsum_qc in opsums_and_qcount_map.items():
pair = (opsum_reindex[m], opsum_qc)
opsums_and_qubit_counts.append(pair)
options["s"] = self.get_seed()
if isinstance(initial_state, int):
return ev_simulator_fn(options, opsums_and_qubit_counts, initial_state)
elif isinstance(initial_state, np.ndarray):
return ev_simulator_fn(options, opsums_and_qubit_counts, input_vector) | [
"def",
"simulate_moment_expectation_values",
"(",
"self",
",",
"program",
":",
"cirq",
".",
"Circuit",
",",
"indexed_observables",
":",
"Union",
"[",
"Dict",
"[",
"int",
",",
"Union",
"[",
"cirq",
".",
"PauliSumLike",
",",
"List",
"[",
"cirq",
".",
"PauliSumLike",
"]",
"]",
"]",
",",
"cirq",
".",
"PauliSumLike",
",",
"List",
"[",
"cirq",
".",
"PauliSumLike",
"]",
",",
"]",
",",
"param_resolver",
":",
"cirq",
".",
"ParamResolver",
",",
"qubit_order",
":",
"cirq",
".",
"QubitOrderOrList",
"=",
"cirq",
".",
"QubitOrder",
".",
"DEFAULT",
",",
"initial_state",
":",
"Any",
"=",
"None",
",",
")",
"->",
"List",
"[",
"List",
"[",
"float",
"]",
"]",
":",
"if",
"not",
"isinstance",
"(",
"indexed_observables",
",",
"Dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"indexed_observables",
",",
"List",
")",
":",
"indexed_observables",
"=",
"[",
"(",
"i",
",",
"[",
"indexed_observables",
"]",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"program",
")",
"]",
"else",
":",
"indexed_observables",
"=",
"[",
"(",
"i",
",",
"indexed_observables",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"program",
")",
"]",
"else",
":",
"indexed_observables",
"=",
"[",
"(",
"i",
",",
"obs",
")",
"if",
"isinstance",
"(",
"obs",
",",
"List",
")",
"else",
"(",
"i",
",",
"[",
"obs",
"]",
")",
"for",
"i",
",",
"obs",
"in",
"indexed_observables",
".",
"items",
"(",
")",
"]",
"indexed_observables",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"psum_pairs",
"=",
"[",
"(",
"i",
",",
"[",
"cirq",
".",
"PauliSum",
".",
"wrap",
"(",
"pslike",
")",
"for",
"pslike",
"in",
"obs_list",
"]",
")",
"for",
"i",
",",
"obs_list",
"in",
"indexed_observables",
"]",
"all_qubits",
"=",
"program",
".",
"all_qubits",
"(",
")",
"cirq_order",
"=",
"cirq",
".",
"QubitOrder",
".",
"as_qubit_order",
"(",
"qubit_order",
")",
".",
"order_for",
"(",
"all_qubits",
")",
"qsim_order",
"=",
"list",
"(",
"reversed",
"(",
"cirq_order",
")",
")",
"num_qubits",
"=",
"len",
"(",
"qsim_order",
")",
"qubit_map",
"=",
"{",
"qubit",
":",
"index",
"for",
"index",
",",
"qubit",
"in",
"enumerate",
"(",
"qsim_order",
")",
"}",
"opsums_and_qcount_map",
"=",
"{",
"}",
"for",
"i",
",",
"psumlist",
"in",
"psum_pairs",
":",
"opsums_and_qcount_map",
"[",
"i",
"]",
"=",
"[",
"]",
"for",
"psum",
"in",
"psumlist",
":",
"opsum",
"=",
"[",
"]",
"opsum_qubits",
"=",
"set",
"(",
")",
"for",
"pstr",
"in",
"psum",
":",
"opstring",
"=",
"qsim",
".",
"OpString",
"(",
")",
"opstring",
".",
"weight",
"=",
"pstr",
".",
"coefficient",
"for",
"q",
",",
"pauli",
"in",
"pstr",
".",
"items",
"(",
")",
":",
"op",
"=",
"pauli",
".",
"on",
"(",
"q",
")",
"opsum_qubits",
".",
"add",
"(",
"q",
")",
"qsimc",
".",
"add_op_to_opstring",
"(",
"op",
",",
"qubit_map",
",",
"opstring",
")",
"opsum",
".",
"append",
"(",
"opstring",
")",
"opsums_and_qcount_map",
"[",
"i",
"]",
".",
"append",
"(",
"(",
"opsum",
",",
"len",
"(",
"opsum_qubits",
")",
")",
")",
"if",
"initial_state",
"is",
"None",
":",
"initial_state",
"=",
"0",
"if",
"not",
"isinstance",
"(",
"initial_state",
",",
"(",
"int",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"initial_state must be an int or state vector.\"",
")",
"# Add noise to the circuit if a noise model was provided.",
"program",
"=",
"qsimc",
".",
"QSimCircuit",
"(",
"self",
".",
"noise",
".",
"noisy_moments",
"(",
"program",
",",
"sorted",
"(",
"all_qubits",
")",
")",
"if",
"self",
".",
"noise",
"is",
"not",
"cirq",
".",
"NO_NOISE",
"else",
"program",
",",
"device",
"=",
"program",
".",
"device",
",",
")",
"options",
"=",
"{",
"}",
"options",
".",
"update",
"(",
"self",
".",
"qsim_options",
")",
"param_resolver",
"=",
"cirq",
".",
"to_resolvers",
"(",
"param_resolver",
")",
"if",
"isinstance",
"(",
"initial_state",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"initial_state",
".",
"dtype",
"!=",
"np",
".",
"complex64",
":",
"raise",
"TypeError",
"(",
"f\"initial_state vector must have dtype np.complex64.\"",
")",
"input_vector",
"=",
"initial_state",
".",
"view",
"(",
"np",
".",
"float32",
")",
"if",
"len",
"(",
"input_vector",
")",
"!=",
"2",
"**",
"num_qubits",
"*",
"2",
":",
"raise",
"ValueError",
"(",
"f\"initial_state vector size must match number of qubits.\"",
"f\"Expected: {2**num_qubits * 2} Received: {len(input_vector)}\"",
")",
"is_noisy",
"=",
"_needs_trajectories",
"(",
"program",
")",
"if",
"is_noisy",
":",
"translator_fn_name",
"=",
"\"translate_cirq_to_qtrajectory\"",
"ev_simulator_fn",
"=",
"(",
"self",
".",
"_sim_module",
".",
"qtrajectory_simulate_moment_expectation_values",
")",
"else",
":",
"translator_fn_name",
"=",
"\"translate_cirq_to_qsim\"",
"ev_simulator_fn",
"=",
"self",
".",
"_sim_module",
".",
"qsim_simulate_moment_expectation_values",
"solved_circuit",
"=",
"cirq",
".",
"resolve_parameters",
"(",
"program",
",",
"param_resolver",
")",
"options",
"[",
"\"c\"",
"]",
",",
"opsum_reindex",
"=",
"self",
".",
"_translate_circuit",
"(",
"solved_circuit",
",",
"translator_fn_name",
",",
"cirq_order",
",",
")",
"opsums_and_qubit_counts",
"=",
"[",
"]",
"for",
"m",
",",
"opsum_qc",
"in",
"opsums_and_qcount_map",
".",
"items",
"(",
")",
":",
"pair",
"=",
"(",
"opsum_reindex",
"[",
"m",
"]",
",",
"opsum_qc",
")",
"opsums_and_qubit_counts",
".",
"append",
"(",
"pair",
")",
"options",
"[",
"\"s\"",
"]",
"=",
"self",
".",
"get_seed",
"(",
")",
"if",
"isinstance",
"(",
"initial_state",
",",
"int",
")",
":",
"return",
"ev_simulator_fn",
"(",
"options",
",",
"opsums_and_qubit_counts",
",",
"initial_state",
")",
"elif",
"isinstance",
"(",
"initial_state",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"ev_simulator_fn",
"(",
"options",
",",
"opsums_and_qubit_counts",
",",
"input_vector",
")"
] | https://github.com/quantumlib/qsim/blob/8f7f94020c56ad6a8645313743d9985f7ea77808/qsimcirq/qsim_simulator.py#L711-L846 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Clipboard_Get | (*args) | return _misc_.Clipboard_Get(*args) | Clipboard_Get() -> Clipboard
Returns global instance (wxTheClipboard) of the object. | Clipboard_Get() -> Clipboard | [
"Clipboard_Get",
"()",
"-",
">",
"Clipboard"
] | def Clipboard_Get(*args):
"""
Clipboard_Get() -> Clipboard
Returns global instance (wxTheClipboard) of the object.
"""
return _misc_.Clipboard_Get(*args) | [
"def",
"Clipboard_Get",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"Clipboard_Get",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5922-L5928 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/inspect.py | python | _signature_bound_method | (sig) | return sig.replace(parameters=params) | Private helper to transform signatures for unbound
functions to bound methods. | Private helper to transform signatures for unbound
functions to bound methods. | [
"Private",
"helper",
"to",
"transform",
"signatures",
"for",
"unbound",
"functions",
"to",
"bound",
"methods",
"."
] | def _signature_bound_method(sig):
"""Private helper to transform signatures for unbound
functions to bound methods.
"""
params = tuple(sig.parameters.values())
if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
raise ValueError('invalid method signature')
kind = params[0].kind
if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
# Drop first parameter:
# '(p1, p2[, ...])' -> '(p2[, ...])'
params = params[1:]
else:
if kind is not _VAR_POSITIONAL:
# Unless we add a new parameter type we never
# get here
raise ValueError('invalid argument type')
# It's a var-positional parameter.
# Do nothing. '(*args[, ...])' -> '(*args[, ...])'
return sig.replace(parameters=params) | [
"def",
"_signature_bound_method",
"(",
"sig",
")",
":",
"params",
"=",
"tuple",
"(",
"sig",
".",
"parameters",
".",
"values",
"(",
")",
")",
"if",
"not",
"params",
"or",
"params",
"[",
"0",
"]",
".",
"kind",
"in",
"(",
"_VAR_KEYWORD",
",",
"_KEYWORD_ONLY",
")",
":",
"raise",
"ValueError",
"(",
"'invalid method signature'",
")",
"kind",
"=",
"params",
"[",
"0",
"]",
".",
"kind",
"if",
"kind",
"in",
"(",
"_POSITIONAL_OR_KEYWORD",
",",
"_POSITIONAL_ONLY",
")",
":",
"# Drop first parameter:",
"# '(p1, p2[, ...])' -> '(p2[, ...])'",
"params",
"=",
"params",
"[",
"1",
":",
"]",
"else",
":",
"if",
"kind",
"is",
"not",
"_VAR_POSITIONAL",
":",
"# Unless we add a new parameter type we never",
"# get here",
"raise",
"ValueError",
"(",
"'invalid argument type'",
")",
"# It's a var-positional parameter.",
"# Do nothing. '(*args[, ...])' -> '(*args[, ...])'",
"return",
"sig",
".",
"replace",
"(",
"parameters",
"=",
"params",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/inspect.py#L1799-L1822 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py | python | ISkypeEvents.GroupVisible | (self, Group, Visible) | This event is caused by a user hiding/showing a group in the contacts tab.
@param Group: Group object.
@type Group: L{IGroup}
@param Visible: Tells if the group is visible or not.
@type Visible: bool | This event is caused by a user hiding/showing a group in the contacts tab. | [
"This",
"event",
"is",
"caused",
"by",
"a",
"user",
"hiding",
"/",
"showing",
"a",
"group",
"in",
"the",
"contacts",
"tab",
"."
] | def GroupVisible(self, Group, Visible):
'''This event is caused by a user hiding/showing a group in the contacts tab.
@param Group: Group object.
@type Group: L{IGroup}
@param Visible: Tells if the group is visible or not.
@type Visible: bool
''' | [
"def",
"GroupVisible",
"(",
"self",
",",
"Group",
",",
"Visible",
")",
":"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py#L1555-L1562 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/deep_cfr.py | python | ReservoirBuffer.add | (self, element) | Potentially adds `element` to the reservoir buffer.
Args:
element: data to be added to the reservoir buffer. | Potentially adds `element` to the reservoir buffer. | [
"Potentially",
"adds",
"element",
"to",
"the",
"reservoir",
"buffer",
"."
] | def add(self, element):
"""Potentially adds `element` to the reservoir buffer.
Args:
element: data to be added to the reservoir buffer.
"""
if len(self._data) < self._reservoir_buffer_capacity:
self._data.append(element)
else:
idx = np.random.randint(0, self._add_calls + 1)
if idx < self._reservoir_buffer_capacity:
self._data[idx] = element
self._add_calls += 1 | [
"def",
"add",
"(",
"self",
",",
"element",
")",
":",
"if",
"len",
"(",
"self",
".",
"_data",
")",
"<",
"self",
".",
"_reservoir_buffer_capacity",
":",
"self",
".",
"_data",
".",
"append",
"(",
"element",
")",
"else",
":",
"idx",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"self",
".",
"_add_calls",
"+",
"1",
")",
"if",
"idx",
"<",
"self",
".",
"_reservoir_buffer_capacity",
":",
"self",
".",
"_data",
"[",
"idx",
"]",
"=",
"element",
"self",
".",
"_add_calls",
"+=",
"1"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/deep_cfr.py#L64-L76 | ||
SmileiPIC/Smilei | 07dcb51200029e10f626e1546558c1ae7599c8b1 | validation/easi/machines/llr.py | python | MachineLLR.compile | (self, dir) | Compile Smilei | Compile Smilei | [
"Compile",
"Smilei"
] | def compile(self, dir):
"""
Compile Smilei
"""
with open(self.smilei_path.exec_script, 'w') as f:
f.write( self.script.format(command=self.COMPILE_COMMAND, nodes=self.NODES, ppn=self.ppn, max_time=self.options.max_time, omp=self.options.omp, dir=dir) )
self.launch_job(self.COMPILE_COMMAND, self.JOB, dir, self.options.max_time_seconds, self.smilei_path.COMPILE_ERRORS, repeat=2) | [
"def",
"compile",
"(",
"self",
",",
"dir",
")",
":",
"with",
"open",
"(",
"self",
".",
"smilei_path",
".",
"exec_script",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"script",
".",
"format",
"(",
"command",
"=",
"self",
".",
"COMPILE_COMMAND",
",",
"nodes",
"=",
"self",
".",
"NODES",
",",
"ppn",
"=",
"self",
".",
"ppn",
",",
"max_time",
"=",
"self",
".",
"options",
".",
"max_time",
",",
"omp",
"=",
"self",
".",
"options",
".",
"omp",
",",
"dir",
"=",
"dir",
")",
")",
"self",
".",
"launch_job",
"(",
"self",
".",
"COMPILE_COMMAND",
",",
"self",
".",
"JOB",
",",
"dir",
",",
"self",
".",
"options",
".",
"max_time_seconds",
",",
"self",
".",
"smilei_path",
".",
"COMPILE_ERRORS",
",",
"repeat",
"=",
"2",
")"
] | https://github.com/SmileiPIC/Smilei/blob/07dcb51200029e10f626e1546558c1ae7599c8b1/validation/easi/machines/llr.py#L61-L68 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/cygwinccompiler.py | python | get_msvcr | () | Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later. | Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later. | [
"Include",
"the",
"appropriate",
"MSVC",
"runtime",
"library",
"if",
"Python",
"was",
"built",
"with",
"MSVC",
"7",
".",
"0",
"or",
"later",
"."
] | def get_msvcr():
"""Include the appropriate MSVC runtime library if Python was built
with MSVC 7.0 or later.
"""
# FIXME: next code is from issue870382
# MS C-runtime libraries never support backward compatibility.
# Linking to a different library without to specify correct runtime
# version for the headers will link renamed functions to msvcrt.
# See issue3308: this piece of code is python problem even
# with correct w32api headers.
# Issue: for MSVC compiler we can get the version and from version
# to determine mcvcrt as code below. But what about if python is
# build with GCC compiler?
# Output of sys.version is information for python build on first
# line, on the next line is information for the compiler and the
# output lack information for the C-runtime.
msc_pos = sys.version.find('MSC v.')
if msc_pos != -1:
msc_ver = sys.version[msc_pos+6:msc_pos+10]
if msc_ver == '1300':
# MSVC 7.0
return ['msvcr70']
elif msc_ver == '1310':
# MSVC 7.1
return ['msvcr71']
elif msc_ver == '1400':
# VS2005 / MSVC 8.0
return ['msvcr80']
elif msc_ver == '1500':
# VS2008 / MSVC 9.0
return ['msvcr90']
else:
raise ValueError("Unknown MS Compiler version %s " % msc_ver)
else:
return [] | [
"def",
"get_msvcr",
"(",
")",
":",
"# FIXME: next code is from issue870382",
"# MS C-runtime libraries never support backward compatibility.",
"# Linking to a different library without to specify correct runtime",
"# version for the headers will link renamed functions to msvcrt.",
"# See issue3308: this piece of code is python problem even",
"# with correct w32api headers.",
"# Issue: for MSVC compiler we can get the version and from version",
"# to determine mcvcrt as code below. But what about if python is",
"# build with GCC compiler?",
"# Output of sys.version is information for python build on first",
"# line, on the next line is information for the compiler and the",
"# output lack information for the C-runtime.",
"msc_pos",
"=",
"sys",
".",
"version",
".",
"find",
"(",
"'MSC v.'",
")",
"if",
"msc_pos",
"!=",
"-",
"1",
":",
"msc_ver",
"=",
"sys",
".",
"version",
"[",
"msc_pos",
"+",
"6",
":",
"msc_pos",
"+",
"10",
"]",
"if",
"msc_ver",
"==",
"'1300'",
":",
"# MSVC 7.0",
"return",
"[",
"'msvcr70'",
"]",
"elif",
"msc_ver",
"==",
"'1310'",
":",
"# MSVC 7.1",
"return",
"[",
"'msvcr71'",
"]",
"elif",
"msc_ver",
"==",
"'1400'",
":",
"# VS2005 / MSVC 8.0",
"return",
"[",
"'msvcr80'",
"]",
"elif",
"msc_ver",
"==",
"'1500'",
":",
"# VS2008 / MSVC 9.0",
"return",
"[",
"'msvcr90'",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown MS Compiler version %s \"",
"%",
"msc_ver",
")",
"else",
":",
"return",
"[",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/cygwinccompiler.py#L59-L93 | ||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/go/__init__.py | python | Config.add_ldflag | (self, flag) | return self.add_ldflags([flag]) | Add a single ldflag at the end of the current ldflag.
:param flag: An ldflag.
:type flag: str
:return: self | Add a single ldflag at the end of the current ldflag. | [
"Add",
"a",
"single",
"ldflag",
"at",
"the",
"end",
"of",
"the",
"current",
"ldflag",
"."
] | def add_ldflag(self, flag):
"""
Add a single ldflag at the end of the current ldflag.
:param flag: An ldflag.
:type flag: str
:return: self
"""
return self.add_ldflags([flag]) | [
"def",
"add_ldflag",
"(",
"self",
",",
"flag",
")",
":",
"return",
"self",
".",
"add_ldflags",
"(",
"[",
"flag",
"]",
")"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/go/__init__.py#L94-L103 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/nn_ops.py | python | AvgPool3D.__init__ | (self, kernel_size=1, strides=1, pad_mode="valid", pad=0, ceil_mode=False,
count_include_pad=True, divisor_override=0, data_format="NCDHW") | Initialize AvgPool3D | Initialize AvgPool3D | [
"Initialize",
"AvgPool3D"
] | def __init__(self, kernel_size=1, strides=1, pad_mode="valid", pad=0, ceil_mode=False,
count_include_pad=True, divisor_override=0, data_format="NCDHW"):
"""Initialize AvgPool3D"""
self.init_prim_io_names(inputs=['input'], outputs=['output'])
self.kernel_size = _check_3d_int_or_tuple('kernel_size', kernel_size, self.name)
self.add_prim_attr('kernel_size', self.kernel_size)
self.strides = _check_3d_int_or_tuple('strides', strides, self.name)
validator.check_value_type('pad', pad, (int, tuple), self.name)
self.add_prim_attr('strides', self.strides)
if isinstance(pad, int):
pad = (pad,) * 6
if len(pad) != 6:
raise ValueError(f"For '{self.name}', attr 'pad' should be an positive int number or a tuple of "
f"six positive int numbers, but got {self.pad}.")
self.pad_list = pad
self.add_prim_attr('pad_list', self.pad_list)
validator.check_value_type('pad_mode', pad_mode, [str], self.name)
self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME', 'PAD'], 'pad_mode', self.name)
self.add_prim_attr('pad_mode', self.pad_mode)
if self.pad_mode != 'PAD' and pad != (0, 0, 0, 0, 0, 0):
raise ValueError(f"For '{self.name}', the 'pad' must be zero or (0, 0, 0, 0, 0, 0) when 'pad_mode' "
f"is not \"PAD\", but got 'pad' is {self.pad} and 'pad_mode' is {pad_mode}.")
if self.pad_mode == 'PAD':
for item in pad:
validator.check_non_negative_int(item, 'pad or item of pad', self.name)
self.ceil_mode = validator.check_value_type('ceil_mode', ceil_mode, bool, self.name)
self.count_include_pad = validator.check_value_type('count_include_pad', count_include_pad, bool, self.name)
self.divisor_override = validator.check_non_negative_int(divisor_override, 'divisor_override', self.name)
self.format = validator.check_string(data_format, ['NCDHW'], 'format', self.name) | [
"def",
"__init__",
"(",
"self",
",",
"kernel_size",
"=",
"1",
",",
"strides",
"=",
"1",
",",
"pad_mode",
"=",
"\"valid\"",
",",
"pad",
"=",
"0",
",",
"ceil_mode",
"=",
"False",
",",
"count_include_pad",
"=",
"True",
",",
"divisor_override",
"=",
"0",
",",
"data_format",
"=",
"\"NCDHW\"",
")",
":",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'input'",
"]",
",",
"outputs",
"=",
"[",
"'output'",
"]",
")",
"self",
".",
"kernel_size",
"=",
"_check_3d_int_or_tuple",
"(",
"'kernel_size'",
",",
"kernel_size",
",",
"self",
".",
"name",
")",
"self",
".",
"add_prim_attr",
"(",
"'kernel_size'",
",",
"self",
".",
"kernel_size",
")",
"self",
".",
"strides",
"=",
"_check_3d_int_or_tuple",
"(",
"'strides'",
",",
"strides",
",",
"self",
".",
"name",
")",
"validator",
".",
"check_value_type",
"(",
"'pad'",
",",
"pad",
",",
"(",
"int",
",",
"tuple",
")",
",",
"self",
".",
"name",
")",
"self",
".",
"add_prim_attr",
"(",
"'strides'",
",",
"self",
".",
"strides",
")",
"if",
"isinstance",
"(",
"pad",
",",
"int",
")",
":",
"pad",
"=",
"(",
"pad",
",",
")",
"*",
"6",
"if",
"len",
"(",
"pad",
")",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"f\"For '{self.name}', attr 'pad' should be an positive int number or a tuple of \"",
"f\"six positive int numbers, but got {self.pad}.\"",
")",
"self",
".",
"pad_list",
"=",
"pad",
"self",
".",
"add_prim_attr",
"(",
"'pad_list'",
",",
"self",
".",
"pad_list",
")",
"validator",
".",
"check_value_type",
"(",
"'pad_mode'",
",",
"pad_mode",
",",
"[",
"str",
"]",
",",
"self",
".",
"name",
")",
"self",
".",
"pad_mode",
"=",
"validator",
".",
"check_string",
"(",
"pad_mode",
".",
"upper",
"(",
")",
",",
"[",
"'VALID'",
",",
"'SAME'",
",",
"'PAD'",
"]",
",",
"'pad_mode'",
",",
"self",
".",
"name",
")",
"self",
".",
"add_prim_attr",
"(",
"'pad_mode'",
",",
"self",
".",
"pad_mode",
")",
"if",
"self",
".",
"pad_mode",
"!=",
"'PAD'",
"and",
"pad",
"!=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
":",
"raise",
"ValueError",
"(",
"f\"For '{self.name}', the 'pad' must be zero or (0, 0, 0, 0, 0, 0) when 'pad_mode' \"",
"f\"is not \\\"PAD\\\", but got 'pad' is {self.pad} and 'pad_mode' is {pad_mode}.\"",
")",
"if",
"self",
".",
"pad_mode",
"==",
"'PAD'",
":",
"for",
"item",
"in",
"pad",
":",
"validator",
".",
"check_non_negative_int",
"(",
"item",
",",
"'pad or item of pad'",
",",
"self",
".",
"name",
")",
"self",
".",
"ceil_mode",
"=",
"validator",
".",
"check_value_type",
"(",
"'ceil_mode'",
",",
"ceil_mode",
",",
"bool",
",",
"self",
".",
"name",
")",
"self",
".",
"count_include_pad",
"=",
"validator",
".",
"check_value_type",
"(",
"'count_include_pad'",
",",
"count_include_pad",
",",
"bool",
",",
"self",
".",
"name",
")",
"self",
".",
"divisor_override",
"=",
"validator",
".",
"check_non_negative_int",
"(",
"divisor_override",
",",
"'divisor_override'",
",",
"self",
".",
"name",
")",
"self",
".",
"format",
"=",
"validator",
".",
"check_string",
"(",
"data_format",
",",
"[",
"'NCDHW'",
"]",
",",
"'format'",
",",
"self",
".",
"name",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/nn_ops.py#L7667-L7696 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_abcoll.py | python | MutableSet.remove | (self, value) | Remove an element. If not a member, raise a KeyError. | Remove an element. If not a member, raise a KeyError. | [
"Remove",
"an",
"element",
".",
"If",
"not",
"a",
"member",
"raise",
"a",
"KeyError",
"."
] | def remove(self, value):
"""Remove an element. If not a member, raise a KeyError."""
if value not in self:
raise KeyError(value)
self.discard(value) | [
"def",
"remove",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"self",
":",
"raise",
"KeyError",
"(",
"value",
")",
"self",
".",
"discard",
"(",
"value",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_abcoll.py#L285-L289 | ||
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | tools/api_proto_plugin/utils.py | python | bazel_bin_path_for_output_artifact | (label, suffix, root='') | return os.path.join(
root, 'bazel-bin/external/envoy_api', os.path.dirname(proto_file_path), 'pkg',
proto_file_path + suffix) | Find the location in bazel-bin/ for an api_proto_plugin output file.
Args:
label: Bazel source proto label string.
suffix: output suffix for the artifact from label, e.g. ".types.pb_text".
root: location of bazel-bin/, if not specified, PWD.
Returns:
Path in bazel-bin/external/envoy_api for label output with given suffix. | Find the location in bazel-bin/ for an api_proto_plugin output file. | [
"Find",
"the",
"location",
"in",
"bazel",
"-",
"bin",
"/",
"for",
"an",
"api_proto_plugin",
"output",
"file",
"."
] | def bazel_bin_path_for_output_artifact(label, suffix, root=''):
"""Find the location in bazel-bin/ for an api_proto_plugin output file.
Args:
label: Bazel source proto label string.
suffix: output suffix for the artifact from label, e.g. ".types.pb_text".
root: location of bazel-bin/, if not specified, PWD.
Returns:
Path in bazel-bin/external/envoy_api for label output with given suffix.
"""
proto_file_path = proto_file_canonical_from_label(label)
return os.path.join(
root, 'bazel-bin/external/envoy_api', os.path.dirname(proto_file_path), 'pkg',
proto_file_path + suffix) | [
"def",
"bazel_bin_path_for_output_artifact",
"(",
"label",
",",
"suffix",
",",
"root",
"=",
"''",
")",
":",
"proto_file_path",
"=",
"proto_file_canonical_from_label",
"(",
"label",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'bazel-bin/external/envoy_api'",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"proto_file_path",
")",
",",
"'pkg'",
",",
"proto_file_path",
"+",
"suffix",
")"
] | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/tools/api_proto_plugin/utils.py#L18-L32 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column.py | python | _LazyBuilder.get | (self, key) | return transformed | Returns a `Tensor` for the given key.
A `str` key is used to access a base feature (not-transformed). When a
`_FeatureColumn` is passed, the transformed feature is returned if it
already exists, otherwise the given `_FeatureColumn` is asked to provide its
transformed output, which is then cached.
Args:
key: a `str` or a `_FeatureColumn`.
Returns:
The transformed `Tensor` corresponding to the `key`.
Raises:
ValueError: if key is not found or a transformed `Tensor` cannot be
computed. | Returns a `Tensor` for the given key. | [
"Returns",
"a",
"Tensor",
"for",
"the",
"given",
"key",
"."
] | def get(self, key):
"""Returns a `Tensor` for the given key.
A `str` key is used to access a base feature (not-transformed). When a
`_FeatureColumn` is passed, the transformed feature is returned if it
already exists, otherwise the given `_FeatureColumn` is asked to provide its
transformed output, which is then cached.
Args:
key: a `str` or a `_FeatureColumn`.
Returns:
The transformed `Tensor` corresponding to the `key`.
Raises:
ValueError: if key is not found or a transformed `Tensor` cannot be
computed.
"""
if key in self._feature_tensors:
# FeatureColumn is already transformed or converted.
return self._feature_tensors[key]
if key in self._features:
feature_tensor = self._get_raw_feature_as_tensor(key)
self._feature_tensors[key] = feature_tensor
return feature_tensor
if isinstance(key, six.string_types):
raise ValueError('Feature {} is not in features dictionary.'.format(key))
if not isinstance(key, _FeatureColumn):
raise TypeError('"key" must be either a "str" or "_FeatureColumn". '
'Provided: {}'.format(key))
column = key
logging.debug('Transforming feature_column %s.', column)
transformed = column._transform_feature(self) # pylint: disable=protected-access
if transformed is None:
raise ValueError('Column {} is not supported.'.format(column.name))
self._feature_tensors[column] = transformed
return transformed | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_feature_tensors",
":",
"# FeatureColumn is already transformed or converted.",
"return",
"self",
".",
"_feature_tensors",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"_features",
":",
"feature_tensor",
"=",
"self",
".",
"_get_raw_feature_as_tensor",
"(",
"key",
")",
"self",
".",
"_feature_tensors",
"[",
"key",
"]",
"=",
"feature_tensor",
"return",
"feature_tensor",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"'Feature {} is not in features dictionary.'",
".",
"format",
"(",
"key",
")",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"_FeatureColumn",
")",
":",
"raise",
"TypeError",
"(",
"'\"key\" must be either a \"str\" or \"_FeatureColumn\". '",
"'Provided: {}'",
".",
"format",
"(",
"key",
")",
")",
"column",
"=",
"key",
"logging",
".",
"debug",
"(",
"'Transforming feature_column %s.'",
",",
"column",
")",
"transformed",
"=",
"column",
".",
"_transform_feature",
"(",
"self",
")",
"# pylint: disable=protected-access",
"if",
"transformed",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Column {} is not supported.'",
".",
"format",
"(",
"column",
".",
"name",
")",
")",
"self",
".",
"_feature_tensors",
"[",
"column",
"]",
"=",
"transformed",
"return",
"transformed"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column.py#L2122-L2162 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/search.py | python | SearchConnection.search | (self, q=None, parser=None, fq=None, rank=None, return_fields=None,
size=10, start=0, facet=None, highlight=None, sort=None, partial=None,
options=None) | return self(query) | Send a query to CloudSearch
Each search query should use at least the q or bq argument to specify
the search parameter. The other options are used to specify the
criteria of the search.
:type q: string
:param q: A string to search the default search fields for.
:type parser: string
:param parser: The parser to use. 'simple', 'structured', 'lucene', 'dismax'
:type fq: string
:param fq: The filter query to use.
:type sort: List of strings
:param sort: A list of fields or rank expressions used to order the
search results. Order is handled by adding 'desc' or 'asc' after the field name.
``['year desc', 'author asc']``
:type return_fields: List of strings
:param return_fields: A list of fields which should be returned by the
search. If this field is not specified, only IDs will be returned.
``['headline']``
:type size: int
:param size: Number of search results to specify
:type start: int
:param start: Offset of the first search result to return (can be used
for paging)
:type facet: dict
:param facet: Dictionary of fields for which facets should be returned
The facet value is string of JSON options
``{'year': '{sort:"bucket", size:3}', 'genres': '{buckets:["Action","Adventure","Sci-Fi"]}'}``
:type highlight: dict
:param highlight: Dictionary of fields for which highlights should be returned
The facet value is string of JSON options
``{'genres': '{format:'text',max_phrases:2,pre_tag:'<b>',post_tag:'</b>'}'}``
:type partial: bool
:param partial: Should partial results from a partioned service be returned if
one or more index partitions are unreachable.
:type options: str
:param options: Options for the query parser specified in *parser*.
Specified as a string in JSON format.
``{fields: ['title^5', 'description']}``
:rtype: :class:`boto.cloudsearch2.search.SearchResults`
:return: Returns the results of this search
The following examples all assume we have indexed a set of documents
with fields: *author*, *date*, *headline*
A simple search will look for documents whose default text search
fields will contain the search word exactly:
>>> search(q='Tim') # Return documents with the word Tim in them (but not Timothy)
A simple search with more keywords will return documents whose default
text search fields contain the search strings together or separately.
>>> search(q='Tim apple') # Will match "tim" and "apple"
More complex searches require the boolean search operator.
Wildcard searches can be used to search for any words that start with
the search string.
>>> search(q="'Tim*'") # Return documents with words like Tim or Timothy)
Search terms can also be combined. Allowed operators are "and", "or",
"not", "field", "optional", "token", "phrase", or "filter"
>>> search(q="(and 'Tim' (field author 'John Smith'))", parser='structured')
Facets allow you to show classification information about the search
results. For example, you can retrieve the authors who have written
about Tim with a max of 3
>>> search(q='Tim', facet={'Author': '{sort:"bucket", size:3}'}) | Send a query to CloudSearch | [
"Send",
"a",
"query",
"to",
"CloudSearch"
] | def search(self, q=None, parser=None, fq=None, rank=None, return_fields=None,
size=10, start=0, facet=None, highlight=None, sort=None, partial=None,
options=None):
"""
Send a query to CloudSearch
Each search query should use at least the q or bq argument to specify
the search parameter. The other options are used to specify the
criteria of the search.
:type q: string
:param q: A string to search the default search fields for.
:type parser: string
:param parser: The parser to use. 'simple', 'structured', 'lucene', 'dismax'
:type fq: string
:param fq: The filter query to use.
:type sort: List of strings
:param sort: A list of fields or rank expressions used to order the
search results. Order is handled by adding 'desc' or 'asc' after the field name.
``['year desc', 'author asc']``
:type return_fields: List of strings
:param return_fields: A list of fields which should be returned by the
search. If this field is not specified, only IDs will be returned.
``['headline']``
:type size: int
:param size: Number of search results to specify
:type start: int
:param start: Offset of the first search result to return (can be used
for paging)
:type facet: dict
:param facet: Dictionary of fields for which facets should be returned
The facet value is string of JSON options
``{'year': '{sort:"bucket", size:3}', 'genres': '{buckets:["Action","Adventure","Sci-Fi"]}'}``
:type highlight: dict
:param highlight: Dictionary of fields for which highlights should be returned
The facet value is string of JSON options
``{'genres': '{format:'text',max_phrases:2,pre_tag:'<b>',post_tag:'</b>'}'}``
:type partial: bool
:param partial: Should partial results from a partioned service be returned if
one or more index partitions are unreachable.
:type options: str
:param options: Options for the query parser specified in *parser*.
Specified as a string in JSON format.
``{fields: ['title^5', 'description']}``
:rtype: :class:`boto.cloudsearch2.search.SearchResults`
:return: Returns the results of this search
The following examples all assume we have indexed a set of documents
with fields: *author*, *date*, *headline*
A simple search will look for documents whose default text search
fields will contain the search word exactly:
>>> search(q='Tim') # Return documents with the word Tim in them (but not Timothy)
A simple search with more keywords will return documents whose default
text search fields contain the search strings together or separately.
>>> search(q='Tim apple') # Will match "tim" and "apple"
More complex searches require the boolean search operator.
Wildcard searches can be used to search for any words that start with
the search string.
>>> search(q="'Tim*'") # Return documents with words like Tim or Timothy)
Search terms can also be combined. Allowed operators are "and", "or",
"not", "field", "optional", "token", "phrase", or "filter"
>>> search(q="(and 'Tim' (field author 'John Smith'))", parser='structured')
Facets allow you to show classification information about the search
results. For example, you can retrieve the authors who have written
about Tim with a max of 3
>>> search(q='Tim', facet={'Author': '{sort:"bucket", size:3}'})
"""
query = self.build_query(q=q, parser=parser, fq=fq, rank=rank,
return_fields=return_fields,
size=size, start=start, facet=facet,
highlight=highlight, sort=sort,
partial=partial, options=options)
return self(query) | [
"def",
"search",
"(",
"self",
",",
"q",
"=",
"None",
",",
"parser",
"=",
"None",
",",
"fq",
"=",
"None",
",",
"rank",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"size",
"=",
"10",
",",
"start",
"=",
"0",
",",
"facet",
"=",
"None",
",",
"highlight",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"partial",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"build_query",
"(",
"q",
"=",
"q",
",",
"parser",
"=",
"parser",
",",
"fq",
"=",
"fq",
",",
"rank",
"=",
"rank",
",",
"return_fields",
"=",
"return_fields",
",",
"size",
"=",
"size",
",",
"start",
"=",
"start",
",",
"facet",
"=",
"facet",
",",
"highlight",
"=",
"highlight",
",",
"sort",
"=",
"sort",
",",
"partial",
"=",
"partial",
",",
"options",
"=",
"options",
")",
"return",
"self",
"(",
"query",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/search.py#L241-L336 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/xml/sax/handler.py | python | ErrorHandler.warning | (self, exception) | Handle a warning. | Handle a warning. | [
"Handle",
"a",
"warning",
"."
] | def warning(self, exception):
"Handle a warning."
print exception | [
"def",
"warning",
"(",
"self",
",",
"exception",
")",
":",
"print",
"exception"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/xml/sax/handler.py#L40-L42 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | uCSIsHighSurrogates | (code) | return ret | Check whether the character is part of HighSurrogates UCS
Block | Check whether the character is part of HighSurrogates UCS
Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"HighSurrogates",
"UCS",
"Block"
] | def uCSIsHighSurrogates(code):
"""Check whether the character is part of HighSurrogates UCS
Block """
ret = libxml2mod.xmlUCSIsHighSurrogates(code)
return ret | [
"def",
"uCSIsHighSurrogates",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsHighSurrogates",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2602-L2606 | |
Smorodov/Multitarget-tracker | bee300e8bfd660c86cbeb6892c65a5b7195c9381 | thirdparty/pybind11/tools/clang/cindex.py | python | CursorKind.is_attribute | (self) | return conf.lib.clang_isAttribute(self) | Test if this is an attribute kind. | Test if this is an attribute kind. | [
"Test",
"if",
"this",
"is",
"an",
"attribute",
"kind",
"."
] | def is_attribute(self):
"""Test if this is an attribute kind."""
return conf.lib.clang_isAttribute(self) | [
"def",
"is_attribute",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isAttribute",
"(",
"self",
")"
] | https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L592-L594 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.GetImageSize | (self, index) | return width, height | Returns the image size for the item.
:param `index`: the image index. | Returns the image size for the item. | [
"Returns",
"the",
"image",
"size",
"for",
"the",
"item",
"."
] | def GetImageSize(self, index):
"""
Returns the image size for the item.
:param `index`: the image index.
"""
width = height = 0
if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
for indx in index:
w, h = self._normal_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
for indx in index:
w, h = self._small_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:
for indx in index:
w, h = self._small_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
elif self.InReportView() and self._small_image_list:
for indx in index:
w, h = self._small_image_list.GetSize(indx)
width += w + MARGIN_BETWEEN_TEXT_AND_ICON
height = max(height, h)
return width, height | [
"def",
"GetImageSize",
"(",
"self",
",",
"index",
")",
":",
"width",
"=",
"height",
"=",
"0",
"if",
"self",
".",
"HasAGWFlag",
"(",
"ULC_ICON",
")",
"and",
"self",
".",
"_normal_image_list",
":",
"for",
"indx",
"in",
"index",
":",
"w",
",",
"h",
"=",
"self",
".",
"_normal_image_list",
".",
"GetSize",
"(",
"indx",
")",
"width",
"+=",
"w",
"+",
"MARGIN_BETWEEN_TEXT_AND_ICON",
"height",
"=",
"max",
"(",
"height",
",",
"h",
")",
"elif",
"self",
".",
"HasAGWFlag",
"(",
"ULC_SMALL_ICON",
")",
"and",
"self",
".",
"_small_image_list",
":",
"for",
"indx",
"in",
"index",
":",
"w",
",",
"h",
"=",
"self",
".",
"_small_image_list",
".",
"GetSize",
"(",
"indx",
")",
"width",
"+=",
"w",
"+",
"MARGIN_BETWEEN_TEXT_AND_ICON",
"height",
"=",
"max",
"(",
"height",
",",
"h",
")",
"elif",
"self",
".",
"HasAGWFlag",
"(",
"ULC_LIST",
")",
"and",
"self",
".",
"_small_image_list",
":",
"for",
"indx",
"in",
"index",
":",
"w",
",",
"h",
"=",
"self",
".",
"_small_image_list",
".",
"GetSize",
"(",
"indx",
")",
"width",
"+=",
"w",
"+",
"MARGIN_BETWEEN_TEXT_AND_ICON",
"height",
"=",
"max",
"(",
"height",
",",
"h",
")",
"elif",
"self",
".",
"InReportView",
"(",
")",
"and",
"self",
".",
"_small_image_list",
":",
"for",
"indx",
"in",
"index",
":",
"w",
",",
"h",
"=",
"self",
".",
"_small_image_list",
".",
"GetSize",
"(",
"indx",
")",
"width",
"+=",
"w",
"+",
"MARGIN_BETWEEN_TEXT_AND_ICON",
"height",
"=",
"max",
"(",
"height",
",",
"h",
")",
"return",
"width",
",",
"height"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L8349-L8386 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/engine.py | python | LogEngine.add_console_handler | (self) | Add console output of log. | Add console output of log. | [
"Add",
"console",
"output",
"of",
"log",
"."
] | def add_console_handler(self) -> None:
"""
Add console output of log.
"""
console_handler = logging.StreamHandler()
console_handler.setLevel(self.level)
console_handler.setFormatter(self.formatter)
self.logger.addHandler(console_handler) | [
"def",
"add_console_handler",
"(",
"self",
")",
"->",
"None",
":",
"console_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"console_handler",
".",
"setLevel",
"(",
"self",
".",
"level",
")",
"console_handler",
".",
"setFormatter",
"(",
"self",
".",
"formatter",
")",
"self",
".",
"logger",
".",
"addHandler",
"(",
"console_handler",
")"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/engine.py#L299-L306 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBarItem.SetHoverBitmap | (*args, **kwargs) | return _aui.AuiToolBarItem_SetHoverBitmap(*args, **kwargs) | SetHoverBitmap(self, Bitmap bmp) | SetHoverBitmap(self, Bitmap bmp) | [
"SetHoverBitmap",
"(",
"self",
"Bitmap",
"bmp",
")"
] | def SetHoverBitmap(*args, **kwargs):
"""SetHoverBitmap(self, Bitmap bmp)"""
return _aui.AuiToolBarItem_SetHoverBitmap(*args, **kwargs) | [
"def",
"SetHoverBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBarItem_SetHoverBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1793-L1795 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/matfuncs.py | python | _fragment_2_1 | (X, T, s) | return X | A helper function for expm_2009.
Notes
-----
The argument X is modified in-place, but this modification is not the same
as the returned value of the function.
This function also takes pains to do things in ways that are compatible
with sparse matrices, for example by avoiding fancy indexing
and by using methods of the matrices whenever possible instead of
using functions of the numpy or scipy libraries themselves. | A helper function for expm_2009. | [
"A",
"helper",
"function",
"for",
"expm_2009",
"."
] | def _fragment_2_1(X, T, s):
"""
A helper function for expm_2009.
Notes
-----
The argument X is modified in-place, but this modification is not the same
as the returned value of the function.
This function also takes pains to do things in ways that are compatible
with sparse matrices, for example by avoiding fancy indexing
and by using methods of the matrices whenever possible instead of
using functions of the numpy or scipy libraries themselves.
"""
# Form X = r_m(2^-s T)
# Replace diag(X) by exp(2^-s diag(T)).
n = X.shape[0]
diag_T = np.ravel(T.diagonal().copy())
# Replace diag(X) by exp(2^-s diag(T)).
scale = 2 ** -s
exp_diag = np.exp(scale * diag_T)
for k in range(n):
X[k, k] = exp_diag[k]
for i in range(s-1, -1, -1):
X = X.dot(X)
# Replace diag(X) by exp(2^-i diag(T)).
scale = 2 ** -i
exp_diag = np.exp(scale * diag_T)
for k in range(n):
X[k, k] = exp_diag[k]
# Replace (first) superdiagonal of X by explicit formula
# for superdiagonal of exp(2^-i T) from Eq (10.42) of
# the author's 2008 textbook
# Functions of Matrices: Theory and Computation.
for k in range(n-1):
lam_1 = scale * diag_T[k]
lam_2 = scale * diag_T[k+1]
t_12 = scale * T[k, k+1]
value = _eq_10_42(lam_1, lam_2, t_12)
X[k, k+1] = value
# Return the updated X matrix.
return X | [
"def",
"_fragment_2_1",
"(",
"X",
",",
"T",
",",
"s",
")",
":",
"# Form X = r_m(2^-s T)",
"# Replace diag(X) by exp(2^-s diag(T)).",
"n",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"diag_T",
"=",
"np",
".",
"ravel",
"(",
"T",
".",
"diagonal",
"(",
")",
".",
"copy",
"(",
")",
")",
"# Replace diag(X) by exp(2^-s diag(T)).",
"scale",
"=",
"2",
"**",
"-",
"s",
"exp_diag",
"=",
"np",
".",
"exp",
"(",
"scale",
"*",
"diag_T",
")",
"for",
"k",
"in",
"range",
"(",
"n",
")",
":",
"X",
"[",
"k",
",",
"k",
"]",
"=",
"exp_diag",
"[",
"k",
"]",
"for",
"i",
"in",
"range",
"(",
"s",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"X",
"=",
"X",
".",
"dot",
"(",
"X",
")",
"# Replace diag(X) by exp(2^-i diag(T)).",
"scale",
"=",
"2",
"**",
"-",
"i",
"exp_diag",
"=",
"np",
".",
"exp",
"(",
"scale",
"*",
"diag_T",
")",
"for",
"k",
"in",
"range",
"(",
"n",
")",
":",
"X",
"[",
"k",
",",
"k",
"]",
"=",
"exp_diag",
"[",
"k",
"]",
"# Replace (first) superdiagonal of X by explicit formula",
"# for superdiagonal of exp(2^-i T) from Eq (10.42) of",
"# the author's 2008 textbook",
"# Functions of Matrices: Theory and Computation.",
"for",
"k",
"in",
"range",
"(",
"n",
"-",
"1",
")",
":",
"lam_1",
"=",
"scale",
"*",
"diag_T",
"[",
"k",
"]",
"lam_2",
"=",
"scale",
"*",
"diag_T",
"[",
"k",
"+",
"1",
"]",
"t_12",
"=",
"scale",
"*",
"T",
"[",
"k",
",",
"k",
"+",
"1",
"]",
"value",
"=",
"_eq_10_42",
"(",
"lam_1",
",",
"lam_2",
",",
"t_12",
")",
"X",
"[",
"k",
",",
"k",
"+",
"1",
"]",
"=",
"value",
"# Return the updated X matrix.",
"return",
"X"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/matfuncs.py#L778-L824 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py | python | ConfigDialog.create_action_buttons | (self) | return outer | Return frame of action buttons for dialog.
Methods:
ok
apply
cancel
help
Widget Structure:
outer: Frame
buttons: Frame
(no assignment): Button (ok)
(no assignment): Button (apply)
(no assignment): Button (cancel)
(no assignment): Button (help)
(no assignment): Frame | Return frame of action buttons for dialog. | [
"Return",
"frame",
"of",
"action",
"buttons",
"for",
"dialog",
"."
] | def create_action_buttons(self):
"""Return frame of action buttons for dialog.
Methods:
ok
apply
cancel
help
Widget Structure:
outer: Frame
buttons: Frame
(no assignment): Button (ok)
(no assignment): Button (apply)
(no assignment): Button (cancel)
(no assignment): Button (help)
(no assignment): Frame
"""
if macosx.isAquaTk():
# Changing the default padding on OSX results in unreadable
# text in the buttons.
padding_args = {}
else:
padding_args = {'padding': (6, 3)}
outer = Frame(self, padding=2)
buttons_frame = Frame(outer, padding=2)
self.buttons = {}
for txt, cmd in (
('Ok', self.ok),
('Apply', self.apply),
('Cancel', self.cancel),
('Help', self.help)):
self.buttons[txt] = Button(buttons_frame, text=txt, command=cmd,
takefocus=FALSE, **padding_args)
self.buttons[txt].pack(side=LEFT, padx=5)
# Add space above buttons.
Frame(outer, height=2, borderwidth=0).pack(side=TOP)
buttons_frame.pack(side=BOTTOM)
return outer | [
"def",
"create_action_buttons",
"(",
"self",
")",
":",
"if",
"macosx",
".",
"isAquaTk",
"(",
")",
":",
"# Changing the default padding on OSX results in unreadable",
"# text in the buttons.",
"padding_args",
"=",
"{",
"}",
"else",
":",
"padding_args",
"=",
"{",
"'padding'",
":",
"(",
"6",
",",
"3",
")",
"}",
"outer",
"=",
"Frame",
"(",
"self",
",",
"padding",
"=",
"2",
")",
"buttons_frame",
"=",
"Frame",
"(",
"outer",
",",
"padding",
"=",
"2",
")",
"self",
".",
"buttons",
"=",
"{",
"}",
"for",
"txt",
",",
"cmd",
"in",
"(",
"(",
"'Ok'",
",",
"self",
".",
"ok",
")",
",",
"(",
"'Apply'",
",",
"self",
".",
"apply",
")",
",",
"(",
"'Cancel'",
",",
"self",
".",
"cancel",
")",
",",
"(",
"'Help'",
",",
"self",
".",
"help",
")",
")",
":",
"self",
".",
"buttons",
"[",
"txt",
"]",
"=",
"Button",
"(",
"buttons_frame",
",",
"text",
"=",
"txt",
",",
"command",
"=",
"cmd",
",",
"takefocus",
"=",
"FALSE",
",",
"*",
"*",
"padding_args",
")",
"self",
".",
"buttons",
"[",
"txt",
"]",
".",
"pack",
"(",
"side",
"=",
"LEFT",
",",
"padx",
"=",
"5",
")",
"# Add space above buttons.",
"Frame",
"(",
"outer",
",",
"height",
"=",
"2",
",",
"borderwidth",
"=",
"0",
")",
".",
"pack",
"(",
"side",
"=",
"TOP",
")",
"buttons_frame",
".",
"pack",
"(",
"side",
"=",
"BOTTOM",
")",
"return",
"outer"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L127-L165 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/completer.py | python | IPCompleter.python_matches | (self, text) | return matches | Match attributes or global python names | Match attributes or global python names | [
"Match",
"attributes",
"or",
"global",
"python",
"names"
] | def python_matches(self, text):
"""Match attributes or global python names"""
if "." in text:
try:
matches = self.attr_matches(text)
if text.endswith('.') and self.omit__names:
if self.omit__names == 1:
# true if txt is _not_ a __ name, false otherwise:
no__name = (lambda txt:
re.match(r'.*\.__.*?__',txt) is None)
else:
# true if txt is _not_ a _ name, false otherwise:
no__name = (lambda txt:
re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
matches = filter(no__name, matches)
except NameError:
# catches <undefined attributes>.<tab>
matches = []
else:
matches = self.global_matches(text)
return matches | [
"def",
"python_matches",
"(",
"self",
",",
"text",
")",
":",
"if",
"\".\"",
"in",
"text",
":",
"try",
":",
"matches",
"=",
"self",
".",
"attr_matches",
"(",
"text",
")",
"if",
"text",
".",
"endswith",
"(",
"'.'",
")",
"and",
"self",
".",
"omit__names",
":",
"if",
"self",
".",
"omit__names",
"==",
"1",
":",
"# true if txt is _not_ a __ name, false otherwise:",
"no__name",
"=",
"(",
"lambda",
"txt",
":",
"re",
".",
"match",
"(",
"r'.*\\.__.*?__'",
",",
"txt",
")",
"is",
"None",
")",
"else",
":",
"# true if txt is _not_ a _ name, false otherwise:",
"no__name",
"=",
"(",
"lambda",
"txt",
":",
"re",
".",
"match",
"(",
"r'\\._.*?'",
",",
"txt",
"[",
"txt",
".",
"rindex",
"(",
"'.'",
")",
":",
"]",
")",
"is",
"None",
")",
"matches",
"=",
"filter",
"(",
"no__name",
",",
"matches",
")",
"except",
"NameError",
":",
"# catches <undefined attributes>.<tab>",
"matches",
"=",
"[",
"]",
"else",
":",
"matches",
"=",
"self",
".",
"global_matches",
"(",
"text",
")",
"return",
"matches"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/completer.py#L1432-L1452 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/aio/_base_channel.py | python | UnaryUnaryMultiCallable.__call__ | (
self,
request: Any,
*,
timeout: Optional[float] = None,
metadata: Optional[MetadataType] = None,
credentials: Optional[grpc.CallCredentials] = None,
wait_for_ready: Optional[bool] = None,
compression: Optional[grpc.Compression] = None
) | Asynchronously invokes the underlying RPC.
Args:
request: The request value for the RPC.
timeout: An optional duration of time in seconds to allow
for the RPC.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
credentials: An optional CallCredentials for the RPC. Only valid for
secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
compression: An element of grpc.compression, e.g.
grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
A UnaryUnaryCall object.
Raises:
RpcError: Indicates that the RPC terminated with non-OK status. The
raised RpcError will also be a Call for the RPC affording the RPC's
metadata, status code, and details. | Asynchronously invokes the underlying RPC. | [
"Asynchronously",
"invokes",
"the",
"underlying",
"RPC",
"."
] | def __call__(
self,
request: Any,
*,
timeout: Optional[float] = None,
metadata: Optional[MetadataType] = None,
credentials: Optional[grpc.CallCredentials] = None,
wait_for_ready: Optional[bool] = None,
compression: Optional[grpc.Compression] = None
) -> _base_call.UnaryUnaryCall:
"""Asynchronously invokes the underlying RPC.
Args:
request: The request value for the RPC.
timeout: An optional duration of time in seconds to allow
for the RPC.
metadata: Optional :term:`metadata` to be transmitted to the
service-side of the RPC.
credentials: An optional CallCredentials for the RPC. Only valid for
secure Channel.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
flag to enable :term:`wait_for_ready` mechanism.
compression: An element of grpc.compression, e.g.
grpc.compression.Gzip. This is an EXPERIMENTAL option.
Returns:
A UnaryUnaryCall object.
Raises:
RpcError: Indicates that the RPC terminated with non-OK status. The
raised RpcError will also be a Call for the RPC affording the RPC's
metadata, status code, and details.
""" | [
"def",
"__call__",
"(",
"self",
",",
"request",
":",
"Any",
",",
"*",
",",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"metadata",
":",
"Optional",
"[",
"MetadataType",
"]",
"=",
"None",
",",
"credentials",
":",
"Optional",
"[",
"grpc",
".",
"CallCredentials",
"]",
"=",
"None",
",",
"wait_for_ready",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"compression",
":",
"Optional",
"[",
"grpc",
".",
"Compression",
"]",
"=",
"None",
")",
"->",
"_base_call",
".",
"UnaryUnaryCall",
":"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_base_channel.py#L32-L64 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridTableBase.GetView | (*args, **kwargs) | return _grid.GridTableBase_GetView(*args, **kwargs) | GetView(self) -> Grid | GetView(self) -> Grid | [
"GetView",
"(",
"self",
")",
"-",
">",
"Grid"
] | def GetView(*args, **kwargs):
"""GetView(self) -> Grid"""
return _grid.GridTableBase_GetView(*args, **kwargs) | [
"def",
"GetView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_GetView",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L786-L788 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/preprocessing/text.py | python | VocabularyProcessor.restore | (cls, filename) | Restores vocabulary processor from given file.
Args:
filename: Path to file to load from.
Returns:
VocabularyProcessor object. | Restores vocabulary processor from given file. | [
"Restores",
"vocabulary",
"processor",
"from",
"given",
"file",
"."
] | def restore(cls, filename):
"""Restores vocabulary processor from given file.
Args:
filename: Path to file to load from.
Returns:
VocabularyProcessor object.
"""
with gfile.Open(filename, 'rb') as f:
return pickle.loads(f.read()) | [
"def",
"restore",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"pickle",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/preprocessing/text.py#L216-L226 | ||
ucsb-seclab/difuze | bb59a12ff87ad5ae45d9c60e349891bf80d72877 | helper_scripts/components/bear_llvm_build.py | python | _get_llvm_link_str | (llvm_link_path, src_root_dir, input_files, input_bc_map,
output_file, work_dir, llvm_bit_code_out) | return work_dir, output_file, curr_output_file, ' '.join(modified_build_args) | Given a linker command from the json, this function converts it into corresponding
llvm-link command with all the correct parameters.
:param llvm_link_path: Path to llvm-link
:param src_root_dir: Path to the kernel source directory.
:param input_files: input files for the linker.
:param input_bc_map: Map containing object files to corresponding bitcode file.
:param output_file: Original output object file path.
:param work_dir: Directory where the original command was run.
:param llvm_bit_code_out: Folder where all the linked bitcode files should be stored.
:return: | Given a linker command from the json, this function converts it into corresponding
llvm-link command with all the correct parameters.
:param llvm_link_path: Path to llvm-link
:param src_root_dir: Path to the kernel source directory.
:param input_files: input files for the linker.
:param input_bc_map: Map containing object files to corresponding bitcode file.
:param output_file: Original output object file path.
:param work_dir: Directory where the original command was run.
:param llvm_bit_code_out: Folder where all the linked bitcode files should be stored.
:return: | [
"Given",
"a",
"linker",
"command",
"from",
"the",
"json",
"this",
"function",
"converts",
"it",
"into",
"corresponding",
"llvm",
"-",
"link",
"command",
"with",
"all",
"the",
"correct",
"parameters",
".",
":",
"param",
"llvm_link_path",
":",
"Path",
"to",
"llvm",
"-",
"link",
":",
"param",
"src_root_dir",
":",
"Path",
"to",
"the",
"kernel",
"source",
"directory",
".",
":",
"param",
"input_files",
":",
"input",
"files",
"for",
"the",
"linker",
".",
":",
"param",
"input_bc_map",
":",
"Map",
"containing",
"object",
"files",
"to",
"corresponding",
"bitcode",
"file",
".",
":",
"param",
"output_file",
":",
"Original",
"output",
"object",
"file",
"path",
".",
":",
"param",
"work_dir",
":",
"Directory",
"where",
"the",
"original",
"command",
"was",
"run",
".",
":",
"param",
"llvm_bit_code_out",
":",
"Folder",
"where",
"all",
"the",
"linked",
"bitcode",
"files",
"should",
"be",
"stored",
".",
":",
"return",
":"
] | def _get_llvm_link_str(llvm_link_path, src_root_dir, input_files, input_bc_map,
output_file, work_dir, llvm_bit_code_out):
"""
Given a linker command from the json, this function converts it into corresponding
llvm-link command with all the correct parameters.
:param llvm_link_path: Path to llvm-link
:param src_root_dir: Path to the kernel source directory.
:param input_files: input files for the linker.
:param input_bc_map: Map containing object files to corresponding bitcode file.
:param output_file: Original output object file path.
:param work_dir: Directory where the original command was run.
:param llvm_bit_code_out: Folder where all the linked bitcode files should be stored.
:return:
"""
modified_build_args = list()
modified_build_args.append(llvm_link_path)
for curr_input_file in input_files:
if curr_input_file not in input_bc_map:
return None
target_bc_file = input_bc_map[curr_input_file]
if not os.path.exists(target_bc_file):
return None
else:
modified_build_args.append(input_bc_map[curr_input_file])
rel_output_file = output_file
if str(output_file).startswith("../"):
rel_output_file = output_file[3:]
if str(output_file).startswith('/'):
rel_output_file = os.path.abspath(output_file)
if src_root_dir[-1] == '/':
rel_output_file = rel_output_file[len(src_root_dir):]
else:
rel_output_file = rel_output_file[len(src_root_dir) + 1:]
# replace output file with llvm bc file
out_dir_name = os.path.dirname(rel_output_file)
output_file_name = os.path.basename(output_file)
curr_output_dir = os.path.join(llvm_bit_code_out, out_dir_name)
os.system('mkdir -p ' + curr_output_dir)
curr_output_file = os.path.abspath(os.path.join(curr_output_dir, output_file_name[:-2] + '.final.linked.bc'))
# append output file path
modified_build_args.append("-o")
modified_build_args.append(curr_output_file)
return work_dir, output_file, curr_output_file, ' '.join(modified_build_args) | [
"def",
"_get_llvm_link_str",
"(",
"llvm_link_path",
",",
"src_root_dir",
",",
"input_files",
",",
"input_bc_map",
",",
"output_file",
",",
"work_dir",
",",
"llvm_bit_code_out",
")",
":",
"modified_build_args",
"=",
"list",
"(",
")",
"modified_build_args",
".",
"append",
"(",
"llvm_link_path",
")",
"for",
"curr_input_file",
"in",
"input_files",
":",
"if",
"curr_input_file",
"not",
"in",
"input_bc_map",
":",
"return",
"None",
"target_bc_file",
"=",
"input_bc_map",
"[",
"curr_input_file",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target_bc_file",
")",
":",
"return",
"None",
"else",
":",
"modified_build_args",
".",
"append",
"(",
"input_bc_map",
"[",
"curr_input_file",
"]",
")",
"rel_output_file",
"=",
"output_file",
"if",
"str",
"(",
"output_file",
")",
".",
"startswith",
"(",
"\"../\"",
")",
":",
"rel_output_file",
"=",
"output_file",
"[",
"3",
":",
"]",
"if",
"str",
"(",
"output_file",
")",
".",
"startswith",
"(",
"'/'",
")",
":",
"rel_output_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"output_file",
")",
"if",
"src_root_dir",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"rel_output_file",
"=",
"rel_output_file",
"[",
"len",
"(",
"src_root_dir",
")",
":",
"]",
"else",
":",
"rel_output_file",
"=",
"rel_output_file",
"[",
"len",
"(",
"src_root_dir",
")",
"+",
"1",
":",
"]",
"# replace output file with llvm bc file",
"out_dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"rel_output_file",
")",
"output_file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"output_file",
")",
"curr_output_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"llvm_bit_code_out",
",",
"out_dir_name",
")",
"os",
".",
"system",
"(",
"'mkdir -p '",
"+",
"curr_output_dir",
")",
"curr_output_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_output_dir",
",",
"output_file_name",
"[",
":",
"-",
"2",
"]",
"+",
"'.final.linked.bc'",
")",
")",
"# append output file path",
"modified_build_args",
".",
"append",
"(",
"\"-o\"",
")",
"modified_build_args",
".",
"append",
"(",
"curr_output_file",
")",
"return",
"work_dir",
",",
"output_file",
",",
"curr_output_file",
",",
"' '",
".",
"join",
"(",
"modified_build_args",
")"
] | https://github.com/ucsb-seclab/difuze/blob/bb59a12ff87ad5ae45d9c60e349891bf80d72877/helper_scripts/components/bear_llvm_build.py#L207-L252 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/glcanvas.py | python | GLCanvasWithContext | (*args, **kwargs) | return val | GLCanvasWithContext(Window parent, GLContext shared=None, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize,
long style=0, String name=GLCanvasNameStr,
int attribList=None, Palette palette=wxNullPalette) -> GLCanvas | GLCanvasWithContext(Window parent, GLContext shared=None, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize,
long style=0, String name=GLCanvasNameStr,
int attribList=None, Palette palette=wxNullPalette) -> GLCanvas | [
"GLCanvasWithContext",
"(",
"Window",
"parent",
"GLContext",
"shared",
"=",
"None",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"String",
"name",
"=",
"GLCanvasNameStr",
"int",
"attribList",
"=",
"None",
"Palette",
"palette",
"=",
"wxNullPalette",
")",
"-",
">",
"GLCanvas"
] | def GLCanvasWithContext(*args, **kwargs):
"""
GLCanvasWithContext(Window parent, GLContext shared=None, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize,
long style=0, String name=GLCanvasNameStr,
int attribList=None, Palette palette=wxNullPalette) -> GLCanvas
"""
val = _glcanvas.new_GLCanvasWithContext(*args, **kwargs)
val._setOORInfo(val)
return val | [
"def",
"GLCanvasWithContext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_glcanvas",
".",
"new_GLCanvasWithContext",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"val",
".",
"_setOORInfo",
"(",
"val",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/glcanvas.py#L155-L164 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | samples/culling/portal_culling.py | python | Game.update | (self, task) | return task.cont | Updates the camera based on the keyboard input. Once this is
done, then the CellManager's update function is called. | Updates the camera based on the keyboard input. Once this is
done, then the CellManager's update function is called. | [
"Updates",
"the",
"camera",
"based",
"on",
"the",
"keyboard",
"input",
".",
"Once",
"this",
"is",
"done",
"then",
"the",
"CellManager",
"s",
"update",
"function",
"is",
"called",
"."
] | def update(self, task):
"""Updates the camera based on the keyboard input. Once this is
done, then the CellManager's update function is called."""
delta = base.clock.dt
move_x = delta * 3 * -self.keys['a'] + delta * 3 * self.keys['d']
move_z = delta * 3 * self.keys['s'] + delta * 3 * -self.keys['w']
self.camera.setPos(self.camera, move_x, -move_z, 0)
self.heading += (delta * 90 * self.keys['arrow_left'] +
delta * 90 * -self.keys['arrow_right'])
self.pitch += (delta * 90 * self.keys['arrow_up'] +
delta * 90 * -self.keys['arrow_down'])
self.camera.setHpr(self.heading, self.pitch, 0)
if ENABLE_PORTALS:
self.cellmanager.update()
return task.cont | [
"def",
"update",
"(",
"self",
",",
"task",
")",
":",
"delta",
"=",
"base",
".",
"clock",
".",
"dt",
"move_x",
"=",
"delta",
"*",
"3",
"*",
"-",
"self",
".",
"keys",
"[",
"'a'",
"]",
"+",
"delta",
"*",
"3",
"*",
"self",
".",
"keys",
"[",
"'d'",
"]",
"move_z",
"=",
"delta",
"*",
"3",
"*",
"self",
".",
"keys",
"[",
"'s'",
"]",
"+",
"delta",
"*",
"3",
"*",
"-",
"self",
".",
"keys",
"[",
"'w'",
"]",
"self",
".",
"camera",
".",
"setPos",
"(",
"self",
".",
"camera",
",",
"move_x",
",",
"-",
"move_z",
",",
"0",
")",
"self",
".",
"heading",
"+=",
"(",
"delta",
"*",
"90",
"*",
"self",
".",
"keys",
"[",
"'arrow_left'",
"]",
"+",
"delta",
"*",
"90",
"*",
"-",
"self",
".",
"keys",
"[",
"'arrow_right'",
"]",
")",
"self",
".",
"pitch",
"+=",
"(",
"delta",
"*",
"90",
"*",
"self",
".",
"keys",
"[",
"'arrow_up'",
"]",
"+",
"delta",
"*",
"90",
"*",
"-",
"self",
".",
"keys",
"[",
"'arrow_down'",
"]",
")",
"self",
".",
"camera",
".",
"setHpr",
"(",
"self",
".",
"heading",
",",
"self",
".",
"pitch",
",",
"0",
")",
"if",
"ENABLE_PORTALS",
":",
"self",
".",
"cellmanager",
".",
"update",
"(",
")",
"return",
"task",
".",
"cont"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/culling/portal_culling.py#L135-L149 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm.assignments | (self) | return ret | Returns a list of Tensors with the matrix of assignments per shard. | Returns a list of Tensors with the matrix of assignments per shard. | [
"Returns",
"a",
"list",
"of",
"Tensors",
"with",
"the",
"matrix",
"of",
"assignments",
"per",
"shard",
"."
] | def assignments(self):
"""Returns a list of Tensors with the matrix of assignments per shard."""
ret = []
for w in self._w:
ret.append(tf.argmax(w, 1))
return ret | [
"def",
"assignments",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"w",
"in",
"self",
".",
"_w",
":",
"ret",
".",
"append",
"(",
"tf",
".",
"argmax",
"(",
"w",
",",
"1",
")",
")",
"return",
"ret"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L187-L192 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py | python | IMAP4.store | (self, message_set, command, flags) | return self._untagged_response(typ, dat, 'FETCH') | Alters flag dispositions for messages in mailbox.
(typ, [data]) = <instance>.store(message_set, command, flags) | Alters flag dispositions for messages in mailbox. | [
"Alters",
"flag",
"dispositions",
"for",
"messages",
"in",
"mailbox",
"."
] | def store(self, message_set, command, flags):
"""Alters flag dispositions for messages in mailbox.
(typ, [data]) = <instance>.store(message_set, command, flags)
"""
if (flags[0],flags[-1]) != ('(',')'):
flags = '(%s)' % flags # Avoid quoting the flags
typ, dat = self._simple_command('STORE', message_set, command, flags)
return self._untagged_response(typ, dat, 'FETCH') | [
"def",
"store",
"(",
"self",
",",
"message_set",
",",
"command",
",",
"flags",
")",
":",
"if",
"(",
"flags",
"[",
"0",
"]",
",",
"flags",
"[",
"-",
"1",
"]",
")",
"!=",
"(",
"'('",
",",
"')'",
")",
":",
"flags",
"=",
"'(%s)'",
"%",
"flags",
"# Avoid quoting the flags",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"'STORE'",
",",
"message_set",
",",
"command",
",",
"flags",
")",
"return",
"self",
".",
"_untagged_response",
"(",
"typ",
",",
"dat",
",",
"'FETCH'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py#L833-L841 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | driver/python/pysequoiadb/collection.py | python | collection.split_by_condition | (self, source_group_name, target_group_name,
split_condition,
split_end_condition=None) | Split the specified collection from source replica group to target
replica group by range.
Parameters:
Name Type Info:
source_group_name str The source replica group name.
target_group_name str The target replica group name.
split_condition dict The matching rule, return the count
of all documents if None.
split_end_condition dict The split end condition or None.
eg:
If we create a collection with the
option { ShardingKey:{"age":1},
ShardingType:"Hash",Partition:2^10 },
we can fill {age:30} as the
splitCondition, and fill {age:60}
as the splitEndCondition. when
split, the target replica group
will get the records whose age's
hash value are in [30,60).
If splitEndCondition is null, they
are in [30,max).
Exceptions:
pysequoiadb.error.SDBBaseError | Split the specified collection from source replica group to target
replica group by range. | [
"Split",
"the",
"specified",
"collection",
"from",
"source",
"replica",
"group",
"to",
"target",
"replica",
"group",
"by",
"range",
"."
] | def split_by_condition(self, source_group_name, target_group_name,
split_condition,
split_end_condition=None):
"""Split the specified collection from source replica group to target
replica group by range.
Parameters:
Name Type Info:
source_group_name str The source replica group name.
target_group_name str The target replica group name.
split_condition dict The matching rule, return the count
of all documents if None.
split_end_condition dict The split end condition or None.
eg:
If we create a collection with the
option { ShardingKey:{"age":1},
ShardingType:"Hash",Partition:2^10 },
we can fill {age:30} as the
splitCondition, and fill {age:60}
as the splitEndCondition. when
split, the target replica group
will get the records whose age's
hash value are in [30,60).
If splitEndCondition is null, they
are in [30,max).
Exceptions:
pysequoiadb.error.SDBBaseError
"""
if not isinstance(source_group_name, str_type):
raise SDBTypeError("source group name must be an instance of str_type")
if not isinstance(target_group_name, str_type):
raise SDBTypeError("target group name must be an instance of str_type")
bson_split_condition = None
if split_condition is not None:
if not isinstance(split_condition, dict):
raise SDBTypeError("split condition must be an instance of dict")
bson_split_condition = bson.BSON.encode(split_condition)
bson_end_condition = None
if split_end_condition is not None:
if not isinstance(split_end_condition, dict):
raise SDBTypeError("split end condition must be an instance of dict")
bson_end_condition = bson.BSON.encode(split_end_condition)
rc = sdb.cl_split_by_condition(self._cl, source_group_name,
target_group_name,
bson_split_condition,
bson_end_condition)
raise_if_error(rc, "Failed to split") | [
"def",
"split_by_condition",
"(",
"self",
",",
"source_group_name",
",",
"target_group_name",
",",
"split_condition",
",",
"split_end_condition",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"source_group_name",
",",
"str_type",
")",
":",
"raise",
"SDBTypeError",
"(",
"\"source group name must be an instance of str_type\"",
")",
"if",
"not",
"isinstance",
"(",
"target_group_name",
",",
"str_type",
")",
":",
"raise",
"SDBTypeError",
"(",
"\"target group name must be an instance of str_type\"",
")",
"bson_split_condition",
"=",
"None",
"if",
"split_condition",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"split_condition",
",",
"dict",
")",
":",
"raise",
"SDBTypeError",
"(",
"\"split condition must be an instance of dict\"",
")",
"bson_split_condition",
"=",
"bson",
".",
"BSON",
".",
"encode",
"(",
"split_condition",
")",
"bson_end_condition",
"=",
"None",
"if",
"split_end_condition",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"split_end_condition",
",",
"dict",
")",
":",
"raise",
"SDBTypeError",
"(",
"\"split end condition must be an instance of dict\"",
")",
"bson_end_condition",
"=",
"bson",
".",
"BSON",
".",
"encode",
"(",
"split_end_condition",
")",
"rc",
"=",
"sdb",
".",
"cl_split_by_condition",
"(",
"self",
".",
"_cl",
",",
"source_group_name",
",",
"target_group_name",
",",
"bson_split_condition",
",",
"bson_end_condition",
")",
"raise_if_error",
"(",
"rc",
",",
"\"Failed to split\"",
")"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/collection.py#L122-L171 | ||
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32com/client/__init__.py | python | Moniker | (Pathname, clsctx=pythoncom.CLSCTX_ALL) | return __WrapDispatch(dispatch, Pathname, clsctx=clsctx) | Python friendly version of GetObject's moniker functionality. | Python friendly version of GetObject's moniker functionality. | [
"Python",
"friendly",
"version",
"of",
"GetObject",
"s",
"moniker",
"functionality",
"."
] | def Moniker(Pathname, clsctx=pythoncom.CLSCTX_ALL):
"""
Python friendly version of GetObject's moniker functionality.
"""
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
return __WrapDispatch(dispatch, Pathname, clsctx=clsctx) | [
"def",
"Moniker",
"(",
"Pathname",
",",
"clsctx",
"=",
"pythoncom",
".",
"CLSCTX_ALL",
")",
":",
"moniker",
",",
"i",
",",
"bindCtx",
"=",
"pythoncom",
".",
"MkParseDisplayName",
"(",
"Pathname",
")",
"dispatch",
"=",
"moniker",
".",
"BindToObject",
"(",
"bindCtx",
",",
"None",
",",
"pythoncom",
".",
"IID_IDispatch",
")",
"return",
"__WrapDispatch",
"(",
"dispatch",
",",
"Pathname",
",",
"clsctx",
"=",
"clsctx",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/client/__init__.py#L98-L104 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus2.in.py | python | exodus.put_elem_blk_info | (self, elem_blk_id, elem_type, num_blk_elems,
num_elem_nodes, num_elem_attrs) | exo.put_elem_blk_info(elem_blk_id, \\
elem_type, \\
num_blk_elems, \\
num_elem_nodes, \\
num_elem_attrs)
-> store the element block *ID* and element block info
input value(s):
<int> elem_blk_id element block *ID* (not *INDEX*)
<string> elem_type element type (all caps), e.g. 'HEX8'
<int> num_blk_elems number of elements in the block
<int> num_elem_nodes number of nodes per element
<int> num_elem_attrs number of attributes per element | exo.put_elem_blk_info(elem_blk_id, \\
elem_type, \\
num_blk_elems, \\
num_elem_nodes, \\
num_elem_attrs) | [
"exo",
".",
"put_elem_blk_info",
"(",
"elem_blk_id",
"\\\\",
"elem_type",
"\\\\",
"num_blk_elems",
"\\\\",
"num_elem_nodes",
"\\\\",
"num_elem_attrs",
")"
] | def put_elem_blk_info(self, elem_blk_id, elem_type, num_blk_elems,
num_elem_nodes, num_elem_attrs):
"""
exo.put_elem_blk_info(elem_blk_id, \\
elem_type, \\
num_blk_elems, \\
num_elem_nodes, \\
num_elem_attrs)
-> store the element block *ID* and element block info
input value(s):
<int> elem_blk_id element block *ID* (not *INDEX*)
<string> elem_type element type (all caps), e.g. 'HEX8'
<int> num_blk_elems number of elements in the block
<int> num_elem_nodes number of nodes per element
<int> num_elem_attrs number of attributes per element
"""
self.__ex_put_elem_block(elem_blk_id, elem_type, num_blk_elems,
num_elem_nodes, num_elem_attrs) | [
"def",
"put_elem_blk_info",
"(",
"self",
",",
"elem_blk_id",
",",
"elem_type",
",",
"num_blk_elems",
",",
"num_elem_nodes",
",",
"num_elem_attrs",
")",
":",
"self",
".",
"__ex_put_elem_block",
"(",
"elem_blk_id",
",",
"elem_type",
",",
"num_blk_elems",
",",
"num_elem_nodes",
",",
"num_elem_attrs",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L1318-L1337 | ||
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/Roomba/RTNEATAgent.py | python | RTNEATAgent.start | (self, time, sensors) | return self.network_action(sensors) | start of an episode | start of an episode | [
"start",
"of",
"an",
"episode"
] | def start(self, time, sensors):
"""
start of an episode
"""
return self.network_action(sensors) | [
"def",
"start",
"(",
"self",
",",
"time",
",",
"sensors",
")",
":",
"return",
"self",
".",
"network_action",
"(",
"sensors",
")"
] | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/RTNEATAgent.py#L26-L30 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGrid.GetLabelEditor | (*args, **kwargs) | return _propgrid.PropertyGrid_GetLabelEditor(*args, **kwargs) | GetLabelEditor(self) -> wxTextCtrl | GetLabelEditor(self) -> wxTextCtrl | [
"GetLabelEditor",
"(",
"self",
")",
"-",
">",
"wxTextCtrl"
] | def GetLabelEditor(*args, **kwargs):
"""GetLabelEditor(self) -> wxTextCtrl"""
return _propgrid.PropertyGrid_GetLabelEditor(*args, **kwargs) | [
"def",
"GetLabelEditor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetLabelEditor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2223-L2225 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.version_num | (self) | return "%1.2f" % self.version.value | get exodus version number used to create the database
>>> version = exo.version_num()
Returns
-------
version : string
representation of version number | get exodus version number used to create the database | [
"get",
"exodus",
"version",
"number",
"used",
"to",
"create",
"the",
"database"
] | def version_num(self):
"""
get exodus version number used to create the database
>>> version = exo.version_num()
Returns
-------
version : string
representation of version number
"""
return "%1.2f" % self.version.value | [
"def",
"version_num",
"(",
"self",
")",
":",
"return",
"\"%1.2f\"",
"%",
"self",
".",
"version",
".",
"value"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L867-L878 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/cmd.py | python | Command.make_file | (self, infiles, outfile, func, args,
exec_msg=None, skip_msg=None, level=1) | Special case of 'execute()' for operations that process one or
more input files and generate one output file. Works just like
'execute()', except the operation is skipped and a different
message printed if 'outfile' already exists and is newer than all
files listed in 'infiles'. If the command defined 'self.force',
and it is true, then the command is unconditionally run -- does no
timestamp checks. | Special case of 'execute()' for operations that process one or
more input files and generate one output file. Works just like
'execute()', except the operation is skipped and a different
message printed if 'outfile' already exists and is newer than all
files listed in 'infiles'. If the command defined 'self.force',
and it is true, then the command is unconditionally run -- does no
timestamp checks. | [
"Special",
"case",
"of",
"execute",
"()",
"for",
"operations",
"that",
"process",
"one",
"or",
"more",
"input",
"files",
"and",
"generate",
"one",
"output",
"file",
".",
"Works",
"just",
"like",
"execute",
"()",
"except",
"the",
"operation",
"is",
"skipped",
"and",
"a",
"different",
"message",
"printed",
"if",
"outfile",
"already",
"exists",
"and",
"is",
"newer",
"than",
"all",
"files",
"listed",
"in",
"infiles",
".",
"If",
"the",
"command",
"defined",
"self",
".",
"force",
"and",
"it",
"is",
"true",
"then",
"the",
"command",
"is",
"unconditionally",
"run",
"--",
"does",
"no",
"timestamp",
"checks",
"."
] | def make_file(self, infiles, outfile, func, args,
exec_msg=None, skip_msg=None, level=1):
"""Special case of 'execute()' for operations that process one or
more input files and generate one output file. Works just like
'execute()', except the operation is skipped and a different
message printed if 'outfile' already exists and is newer than all
files listed in 'infiles'. If the command defined 'self.force',
and it is true, then the command is unconditionally run -- does no
timestamp checks.
"""
if skip_msg is None:
skip_msg = "skipping %s (inputs unchanged)" % outfile
# Allow 'infiles' to be a single string
if isinstance(infiles, str):
infiles = (infiles,)
elif not isinstance(infiles, (list, tuple)):
raise TypeError, \
"'infiles' must be a string, or a list or tuple of strings"
if exec_msg is None:
exec_msg = "generating %s from %s" % \
(outfile, ', '.join(infiles))
# If 'outfile' must be regenerated (either because it doesn't
# exist, is out-of-date, or the 'force' flag is true) then
# perform the action that presumably regenerates it
if self.force or dep_util.newer_group(infiles, outfile):
self.execute(func, args, exec_msg, level)
# Otherwise, print the "skip" message
else:
log.debug(skip_msg) | [
"def",
"make_file",
"(",
"self",
",",
"infiles",
",",
"outfile",
",",
"func",
",",
"args",
",",
"exec_msg",
"=",
"None",
",",
"skip_msg",
"=",
"None",
",",
"level",
"=",
"1",
")",
":",
"if",
"skip_msg",
"is",
"None",
":",
"skip_msg",
"=",
"\"skipping %s (inputs unchanged)\"",
"%",
"outfile",
"# Allow 'infiles' to be a single string",
"if",
"isinstance",
"(",
"infiles",
",",
"str",
")",
":",
"infiles",
"=",
"(",
"infiles",
",",
")",
"elif",
"not",
"isinstance",
"(",
"infiles",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
",",
"\"'infiles' must be a string, or a list or tuple of strings\"",
"if",
"exec_msg",
"is",
"None",
":",
"exec_msg",
"=",
"\"generating %s from %s\"",
"%",
"(",
"outfile",
",",
"', '",
".",
"join",
"(",
"infiles",
")",
")",
"# If 'outfile' must be regenerated (either because it doesn't",
"# exist, is out-of-date, or the 'force' flag is true) then",
"# perform the action that presumably regenerates it",
"if",
"self",
".",
"force",
"or",
"dep_util",
".",
"newer_group",
"(",
"infiles",
",",
"outfile",
")",
":",
"self",
".",
"execute",
"(",
"func",
",",
"args",
",",
"exec_msg",
",",
"level",
")",
"# Otherwise, print the \"skip\" message",
"else",
":",
"log",
".",
"debug",
"(",
"skip_msg",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/cmd.py#L394-L426 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/monitoring.py | python | Metric.__init__ | (self, metric_name, metric_methods, label_length, *args) | Creates a new metric.
Args:
metric_name: name of the metric class.
metric_methods: list of swig metric methods.
label_length: length of label args.
*args: the arguments to call create method. | Creates a new metric. | [
"Creates",
"a",
"new",
"metric",
"."
] | def __init__(self, metric_name, metric_methods, label_length, *args):
"""Creates a new metric.
Args:
metric_name: name of the metric class.
metric_methods: list of swig metric methods.
label_length: length of label args.
*args: the arguments to call create method.
"""
self._metric_name = metric_name
self._metric_methods = metric_methods
self._label_length = label_length
if label_length >= len(self._metric_methods):
raise ValueError('Cannot create {} metric with label >= {}'.format(
self._metric_name, len(self._metric_methods)))
self._metric = self._metric_methods[self._label_length].create(*args) | [
"def",
"__init__",
"(",
"self",
",",
"metric_name",
",",
"metric_methods",
",",
"label_length",
",",
"*",
"args",
")",
":",
"self",
".",
"_metric_name",
"=",
"metric_name",
"self",
".",
"_metric_methods",
"=",
"metric_methods",
"self",
".",
"_label_length",
"=",
"label_length",
"if",
"label_length",
">=",
"len",
"(",
"self",
".",
"_metric_methods",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot create {} metric with label >= {}'",
".",
"format",
"(",
"self",
".",
"_metric_name",
",",
"len",
"(",
"self",
".",
"_metric_methods",
")",
")",
")",
"self",
".",
"_metric",
"=",
"self",
".",
"_metric_methods",
"[",
"self",
".",
"_label_length",
"]",
".",
"create",
"(",
"*",
"args",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/monitoring.py#L114-L131 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/timeout.py | python | Timeout.read_timeout | (self) | Get the value for the read timeout.
This assumes some time has elapsed in the connection timeout and
computes the read timeout appropriately.
If self.total is set, the read timeout is dependent on the amount of
time taken by the connect timeout. If the connection time has not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has not yet been called on this object. | Get the value for the read timeout. | [
"Get",
"the",
"value",
"for",
"the",
"read",
"timeout",
"."
] | def read_timeout(self):
""" Get the value for the read timeout.
This assumes some time has elapsed in the connection timeout and
computes the read timeout appropriately.
If self.total is set, the read timeout is dependent on the amount of
time taken by the connect timeout. If the connection time has not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has not yet been called on this object.
"""
if (
self.total is not None
and self.total is not self.DEFAULT_TIMEOUT
and self._read is not None
and self._read is not self.DEFAULT_TIMEOUT
):
# In case the connect timeout has not yet been established.
if self._start_connect is None:
return self._read
return max(0, min(self.total - self.get_connect_duration(), self._read))
elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
return max(0, self.total - self.get_connect_duration())
else:
return self._read | [
"def",
"read_timeout",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"total",
"is",
"not",
"None",
"and",
"self",
".",
"total",
"is",
"not",
"self",
".",
"DEFAULT_TIMEOUT",
"and",
"self",
".",
"_read",
"is",
"not",
"None",
"and",
"self",
".",
"_read",
"is",
"not",
"self",
".",
"DEFAULT_TIMEOUT",
")",
":",
"# In case the connect timeout has not yet been established.",
"if",
"self",
".",
"_start_connect",
"is",
"None",
":",
"return",
"self",
".",
"_read",
"return",
"max",
"(",
"0",
",",
"min",
"(",
"self",
".",
"total",
"-",
"self",
".",
"get_connect_duration",
"(",
")",
",",
"self",
".",
"_read",
")",
")",
"elif",
"self",
".",
"total",
"is",
"not",
"None",
"and",
"self",
".",
"total",
"is",
"not",
"self",
".",
"DEFAULT_TIMEOUT",
":",
"return",
"max",
"(",
"0",
",",
"self",
".",
"total",
"-",
"self",
".",
"get_connect_duration",
"(",
")",
")",
"else",
":",
"return",
"self",
".",
"_read"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/timeout.py#L229-L258 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/timeline/trace_data.py | python | TraceData.Serialize | (self, f, gzip_result=False) | Serializes the trace result to a file-like object.
Write in trace container format if gzip_result=False.
Writes to a .zip file if gzip_result=True. | Serializes the trace result to a file-like object. | [
"Serializes",
"the",
"trace",
"result",
"to",
"a",
"file",
"-",
"like",
"object",
"."
] | def Serialize(self, f, gzip_result=False):
"""Serializes the trace result to a file-like object.
Write in trace container format if gzip_result=False.
Writes to a .zip file if gzip_result=True.
"""
if gzip_result:
zip_file = zipfile.ZipFile(f, mode='w')
try:
for part in self.active_parts:
tmp_file_name = None
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
tmp_file_name = tmp_file.name
tmp_file.write(str(self._raw_data[part.raw_field_name]))
zip_file.write(tmp_file_name, arcname=part.raw_field_name)
os.remove(tmp_file_name)
finally:
zip_file.close()
else:
json.dump(self._raw_data, f) | [
"def",
"Serialize",
"(",
"self",
",",
"f",
",",
"gzip_result",
"=",
"False",
")",
":",
"if",
"gzip_result",
":",
"zip_file",
"=",
"zipfile",
".",
"ZipFile",
"(",
"f",
",",
"mode",
"=",
"'w'",
")",
"try",
":",
"for",
"part",
"in",
"self",
".",
"active_parts",
":",
"tmp_file_name",
"=",
"None",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"as",
"tmp_file",
":",
"tmp_file_name",
"=",
"tmp_file",
".",
"name",
"tmp_file",
".",
"write",
"(",
"str",
"(",
"self",
".",
"_raw_data",
"[",
"part",
".",
"raw_field_name",
"]",
")",
")",
"zip_file",
".",
"write",
"(",
"tmp_file_name",
",",
"arcname",
"=",
"part",
".",
"raw_field_name",
")",
"os",
".",
"remove",
"(",
"tmp_file_name",
")",
"finally",
":",
"zip_file",
".",
"close",
"(",
")",
"else",
":",
"json",
".",
"dump",
"(",
"self",
".",
"_raw_data",
",",
"f",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/timeline/trace_data.py#L154-L173 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/cluster/_kmeans.py | python | _mini_batch_convergence | (model, iteration_idx, n_iter, tol,
n_samples, centers_squared_diff, batch_inertia,
context, verbose=0) | return False | Helper function to encapsulate the early stopping logic | Helper function to encapsulate the early stopping logic | [
"Helper",
"function",
"to",
"encapsulate",
"the",
"early",
"stopping",
"logic"
] | def _mini_batch_convergence(model, iteration_idx, n_iter, tol,
n_samples, centers_squared_diff, batch_inertia,
context, verbose=0):
"""Helper function to encapsulate the early stopping logic"""
# Normalize inertia to be able to compare values when
# batch_size changes
batch_inertia /= model.batch_size
centers_squared_diff /= model.batch_size
# Compute an Exponentially Weighted Average of the squared
# diff to monitor the convergence while discarding
# minibatch-local stochastic variability:
# https://en.wikipedia.org/wiki/Moving_average
ewa_diff = context.get('ewa_diff')
ewa_inertia = context.get('ewa_inertia')
if ewa_diff is None:
ewa_diff = centers_squared_diff
ewa_inertia = batch_inertia
else:
alpha = float(model.batch_size) * 2.0 / (n_samples + 1)
alpha = 1.0 if alpha > 1.0 else alpha
ewa_diff = ewa_diff * (1 - alpha) + centers_squared_diff * alpha
ewa_inertia = ewa_inertia * (1 - alpha) + batch_inertia * alpha
# Log progress to be able to monitor convergence
if verbose:
progress_msg = (
'Minibatch iteration %d/%d:'
' mean batch inertia: %f, ewa inertia: %f ' % (
iteration_idx + 1, n_iter, batch_inertia,
ewa_inertia))
print(progress_msg)
# Early stopping based on absolute tolerance on squared change of
# centers position (using EWA smoothing)
if tol > 0.0 and ewa_diff <= tol:
if verbose:
print('Converged (small centers change) at iteration %d/%d'
% (iteration_idx + 1, n_iter))
return True
# Early stopping heuristic due to lack of improvement on smoothed inertia
ewa_inertia_min = context.get('ewa_inertia_min')
no_improvement = context.get('no_improvement', 0)
if ewa_inertia_min is None or ewa_inertia < ewa_inertia_min:
no_improvement = 0
ewa_inertia_min = ewa_inertia
else:
no_improvement += 1
if (model.max_no_improvement is not None
and no_improvement >= model.max_no_improvement):
if verbose:
print('Converged (lack of improvement in inertia)'
' at iteration %d/%d'
% (iteration_idx + 1, n_iter))
return True
# update the convergence context to maintain state across successive calls:
context['ewa_diff'] = ewa_diff
context['ewa_inertia'] = ewa_inertia
context['ewa_inertia_min'] = ewa_inertia_min
context['no_improvement'] = no_improvement
return False | [
"def",
"_mini_batch_convergence",
"(",
"model",
",",
"iteration_idx",
",",
"n_iter",
",",
"tol",
",",
"n_samples",
",",
"centers_squared_diff",
",",
"batch_inertia",
",",
"context",
",",
"verbose",
"=",
"0",
")",
":",
"# Normalize inertia to be able to compare values when",
"# batch_size changes",
"batch_inertia",
"/=",
"model",
".",
"batch_size",
"centers_squared_diff",
"/=",
"model",
".",
"batch_size",
"# Compute an Exponentially Weighted Average of the squared",
"# diff to monitor the convergence while discarding",
"# minibatch-local stochastic variability:",
"# https://en.wikipedia.org/wiki/Moving_average",
"ewa_diff",
"=",
"context",
".",
"get",
"(",
"'ewa_diff'",
")",
"ewa_inertia",
"=",
"context",
".",
"get",
"(",
"'ewa_inertia'",
")",
"if",
"ewa_diff",
"is",
"None",
":",
"ewa_diff",
"=",
"centers_squared_diff",
"ewa_inertia",
"=",
"batch_inertia",
"else",
":",
"alpha",
"=",
"float",
"(",
"model",
".",
"batch_size",
")",
"*",
"2.0",
"/",
"(",
"n_samples",
"+",
"1",
")",
"alpha",
"=",
"1.0",
"if",
"alpha",
">",
"1.0",
"else",
"alpha",
"ewa_diff",
"=",
"ewa_diff",
"*",
"(",
"1",
"-",
"alpha",
")",
"+",
"centers_squared_diff",
"*",
"alpha",
"ewa_inertia",
"=",
"ewa_inertia",
"*",
"(",
"1",
"-",
"alpha",
")",
"+",
"batch_inertia",
"*",
"alpha",
"# Log progress to be able to monitor convergence",
"if",
"verbose",
":",
"progress_msg",
"=",
"(",
"'Minibatch iteration %d/%d:'",
"' mean batch inertia: %f, ewa inertia: %f '",
"%",
"(",
"iteration_idx",
"+",
"1",
",",
"n_iter",
",",
"batch_inertia",
",",
"ewa_inertia",
")",
")",
"print",
"(",
"progress_msg",
")",
"# Early stopping based on absolute tolerance on squared change of",
"# centers position (using EWA smoothing)",
"if",
"tol",
">",
"0.0",
"and",
"ewa_diff",
"<=",
"tol",
":",
"if",
"verbose",
":",
"print",
"(",
"'Converged (small centers change) at iteration %d/%d'",
"%",
"(",
"iteration_idx",
"+",
"1",
",",
"n_iter",
")",
")",
"return",
"True",
"# Early stopping heuristic due to lack of improvement on smoothed inertia",
"ewa_inertia_min",
"=",
"context",
".",
"get",
"(",
"'ewa_inertia_min'",
")",
"no_improvement",
"=",
"context",
".",
"get",
"(",
"'no_improvement'",
",",
"0",
")",
"if",
"ewa_inertia_min",
"is",
"None",
"or",
"ewa_inertia",
"<",
"ewa_inertia_min",
":",
"no_improvement",
"=",
"0",
"ewa_inertia_min",
"=",
"ewa_inertia",
"else",
":",
"no_improvement",
"+=",
"1",
"if",
"(",
"model",
".",
"max_no_improvement",
"is",
"not",
"None",
"and",
"no_improvement",
">=",
"model",
".",
"max_no_improvement",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"'Converged (lack of improvement in inertia)'",
"' at iteration %d/%d'",
"%",
"(",
"iteration_idx",
"+",
"1",
",",
"n_iter",
")",
")",
"return",
"True",
"# update the convergence context to maintain state across successive calls:",
"context",
"[",
"'ewa_diff'",
"]",
"=",
"ewa_diff",
"context",
"[",
"'ewa_inertia'",
"]",
"=",
"ewa_inertia",
"context",
"[",
"'ewa_inertia_min'",
"]",
"=",
"ewa_inertia_min",
"context",
"[",
"'no_improvement'",
"]",
"=",
"no_improvement",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_kmeans.py#L1264-L1327 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/_haskell.py | python | SyntaxData.GetCommentPattern | (self) | return [u'--'] | Returns a list of characters used to comment a block of code | Returns a list of characters used to comment a block of code | [
"Returns",
"a",
"list",
"of",
"characters",
"used",
"to",
"comment",
"a",
"block",
"of",
"code"
] | def GetCommentPattern(self):
"""Returns a list of characters used to comment a block of code """
return [u'--'] | [
"def",
"GetCommentPattern",
"(",
"self",
")",
":",
"return",
"[",
"u'--'",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_haskell.py#L82-L84 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/xcodeproj_file.py | python | PBXProject.AddOrGetFileInRootGroup | (self, path) | return group.AddOrGetFileByPath(path, hierarchical) | Returns a PBXFileReference corresponding to path in the correct group
according to RootGroupForPath's heuristics.
If an existing PBXFileReference for path exists, it will be returned.
Otherwise, one will be created and returned. | Returns a PBXFileReference corresponding to path in the correct group
according to RootGroupForPath's heuristics. | [
"Returns",
"a",
"PBXFileReference",
"corresponding",
"to",
"path",
"in",
"the",
"correct",
"group",
"according",
"to",
"RootGroupForPath",
"s",
"heuristics",
"."
] | def AddOrGetFileInRootGroup(self, path):
"""Returns a PBXFileReference corresponding to path in the correct group
according to RootGroupForPath's heuristics.
If an existing PBXFileReference for path exists, it will be returned.
Otherwise, one will be created and returned.
"""
(group, hierarchical) = self.RootGroupForPath(path)
return group.AddOrGetFileByPath(path, hierarchical) | [
"def",
"AddOrGetFileInRootGroup",
"(",
"self",
",",
"path",
")",
":",
"(",
"group",
",",
"hierarchical",
")",
"=",
"self",
".",
"RootGroupForPath",
"(",
"path",
")",
"return",
"group",
".",
"AddOrGetFileByPath",
"(",
"path",
",",
"hierarchical",
")"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/xcodeproj_file.py#L2617-L2626 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.__mul__ | (self,other) | return ret | Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr} | Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} | [
"Implementation",
"of",
"*",
"operator",
"allows",
"use",
"of",
"C",
"{",
"expr",
"*",
"3",
"}",
"in",
"place",
"of",
"C",
"{",
"expr",
"+",
"expr",
"+",
"expr",
"}",
".",
"Expressions",
"may",
"also",
"me",
"multiplied",
"by",
"a",
"2",
"-",
"integer",
"tuple",
"similar",
"to",
"C",
"{{",
"min",
"max",
"}}",
"multipliers",
"in",
"regular",
"expressions",
".",
"Tuples",
"may",
"also",
"include",
"C",
"{",
"None",
"}",
"as",
"in",
":",
"-",
"C",
"{",
"expr",
"*",
"(",
"n",
"None",
")",
"}",
"or",
"C",
"{",
"expr",
"*",
"(",
"n",
")",
"}",
"is",
"equivalent",
"to",
"C",
"{",
"expr",
"*",
"n",
"+",
"L",
"{",
"ZeroOrMore",
"}",
"(",
"expr",
")",
"}",
"(",
"read",
"as",
"at",
"least",
"n",
"instances",
"of",
"C",
"{",
"expr",
"}",
")",
"-",
"C",
"{",
"expr",
"*",
"(",
"None",
"n",
")",
"}",
"is",
"equivalent",
"to",
"C",
"{",
"expr",
"*",
"(",
"0",
"n",
")",
"}",
"(",
"read",
"as",
"0",
"to",
"n",
"instances",
"of",
"C",
"{",
"expr",
"}",
")",
"-",
"C",
"{",
"expr",
"*",
"(",
"None",
"None",
")",
"}",
"is",
"equivalent",
"to",
"C",
"{",
"L",
"{",
"ZeroOrMore",
"}",
"(",
"expr",
")",
"}",
"-",
"C",
"{",
"expr",
"*",
"(",
"1",
"None",
")",
"}",
"is",
"equivalent",
"to",
"C",
"{",
"L",
"{",
"OneOrMore",
"}",
"(",
"expr",
")",
"}"
] | def __mul__(self,other):
"""
Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr}
"""
if isinstance(other,int):
minElements, optElements = other,0
elif isinstance(other,tuple):
other = (other + (None, None))[:2]
if other[0] is None:
other = (0, other[1])
if isinstance(other[0],int) and other[1] is None:
if other[0] == 0:
return ZeroOrMore(self)
if other[0] == 1:
return OneOrMore(self)
else:
return self*other[0] + ZeroOrMore(self)
elif isinstance(other[0],int) and isinstance(other[1],int):
minElements, optElements = other
optElements -= minElements
else:
raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
else:
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
if minElements < 0:
raise ValueError("cannot multiply ParserElement by negative value")
if optElements < 0:
raise ValueError("second tuple value must be greater or equal to first tuple value")
if minElements == optElements == 0:
raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
if (optElements):
def makeOptionalList(n):
if n>1:
return Optional(self + makeOptionalList(n-1))
else:
return Optional(self)
if minElements:
if minElements == 1:
ret = self + makeOptionalList(optElements)
else:
ret = And([self]*minElements) + makeOptionalList(optElements)
else:
ret = makeOptionalList(optElements)
else:
if minElements == 1:
ret = self
else:
ret = And([self]*minElements)
return ret | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
",",
"0",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",
")",
":",
"other",
"=",
"(",
"other",
"+",
"(",
"None",
",",
"None",
")",
")",
"[",
":",
"2",
"]",
"if",
"other",
"[",
"0",
"]",
"is",
"None",
":",
"other",
"=",
"(",
"0",
",",
"other",
"[",
"1",
"]",
")",
"if",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"other",
"[",
"1",
"]",
"is",
"None",
":",
"if",
"other",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"ZeroOrMore",
"(",
"self",
")",
"if",
"other",
"[",
"0",
"]",
"==",
"1",
":",
"return",
"OneOrMore",
"(",
"self",
")",
"else",
":",
"return",
"self",
"*",
"other",
"[",
"0",
"]",
"+",
"ZeroOrMore",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"other",
"[",
"1",
"]",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
"optElements",
"-=",
"minElements",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and ('%s','%s') objects\"",
",",
"type",
"(",
"other",
"[",
"0",
"]",
")",
",",
"type",
"(",
"other",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and '%s' objects\"",
",",
"type",
"(",
"other",
")",
")",
"if",
"minElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by negative value\"",
")",
"if",
"optElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"second tuple value must be greater or equal to first tuple value\"",
")",
"if",
"minElements",
"==",
"optElements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by 0 or (0,0)\"",
")",
"if",
"(",
"optElements",
")",
":",
"def",
"makeOptionalList",
"(",
"n",
")",
":",
"if",
"n",
">",
"1",
":",
"return",
"Optional",
"(",
"self",
"+",
"makeOptionalList",
"(",
"n",
"-",
"1",
")",
")",
"else",
":",
"return",
"Optional",
"(",
"self",
")",
"if",
"minElements",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"return",
"ret"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L1877-L1943 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/png/png.py | python | Test.testPackedIter | (self) | Test iterator for row when using write_packed.
Indicative for Issue 47. | Test iterator for row when using write_packed. | [
"Test",
"iterator",
"for",
"row",
"when",
"using",
"write_packed",
"."
] | def testPackedIter(self):
"""Test iterator for row when using write_packed.
Indicative for Issue 47.
"""
w = Writer(16, 2, greyscale=True, alpha=False, bitdepth=1)
o = BytesIO()
w.write_packed(o, [itertools.chain([0x0a], [0xaa]),
itertools.chain([0x0f], [0xff])])
r = Reader(bytes=o.getvalue())
x,y,pixels,info = r.asDirect()
pixels = list(pixels)
self.assertEqual(len(pixels), 2)
self.assertEqual(len(pixels[0]), 16) | [
"def",
"testPackedIter",
"(",
"self",
")",
":",
"w",
"=",
"Writer",
"(",
"16",
",",
"2",
",",
"greyscale",
"=",
"True",
",",
"alpha",
"=",
"False",
",",
"bitdepth",
"=",
"1",
")",
"o",
"=",
"BytesIO",
"(",
")",
"w",
".",
"write_packed",
"(",
"o",
",",
"[",
"itertools",
".",
"chain",
"(",
"[",
"0x0a",
"]",
",",
"[",
"0xaa",
"]",
")",
",",
"itertools",
".",
"chain",
"(",
"[",
"0x0f",
"]",
",",
"[",
"0xff",
"]",
")",
"]",
")",
"r",
"=",
"Reader",
"(",
"bytes",
"=",
"o",
".",
"getvalue",
"(",
")",
")",
"x",
",",
"y",
",",
"pixels",
",",
"info",
"=",
"r",
".",
"asDirect",
"(",
")",
"pixels",
"=",
"list",
"(",
"pixels",
")",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"pixels",
")",
",",
"2",
")",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"pixels",
"[",
"0",
"]",
")",
",",
"16",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L2767-L2780 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | uCSIsByzantineMusicalSymbols | (code) | return ret | Check whether the character is part of
ByzantineMusicalSymbols UCS Block | Check whether the character is part of
ByzantineMusicalSymbols UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"ByzantineMusicalSymbols",
"UCS",
"Block"
] | def uCSIsByzantineMusicalSymbols(code):
"""Check whether the character is part of
ByzantineMusicalSymbols UCS Block """
ret = libxml2mod.xmlUCSIsByzantineMusicalSymbols(code)
return ret | [
"def",
"uCSIsByzantineMusicalSymbols",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsByzantineMusicalSymbols",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2131-L2135 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.AcceptsFocusFromKeyboard | (*args, **kwargs) | return _core_.Window_AcceptsFocusFromKeyboard(*args, **kwargs) | AcceptsFocusFromKeyboard(self) -> bool
Can this window be given focus by keyboard navigation? if not, the
only way to give it focus (provided it accepts it at all) is to click
it. | AcceptsFocusFromKeyboard(self) -> bool | [
"AcceptsFocusFromKeyboard",
"(",
"self",
")",
"-",
">",
"bool"
] | def AcceptsFocusFromKeyboard(*args, **kwargs):
"""
AcceptsFocusFromKeyboard(self) -> bool
Can this window be given focus by keyboard navigation? if not, the
only way to give it focus (provided it accepts it at all) is to click
it.
"""
return _core_.Window_AcceptsFocusFromKeyboard(*args, **kwargs) | [
"def",
"AcceptsFocusFromKeyboard",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_AcceptsFocusFromKeyboard",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L10174-L10182 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/training/supervisor.py | python | Supervisor.__init__ | (self, graph=None, ready_op=USE_DEFAULT, is_chief=True,
init_op=USE_DEFAULT, init_feed_dict=None,
local_init_op=USE_DEFAULT, logdir=None,
summary_op=USE_DEFAULT, saver=USE_DEFAULT,
global_step=USE_DEFAULT, save_summaries_secs=120,
save_model_secs=600, recovery_wait_secs=30, stop_grace_secs=120,
checkpoint_basename="model.ckpt", session_manager=None,
summary_writer=USE_DEFAULT, init_fn=None) | Create a `Supervisor`.
Args:
graph: A `Graph`. The graph that the model will use. Defaults to the
default `Graph`. The supervisor may add operations to the graph before
creating a session, but the graph should not be modified by the caller
after passing it to the supervisor.
ready_op: 1-D string `Tensor`. This tensor is evaluated by supervisors in
`prepare_or_wait_for_session()` to check if the model is ready to use.
The model is considered ready if it returns an empty array. Defaults to
the tensor returned from `tf.report_uninitialized_variables()` If
`None`, the model is not checked for readiness.
is_chief: If True, create a chief supervisor in charge of initializing
and restoring the model. If False, create a supervisor that relies
on a chief supervisor for inits and restore.
init_op: `Operation`. Used by chief supervisors to initialize the model
when it can not be recovered. Defaults to an `Operation` that
initializes all variables. If `None`, no initialization is done
automatically unless you pass a value for `init_fn`, see below.
init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
This feed dictionary will be used when `init_op` is evaluated.
local_init_op: `Operation`. Used by all supervisors to run initializations
that should run for every new supervisor instance. By default these
are table initializers and initializers for local variables.
If `None`, no further per supervisor-instance initialization is
done automatically.
logdir: A string. Optional path to a directory where to checkpoint the
model and log events for the visualizer. Used by chief supervisors.
The directory will be created if it does not exist.
summary_op: An `Operation` that returns a Summary for the event logs.
Used by chief supervisors if a `logdir` was specified. Defaults to the
operation returned from merge_all_summaries(). If `None`, summaries are
not computed automatically.
saver: A Saver object. Used by chief supervisors if a `logdir` was
specified. Defaults to the saved returned by Saver().
If `None`, the model is not saved automatically.
global_step: An integer Tensor of size 1 that counts steps. The value
from 'global_step' is used in summaries and checkpoint filenames.
Default to the op named 'global_step' in the graph if it exists, is of
rank 1, size 1, and of type tf.int32 ot tf.int64. If `None` the global
step is not recorded in summaries and checkpoint files. Used by chief
supervisors if a `logdir` was specified.
save_summaries_secs: Number of seconds between the computation of
summaries for the event log. Defaults to 120 seconds. Pass 0 to
disable summaries.
save_model_secs: Number of seconds between the creation of model
checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints.
recovery_wait_secs: Number of seconds between checks that the model
is ready. Used by supervisors when waiting for a chief supervisor
to initialize or restore the model. Defaults to 30 seconds.
stop_grace_secs: Grace period, in seconds, given to running threads to
stop when `stop()` is called. Defaults to 120 seconds.
checkpoint_basename: The basename for checkpoint saving.
session_manager: `SessionManager`, which manages Session creation and
recovery. If it is `None`, a default `SessionManager` will be created
with the set of arguments passed in for backwards compatibility.
summary_writer: `SummaryWriter` to use or `USE_DEFAULT`. Can be `None`
to indicate that no summaries should be written.
init_fn: Optional callable used to initialize the model. Called
after the optional `init_op` is called. The callable must accept one
argument, the session being initialized.
Returns:
A `Supervisor`. | Create a `Supervisor`. | [
"Create",
"a",
"Supervisor",
"."
] | def __init__(self, graph=None, ready_op=USE_DEFAULT, is_chief=True,
init_op=USE_DEFAULT, init_feed_dict=None,
local_init_op=USE_DEFAULT, logdir=None,
summary_op=USE_DEFAULT, saver=USE_DEFAULT,
global_step=USE_DEFAULT, save_summaries_secs=120,
save_model_secs=600, recovery_wait_secs=30, stop_grace_secs=120,
checkpoint_basename="model.ckpt", session_manager=None,
summary_writer=USE_DEFAULT, init_fn=None):
"""Create a `Supervisor`.
Args:
graph: A `Graph`. The graph that the model will use. Defaults to the
default `Graph`. The supervisor may add operations to the graph before
creating a session, but the graph should not be modified by the caller
after passing it to the supervisor.
ready_op: 1-D string `Tensor`. This tensor is evaluated by supervisors in
`prepare_or_wait_for_session()` to check if the model is ready to use.
The model is considered ready if it returns an empty array. Defaults to
the tensor returned from `tf.report_uninitialized_variables()` If
`None`, the model is not checked for readiness.
is_chief: If True, create a chief supervisor in charge of initializing
and restoring the model. If False, create a supervisor that relies
on a chief supervisor for inits and restore.
init_op: `Operation`. Used by chief supervisors to initialize the model
when it can not be recovered. Defaults to an `Operation` that
initializes all variables. If `None`, no initialization is done
automatically unless you pass a value for `init_fn`, see below.
init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
This feed dictionary will be used when `init_op` is evaluated.
local_init_op: `Operation`. Used by all supervisors to run initializations
that should run for every new supervisor instance. By default these
are table initializers and initializers for local variables.
If `None`, no further per supervisor-instance initialization is
done automatically.
logdir: A string. Optional path to a directory where to checkpoint the
model and log events for the visualizer. Used by chief supervisors.
The directory will be created if it does not exist.
summary_op: An `Operation` that returns a Summary for the event logs.
Used by chief supervisors if a `logdir` was specified. Defaults to the
operation returned from merge_all_summaries(). If `None`, summaries are
not computed automatically.
saver: A Saver object. Used by chief supervisors if a `logdir` was
specified. Defaults to the saved returned by Saver().
If `None`, the model is not saved automatically.
global_step: An integer Tensor of size 1 that counts steps. The value
from 'global_step' is used in summaries and checkpoint filenames.
Default to the op named 'global_step' in the graph if it exists, is of
rank 1, size 1, and of type tf.int32 ot tf.int64. If `None` the global
step is not recorded in summaries and checkpoint files. Used by chief
supervisors if a `logdir` was specified.
save_summaries_secs: Number of seconds between the computation of
summaries for the event log. Defaults to 120 seconds. Pass 0 to
disable summaries.
save_model_secs: Number of seconds between the creation of model
checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints.
recovery_wait_secs: Number of seconds between checks that the model
is ready. Used by supervisors when waiting for a chief supervisor
to initialize or restore the model. Defaults to 30 seconds.
stop_grace_secs: Grace period, in seconds, given to running threads to
stop when `stop()` is called. Defaults to 120 seconds.
checkpoint_basename: The basename for checkpoint saving.
session_manager: `SessionManager`, which manages Session creation and
recovery. If it is `None`, a default `SessionManager` will be created
with the set of arguments passed in for backwards compatibility.
summary_writer: `SummaryWriter` to use or `USE_DEFAULT`. Can be `None`
to indicate that no summaries should be written.
init_fn: Optional callable used to initialize the model. Called
after the optional `init_op` is called. The callable must accept one
argument, the session being initialized.
Returns:
A `Supervisor`.
"""
# Set default values of arguments.
if graph is None:
graph = ops.get_default_graph()
with graph.as_default():
self._init_ready_op(ready_op=ready_op)
self._init_init_op(init_op=init_op, init_feed_dict=init_feed_dict)
self._init_local_init_op(local_init_op=local_init_op)
self._init_saver(saver=saver)
self._init_summary_op(summary_op=summary_op)
self._init_global_step(global_step=global_step)
self._graph = graph
self._is_chief = is_chief
self._coord = coordinator.Coordinator()
self._recovery_wait_secs = recovery_wait_secs
self._stop_grace_secs = stop_grace_secs
self._init_fn = init_fn
# Set all attributes related to checkpointing and writing events to None.
# Afterwards, set them appropriately for chief supervisors, as these are
# the only supervisors that can write checkpoints and events.
self._logdir = None
self._save_summaries_secs = None
self._save_model_secs = None
self._save_path = None
self._summary_writer = None
if self._is_chief:
self._logdir = logdir
self._save_summaries_secs = save_summaries_secs
self._save_model_secs = save_model_secs
if self._logdir:
self._save_path = os.path.join(self._logdir, checkpoint_basename)
if summary_writer is Supervisor.USE_DEFAULT:
if self._logdir:
self._summary_writer = summary_io.SummaryWriter(self._logdir)
else:
self._summary_writer = summary_writer
self._graph_added_to_summary = False
self._init_session_manager(session_manager=session_manager)
self._verify_setup()
# The graph is not allowed to change anymore.
graph.finalize() | [
"def",
"__init__",
"(",
"self",
",",
"graph",
"=",
"None",
",",
"ready_op",
"=",
"USE_DEFAULT",
",",
"is_chief",
"=",
"True",
",",
"init_op",
"=",
"USE_DEFAULT",
",",
"init_feed_dict",
"=",
"None",
",",
"local_init_op",
"=",
"USE_DEFAULT",
",",
"logdir",
"=",
"None",
",",
"summary_op",
"=",
"USE_DEFAULT",
",",
"saver",
"=",
"USE_DEFAULT",
",",
"global_step",
"=",
"USE_DEFAULT",
",",
"save_summaries_secs",
"=",
"120",
",",
"save_model_secs",
"=",
"600",
",",
"recovery_wait_secs",
"=",
"30",
",",
"stop_grace_secs",
"=",
"120",
",",
"checkpoint_basename",
"=",
"\"model.ckpt\"",
",",
"session_manager",
"=",
"None",
",",
"summary_writer",
"=",
"USE_DEFAULT",
",",
"init_fn",
"=",
"None",
")",
":",
"# Set default values of arguments.",
"if",
"graph",
"is",
"None",
":",
"graph",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
"with",
"graph",
".",
"as_default",
"(",
")",
":",
"self",
".",
"_init_ready_op",
"(",
"ready_op",
"=",
"ready_op",
")",
"self",
".",
"_init_init_op",
"(",
"init_op",
"=",
"init_op",
",",
"init_feed_dict",
"=",
"init_feed_dict",
")",
"self",
".",
"_init_local_init_op",
"(",
"local_init_op",
"=",
"local_init_op",
")",
"self",
".",
"_init_saver",
"(",
"saver",
"=",
"saver",
")",
"self",
".",
"_init_summary_op",
"(",
"summary_op",
"=",
"summary_op",
")",
"self",
".",
"_init_global_step",
"(",
"global_step",
"=",
"global_step",
")",
"self",
".",
"_graph",
"=",
"graph",
"self",
".",
"_is_chief",
"=",
"is_chief",
"self",
".",
"_coord",
"=",
"coordinator",
".",
"Coordinator",
"(",
")",
"self",
".",
"_recovery_wait_secs",
"=",
"recovery_wait_secs",
"self",
".",
"_stop_grace_secs",
"=",
"stop_grace_secs",
"self",
".",
"_init_fn",
"=",
"init_fn",
"# Set all attributes related to checkpointing and writing events to None.",
"# Afterwards, set them appropriately for chief supervisors, as these are",
"# the only supervisors that can write checkpoints and events.",
"self",
".",
"_logdir",
"=",
"None",
"self",
".",
"_save_summaries_secs",
"=",
"None",
"self",
".",
"_save_model_secs",
"=",
"None",
"self",
".",
"_save_path",
"=",
"None",
"self",
".",
"_summary_writer",
"=",
"None",
"if",
"self",
".",
"_is_chief",
":",
"self",
".",
"_logdir",
"=",
"logdir",
"self",
".",
"_save_summaries_secs",
"=",
"save_summaries_secs",
"self",
".",
"_save_model_secs",
"=",
"save_model_secs",
"if",
"self",
".",
"_logdir",
":",
"self",
".",
"_save_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_logdir",
",",
"checkpoint_basename",
")",
"if",
"summary_writer",
"is",
"Supervisor",
".",
"USE_DEFAULT",
":",
"if",
"self",
".",
"_logdir",
":",
"self",
".",
"_summary_writer",
"=",
"summary_io",
".",
"SummaryWriter",
"(",
"self",
".",
"_logdir",
")",
"else",
":",
"self",
".",
"_summary_writer",
"=",
"summary_writer",
"self",
".",
"_graph_added_to_summary",
"=",
"False",
"self",
".",
"_init_session_manager",
"(",
"session_manager",
"=",
"session_manager",
")",
"self",
".",
"_verify_setup",
"(",
")",
"# The graph is not allowed to change anymore.",
"graph",
".",
"finalize",
"(",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/supervisor.py#L213-L328 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/subgraph.py | python | _finalize_indices | (list_of_index_or_t, ts) | return [_finalize_index(index_or_t, ts) for index_or_t in list_of_index_or_t] | Returns index in `indices` as is or replace with tensor's index. | Returns index in `indices` as is or replace with tensor's index. | [
"Returns",
"index",
"in",
"indices",
"as",
"is",
"or",
"replace",
"with",
"tensor",
"s",
"index",
"."
] | def _finalize_indices(list_of_index_or_t, ts):
"""Returns index in `indices` as is or replace with tensor's index."""
return [_finalize_index(index_or_t, ts) for index_or_t in list_of_index_or_t] | [
"def",
"_finalize_indices",
"(",
"list_of_index_or_t",
",",
"ts",
")",
":",
"return",
"[",
"_finalize_index",
"(",
"index_or_t",
",",
"ts",
")",
"for",
"index_or_t",
"in",
"list_of_index_or_t",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/subgraph.py#L47-L49 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | MenuBar.Append | (*args, **kwargs) | return _core_.MenuBar_Append(*args, **kwargs) | Append(self, Menu menu, String title) -> bool | Append(self, Menu menu, String title) -> bool | [
"Append",
"(",
"self",
"Menu",
"menu",
"String",
"title",
")",
"-",
">",
"bool"
] | def Append(*args, **kwargs):
"""Append(self, Menu menu, String title) -> bool"""
return _core_.MenuBar_Append(*args, **kwargs) | [
"def",
"Append",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MenuBar_Append",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L12272-L12274 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/serialutil.py | python | FileLike.readlines | (self, sizehint=None, eol=LF) | return lines | read a list of lines, until timeout.
sizehint is ignored. | read a list of lines, until timeout.
sizehint is ignored. | [
"read",
"a",
"list",
"of",
"lines",
"until",
"timeout",
".",
"sizehint",
"is",
"ignored",
"."
] | def readlines(self, sizehint=None, eol=LF):
"""read a list of lines, until timeout.
sizehint is ignored."""
if self.timeout is None:
raise ValueError("Serial port MUST have enabled timeout for this function!")
leneol = len(eol)
lines = []
while True:
line = self.readline(eol=eol)
if line:
lines.append(line)
if line[-leneol:] != eol: # was the line received with a timeout?
break
else:
break
return lines | [
"def",
"readlines",
"(",
"self",
",",
"sizehint",
"=",
"None",
",",
"eol",
"=",
"LF",
")",
":",
"if",
"self",
".",
"timeout",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Serial port MUST have enabled timeout for this function!\"",
")",
"leneol",
"=",
"len",
"(",
"eol",
")",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
"eol",
"=",
"eol",
")",
"if",
"line",
":",
"lines",
".",
"append",
"(",
"line",
")",
"if",
"line",
"[",
"-",
"leneol",
":",
"]",
"!=",
"eol",
":",
"# was the line received with a timeout?",
"break",
"else",
":",
"break",
"return",
"lines"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialutil.py#L179-L194 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/difference_table_widget/difference_table_widget_view.py | python | DifferenceTableView.on_item_changed | (self) | Not yet implemented. | Not yet implemented. | [
"Not",
"yet",
"implemented",
"."
] | def on_item_changed(self):
"""Not yet implemented."""
if not self._updating:
pass | [
"def",
"on_item_changed",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_updating",
":",
"pass"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/difference_table_widget/difference_table_widget_view.py#L203-L206 | ||
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/wubi/application.py | python | Wubi.set_logger | (self, log_to_console=True) | Adjust the application root logger settings | Adjust the application root logger settings | [
"Adjust",
"the",
"application",
"root",
"logger",
"settings"
] | def set_logger(self, log_to_console=True):
'''
Adjust the application root logger settings
'''
# file logging
if not self.info.log_file or self.info.log_file.lower() != "none":
if not self.info.log_file:
fname = self.info.full_application_name + ".log"
dname = tempfile.gettempdir()
self.info.log_file = os.path.join(dname, fname)
handler = logging.FileHandler(self.info.log_file)
formatter = logging.Formatter('%(asctime)s %(levelname)-6s %(name)s: %(message)s', datefmt='%m-%d %H:%M')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
log.addHandler(handler)
# console logging
if log_to_console and not bool(self.info.original_exe):
handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s', datefmt='%m-%d %H:%M')
handler.setFormatter(formatter)
if self.info.verbosity == "verbose":
handler.setLevel(logging.DEBUG)
elif self.info.verbosity == "quiet":
handler.setLevel(logging.ERROR)
else:
handler.setLevel(logging.INFO)
log.addHandler(handler)
log.setLevel(logging.DEBUG) | [
"def",
"set_logger",
"(",
"self",
",",
"log_to_console",
"=",
"True",
")",
":",
"# file logging",
"if",
"not",
"self",
".",
"info",
".",
"log_file",
"or",
"self",
".",
"info",
".",
"log_file",
".",
"lower",
"(",
")",
"!=",
"\"none\"",
":",
"if",
"not",
"self",
".",
"info",
".",
"log_file",
":",
"fname",
"=",
"self",
".",
"info",
".",
"full_application_name",
"+",
"\".log\"",
"dname",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"self",
".",
"info",
".",
"log_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dname",
",",
"fname",
")",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"self",
".",
"info",
".",
"log_file",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(levelname)-6s %(name)s: %(message)s'",
",",
"datefmt",
"=",
"'%m-%d %H:%M'",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"log",
".",
"addHandler",
"(",
"handler",
")",
"# console logging",
"if",
"log_to_console",
"and",
"not",
"bool",
"(",
"self",
".",
"info",
".",
"original_exe",
")",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(message)s'",
",",
"datefmt",
"=",
"'%m-%d %H:%M'",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"if",
"self",
".",
"info",
".",
"verbosity",
"==",
"\"verbose\"",
":",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"elif",
"self",
".",
"info",
".",
"verbosity",
"==",
"\"quiet\"",
":",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"ERROR",
")",
"else",
":",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"log",
".",
"addHandler",
"(",
"handler",
")",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/wubi/application.py#L292-L319 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/oinspect.py | python | get_encoding | (obj) | Get encoding for python source file defining obj
Returns None if obj is not defined in a sourcefile. | Get encoding for python source file defining obj | [
"Get",
"encoding",
"for",
"python",
"source",
"file",
"defining",
"obj"
] | def get_encoding(obj):
"""Get encoding for python source file defining obj
Returns None if obj is not defined in a sourcefile.
"""
ofile = find_file(obj)
# run contents of file through pager starting at line where the object
# is defined, as long as the file isn't binary and is actually on the
# filesystem.
if ofile is None:
return None
elif ofile.endswith(('.so', '.dll', '.pyd')):
return None
elif not os.path.isfile(ofile):
return None
else:
# Print only text files, not extension binaries. Note that
# getsourcelines returns lineno with 1-offset and page() uses
# 0-offset, so we must adjust.
with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
encoding, lines = openpy.detect_encoding(buffer.readline)
return encoding | [
"def",
"get_encoding",
"(",
"obj",
")",
":",
"ofile",
"=",
"find_file",
"(",
"obj",
")",
"# run contents of file through pager starting at line where the object",
"# is defined, as long as the file isn't binary and is actually on the",
"# filesystem.",
"if",
"ofile",
"is",
"None",
":",
"return",
"None",
"elif",
"ofile",
".",
"endswith",
"(",
"(",
"'.so'",
",",
"'.dll'",
",",
"'.pyd'",
")",
")",
":",
"return",
"None",
"elif",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"ofile",
")",
":",
"return",
"None",
"else",
":",
"# Print only text files, not extension binaries. Note that",
"# getsourcelines returns lineno with 1-offset and page() uses",
"# 0-offset, so we must adjust.",
"with",
"stdlib_io",
".",
"open",
"(",
"ofile",
",",
"'rb'",
")",
"as",
"buffer",
":",
"# Tweaked to use io.open for Python 2",
"encoding",
",",
"lines",
"=",
"openpy",
".",
"detect_encoding",
"(",
"buffer",
".",
"readline",
")",
"return",
"encoding"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/oinspect.py#L97-L118 | ||
lighttransport/nanort | 74063967336311f54ede5dffdfa242123825033b | deps/cpplint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
TODO(unknown): cpplint spends a fair bit of time matching parentheses.
Ideally we would want to index all opening and closing parentheses once
and have CloseExpression be just a simple lookup, but due to preprocessor
tricks, this is not so easy.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
TODO(unknown): cpplint spends a fair bit of time matching parentheses.
Ideally we would want to index all opening and closing parentheses once
and have CloseExpression be just a simple lookup, but due to preprocessor
tricks, this is not so easy.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
return (line, clean_lines.NumLines(), -1)
# Check first line
(end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while stack and linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find end of expression before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"(",
"line",
"[",
"pos",
"]",
"not",
"in",
"'({[<'",
")",
"or",
"Match",
"(",
"r'<[<=]'",
",",
"line",
"[",
"pos",
":",
"]",
")",
":",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")",
"# Check first line",
"(",
"end_pos",
",",
"stack",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"[",
"]",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Continue scanning forward",
"while",
"stack",
"and",
"linenum",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
":",
"linenum",
"+=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"end_pos",
",",
"stack",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"0",
",",
"stack",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Did not find end of expression before end of file, give up",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")"
] | https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L1463-L1504 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/tools/transformers/float16.py | python | convert_np_to_float16 | (np_array, min_positive_val=1e-7, max_finite_val=1e4) | return np.float16(np_array) | Convert float32 numpy array to float16 without changing sign or finiteness.
Positive values less than min_positive_val are mapped to min_positive_val.
Positive finite values greater than max_finite_val are mapped to max_finite_val.
Similar for negative values. NaN, 0, inf, and -inf are unchanged. | Convert float32 numpy array to float16 without changing sign or finiteness.
Positive values less than min_positive_val are mapped to min_positive_val.
Positive finite values greater than max_finite_val are mapped to max_finite_val.
Similar for negative values. NaN, 0, inf, and -inf are unchanged. | [
"Convert",
"float32",
"numpy",
"array",
"to",
"float16",
"without",
"changing",
"sign",
"or",
"finiteness",
".",
"Positive",
"values",
"less",
"than",
"min_positive_val",
"are",
"mapped",
"to",
"min_positive_val",
".",
"Positive",
"finite",
"values",
"greater",
"than",
"max_finite_val",
"are",
"mapped",
"to",
"max_finite_val",
".",
"Similar",
"for",
"negative",
"values",
".",
"NaN",
"0",
"inf",
"and",
"-",
"inf",
"are",
"unchanged",
"."
] | def convert_np_to_float16(np_array, min_positive_val=1e-7, max_finite_val=1e4):
'''
Convert float32 numpy array to float16 without changing sign or finiteness.
Positive values less than min_positive_val are mapped to min_positive_val.
Positive finite values greater than max_finite_val are mapped to max_finite_val.
Similar for negative values. NaN, 0, inf, and -inf are unchanged.
'''
def between(a, b, c):
return np.logical_and(a < b, b < c)
np_array = np.where(between(0, np_array, min_positive_val), min_positive_val, np_array)
np_array = np.where(between(-min_positive_val, np_array, 0), -min_positive_val, np_array)
np_array = np.where(between(max_finite_val, np_array, float('inf')), max_finite_val, np_array)
np_array = np.where(between(float('-inf'), np_array, -max_finite_val), -max_finite_val, np_array)
return np.float16(np_array) | [
"def",
"convert_np_to_float16",
"(",
"np_array",
",",
"min_positive_val",
"=",
"1e-7",
",",
"max_finite_val",
"=",
"1e4",
")",
":",
"def",
"between",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"return",
"np",
".",
"logical_and",
"(",
"a",
"<",
"b",
",",
"b",
"<",
"c",
")",
"np_array",
"=",
"np",
".",
"where",
"(",
"between",
"(",
"0",
",",
"np_array",
",",
"min_positive_val",
")",
",",
"min_positive_val",
",",
"np_array",
")",
"np_array",
"=",
"np",
".",
"where",
"(",
"between",
"(",
"-",
"min_positive_val",
",",
"np_array",
",",
"0",
")",
",",
"-",
"min_positive_val",
",",
"np_array",
")",
"np_array",
"=",
"np",
".",
"where",
"(",
"between",
"(",
"max_finite_val",
",",
"np_array",
",",
"float",
"(",
"'inf'",
")",
")",
",",
"max_finite_val",
",",
"np_array",
")",
"np_array",
"=",
"np",
".",
"where",
"(",
"between",
"(",
"float",
"(",
"'-inf'",
")",
",",
"np_array",
",",
"-",
"max_finite_val",
")",
",",
"-",
"max_finite_val",
",",
"np_array",
")",
"return",
"np",
".",
"float16",
"(",
"np_array",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/float16.py#L31-L45 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_snapper.py | python | Snapper.getPerpendicular | (self, edge, pt) | return np | Return a point on an edge, perpendicular to the given point. | Return a point on an edge, perpendicular to the given point. | [
"Return",
"a",
"point",
"on",
"an",
"edge",
"perpendicular",
"to",
"the",
"given",
"point",
"."
] | def getPerpendicular(self, edge, pt):
"""Return a point on an edge, perpendicular to the given point."""
dv = pt.sub(edge.Vertexes[0].Point)
nv = DraftVecUtils.project(dv, DraftGeomUtils.vec(edge))
np = (edge.Vertexes[0].Point).add(nv)
return np | [
"def",
"getPerpendicular",
"(",
"self",
",",
"edge",
",",
"pt",
")",
":",
"dv",
"=",
"pt",
".",
"sub",
"(",
"edge",
".",
"Vertexes",
"[",
"0",
"]",
".",
"Point",
")",
"nv",
"=",
"DraftVecUtils",
".",
"project",
"(",
"dv",
",",
"DraftGeomUtils",
".",
"vec",
"(",
"edge",
")",
")",
"np",
"=",
"(",
"edge",
".",
"Vertexes",
"[",
"0",
"]",
".",
"Point",
")",
".",
"add",
"(",
"nv",
")",
"return",
"np"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_snapper.py#L1109-L1114 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/all-oone-data-structure.py | python | AllOne.inc | (self, key) | Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void | Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void | [
"Inserts",
"a",
"new",
"key",
"<Key",
">",
"with",
"value",
"1",
".",
"Or",
"increments",
"an",
"existing",
"key",
"by",
"1",
".",
":",
"type",
"key",
":",
"str",
":",
"rtype",
":",
"void"
] | def inc(self, key):
"""
Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void
"""
if key not in self.bucket_of_key:
self.bucket_of_key[key] = self.buckets.insert(self.buckets.begin(), Node(0, set([key])))
bucket, next_bucket = self.bucket_of_key[key], self.bucket_of_key[key].next
if next_bucket is self.buckets.end() or next_bucket.value > bucket.value+1:
next_bucket = self.buckets.insert(next_bucket, Node(bucket.value+1, set()))
next_bucket.keys.add(key)
self.bucket_of_key[key] = next_bucket
bucket.keys.remove(key)
if not bucket.keys:
self.buckets.erase(bucket) | [
"def",
"inc",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"bucket_of_key",
":",
"self",
".",
"bucket_of_key",
"[",
"key",
"]",
"=",
"self",
".",
"buckets",
".",
"insert",
"(",
"self",
".",
"buckets",
".",
"begin",
"(",
")",
",",
"Node",
"(",
"0",
",",
"set",
"(",
"[",
"key",
"]",
")",
")",
")",
"bucket",
",",
"next_bucket",
"=",
"self",
".",
"bucket_of_key",
"[",
"key",
"]",
",",
"self",
".",
"bucket_of_key",
"[",
"key",
"]",
".",
"next",
"if",
"next_bucket",
"is",
"self",
".",
"buckets",
".",
"end",
"(",
")",
"or",
"next_bucket",
".",
"value",
">",
"bucket",
".",
"value",
"+",
"1",
":",
"next_bucket",
"=",
"self",
".",
"buckets",
".",
"insert",
"(",
"next_bucket",
",",
"Node",
"(",
"bucket",
".",
"value",
"+",
"1",
",",
"set",
"(",
")",
")",
")",
"next_bucket",
".",
"keys",
".",
"add",
"(",
"key",
")",
"self",
".",
"bucket_of_key",
"[",
"key",
"]",
"=",
"next_bucket",
"bucket",
".",
"keys",
".",
"remove",
"(",
"key",
")",
"if",
"not",
"bucket",
".",
"keys",
":",
"self",
".",
"buckets",
".",
"erase",
"(",
"bucket",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/all-oone-data-structure.py#L54-L71 | ||
esa/pagmo | 80281d549c8f1b470e1489a5d37c8f06b2e429c0 | PyGMO/util/_analysis.py | python | analysis.f_linearity_convexity | (self, n_pairs=0, tol=10 ** (-8), round_to=3) | This function gives the user information about the probability of linearity and convexity
of the fitness function(s). See analysis._p_lin_conv for a more thorough description of
these tests. All properties are shown per objective.
**USAGE:**
analysis.f_linearity_convexity([n_pairs=1000, tolerance=10**(-8), round_to=4])
* n_pairs: number of pairs of points used in the test. If set to 0, it will use as many pairs of points as points there are in the sample. Defaults to 0.
* tol: tolerance considered to rate the function as linear or convex between two points. Defaults to 10**(-8).
* round_to: precision of the results printed. Defaults to 3.
**Prints to screen or file:**
* Number of pairs of points used in test
* Probability of linearity [0,1].
* Probability of convexity [0,1].
* Mean deviation from linearity, scaled with corresponding fitness scale factor.
**NOTE:** integer variable values are fixed during each of the tests and linearity or convexity
is assessed as regards the continuous part of the chromosome. | This function gives the user information about the probability of linearity and convexity
of the fitness function(s). See analysis._p_lin_conv for a more thorough description of
these tests. All properties are shown per objective. | [
"This",
"function",
"gives",
"the",
"user",
"information",
"about",
"the",
"probability",
"of",
"linearity",
"and",
"convexity",
"of",
"the",
"fitness",
"function",
"(",
"s",
")",
".",
"See",
"analysis",
".",
"_p_lin_conv",
"for",
"a",
"more",
"thorough",
"description",
"of",
"these",
"tests",
".",
"All",
"properties",
"are",
"shown",
"per",
"objective",
"."
] | def f_linearity_convexity(self, n_pairs=0, tol=10 ** (-8), round_to=3):
"""
This function gives the user information about the probability of linearity and convexity
of the fitness function(s). See analysis._p_lin_conv for a more thorough description of
these tests. All properties are shown per objective.
**USAGE:**
analysis.f_linearity_convexity([n_pairs=1000, tolerance=10**(-8), round_to=4])
* n_pairs: number of pairs of points used in the test. If set to 0, it will use as many pairs of points as points there are in the sample. Defaults to 0.
* tol: tolerance considered to rate the function as linear or convex between two points. Defaults to 10**(-8).
* round_to: precision of the results printed. Defaults to 3.
**Prints to screen or file:**
* Number of pairs of points used in test
* Probability of linearity [0,1].
* Probability of convexity [0,1].
* Mean deviation from linearity, scaled with corresponding fitness scale factor.
**NOTE:** integer variable values are fixed during each of the tests and linearity or convexity
is assessed as regards the continuous part of the chromosome.
"""
if self.dir is None:
output = None
else:
output = open(self.dir + '/log.txt', 'r+')
output.seek(0, 2)
print(
"-------------------------------------------------------------------------------", file=output)
print("PROBABILITY OF LINEARITY AND CONVEXITY", file=output)
print(
"-------------------------------------------------------------------------------", file=output)
p = self._p_lin_conv(n_pairs, tol)
print("Number of pairs of points used : ",
[self.lin_conv_npairs], file=output)
print("Probability of linearity : ",
[round(i, round_to) for i in p[0]], file=output)
print("Probability of convexity : ",
[round(i, round_to) for i in p[1]], file=output)
print("Mean deviation from linearity : ",
[round(i, round_to) for i in p[2]], file=output)
if output is not None:
output.close() | [
"def",
"f_linearity_convexity",
"(",
"self",
",",
"n_pairs",
"=",
"0",
",",
"tol",
"=",
"10",
"**",
"(",
"-",
"8",
")",
",",
"round_to",
"=",
"3",
")",
":",
"if",
"self",
".",
"dir",
"is",
"None",
":",
"output",
"=",
"None",
"else",
":",
"output",
"=",
"open",
"(",
"self",
".",
"dir",
"+",
"'/log.txt'",
",",
"'r+'",
")",
"output",
".",
"seek",
"(",
"0",
",",
"2",
")",
"print",
"(",
"\"-------------------------------------------------------------------------------\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"PROBABILITY OF LINEARITY AND CONVEXITY\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"-------------------------------------------------------------------------------\"",
",",
"file",
"=",
"output",
")",
"p",
"=",
"self",
".",
"_p_lin_conv",
"(",
"n_pairs",
",",
"tol",
")",
"print",
"(",
"\"Number of pairs of points used : \"",
",",
"[",
"self",
".",
"lin_conv_npairs",
"]",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"Probability of linearity : \"",
",",
"[",
"round",
"(",
"i",
",",
"round_to",
")",
"for",
"i",
"in",
"p",
"[",
"0",
"]",
"]",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"Probability of convexity : \"",
",",
"[",
"round",
"(",
"i",
",",
"round_to",
")",
"for",
"i",
"in",
"p",
"[",
"1",
"]",
"]",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"Mean deviation from linearity : \"",
",",
"[",
"round",
"(",
"i",
",",
"round_to",
")",
"for",
"i",
"in",
"p",
"[",
"2",
"]",
"]",
",",
"file",
"=",
"output",
")",
"if",
"output",
"is",
"not",
"None",
":",
"output",
".",
"close",
"(",
")"
] | https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/util/_analysis.py#L544-L590 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/descriptor_pool.py | python | DescriptorPool.AddSerializedFile | (self, serialized_file_desc_proto) | Adds the FileDescriptorProto and its types to this pool.
Args:
serialized_file_desc_proto (bytes): A bytes string, serialization of the
:class:`FileDescriptorProto` to add. | Adds the FileDescriptorProto and its types to this pool. | [
"Adds",
"the",
"FileDescriptorProto",
"and",
"its",
"types",
"to",
"this",
"pool",
"."
] | def AddSerializedFile(self, serialized_file_desc_proto):
"""Adds the FileDescriptorProto and its types to this pool.
Args:
serialized_file_desc_proto (bytes): A bytes string, serialization of the
:class:`FileDescriptorProto` to add.
"""
# pylint: disable=g-import-not-at-top
from google.protobuf import descriptor_pb2
file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
serialized_file_desc_proto)
self.Add(file_desc_proto) | [
"def",
"AddSerializedFile",
"(",
"self",
",",
"serialized_file_desc_proto",
")",
":",
"# pylint: disable=g-import-not-at-top",
"from",
"google",
".",
"protobuf",
"import",
"descriptor_pb2",
"file_desc_proto",
"=",
"descriptor_pb2",
".",
"FileDescriptorProto",
".",
"FromString",
"(",
"serialized_file_desc_proto",
")",
"self",
".",
"Add",
"(",
"file_desc_proto",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/descriptor_pool.py#L204-L216 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/nanfunctions.py | python | nanvar | (a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue) | return var | Compute the variance along the specified axis, while ignoring NaNs.
Returns the variance of the array elements, a measure of the spread of
a distribution. The variance is computed for the flattened array by
default, otherwise over the specified axis.
For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the variance is computed. The default is to compute
the variance of the flattened array.
dtype : data-type, optional
Type to use in computing the variance. For arrays of integer type
the default is `float32`; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternate output array in which to place the result. It must have
the same shape as the expected output, but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of non-NaN
elements. By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
Returns
-------
variance : ndarray, see dtype parameter above
If `out` is None, return a new array containing the variance,
otherwise return a reference to the output array. If ddof is >= the
number of non-NaN elements in a slice or the slice contains only
NaNs, then the result for that slice is NaN.
See Also
--------
std : Standard deviation
mean : Average
var : Variance while not ignoring NaNs
nanstd, nanmean
numpy.doc.ufuncs : Section "Output arguments"
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of a hypothetical infinite
population. ``ddof=0`` provides a maximum likelihood estimate of the
variance for normally distributed variables.
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
For floating-point input, the variance is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for `float32` (see example
below). Specifying a higher-accuracy accumulator using the ``dtype``
keyword can alleviate this issue.
For this function to work on sub-classes of ndarray, they must define
`sum` with the kwarg `keepdims`
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.var(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([ 1., 0.])
>>> np.nanvar(a, axis=1)
array([ 0., 0.25]) | Compute the variance along the specified axis, while ignoring NaNs. | [
"Compute",
"the",
"variance",
"along",
"the",
"specified",
"axis",
"while",
"ignoring",
"NaNs",
"."
] | def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):
"""
Compute the variance along the specified axis, while ignoring NaNs.
Returns the variance of the array elements, a measure of the spread of
a distribution. The variance is computed for the flattened array by
default, otherwise over the specified axis.
For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the variance is computed. The default is to compute
the variance of the flattened array.
dtype : data-type, optional
Type to use in computing the variance. For arrays of integer type
the default is `float32`; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternate output array in which to place the result. It must have
the same shape as the expected output, but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of non-NaN
elements. By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
Returns
-------
variance : ndarray, see dtype parameter above
If `out` is None, return a new array containing the variance,
otherwise return a reference to the output array. If ddof is >= the
number of non-NaN elements in a slice or the slice contains only
NaNs, then the result for that slice is NaN.
See Also
--------
std : Standard deviation
mean : Average
var : Variance while not ignoring NaNs
nanstd, nanmean
numpy.doc.ufuncs : Section "Output arguments"
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of a hypothetical infinite
population. ``ddof=0`` provides a maximum likelihood estimate of the
variance for normally distributed variables.
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
For floating-point input, the variance is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for `float32` (see example
below). Specifying a higher-accuracy accumulator using the ``dtype``
keyword can alleviate this issue.
For this function to work on sub-classes of ndarray, they must define
`sum` with the kwarg `keepdims`
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.var(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([ 1., 0.])
>>> np.nanvar(a, axis=1)
array([ 0., 0.25])
"""
arr, mask = _replace_nan(a, 0)
if mask is None:
return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof,
keepdims=keepdims)
if dtype is not None:
dtype = np.dtype(dtype)
if dtype is not None and not issubclass(dtype.type, np.inexact):
raise TypeError("If a is inexact, then dtype must be inexact")
if out is not None and not issubclass(out.dtype.type, np.inexact):
raise TypeError("If a is inexact, then out must be inexact")
# Compute mean
if type(arr) is np.matrix:
_keepdims = np._NoValue
else:
_keepdims = True
# we need to special case matrix for reverse compatibility
# in order for this to work, these sums need to be called with
# keepdims=True, however matrix now raises an error in this case, but
# the reason that it drops the keepdims kwarg is to force keepdims=True
# so this used to work by serendipity.
cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims)
avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims)
avg = _divide_by_count(avg, cnt)
# Compute squared deviation from mean.
np.subtract(arr, avg, out=arr, casting='unsafe')
arr = _copyto(arr, 0, mask)
if issubclass(arr.dtype.type, np.complexfloating):
sqr = np.multiply(arr, arr.conj(), out=arr).real
else:
sqr = np.multiply(arr, arr, out=arr)
# Compute variance.
var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
if var.ndim < cnt.ndim:
# Subclasses of ndarray may ignore keepdims, so check here.
cnt = cnt.squeeze(axis)
dof = cnt - ddof
var = _divide_by_count(var, dof)
isbad = (dof <= 0)
if np.any(isbad):
warnings.warn("Degrees of freedom <= 0 for slice.", RuntimeWarning, stacklevel=2)
# NaN, inf, or negative numbers are all possible bad
# values, so explicitly replace them with NaN.
var = _copyto(var, np.nan, isbad)
return var | [
"def",
"nanvar",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"ddof",
"=",
"0",
",",
"keepdims",
"=",
"np",
".",
"_NoValue",
")",
":",
"arr",
",",
"mask",
"=",
"_replace_nan",
"(",
"a",
",",
"0",
")",
"if",
"mask",
"is",
"None",
":",
"return",
"np",
".",
"var",
"(",
"arr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
",",
"ddof",
"=",
"ddof",
",",
"keepdims",
"=",
"keepdims",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"if",
"dtype",
"is",
"not",
"None",
"and",
"not",
"issubclass",
"(",
"dtype",
".",
"type",
",",
"np",
".",
"inexact",
")",
":",
"raise",
"TypeError",
"(",
"\"If a is inexact, then dtype must be inexact\"",
")",
"if",
"out",
"is",
"not",
"None",
"and",
"not",
"issubclass",
"(",
"out",
".",
"dtype",
".",
"type",
",",
"np",
".",
"inexact",
")",
":",
"raise",
"TypeError",
"(",
"\"If a is inexact, then out must be inexact\"",
")",
"# Compute mean",
"if",
"type",
"(",
"arr",
")",
"is",
"np",
".",
"matrix",
":",
"_keepdims",
"=",
"np",
".",
"_NoValue",
"else",
":",
"_keepdims",
"=",
"True",
"# we need to special case matrix for reverse compatibility",
"# in order for this to work, these sums need to be called with",
"# keepdims=True, however matrix now raises an error in this case, but",
"# the reason that it drops the keepdims kwarg is to force keepdims=True",
"# so this used to work by serendipity.",
"cnt",
"=",
"np",
".",
"sum",
"(",
"~",
"mask",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"np",
".",
"intp",
",",
"keepdims",
"=",
"_keepdims",
")",
"avg",
"=",
"np",
".",
"sum",
"(",
"arr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"keepdims",
"=",
"_keepdims",
")",
"avg",
"=",
"_divide_by_count",
"(",
"avg",
",",
"cnt",
")",
"# Compute squared deviation from mean.",
"np",
".",
"subtract",
"(",
"arr",
",",
"avg",
",",
"out",
"=",
"arr",
",",
"casting",
"=",
"'unsafe'",
")",
"arr",
"=",
"_copyto",
"(",
"arr",
",",
"0",
",",
"mask",
")",
"if",
"issubclass",
"(",
"arr",
".",
"dtype",
".",
"type",
",",
"np",
".",
"complexfloating",
")",
":",
"sqr",
"=",
"np",
".",
"multiply",
"(",
"arr",
",",
"arr",
".",
"conj",
"(",
")",
",",
"out",
"=",
"arr",
")",
".",
"real",
"else",
":",
"sqr",
"=",
"np",
".",
"multiply",
"(",
"arr",
",",
"arr",
",",
"out",
"=",
"arr",
")",
"# Compute variance.",
"var",
"=",
"np",
".",
"sum",
"(",
"sqr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
",",
"keepdims",
"=",
"keepdims",
")",
"if",
"var",
".",
"ndim",
"<",
"cnt",
".",
"ndim",
":",
"# Subclasses of ndarray may ignore keepdims, so check here.",
"cnt",
"=",
"cnt",
".",
"squeeze",
"(",
"axis",
")",
"dof",
"=",
"cnt",
"-",
"ddof",
"var",
"=",
"_divide_by_count",
"(",
"var",
",",
"dof",
")",
"isbad",
"=",
"(",
"dof",
"<=",
"0",
")",
"if",
"np",
".",
"any",
"(",
"isbad",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Degrees of freedom <= 0 for slice.\"",
",",
"RuntimeWarning",
",",
"stacklevel",
"=",
"2",
")",
"# NaN, inf, or negative numbers are all possible bad",
"# values, so explicitly replace them with NaN.",
"var",
"=",
"_copyto",
"(",
"var",
",",
"np",
".",
"nan",
",",
"isbad",
")",
"return",
"var"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/nanfunctions.py#L1386-L1524 | |
bcrusco/Forward-Plus-Renderer | 1f130f1ae58882f651d94695823044f9833cfa30 | Forward-Plus/Forward-Plus/external/assimp-3.1.1/port/PyAssimp/pyassimp/helper.py | python | hasattr_silent | (object, name) | Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2)
functionality of silently catching exceptions.
Returns the result of hasatter() or False if an exception was raised. | Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2)
functionality of silently catching exceptions.
Returns the result of hasatter() or False if an exception was raised. | [
"Calls",
"hasttr",
"()",
"with",
"the",
"given",
"parameters",
"and",
"preserves",
"the",
"legacy",
"(",
"pre",
"-",
"Python",
"3",
".",
"2",
")",
"functionality",
"of",
"silently",
"catching",
"exceptions",
".",
"Returns",
"the",
"result",
"of",
"hasatter",
"()",
"or",
"False",
"if",
"an",
"exception",
"was",
"raised",
"."
] | def hasattr_silent(object, name):
"""
Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2)
functionality of silently catching exceptions.
Returns the result of hasatter() or False if an exception was raised.
"""
try:
return hasattr(object, name)
except:
return False | [
"def",
"hasattr_silent",
"(",
"object",
",",
"name",
")",
":",
"try",
":",
"return",
"hasattr",
"(",
"object",
",",
"name",
")",
"except",
":",
"return",
"False"
] | https://github.com/bcrusco/Forward-Plus-Renderer/blob/1f130f1ae58882f651d94695823044f9833cfa30/Forward-Plus/Forward-Plus/external/assimp-3.1.1/port/PyAssimp/pyassimp/helper.py#L163-L174 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py | python | IRBuilder.mul | (self, lhs, rhs, name='') | Integer multiplication:
name = lhs * rhs | Integer multiplication:
name = lhs * rhs | [
"Integer",
"multiplication",
":",
"name",
"=",
"lhs",
"*",
"rhs"
] | def mul(self, lhs, rhs, name=''):
"""
Integer multiplication:
name = lhs * rhs
""" | [
"def",
"mul",
"(",
"self",
",",
"lhs",
",",
"rhs",
",",
"name",
"=",
"''",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py#L388-L392 | ||
facebook/fbthrift | fb9c8562aba04c4fd9b17716eb5d970cc88a75bb | build/fbcode_builder/shell_quoting.py | python | ShellQuoted.format | (self, **kwargs) | return ShellQuoted(
self.do_not_use_raw_str.format(
**dict(
(k, shell_quote(v).do_not_use_raw_str) for k, v in kwargs.items()
)
)
) | Use instead of str.format() when the arguments are either
`ShellQuoted()` or raw strings needing to be `shell_quote()`d.
Positional args are deliberately not supported since they are more
error-prone. | [] | def format(self, **kwargs):
"""
Use instead of str.format() when the arguments are either
`ShellQuoted()` or raw strings needing to be `shell_quote()`d.
Positional args are deliberately not supported since they are more
error-prone.
"""
return ShellQuoted(
self.do_not_use_raw_str.format(
**dict(
(k, shell_quote(v).do_not_use_raw_str) for k, v in kwargs.items()
)
)
) | [
"def",
"format",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"ShellQuoted",
"(",
"self",
".",
"do_not_use_raw_str",
".",
"format",
"(",
"*",
"*",
"dict",
"(",
"(",
"k",
",",
"shell_quote",
"(",
"v",
")",
".",
"do_not_use_raw_str",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
")",
")",
")"
] | https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/shell_quoting.py#L49-L65 | ||
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/bindings/python/llvm/object.py | python | Symbol.name | (self) | return lib.LLVMGetSymbolName(self) | The str name of the symbol.
This is often a function or variable name. Keep in mind that name
mangling could be in effect. | The str name of the symbol. | [
"The",
"str",
"name",
"of",
"the",
"symbol",
"."
] | def name(self):
"""The str name of the symbol.
This is often a function or variable name. Keep in mind that name
mangling could be in effect.
"""
if self.expired:
raise Exception('Symbol instance has expired.')
return lib.LLVMGetSymbolName(self) | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Symbol instance has expired.'",
")",
"return",
"lib",
".",
"LLVMGetSymbolName",
"(",
"self",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/bindings/python/llvm/object.py#L302-L311 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/sunlink.py | python | generate | (env) | Add Builders and construction variables for Forte to an Environment. | Add Builders and construction variables for Forte to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Forte",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for Forte to an Environment."""
link.generate(env)
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -G')
env['RPATHPREFIX'] = '-R'
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}'
# Support for versioned libraries
link._setup_versioned_lib_variables(env, tool = 'sunlink', use_soname = True)
env['LINKCALLBACKS'] = link._versioned_lib_callbacks() | [
"def",
"generate",
"(",
"env",
")",
":",
"link",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'SHLINKFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$LINKFLAGS -G'",
")",
"env",
"[",
"'RPATHPREFIX'",
"]",
"=",
"'-R'",
"env",
"[",
"'RPATHSUFFIX'",
"]",
"=",
"''",
"env",
"[",
"'_RPATH'",
"]",
"=",
"'${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}'",
"# Support for versioned libraries",
"link",
".",
"_setup_versioned_lib_variables",
"(",
"env",
",",
"tool",
"=",
"'sunlink'",
",",
"use_soname",
"=",
"True",
")",
"env",
"[",
"'LINKCALLBACKS'",
"]",
"=",
"link",
".",
"_versioned_lib_callbacks",
"(",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/sunlink.py#L59-L71 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/instrument.py | python | Instrument.position_currency | (self, position_currency) | Sets the position_currency of this Instrument.
:param position_currency: The position_currency of this Instrument. # noqa: E501
:type: str | Sets the position_currency of this Instrument. | [
"Sets",
"the",
"position_currency",
"of",
"this",
"Instrument",
"."
] | def position_currency(self, position_currency):
"""Sets the position_currency of this Instrument.
:param position_currency: The position_currency of this Instrument. # noqa: E501
:type: str
"""
self._position_currency = position_currency | [
"def",
"position_currency",
"(",
"self",
",",
"position_currency",
")",
":",
"self",
".",
"_position_currency",
"=",
"position_currency"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L908-L916 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/models/image/mnist/convolutional.py | python | data_type | () | Return the type of the activations, weights, and placeholder variables. | Return the type of the activations, weights, and placeholder variables. | [
"Return",
"the",
"type",
"of",
"the",
"activations",
"weights",
"and",
"placeholder",
"variables",
"."
] | def data_type():
"""Return the type of the activations, weights, and placeholder variables."""
if FLAGS.use_fp16:
return tf.float16
else:
return tf.float32 | [
"def",
"data_type",
"(",
")",
":",
"if",
"FLAGS",
".",
"use_fp16",
":",
"return",
"tf",
".",
"float16",
"else",
":",
"return",
"tf",
".",
"float32"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/models/image/mnist/convolutional.py#L54-L59 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/reshape.py | python | merge_sorted | (
objs,
keys=None,
by_index=False,
ignore_index=False,
ascending=True,
na_position="last",
) | return result | Merge a list of sorted DataFrame or Series objects.
Dataframes/Series in objs list MUST be pre-sorted by columns
listed in `keys`, or by the index (if `by_index=True`).
Parameters
----------
objs : list of DataFrame, Series, or Index
keys : list, default None
List of Column names to sort by. If None, all columns used
(Ignored if `index=True`)
by_index : bool, default False
Use index for sorting. `keys` input will be ignored if True
ignore_index : bool, default False
Drop and ignore index during merge. Default range index will
be used in the output dataframe.
ascending : bool, default True
Sorting is in ascending order, otherwise it is descending
na_position : {‘first’, ‘last’}, default ‘last’
'first' nulls at the beginning, 'last' nulls at the end
Returns
-------
A new, lexicographically sorted, DataFrame/Series. | Merge a list of sorted DataFrame or Series objects. | [
"Merge",
"a",
"list",
"of",
"sorted",
"DataFrame",
"or",
"Series",
"objects",
"."
] | def merge_sorted(
objs,
keys=None,
by_index=False,
ignore_index=False,
ascending=True,
na_position="last",
):
"""Merge a list of sorted DataFrame or Series objects.
Dataframes/Series in objs list MUST be pre-sorted by columns
listed in `keys`, or by the index (if `by_index=True`).
Parameters
----------
objs : list of DataFrame, Series, or Index
keys : list, default None
List of Column names to sort by. If None, all columns used
(Ignored if `index=True`)
by_index : bool, default False
Use index for sorting. `keys` input will be ignored if True
ignore_index : bool, default False
Drop and ignore index during merge. Default range index will
be used in the output dataframe.
ascending : bool, default True
Sorting is in ascending order, otherwise it is descending
na_position : {‘first’, ‘last’}, default ‘last’
'first' nulls at the beginning, 'last' nulls at the end
Returns
-------
A new, lexicographically sorted, DataFrame/Series.
"""
if not pd.api.types.is_list_like(objs):
raise TypeError("objs must be a list-like of Frame-like objects")
if len(objs) < 1:
raise ValueError("objs must be non-empty")
if not all(isinstance(table, cudf.core.frame.Frame) for table in objs):
raise TypeError("Elements of objs must be Frame-like")
if len(objs) == 1:
return objs[0]
if by_index and ignore_index:
raise ValueError("`by_index` and `ignore_index` cannot both be True")
result = objs[0].__class__._from_data(
*cudf._lib.merge.merge_sorted(
objs,
keys=keys,
by_index=by_index,
ignore_index=ignore_index,
ascending=ascending,
na_position=na_position,
)
)
result._copy_type_metadata(objs[0])
return result | [
"def",
"merge_sorted",
"(",
"objs",
",",
"keys",
"=",
"None",
",",
"by_index",
"=",
"False",
",",
"ignore_index",
"=",
"False",
",",
"ascending",
"=",
"True",
",",
"na_position",
"=",
"\"last\"",
",",
")",
":",
"if",
"not",
"pd",
".",
"api",
".",
"types",
".",
"is_list_like",
"(",
"objs",
")",
":",
"raise",
"TypeError",
"(",
"\"objs must be a list-like of Frame-like objects\"",
")",
"if",
"len",
"(",
"objs",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"objs must be non-empty\"",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"table",
",",
"cudf",
".",
"core",
".",
"frame",
".",
"Frame",
")",
"for",
"table",
"in",
"objs",
")",
":",
"raise",
"TypeError",
"(",
"\"Elements of objs must be Frame-like\"",
")",
"if",
"len",
"(",
"objs",
")",
"==",
"1",
":",
"return",
"objs",
"[",
"0",
"]",
"if",
"by_index",
"and",
"ignore_index",
":",
"raise",
"ValueError",
"(",
"\"`by_index` and `ignore_index` cannot both be True\"",
")",
"result",
"=",
"objs",
"[",
"0",
"]",
".",
"__class__",
".",
"_from_data",
"(",
"*",
"cudf",
".",
"_lib",
".",
"merge",
".",
"merge_sorted",
"(",
"objs",
",",
"keys",
"=",
"keys",
",",
"by_index",
"=",
"by_index",
",",
"ignore_index",
"=",
"ignore_index",
",",
"ascending",
"=",
"ascending",
",",
"na_position",
"=",
"na_position",
",",
")",
")",
"result",
".",
"_copy_type_metadata",
"(",
"objs",
"[",
"0",
"]",
")",
"return",
"result"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/reshape.py#L755-L815 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterface.py | python | RobotInterfaceBase.sensorUpdateTime | (self, name: str) | Returns the clock time of the last sensor update. | Returns the clock time of the last sensor update. | [
"Returns",
"the",
"clock",
"time",
"of",
"the",
"last",
"sensor",
"update",
"."
] | def sensorUpdateTime(self, name: str) -> float:
"""Returns the clock time of the last sensor update."""
raise NotImplementedError() | [
"def",
"sensorUpdateTime",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"float",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L413-L415 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | RobotModelLink.isRevolute | (self) | return _robotsim.RobotModelLink_isRevolute(self) | isRevolute(RobotModelLink self) -> bool
Returns whether the joint is revolute. | isRevolute(RobotModelLink self) -> bool | [
"isRevolute",
"(",
"RobotModelLink",
"self",
")",
"-",
">",
"bool"
] | def isRevolute(self):
"""
isRevolute(RobotModelLink self) -> bool
Returns whether the joint is revolute.
"""
return _robotsim.RobotModelLink_isRevolute(self) | [
"def",
"isRevolute",
"(",
"self",
")",
":",
"return",
"_robotsim",
".",
"RobotModelLink_isRevolute",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L3887-L3896 | |
polyworld/polyworld | eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26 | scripts/agent/plot/movie.py | python | compress_clusters | (clusters, min_size=700) | return new_clusters | Takes a set of clusters and collapses all clusters below min_size members
into a single miscellaneous cluster. Returns the new list of clusters. | Takes a set of clusters and collapses all clusters below min_size members
into a single miscellaneous cluster. Returns the new list of clusters. | [
"Takes",
"a",
"set",
"of",
"clusters",
"and",
"collapses",
"all",
"clusters",
"below",
"min_size",
"members",
"into",
"a",
"single",
"miscellaneous",
"cluster",
".",
"Returns",
"the",
"new",
"list",
"of",
"clusters",
"."
] | def compress_clusters(clusters, min_size=700):
"""
Takes a set of clusters and collapses all clusters below min_size members
into a single miscellaneous cluster. Returns the new list of clusters.
"""
# initialize new cluster list and misc cluster
new_clusters = []
misc_cluster = []
# append cluster to new cluster if over threshold, otherwise extend misc
for cluster in clusters:
if len(cluster) >= min_size:
new_clusters.append(cluster)
else:
misc_cluster.extend(cluster)
# add misc cluster to list of clusters
new_clusters.append(misc_cluster)
return new_clusters | [
"def",
"compress_clusters",
"(",
"clusters",
",",
"min_size",
"=",
"700",
")",
":",
"# initialize new cluster list and misc cluster",
"new_clusters",
"=",
"[",
"]",
"misc_cluster",
"=",
"[",
"]",
"# append cluster to new cluster if over threshold, otherwise extend misc",
"for",
"cluster",
"in",
"clusters",
":",
"if",
"len",
"(",
"cluster",
")",
">=",
"min_size",
":",
"new_clusters",
".",
"append",
"(",
"cluster",
")",
"else",
":",
"misc_cluster",
".",
"extend",
"(",
"cluster",
")",
"# add misc cluster to list of clusters",
"new_clusters",
".",
"append",
"(",
"misc_cluster",
")",
"return",
"new_clusters"
] | https://github.com/polyworld/polyworld/blob/eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26/scripts/agent/plot/movie.py#L70-L89 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/eager/context.py | python | Context.in_eager_mode | (self) | return self._eager_context.mode == EAGER_MODE | Returns True if current thread is in EAGER mode. | Returns True if current thread is in EAGER mode. | [
"Returns",
"True",
"if",
"current",
"thread",
"is",
"in",
"EAGER",
"mode",
"."
] | def in_eager_mode(self):
"""Returns True if current thread is in EAGER mode."""
return self._eager_context.mode == EAGER_MODE | [
"def",
"in_eager_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_eager_context",
".",
"mode",
"==",
"EAGER_MODE"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/context.py#L195-L197 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | docs/doxygen/doxygenxml.py | python | DocumentationSet.load_details | (self) | Load detailed XML files for each compound. | Load detailed XML files for each compound. | [
"Load",
"detailed",
"XML",
"files",
"for",
"each",
"compound",
"."
] | def load_details(self):
"""Load detailed XML files for each compound."""
for compound in self._compounds.values():
compound.load_details()
if isinstance(compound, File):
self._files[compound.get_path()] = compound | [
"def",
"load_details",
"(",
"self",
")",
":",
"for",
"compound",
"in",
"self",
".",
"_compounds",
".",
"values",
"(",
")",
":",
"compound",
".",
"load_details",
"(",
")",
"if",
"isinstance",
"(",
"compound",
",",
"File",
")",
":",
"self",
".",
"_files",
"[",
"compound",
".",
"get_path",
"(",
")",
"]",
"=",
"compound"
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/doxygenxml.py#L1164-L1169 | ||
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py | python | IConversion.TextToOnlineStatus | (self, Text) | return self._TextTo('ols', Text) | Returns online status code.
@param Text: Text, one of L{Online status<enums.olsUnknown>}.
@type Text: unicode
@return: Online status.
@rtype: L{Online status<enums.olsUnknown>}
@note: Currently, this method only checks if the given string is one of the allowed ones
and returns it or raises a C{ValueError}. | Returns online status code. | [
"Returns",
"online",
"status",
"code",
"."
] | def TextToOnlineStatus(self, Text):
'''Returns online status code.
@param Text: Text, one of L{Online status<enums.olsUnknown>}.
@type Text: unicode
@return: Online status.
@rtype: L{Online status<enums.olsUnknown>}
@note: Currently, this method only checks if the given string is one of the allowed ones
and returns it or raises a C{ValueError}.
'''
return self._TextTo('ols', Text) | [
"def",
"TextToOnlineStatus",
"(",
"self",
",",
"Text",
")",
":",
"return",
"self",
".",
"_TextTo",
"(",
"'ols'",
",",
"Text",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L329-L339 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | boringssl/util/bot/go/bootstrap.py | python | check_hello_world | (toolset_root) | Compiles and runs 'hello world' program to verify that toolset works. | Compiles and runs 'hello world' program to verify that toolset works. | [
"Compiles",
"and",
"runs",
"hello",
"world",
"program",
"to",
"verify",
"that",
"toolset",
"works",
"."
] | def check_hello_world(toolset_root):
"""Compiles and runs 'hello world' program to verify that toolset works."""
with temp_dir(toolset_root) as tmp:
path = os.path.join(tmp, 'hello.go')
write_file([path], r"""
package main
func main() { println("hello, world\n") }
""")
out = subprocess.check_output(
[get_go_exe(toolset_root), 'run', path],
env=get_go_environ(toolset_root, tmp),
stderr=subprocess.STDOUT)
if out.strip() != 'hello, world':
LOGGER.error('Failed to run sample program:\n%s', out)
return False
return True | [
"def",
"check_hello_world",
"(",
"toolset_root",
")",
":",
"with",
"temp_dir",
"(",
"toolset_root",
")",
"as",
"tmp",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp",
",",
"'hello.go'",
")",
"write_file",
"(",
"[",
"path",
"]",
",",
"r\"\"\"\n package main\n func main() { println(\"hello, world\\n\") }\n \"\"\"",
")",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"get_go_exe",
"(",
"toolset_root",
")",
",",
"'run'",
",",
"path",
"]",
",",
"env",
"=",
"get_go_environ",
"(",
"toolset_root",
",",
"tmp",
")",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"if",
"out",
".",
"strip",
"(",
")",
"!=",
"'hello, world'",
":",
"LOGGER",
".",
"error",
"(",
"'Failed to run sample program:\\n%s'",
",",
"out",
")",
"return",
"False",
"return",
"True"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/boringssl/util/bot/go/bootstrap.py#L166-L181 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py | python | Dirichlet.batch_shape | (self, name="batch_shape") | Batch dimensions of this instance as a 1-D int32 `Tensor`.
The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.
Args:
name: name to give to the op
Returns:
`Tensor` `batch_shape` | Batch dimensions of this instance as a 1-D int32 `Tensor`. | [
"Batch",
"dimensions",
"of",
"this",
"instance",
"as",
"a",
"1",
"-",
"D",
"int32",
"Tensor",
"."
] | def batch_shape(self, name="batch_shape"):
"""Batch dimensions of this instance as a 1-D int32 `Tensor`.
The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.
Args:
name: name to give to the op
Returns:
`Tensor` `batch_shape`
"""
with ops.name_scope(self.name):
with ops.op_scope([self._alpha], name):
return array_ops.shape(self._alpha_0) | [
"def",
"batch_shape",
"(",
"self",
",",
"name",
"=",
"\"batch_shape\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"self",
".",
"_alpha",
"]",
",",
"name",
")",
":",
"return",
"array_ops",
".",
"shape",
"(",
"self",
".",
"_alpha_0",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py#L181-L195 | ||
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/Resources/Python/Override/Lib/multiprocessing/__init__.py | python | Pool | (processes=None, initializer=None, initargs=(), maxtasksperchild=None) | return Pool(processes, initializer, initargs, maxtasksperchild) | Returns a process pool object | Returns a process pool object | [
"Returns",
"a",
"process",
"pool",
"object"
] | def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):
'''
Returns a process pool object
'''
from multiprocessing.pool import Pool
return Pool(processes, initializer, initargs, maxtasksperchild) | [
"def",
"Pool",
"(",
"processes",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"initargs",
"=",
"(",
")",
",",
"maxtasksperchild",
"=",
"None",
")",
":",
"from",
"multiprocessing",
".",
"pool",
"import",
"Pool",
"return",
"Pool",
"(",
"processes",
",",
"initializer",
",",
"initargs",
",",
"maxtasksperchild",
")"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/Resources/Python/Override/Lib/multiprocessing/__init__.py#L227-L232 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/genericpath.py | python | samestat | (s1, s2) | return (s1.st_ino == s2.st_ino and
s1.st_dev == s2.st_dev) | Test whether two stat buffers reference the same file | Test whether two stat buffers reference the same file | [
"Test",
"whether",
"two",
"stat",
"buffers",
"reference",
"the",
"same",
"file"
] | def samestat(s1, s2):
"""Test whether two stat buffers reference the same file"""
return (s1.st_ino == s2.st_ino and
s1.st_dev == s2.st_dev) | [
"def",
"samestat",
"(",
"s1",
",",
"s2",
")",
":",
"return",
"(",
"s1",
".",
"st_ino",
"==",
"s2",
".",
"st_ino",
"and",
"s1",
".",
"st_dev",
"==",
"s2",
".",
"st_dev",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/genericpath.py#L87-L90 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/_feature_engineering/_autovectorizer.py | python | _interpretations_class.numerical__int | (self, column_name, output_column_prefix) | return self.__get_copy_transform(column_name, output_column_prefix) | Interprets an integer column as numerical. | Interprets an integer column as numerical. | [
"Interprets",
"an",
"integer",
"column",
"as",
"numerical",
"."
] | def numerical__int(self, column_name, output_column_prefix):
"""
Interprets an integer column as numerical.
"""
return self.__get_copy_transform(column_name, output_column_prefix) | [
"def",
"numerical__int",
"(",
"self",
",",
"column_name",
",",
"output_column_prefix",
")",
":",
"return",
"self",
".",
"__get_copy_transform",
"(",
"column_name",
",",
"output_column_prefix",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/_feature_engineering/_autovectorizer.py#L388-L393 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/environment.py | python | copy_cache | (cache) | return LRUCache(cache.capacity) | Create an empty copy of the given cache. | Create an empty copy of the given cache. | [
"Create",
"an",
"empty",
"copy",
"of",
"the",
"given",
"cache",
"."
] | def copy_cache(cache):
"""Create an empty copy of the given cache."""
if cache is None:
return None
elif type(cache) is dict:
return {}
return LRUCache(cache.capacity) | [
"def",
"copy_cache",
"(",
"cache",
")",
":",
"if",
"cache",
"is",
"None",
":",
"return",
"None",
"elif",
"type",
"(",
"cache",
")",
"is",
"dict",
":",
"return",
"{",
"}",
"return",
"LRUCache",
"(",
"cache",
".",
"capacity",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/environment.py#L69-L75 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | base/android/jni_generator/jni_generator.py | python | InlHeaderFileGenerator.GetLazyCalledByNativeMethodStub | (self, called_by_native) | return template.substitute(values) | Returns a string. | Returns a string. | [
"Returns",
"a",
"string",
"."
] | def GetLazyCalledByNativeMethodStub(self, called_by_native):
"""Returns a string."""
function_signature_template = Template("""\
static ${RETURN_TYPE} Java_${JAVA_CLASS}_${METHOD_ID_VAR_NAME}(\
JNIEnv* env${FIRST_PARAM_IN_DECLARATION}${PARAMS_IN_DECLARATION})""")
function_header_template = Template("""\
${FUNCTION_SIGNATURE} {""")
function_header_with_unused_template = Template("""\
${FUNCTION_SIGNATURE} __attribute__ ((unused));
${FUNCTION_SIGNATURE} {""")
template = Template("""
static base::subtle::AtomicWord g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} = 0;
${FUNCTION_HEADER}
CHECK_CLAZZ(env, ${FIRST_PARAM_IN_CALL},
${JAVA_CLASS}_clazz(env)${OPTIONAL_ERROR_RETURN});
jmethodID method_id =
${GET_METHOD_ID_IMPL}
${RETURN_DECLARATION}
${PRE_CALL}env->${ENV_CALL}(${FIRST_PARAM_IN_CALL},
method_id${PARAMS_IN_CALL})${POST_CALL};
${CHECK_EXCEPTION}
${RETURN_CLAUSE}
}""")
values = self.GetCalledByNativeValues(called_by_native)
values['FUNCTION_SIGNATURE'] = (
function_signature_template.substitute(values))
if called_by_native.system_class:
values['FUNCTION_HEADER'] = (
function_header_with_unused_template.substitute(values))
else:
values['FUNCTION_HEADER'] = function_header_template.substitute(values)
return template.substitute(values) | [
"def",
"GetLazyCalledByNativeMethodStub",
"(",
"self",
",",
"called_by_native",
")",
":",
"function_signature_template",
"=",
"Template",
"(",
"\"\"\"\\\nstatic ${RETURN_TYPE} Java_${JAVA_CLASS}_${METHOD_ID_VAR_NAME}(\\\nJNIEnv* env${FIRST_PARAM_IN_DECLARATION}${PARAMS_IN_DECLARATION})\"\"\"",
")",
"function_header_template",
"=",
"Template",
"(",
"\"\"\"\\\n${FUNCTION_SIGNATURE} {\"\"\"",
")",
"function_header_with_unused_template",
"=",
"Template",
"(",
"\"\"\"\\\n${FUNCTION_SIGNATURE} __attribute__ ((unused));\n${FUNCTION_SIGNATURE} {\"\"\"",
")",
"template",
"=",
"Template",
"(",
"\"\"\"\nstatic base::subtle::AtomicWord g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} = 0;\n${FUNCTION_HEADER}\n CHECK_CLAZZ(env, ${FIRST_PARAM_IN_CALL},\n ${JAVA_CLASS}_clazz(env)${OPTIONAL_ERROR_RETURN});\n jmethodID method_id =\n ${GET_METHOD_ID_IMPL}\n ${RETURN_DECLARATION}\n ${PRE_CALL}env->${ENV_CALL}(${FIRST_PARAM_IN_CALL},\n method_id${PARAMS_IN_CALL})${POST_CALL};\n ${CHECK_EXCEPTION}\n ${RETURN_CLAUSE}\n}\"\"\"",
")",
"values",
"=",
"self",
".",
"GetCalledByNativeValues",
"(",
"called_by_native",
")",
"values",
"[",
"'FUNCTION_SIGNATURE'",
"]",
"=",
"(",
"function_signature_template",
".",
"substitute",
"(",
"values",
")",
")",
"if",
"called_by_native",
".",
"system_class",
":",
"values",
"[",
"'FUNCTION_HEADER'",
"]",
"=",
"(",
"function_header_with_unused_template",
".",
"substitute",
"(",
"values",
")",
")",
"else",
":",
"values",
"[",
"'FUNCTION_HEADER'",
"]",
"=",
"function_header_template",
".",
"substitute",
"(",
"values",
")",
"return",
"template",
".",
"substitute",
"(",
"values",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/base/android/jni_generator/jni_generator.py#L1108-L1139 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TreeCtrl.Create | (*args, **kwargs) | return _controls_.TreeCtrl_Create(*args, **kwargs) | Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> bool
Do the 2nd phase and create the GUI control. | Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"TR_DEFAULT_STYLE",
"Validator",
"validator",
"=",
"DefaultValidator",
"String",
"name",
"=",
"TreeCtrlNameStr",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=TR_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=TreeCtrlNameStr) -> bool
Do the 2nd phase and create the GUI control.
"""
return _controls_.TreeCtrl_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5194-L5203 | |
trailofbits/sienna-locomotive | 09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0 | sl2/harness/config.py | python | update_config_from_args | () | Supplements the global configuration with command-line arguments
passed by the user. | Supplements the global configuration with command-line arguments
passed by the user. | [
"Supplements",
"the",
"global",
"configuration",
"with",
"command",
"-",
"line",
"arguments",
"passed",
"by",
"the",
"user",
"."
] | def update_config_from_args():
"""
Supplements the global configuration with command-line arguments
passed by the user.
"""
global config
# Convert numeric arguments into ints.
for opt in INT_KEYS:
if opt in config:
config[opt] = int(config[opt])
# Convert command line strings into lists
for opt in ARGS_KEYS:
config[opt] = [] if (len(config[opt]) == 0) else winshlex.split(config[opt])
if args.target_application_path is not None and len(config["target_args"]) > 0:
config["target_args"] = []
if args.verbose:
config["drrun_args"].append("-verbose")
if args.debug:
print("WARNING: debug mode may destabilize the binary instrumentation!")
config["drrun_args"].append("-debug")
if not args.nopersist:
config["drrun_args"].append("-persist")
if args.registry:
config["client_args"].append("-registry")
# Replace any values in the config dict with the optional value from the argument.
# Note that if you set a default value for an arg, this will overwrite its value in the config
# file even if the argument is not explicitly set by the user, so make sure you use keys that aren't
# in the config file for any arguments that have default values.
for arg in vars(args):
if getattr(args, arg) is not None:
config[arg] = getattr(args, arg)
for key in PATH_KEYS:
root, extension = os.path.splitdrive(config[key])
if len(root) > 0 and ":" not in root: # UNC Path
print("WARNING: Replacing UNC Path", config[key], "with", extension)
config[key] = extension | [
"def",
"update_config_from_args",
"(",
")",
":",
"global",
"config",
"# Convert numeric arguments into ints.",
"for",
"opt",
"in",
"INT_KEYS",
":",
"if",
"opt",
"in",
"config",
":",
"config",
"[",
"opt",
"]",
"=",
"int",
"(",
"config",
"[",
"opt",
"]",
")",
"# Convert command line strings into lists",
"for",
"opt",
"in",
"ARGS_KEYS",
":",
"config",
"[",
"opt",
"]",
"=",
"[",
"]",
"if",
"(",
"len",
"(",
"config",
"[",
"opt",
"]",
")",
"==",
"0",
")",
"else",
"winshlex",
".",
"split",
"(",
"config",
"[",
"opt",
"]",
")",
"if",
"args",
".",
"target_application_path",
"is",
"not",
"None",
"and",
"len",
"(",
"config",
"[",
"\"target_args\"",
"]",
")",
">",
"0",
":",
"config",
"[",
"\"target_args\"",
"]",
"=",
"[",
"]",
"if",
"args",
".",
"verbose",
":",
"config",
"[",
"\"drrun_args\"",
"]",
".",
"append",
"(",
"\"-verbose\"",
")",
"if",
"args",
".",
"debug",
":",
"print",
"(",
"\"WARNING: debug mode may destabilize the binary instrumentation!\"",
")",
"config",
"[",
"\"drrun_args\"",
"]",
".",
"append",
"(",
"\"-debug\"",
")",
"if",
"not",
"args",
".",
"nopersist",
":",
"config",
"[",
"\"drrun_args\"",
"]",
".",
"append",
"(",
"\"-persist\"",
")",
"if",
"args",
".",
"registry",
":",
"config",
"[",
"\"client_args\"",
"]",
".",
"append",
"(",
"\"-registry\"",
")",
"# Replace any values in the config dict with the optional value from the argument.",
"# Note that if you set a default value for an arg, this will overwrite its value in the config",
"# file even if the argument is not explicitly set by the user, so make sure you use keys that aren't",
"# in the config file for any arguments that have default values.",
"for",
"arg",
"in",
"vars",
"(",
"args",
")",
":",
"if",
"getattr",
"(",
"args",
",",
"arg",
")",
"is",
"not",
"None",
":",
"config",
"[",
"arg",
"]",
"=",
"getattr",
"(",
"args",
",",
"arg",
")",
"for",
"key",
"in",
"PATH_KEYS",
":",
"root",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"config",
"[",
"key",
"]",
")",
"if",
"len",
"(",
"root",
")",
">",
"0",
"and",
"\":\"",
"not",
"in",
"root",
":",
"# UNC Path",
"print",
"(",
"\"WARNING: Replacing UNC Path\"",
",",
"config",
"[",
"key",
"]",
",",
"\"with\"",
",",
"extension",
")",
"config",
"[",
"key",
"]",
"=",
"extension"
] | https://github.com/trailofbits/sienna-locomotive/blob/09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0/sl2/harness/config.py#L325-L368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.