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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/oinspect.py | python | Inspector.info | (self, obj, oname='', formatter=None, info=None, detail_level=0) | return self._info(obj, oname=oname, info=info, detail_level=detail_level) | DEPRECATED. Compute a dict with detailed information about an object. | DEPRECATED. Compute a dict with detailed information about an object. | [
"DEPRECATED",
".",
"Compute",
"a",
"dict",
"with",
"detailed",
"information",
"about",
"an",
"object",
"."
] | def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
"""DEPRECATED. Compute a dict with detailed information about an object.
"""
if formatter is not None:
warnings.warn('The `formatter` keyword argument to `Inspector.info`'
'is deprecated as of IPython 5.0 and will have no effects.',
DeprecationWarning, stacklevel=2)
return self._info(obj, oname=oname, info=info, detail_level=detail_level) | [
"def",
"info",
"(",
"self",
",",
"obj",
",",
"oname",
"=",
"''",
",",
"formatter",
"=",
"None",
",",
"info",
"=",
"None",
",",
"detail_level",
"=",
"0",
")",
":",
"if",
"formatter",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'The `formatter` keyword argument to `Inspector.info`'",
"'is deprecated as of IPython 5.0 and will have no effects.'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".",
"_info",
"(",
"obj",
",",
"oname",
"=",
"oname",
",",
"info",
"=",
"info",
",",
"detail_level",
"=",
"detail_level",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/oinspect.py#L724-L731 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/SimpleXMLRPCServer.py | python | SimpleXMLRPCDispatcher.system_methodHelp | (self, method_name) | system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method. | system.methodHelp('add') => "Adds two integers together" | [
"system",
".",
"methodHelp",
"(",
"add",
")",
"=",
">",
"Adds",
"two",
"integers",
"together"
] | def system_methodHelp(self, method_name):
"""system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method."""
method = None
if method_name in self.funcs:
method = self.funcs[method_name]
elif self.instance is not None:
# Instance can implement _methodHelp to return help for a method
if hasattr(self.instance, '_methodHelp'):
return self.instance._methodHelp(method_name)
# if the instance has a _dispatch method then we
# don't have enough information to provide help
elif not hasattr(self.instance, '_dispatch'):
try:
method = resolve_dotted_attribute(
self.instance,
method_name,
self.allow_dotted_names
)
except AttributeError:
pass
# Note that we aren't checking that the method actually
# be a callable object of some kind
if method is None:
return ""
else:
import pydoc
return pydoc.getdoc(method) | [
"def",
"system_methodHelp",
"(",
"self",
",",
"method_name",
")",
":",
"method",
"=",
"None",
"if",
"method_name",
"in",
"self",
".",
"funcs",
":",
"method",
"=",
"self",
".",
"funcs",
"[",
"method_name",
"]",
"elif",
"self",
".",
"instance",
"is",
"not",
"None",
":",
"# Instance can implement _methodHelp to return help for a method",
"if",
"hasattr",
"(",
"self",
".",
"instance",
",",
"'_methodHelp'",
")",
":",
"return",
"self",
".",
"instance",
".",
"_methodHelp",
"(",
"method_name",
")",
"# if the instance has a _dispatch method then we",
"# don't have enough information to provide help",
"elif",
"not",
"hasattr",
"(",
"self",
".",
"instance",
",",
"'_dispatch'",
")",
":",
"try",
":",
"method",
"=",
"resolve_dotted_attribute",
"(",
"self",
".",
"instance",
",",
"method_name",
",",
"self",
".",
"allow_dotted_names",
")",
"except",
"AttributeError",
":",
"pass",
"# Note that we aren't checking that the method actually",
"# be a callable object of some kind",
"if",
"method",
"is",
"None",
":",
"return",
"\"\"",
"else",
":",
"import",
"pydoc",
"return",
"pydoc",
".",
"getdoc",
"(",
"method",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/SimpleXMLRPCServer.py#L314-L344 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | RobotModel.link | (self, *args) | return _robotsim.RobotModel_link(self, *args) | r"""
Returns a reference to the link by index or name.
link (index): :class:`~klampt.RobotModelLink`
link (name): :class:`~klampt.RobotModelLink`
Args:
index (int, optional):
name (str, optional):
Returns:
:class:`~klampt.RobotModelLink`: | r"""
Returns a reference to the link by index or name. | [
"r",
"Returns",
"a",
"reference",
"to",
"the",
"link",
"by",
"index",
"or",
"name",
"."
] | def link(self, *args) -> "RobotModelLink":
r"""
Returns a reference to the link by index or name.
link (index): :class:`~klampt.RobotModelLink`
link (name): :class:`~klampt.RobotModelLink`
Args:
index (int, optional):
name (str, optional):
Returns:
:class:`~klampt.RobotModelLink`:
"""
return _robotsim.RobotModel_link(self, *args) | [
"def",
"link",
"(",
"self",
",",
"*",
"args",
")",
"->",
"\"RobotModelLink\"",
":",
"return",
"_robotsim",
".",
"RobotModel_link",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L4670-L4686 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/util/struct.py | python | Flags.unknown | (self, unknownflags) | Default handler for any unknown bits. Overload if needed. | Default handler for any unknown bits. Overload if needed. | [
"Default",
"handler",
"for",
"any",
"unknown",
"bits",
".",
"Overload",
"if",
"needed",
"."
] | def unknown(self, unknownflags):
"""
Default handler for any unknown bits. Overload if needed.
"""
raise ValueError(
"unknown flag values: " + bin(unknownflags) + " "
"in addition to existing flags: " + str(self.as_dict())) | [
"def",
"unknown",
"(",
"self",
",",
"unknownflags",
")",
":",
"raise",
"ValueError",
"(",
"\"unknown flag values: \"",
"+",
"bin",
"(",
"unknownflags",
")",
"+",
"\" \"",
"\"in addition to existing flags: \"",
"+",
"str",
"(",
"self",
".",
"as_dict",
"(",
")",
")",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/struct.py#L286-L292 | ||
googlevr/seurat | 7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53 | seurat/generation/maya/seurat_rig.py | python | RotateCamera | (camera_name, face_name) | Rotates a Maya camera node to look at a given cube map face.
Args:
camera_name: Name of the Maya camera's transform node.
face_name: Name of the cube map face.
Raises:
ValueError: face is not a valid cube map face name. | Rotates a Maya camera node to look at a given cube map face. | [
"Rotates",
"a",
"Maya",
"camera",
"node",
"to",
"look",
"at",
"a",
"given",
"cube",
"map",
"face",
"."
] | def RotateCamera(camera_name, face_name):
"""Rotates a Maya camera node to look at a given cube map face.
Args:
camera_name: Name of the Maya camera's transform node.
face_name: Name of the cube map face.
Raises:
ValueError: face is not a valid cube map face name.
"""
# Disable the undefined-variable lint error, because the Maya package is not
# defined in the environment where the linter runs.
#
# pylint: disable=undefined-variable
if face_name is 'front':
pass
elif face_name is 'back':
maya.cmds.setAttr(camera_name + '.rotateY', 180)
elif face_name is 'left':
maya.cmds.setAttr(camera_name + '.rotateY', 90)
elif face_name is 'right':
maya.cmds.setAttr(camera_name + '.rotateY', -90)
elif face_name is 'bottom':
maya.cmds.setAttr(camera_name + '.rotateX', -90)
elif face_name is 'top':
maya.cmds.setAttr(camera_name + '.rotateX', 90)
else:
raise ValueError('Invalid face_name') | [
"def",
"RotateCamera",
"(",
"camera_name",
",",
"face_name",
")",
":",
"# Disable the undefined-variable lint error, because the Maya package is not",
"# defined in the environment where the linter runs.",
"#",
"# pylint: disable=undefined-variable",
"if",
"face_name",
"is",
"'front'",
":",
"pass",
"elif",
"face_name",
"is",
"'back'",
":",
"maya",
".",
"cmds",
".",
"setAttr",
"(",
"camera_name",
"+",
"'.rotateY'",
",",
"180",
")",
"elif",
"face_name",
"is",
"'left'",
":",
"maya",
".",
"cmds",
".",
"setAttr",
"(",
"camera_name",
"+",
"'.rotateY'",
",",
"90",
")",
"elif",
"face_name",
"is",
"'right'",
":",
"maya",
".",
"cmds",
".",
"setAttr",
"(",
"camera_name",
"+",
"'.rotateY'",
",",
"-",
"90",
")",
"elif",
"face_name",
"is",
"'bottom'",
":",
"maya",
".",
"cmds",
".",
"setAttr",
"(",
"camera_name",
"+",
"'.rotateX'",
",",
"-",
"90",
")",
"elif",
"face_name",
"is",
"'top'",
":",
"maya",
".",
"cmds",
".",
"setAttr",
"(",
"camera_name",
"+",
"'.rotateX'",
",",
"90",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid face_name'",
")"
] | https://github.com/googlevr/seurat/blob/7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53/seurat/generation/maya/seurat_rig.py#L205-L232 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/dataview.py | python | DataViewRenderer.EnableEllipsize | (*args, **kwargs) | return _dataview.DataViewRenderer_EnableEllipsize(*args, **kwargs) | EnableEllipsize(self, int mode=ELLIPSIZE_MIDDLE) | EnableEllipsize(self, int mode=ELLIPSIZE_MIDDLE) | [
"EnableEllipsize",
"(",
"self",
"int",
"mode",
"=",
"ELLIPSIZE_MIDDLE",
")"
] | def EnableEllipsize(*args, **kwargs):
"""EnableEllipsize(self, int mode=ELLIPSIZE_MIDDLE)"""
return _dataview.DataViewRenderer_EnableEllipsize(*args, **kwargs) | [
"def",
"EnableEllipsize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_EnableEllipsize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L1197-L1199 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/functional.py | python | _unique_consecutive_impl | (input: Tensor, return_inverse: bool = False,
return_counts: bool = False,
dim: Optional[int] = None) | return output, inverse_indices, counts | r"""Eliminates all but the first element from every consecutive group of equivalent elements.
.. note:: This function is different from :func:`torch.unique` in the sense that this function
only eliminates consecutive duplicate values. This semantics is similar to `std::unique`
in C++.
Args:
input (Tensor): the input tensor
return_inverse (bool): Whether to also return the indices for where
elements in the original input ended up in the returned unique list.
return_counts (bool): Whether to also return the counts for each unique
element.
dim (int): the dimension to apply unique. If ``None``, the unique of the
flattened input is returned. default: ``None``
Returns:
(Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing
- **output** (*Tensor*): the output list of unique scalar elements.
- **inverse_indices** (*Tensor*): (optional) if
:attr:`return_inverse` is True, there will be an additional
returned tensor (same shape as input) representing the indices
for where elements in the original input map to in the output;
otherwise, this function will only return a single tensor.
- **counts** (*Tensor*): (optional) if
:attr:`return_counts` is True, there will be an additional
returned tensor (same shape as output or output.size(dim),
if dim was specified) representing the number of occurrences
for each unique value or tensor.
Example::
>>> x = torch.tensor([1, 1, 2, 2, 3, 1, 1, 2])
>>> output = torch.unique_consecutive(x)
>>> output
tensor([1, 2, 3, 1, 2])
>>> output, inverse_indices = torch.unique_consecutive(x, return_inverse=True)
>>> output
tensor([1, 2, 3, 1, 2])
>>> inverse_indices
tensor([0, 0, 1, 1, 2, 3, 3, 4])
>>> output, counts = torch.unique_consecutive(x, return_counts=True)
>>> output
tensor([1, 2, 3, 1, 2])
>>> counts
tensor([2, 2, 1, 2, 1]) | r"""Eliminates all but the first element from every consecutive group of equivalent elements. | [
"r",
"Eliminates",
"all",
"but",
"the",
"first",
"element",
"from",
"every",
"consecutive",
"group",
"of",
"equivalent",
"elements",
"."
] | def _unique_consecutive_impl(input: Tensor, return_inverse: bool = False,
return_counts: bool = False,
dim: Optional[int] = None) -> _unique_impl_out:
r"""Eliminates all but the first element from every consecutive group of equivalent elements.
.. note:: This function is different from :func:`torch.unique` in the sense that this function
only eliminates consecutive duplicate values. This semantics is similar to `std::unique`
in C++.
Args:
input (Tensor): the input tensor
return_inverse (bool): Whether to also return the indices for where
elements in the original input ended up in the returned unique list.
return_counts (bool): Whether to also return the counts for each unique
element.
dim (int): the dimension to apply unique. If ``None``, the unique of the
flattened input is returned. default: ``None``
Returns:
(Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing
- **output** (*Tensor*): the output list of unique scalar elements.
- **inverse_indices** (*Tensor*): (optional) if
:attr:`return_inverse` is True, there will be an additional
returned tensor (same shape as input) representing the indices
for where elements in the original input map to in the output;
otherwise, this function will only return a single tensor.
- **counts** (*Tensor*): (optional) if
:attr:`return_counts` is True, there will be an additional
returned tensor (same shape as output or output.size(dim),
if dim was specified) representing the number of occurrences
for each unique value or tensor.
Example::
>>> x = torch.tensor([1, 1, 2, 2, 3, 1, 1, 2])
>>> output = torch.unique_consecutive(x)
>>> output
tensor([1, 2, 3, 1, 2])
>>> output, inverse_indices = torch.unique_consecutive(x, return_inverse=True)
>>> output
tensor([1, 2, 3, 1, 2])
>>> inverse_indices
tensor([0, 0, 1, 1, 2, 3, 3, 4])
>>> output, counts = torch.unique_consecutive(x, return_counts=True)
>>> output
tensor([1, 2, 3, 1, 2])
>>> counts
tensor([2, 2, 1, 2, 1])
"""
if has_torch_function_unary(input):
return handle_torch_function(
unique_consecutive, (input,), input, return_inverse=return_inverse,
return_counts=return_counts, dim=dim)
output, inverse_indices, counts = _VF.unique_consecutive( # type: ignore[attr-defined]
input, return_inverse=return_inverse, return_counts=return_counts, dim=dim)
return output, inverse_indices, counts | [
"def",
"_unique_consecutive_impl",
"(",
"input",
":",
"Tensor",
",",
"return_inverse",
":",
"bool",
"=",
"False",
",",
"return_counts",
":",
"bool",
"=",
"False",
",",
"dim",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"_unique_impl_out",
":",
"if",
"has_torch_function_unary",
"(",
"input",
")",
":",
"return",
"handle_torch_function",
"(",
"unique_consecutive",
",",
"(",
"input",
",",
")",
",",
"input",
",",
"return_inverse",
"=",
"return_inverse",
",",
"return_counts",
"=",
"return_counts",
",",
"dim",
"=",
"dim",
")",
"output",
",",
"inverse_indices",
",",
"counts",
"=",
"_VF",
".",
"unique_consecutive",
"(",
"# type: ignore[attr-defined]",
"input",
",",
"return_inverse",
"=",
"return_inverse",
",",
"return_counts",
"=",
"return_counts",
",",
"dim",
"=",
"dim",
")",
"return",
"output",
",",
"inverse_indices",
",",
"counts"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/functional.py#L869-L927 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Spinbox.selection | (self, *args) | return self._getints(
self.tk.call((self._w, 'selection') + args)) or () | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def selection(self, *args):
"""Internal function."""
return self._getints(
self.tk.call((self._w, 'selection') + args)) or () | [
"def",
"selection",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'selection'",
")",
"+",
"args",
")",
")",
"or",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L3492-L3495 | |
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/element.py | python | Element.getElementAsBool | (self, name) | return self.getElement(name).getValueAsBool() | Args:
name (Name or str): Sub-element identifier
Returns:
bool: This element's sub-element with ``name`` as a boolean
Raises:
Exception: If ``name`` is neither a :class:`Name` nor a string, or
if this :class:`Element` is neither a sequence nor a choice, or
in case it has no sub-element with the specified ``name``, or
in case the element's value can't be returned as a boolean. | Args:
name (Name or str): Sub-element identifier | [
"Args",
":",
"name",
"(",
"Name",
"or",
"str",
")",
":",
"Sub",
"-",
"element",
"identifier"
] | def getElementAsBool(self, name):
"""
Args:
name (Name or str): Sub-element identifier
Returns:
bool: This element's sub-element with ``name`` as a boolean
Raises:
Exception: If ``name`` is neither a :class:`Name` nor a string, or
if this :class:`Element` is neither a sequence nor a choice, or
in case it has no sub-element with the specified ``name``, or
in case the element's value can't be returned as a boolean.
"""
return self.getElement(name).getValueAsBool() | [
"def",
"getElementAsBool",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"getElement",
"(",
"name",
")",
".",
"getValueAsBool",
"(",
")"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/element.py#L822-L837 | |
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | stack/two_stack_in_an_array.py | python | main | () | operational function | operational function | [
"operational",
"function"
] | def main():
""" operational function """
ts = TwoStacks(5)
ts.push1(5)
ts.push2(10)
ts.push2(15)
ts.push1(11)
ts.push2(7)
print(ts.pop1())
ts.push2(40)
print(ts.pop2())
print(ts.arr) | [
"def",
"main",
"(",
")",
":",
"ts",
"=",
"TwoStacks",
"(",
"5",
")",
"ts",
".",
"push1",
"(",
"5",
")",
"ts",
".",
"push2",
"(",
"10",
")",
"ts",
".",
"push2",
"(",
"15",
")",
"ts",
".",
"push1",
"(",
"11",
")",
"ts",
".",
"push2",
"(",
"7",
")",
"print",
"(",
"ts",
".",
"pop1",
"(",
")",
")",
"ts",
".",
"push2",
"(",
"40",
")",
"print",
"(",
"ts",
".",
"pop2",
"(",
")",
")",
"print",
"(",
"ts",
".",
"arr",
")"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/stack/two_stack_in_an_array.py#L47-L59 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/InputTree.py | python | InputTree.setBlockType | (self, parent, new_type) | Changes the block type | Changes the block type | [
"Changes",
"the",
"block",
"type"
] | def setBlockType(self, parent, new_type):
"""
Changes the block type
"""
info = self.path_map.get(parent)
if info:
info.setBlockType(new_type) | [
"def",
"setBlockType",
"(",
"self",
",",
"parent",
",",
"new_type",
")",
":",
"info",
"=",
"self",
".",
"path_map",
".",
"get",
"(",
"parent",
")",
"if",
"info",
":",
"info",
".",
"setBlockType",
"(",
"new_type",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputTree.py#L274-L280 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/cpp.py | python | PreProcessor.do_include | (self, t) | Default handling of a #include line. | Default handling of a #include line. | [
"Default",
"handling",
"of",
"a",
"#include",
"line",
"."
] | def do_include(self, t):
"""
Default handling of a #include line.
"""
t = self.resolve_include(t)
include_file = self.find_include_file(t)
if include_file:
#print "include_file =", include_file
self.result.append(include_file)
contents = self.read_file(include_file)
new_tuples = [('scons_current_file', include_file)] + \
self.tupleize(contents) + \
[('scons_current_file', self.current_file)]
self.tuples[:] = new_tuples + self.tuples | [
"def",
"do_include",
"(",
"self",
",",
"t",
")",
":",
"t",
"=",
"self",
".",
"resolve_include",
"(",
"t",
")",
"include_file",
"=",
"self",
".",
"find_include_file",
"(",
"t",
")",
"if",
"include_file",
":",
"#print \"include_file =\", include_file",
"self",
".",
"result",
".",
"append",
"(",
"include_file",
")",
"contents",
"=",
"self",
".",
"read_file",
"(",
"include_file",
")",
"new_tuples",
"=",
"[",
"(",
"'scons_current_file'",
",",
"include_file",
")",
"]",
"+",
"self",
".",
"tupleize",
"(",
"contents",
")",
"+",
"[",
"(",
"'scons_current_file'",
",",
"self",
".",
"current_file",
")",
"]",
"self",
".",
"tuples",
"[",
":",
"]",
"=",
"new_tuples",
"+",
"self",
".",
"tuples"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/cpp.py#L506-L519 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetStyleAt | (*args, **kwargs) | return _stc.StyledTextCtrl_GetStyleAt(*args, **kwargs) | GetStyleAt(self, int pos) -> int
Returns the style byte at the position. | GetStyleAt(self, int pos) -> int | [
"GetStyleAt",
"(",
"self",
"int",
"pos",
")",
"-",
">",
"int"
] | def GetStyleAt(*args, **kwargs):
"""
GetStyleAt(self, int pos) -> int
Returns the style byte at the position.
"""
return _stc.StyledTextCtrl_GetStyleAt(*args, **kwargs) | [
"def",
"GetStyleAt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetStyleAt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2111-L2117 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | support/cpplint.py | python | NestingState.InExternC | (self) | return self.stack and isinstance(self.stack[-1], _ExternCInfo) | Check if we are currently one level inside an 'extern "C"' block.
Returns:
True if top of the stack is an extern block, False otherwise. | Check if we are currently one level inside an 'extern "C"' block. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"an",
"extern",
"C",
"block",
"."
] | def InExternC(self):
"""Check if we are currently one level inside an 'extern "C"' block.
Returns:
True if top of the stack is an extern block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ExternCInfo) | [
"def",
"InExternC",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ExternCInfo",
")"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L2454-L2460 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/tlslite/tlslite/X509CertChain.py | python | X509CertChain.getFingerprint | (self) | return self.x509List[0].getFingerprint() | Get the hex-encoded fingerprint of the end-entity certificate.
@rtype: str
@return: A hex-encoded fingerprint. | Get the hex-encoded fingerprint of the end-entity certificate. | [
"Get",
"the",
"hex",
"-",
"encoded",
"fingerprint",
"of",
"the",
"end",
"-",
"entity",
"certificate",
"."
] | def getFingerprint(self):
"""Get the hex-encoded fingerprint of the end-entity certificate.
@rtype: str
@return: A hex-encoded fingerprint.
"""
if self.getNumCerts() == 0:
raise AssertionError()
return self.x509List[0].getFingerprint() | [
"def",
"getFingerprint",
"(",
"self",
")",
":",
"if",
"self",
".",
"getNumCerts",
"(",
")",
"==",
"0",
":",
"raise",
"AssertionError",
"(",
")",
"return",
"self",
".",
"x509List",
"[",
"0",
"]",
".",
"getFingerprint",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/tlslite/tlslite/X509CertChain.py#L104-L112 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/bison.py | python | configure | (conf) | Detects the *bison* program | Detects the *bison* program | [
"Detects",
"the",
"*",
"bison",
"*",
"program"
] | def configure(conf):
"""
Detects the *bison* program
"""
conf.find_program('bison', var='BISON')
conf.env.BISONFLAGS = ['-d'] | [
"def",
"configure",
"(",
"conf",
")",
":",
"conf",
".",
"find_program",
"(",
"'bison'",
",",
"var",
"=",
"'BISON'",
")",
"conf",
".",
"env",
".",
"BISONFLAGS",
"=",
"[",
"'-d'",
"]"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/bison.py#L43-L48 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiDockingGuideWindow.Draw | (self, dc) | Draws the whole docking guide window (not used if the docking guide images are ok).
:param `dc`: a :class:`DC` device context object. | Draws the whole docking guide window (not used if the docking guide images are ok). | [
"Draws",
"the",
"whole",
"docking",
"guide",
"window",
"(",
"not",
"used",
"if",
"the",
"docking",
"guide",
"images",
"are",
"ok",
")",
"."
] | def Draw(self, dc):
"""
Draws the whole docking guide window (not used if the docking guide images are ok).
:param `dc`: a :class:`DC` device context object.
"""
self.DrawBackground(dc)
if self._valid:
self.DrawIcon(dc)
self.DrawArrow(dc) | [
"def",
"Draw",
"(",
"self",
",",
"dc",
")",
":",
"self",
".",
"DrawBackground",
"(",
"dc",
")",
"if",
"self",
".",
"_valid",
":",
"self",
".",
"DrawIcon",
"(",
"dc",
")",
"self",
".",
"DrawArrow",
"(",
"dc",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L2169-L2180 | ||
davidstutz/mesh-voxelization | 81a237c3b345062e364b180a8a4fc7ac98e107a4 | examples/fill_occupancy.py | python | write_hdf5 | (file, tensor, key = 'tensor') | Write a simple tensor, i.e. numpy array ,to HDF5.
:param file: path to file to write
:type file: str
:param tensor: tensor to write
:type tensor: numpy.ndarray
:param key: key to use for tensor
:type key: str | Write a simple tensor, i.e. numpy array ,to HDF5. | [
"Write",
"a",
"simple",
"tensor",
"i",
".",
"e",
".",
"numpy",
"array",
"to",
"HDF5",
"."
] | def write_hdf5(file, tensor, key = 'tensor'):
"""
Write a simple tensor, i.e. numpy array ,to HDF5.
:param file: path to file to write
:type file: str
:param tensor: tensor to write
:type tensor: numpy.ndarray
:param key: key to use for tensor
:type key: str
"""
assert type(tensor) == np.ndarray, 'expects numpy.ndarray'
h5f = h5py.File(file, 'w')
chunks = list(tensor.shape)
if len(chunks) > 2:
chunks[2] = 1
if len(chunks) > 3:
chunks[3] = 1
if len(chunks) > 4:
chunks[4] = 1
h5f.create_dataset(key, data = tensor, chunks = tuple(chunks), compression = 'gzip')
h5f.close() | [
"def",
"write_hdf5",
"(",
"file",
",",
"tensor",
",",
"key",
"=",
"'tensor'",
")",
":",
"assert",
"type",
"(",
"tensor",
")",
"==",
"np",
".",
"ndarray",
",",
"'expects numpy.ndarray'",
"h5f",
"=",
"h5py",
".",
"File",
"(",
"file",
",",
"'w'",
")",
"chunks",
"=",
"list",
"(",
"tensor",
".",
"shape",
")",
"if",
"len",
"(",
"chunks",
")",
">",
"2",
":",
"chunks",
"[",
"2",
"]",
"=",
"1",
"if",
"len",
"(",
"chunks",
")",
">",
"3",
":",
"chunks",
"[",
"3",
"]",
"=",
"1",
"if",
"len",
"(",
"chunks",
")",
">",
"4",
":",
"chunks",
"[",
"4",
"]",
"=",
"1",
"h5f",
".",
"create_dataset",
"(",
"key",
",",
"data",
"=",
"tensor",
",",
"chunks",
"=",
"tuple",
"(",
"chunks",
")",
",",
"compression",
"=",
"'gzip'",
")",
"h5f",
".",
"close",
"(",
")"
] | https://github.com/davidstutz/mesh-voxelization/blob/81a237c3b345062e364b180a8a4fc7ac98e107a4/examples/fill_occupancy.py#L7-L32 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/decimal.py | python | Decimal.is_subnormal | (self, context=None) | return self.adjusted() < context.Emin | Return True if self is subnormal; otherwise return False. | Return True if self is subnormal; otherwise return False. | [
"Return",
"True",
"if",
"self",
"is",
"subnormal",
";",
"otherwise",
"return",
"False",
"."
] | def is_subnormal(self, context=None):
"""Return True if self is subnormal; otherwise return False."""
if self._is_special or not self:
return False
if context is None:
context = getcontext()
return self.adjusted() < context.Emin | [
"def",
"is_subnormal",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"_is_special",
"or",
"not",
"self",
":",
"return",
"False",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"return",
"self",
".",
"adjusted",
"(",
")",
"<",
"context",
".",
"Emin"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L2895-L2901 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/bayesflow/examples/reinforce_simple/reinforce_simple_example.py | python | build_split_apply_merge_model | () | return (route_selection, routing_loss, final_loss) | Build the Split-Apply-Merge Model.
Route each value of input [-1, -1, 1, 1] through one of the
functions, plus_1, minus_1. The decision for routing is made by
4 Bernoulli R.V.s whose parameters are determined by a neural network
applied to the input. REINFORCE is used to update the NN parameters.
Returns:
The 3-tuple (route_selection, routing_loss, final_loss), where:
- route_selection is an int 4-vector
- routing_loss is a float 4-vector
- final_loss is a float scalar. | Build the Split-Apply-Merge Model. | [
"Build",
"the",
"Split",
"-",
"Apply",
"-",
"Merge",
"Model",
"."
] | def build_split_apply_merge_model():
"""Build the Split-Apply-Merge Model.
Route each value of input [-1, -1, 1, 1] through one of the
functions, plus_1, minus_1. The decision for routing is made by
4 Bernoulli R.V.s whose parameters are determined by a neural network
applied to the input. REINFORCE is used to update the NN parameters.
Returns:
The 3-tuple (route_selection, routing_loss, final_loss), where:
- route_selection is an int 4-vector
- routing_loss is a float 4-vector
- final_loss is a float scalar.
"""
inputs = tf.constant([[-1.0], [-1.0], [1.0], [1.0]])
targets = tf.constant([[0.0], [0.0], [0.0], [0.0]])
paths = [plus_1, minus_1]
weights = tf.get_variable("w", [1, 2])
bias = tf.get_variable("b", [1, 1])
logits = tf.matmul(inputs, weights) + bias
# REINFORCE forward step
route_selection = st.StochasticTensor(
distributions.Categorical, logits=logits)
# Accessing route_selection as a Tensor below forces a sample of
# the Categorical distribution based on its logits.
# This is equivalent to calling route_selection.value().
#
# route_selection.value() returns an int32 4-vector with random
# values in {0, 1}
# COPY+ROUTE+PASTE
outputs = split_apply_merge(inputs, route_selection, paths)
# flatten routing_loss to a row vector (from a column vector)
routing_loss = tf.reshape(tf.square(outputs - targets), shape=[-1])
# Total loss: score function loss + routing loss.
# The score function loss (through `route_selection.loss(routing_loss)`)
# returns:
# [stop_gradient(routing_loss) *
# route_selection.log_pmf(stop_gradient(route_selection.value()))],
# where log_pmf has gradients going all the way back to weights and bias.
# In this case, the routing_loss depends on the variables only through
# "route_selection", which has a stop_gradient on it. So the
# gradient of the loss really come through the score function
surrogate_loss = sg.surrogate_loss([routing_loss])
final_loss = tf.reduce_sum(surrogate_loss)
return (route_selection, routing_loss, final_loss) | [
"def",
"build_split_apply_merge_model",
"(",
")",
":",
"inputs",
"=",
"tf",
".",
"constant",
"(",
"[",
"[",
"-",
"1.0",
"]",
",",
"[",
"-",
"1.0",
"]",
",",
"[",
"1.0",
"]",
",",
"[",
"1.0",
"]",
"]",
")",
"targets",
"=",
"tf",
".",
"constant",
"(",
"[",
"[",
"0.0",
"]",
",",
"[",
"0.0",
"]",
",",
"[",
"0.0",
"]",
",",
"[",
"0.0",
"]",
"]",
")",
"paths",
"=",
"[",
"plus_1",
",",
"minus_1",
"]",
"weights",
"=",
"tf",
".",
"get_variable",
"(",
"\"w\"",
",",
"[",
"1",
",",
"2",
"]",
")",
"bias",
"=",
"tf",
".",
"get_variable",
"(",
"\"b\"",
",",
"[",
"1",
",",
"1",
"]",
")",
"logits",
"=",
"tf",
".",
"matmul",
"(",
"inputs",
",",
"weights",
")",
"+",
"bias",
"# REINFORCE forward step",
"route_selection",
"=",
"st",
".",
"StochasticTensor",
"(",
"distributions",
".",
"Categorical",
",",
"logits",
"=",
"logits",
")",
"# Accessing route_selection as a Tensor below forces a sample of",
"# the Categorical distribution based on its logits.",
"# This is equivalent to calling route_selection.value().",
"#",
"# route_selection.value() returns an int32 4-vector with random",
"# values in {0, 1}",
"# COPY+ROUTE+PASTE",
"outputs",
"=",
"split_apply_merge",
"(",
"inputs",
",",
"route_selection",
",",
"paths",
")",
"# flatten routing_loss to a row vector (from a column vector)",
"routing_loss",
"=",
"tf",
".",
"reshape",
"(",
"tf",
".",
"square",
"(",
"outputs",
"-",
"targets",
")",
",",
"shape",
"=",
"[",
"-",
"1",
"]",
")",
"# Total loss: score function loss + routing loss.",
"# The score function loss (through `route_selection.loss(routing_loss)`)",
"# returns:",
"# [stop_gradient(routing_loss) *",
"# route_selection.log_pmf(stop_gradient(route_selection.value()))],",
"# where log_pmf has gradients going all the way back to weights and bias.",
"# In this case, the routing_loss depends on the variables only through",
"# \"route_selection\", which has a stop_gradient on it. So the",
"# gradient of the loss really come through the score function",
"surrogate_loss",
"=",
"sg",
".",
"surrogate_loss",
"(",
"[",
"routing_loss",
"]",
")",
"final_loss",
"=",
"tf",
".",
"reduce_sum",
"(",
"surrogate_loss",
")",
"return",
"(",
"route_selection",
",",
"routing_loss",
",",
"final_loss",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/bayesflow/examples/reinforce_simple/reinforce_simple_example.py#L55-L105 | |
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/build/virtual_target.py | python | VirtualTarget.project | (self) | return self.project_ | Project of this target. | Project of this target. | [
"Project",
"of",
"this",
"target",
"."
] | def project (self):
""" Project of this target.
"""
return self.project_ | [
"def",
"project",
"(",
"self",
")",
":",
"return",
"self",
".",
"project_"
] | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/virtual_target.py#L276-L279 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TreeCtrl.EditLabel | (*args, **kwargs) | return _controls_.TreeCtrl_EditLabel(*args, **kwargs) | EditLabel(self, TreeItemId item) | EditLabel(self, TreeItemId item) | [
"EditLabel",
"(",
"self",
"TreeItemId",
"item",
")"
] | def EditLabel(*args, **kwargs):
"""EditLabel(self, TreeItemId item)"""
return _controls_.TreeCtrl_EditLabel(*args, **kwargs) | [
"def",
"EditLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_EditLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5527-L5529 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/packages/six.py | python | remove_move | (name) | Remove item from six.moves. | Remove item from six.moves. | [
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
"(",
"\"no such move, %r\"",
"%",
"(",
"name",
",",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/packages/six.py#L491-L499 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/__init__.py | python | Scanner | (function, *args, **kw) | Public interface factory function for creating different types
of Scanners based on the different types of "functions" that may
be supplied.
TODO: Deprecate this some day. We've moved the functionality
inside the Base class and really don't need this factory function
any more. It was, however, used by some of our Tool modules, so
the call probably ended up in various people's custom modules
patterned on SCons code. | Public interface factory function for creating different types
of Scanners based on the different types of "functions" that may
be supplied. | [
"Public",
"interface",
"factory",
"function",
"for",
"creating",
"different",
"types",
"of",
"Scanners",
"based",
"on",
"the",
"different",
"types",
"of",
"functions",
"that",
"may",
"be",
"supplied",
"."
] | def Scanner(function, *args, **kw):
"""
Public interface factory function for creating different types
of Scanners based on the different types of "functions" that may
be supplied.
TODO: Deprecate this some day. We've moved the functionality
inside the Base class and really don't need this factory function
any more. It was, however, used by some of our Tool modules, so
the call probably ended up in various people's custom modules
patterned on SCons code.
"""
if SCons.Util.is_Dict(function):
return Selector(function, *args, **kw)
else:
return Base(function, *args, **kw) | [
"def",
"Scanner",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_Dict",
"(",
"function",
")",
":",
"return",
"Selector",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"else",
":",
"return",
"Base",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/__init__.py#L45-L60 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | TPen.hideturtle | (self) | Makes the turtle invisible.
Aliases: hideturtle | ht
No argument.
It's a good idea to do this while you're in the
middle of a complicated drawing, because hiding
the turtle speeds up the drawing observably.
Example (for a Turtle instance named turtle):
>>> turtle.hideturtle() | Makes the turtle invisible. | [
"Makes",
"the",
"turtle",
"invisible",
"."
] | def hideturtle(self):
"""Makes the turtle invisible.
Aliases: hideturtle | ht
No argument.
It's a good idea to do this while you're in the
middle of a complicated drawing, because hiding
the turtle speeds up the drawing observably.
Example (for a Turtle instance named turtle):
>>> turtle.hideturtle()
"""
self.pen(shown=False) | [
"def",
"hideturtle",
"(",
"self",
")",
":",
"self",
".",
"pen",
"(",
"shown",
"=",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L2309-L2323 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.image_types | (self) | return self.tk.splitlist(self.tk.call('image', 'types')) | Return a list of all available image types (e.g. photo bitmap). | Return a list of all available image types (e.g. photo bitmap). | [
"Return",
"a",
"list",
"of",
"all",
"available",
"image",
"types",
"(",
"e",
".",
"g",
".",
"photo",
"bitmap",
")",
"."
] | def image_types(self):
"""Return a list of all available image types (e.g. photo bitmap)."""
return self.tk.splitlist(self.tk.call('image', 'types')) | [
"def",
"image_types",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"splitlist",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'image'",
",",
"'types'",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1687-L1689 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/training/queue_runner_impl.py | python | QueueRunner._run | (self, sess, enqueue_op, coord=None) | Execute the enqueue op in a loop, close the queue in case of error.
Args:
sess: A Session.
enqueue_op: The Operation to run.
coord: Optional Coordinator object for reporting errors and checking
for stop conditions. | Execute the enqueue op in a loop, close the queue in case of error. | [
"Execute",
"the",
"enqueue",
"op",
"in",
"a",
"loop",
"close",
"the",
"queue",
"in",
"case",
"of",
"error",
"."
] | def _run(self, sess, enqueue_op, coord=None):
"""Execute the enqueue op in a loop, close the queue in case of error.
Args:
sess: A Session.
enqueue_op: The Operation to run.
coord: Optional Coordinator object for reporting errors and checking
for stop conditions.
"""
decremented = False
try:
# Make a cached callable from the `enqueue_op` to decrease the
# Python overhead in the queue-runner loop.
enqueue_callable = sess.make_callable(enqueue_op)
while True:
if coord and coord.should_stop():
break
try:
enqueue_callable()
except self._queue_closed_exception_types: # pylint: disable=catching-non-exception
# This exception indicates that a queue was closed.
with self._lock:
self._runs_per_session[sess] -= 1
decremented = True
if self._runs_per_session[sess] == 0:
try:
sess.run(self._close_op)
except Exception as e:
# Intentionally ignore errors from close_op.
logging.vlog(1, "Ignored exception: %s", str(e))
return
except Exception as e:
# This catches all other exceptions.
if coord:
coord.request_stop(e)
else:
logging.error("Exception in QueueRunner: %s", str(e))
with self._lock:
self._exceptions_raised.append(e)
raise
finally:
# Make sure we account for all terminations: normal or errors.
if not decremented:
with self._lock:
self._runs_per_session[sess] -= 1 | [
"def",
"_run",
"(",
"self",
",",
"sess",
",",
"enqueue_op",
",",
"coord",
"=",
"None",
")",
":",
"decremented",
"=",
"False",
"try",
":",
"# Make a cached callable from the `enqueue_op` to decrease the",
"# Python overhead in the queue-runner loop.",
"enqueue_callable",
"=",
"sess",
".",
"make_callable",
"(",
"enqueue_op",
")",
"while",
"True",
":",
"if",
"coord",
"and",
"coord",
".",
"should_stop",
"(",
")",
":",
"break",
"try",
":",
"enqueue_callable",
"(",
")",
"except",
"self",
".",
"_queue_closed_exception_types",
":",
"# pylint: disable=catching-non-exception",
"# This exception indicates that a queue was closed.",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_runs_per_session",
"[",
"sess",
"]",
"-=",
"1",
"decremented",
"=",
"True",
"if",
"self",
".",
"_runs_per_session",
"[",
"sess",
"]",
"==",
"0",
":",
"try",
":",
"sess",
".",
"run",
"(",
"self",
".",
"_close_op",
")",
"except",
"Exception",
"as",
"e",
":",
"# Intentionally ignore errors from close_op.",
"logging",
".",
"vlog",
"(",
"1",
",",
"\"Ignored exception: %s\"",
",",
"str",
"(",
"e",
")",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"# This catches all other exceptions.",
"if",
"coord",
":",
"coord",
".",
"request_stop",
"(",
"e",
")",
"else",
":",
"logging",
".",
"error",
"(",
"\"Exception in QueueRunner: %s\"",
",",
"str",
"(",
"e",
")",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_exceptions_raised",
".",
"append",
"(",
"e",
")",
"raise",
"finally",
":",
"# Make sure we account for all terminations: normal or errors.",
"if",
"not",
"decremented",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_runs_per_session",
"[",
"sess",
"]",
"-=",
"1"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/queue_runner_impl.py#L220-L264 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Canvas.delete | (self, *args) | Delete items identified by all tag or ids contained in ARGS. | Delete items identified by all tag or ids contained in ARGS. | [
"Delete",
"items",
"identified",
"by",
"all",
"tag",
"or",
"ids",
"contained",
"in",
"ARGS",
"."
] | def delete(self, *args):
"""Delete items identified by all tag or ids contained in ARGS."""
self.tk.call((self._w, 'delete') + args) | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'delete'",
")",
"+",
"args",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2283-L2285 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/vcs/mercurial.py | python | Mercurial.get_requirement_revision | (cls, location) | return current_rev_hash | Return the changeset identification hash, as a 40-character
hexadecimal string | Return the changeset identification hash, as a 40-character
hexadecimal string | [
"Return",
"the",
"changeset",
"identification",
"hash",
"as",
"a",
"40",
"-",
"character",
"hexadecimal",
"string"
] | def get_requirement_revision(cls, location):
"""
Return the changeset identification hash, as a 40-character
hexadecimal string
"""
current_rev_hash = cls.run_command(
['parents', '--template={node}'],
show_stdout=False,
stdout_only=True,
cwd=location,
).strip()
return current_rev_hash | [
"def",
"get_requirement_revision",
"(",
"cls",
",",
"location",
")",
":",
"current_rev_hash",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'parents'",
",",
"'--template={node}'",
"]",
",",
"show_stdout",
"=",
"False",
",",
"stdout_only",
"=",
"True",
",",
"cwd",
"=",
"location",
",",
")",
".",
"strip",
"(",
")",
"return",
"current_rev_hash"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/vcs/mercurial.py#L116-L127 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/tlslite/tlslite/integration/AsyncStateMachine.py | python | AsyncStateMachine.inWriteEvent | (self) | Tell the state machine it can write to the socket. | Tell the state machine it can write to the socket. | [
"Tell",
"the",
"state",
"machine",
"it",
"can",
"write",
"to",
"the",
"socket",
"."
] | def inWriteEvent(self):
"""Tell the state machine it can write to the socket."""
try:
self._checkAssert()
if self.handshaker:
self._doHandshakeOp()
elif self.closer:
self._doCloseOp()
elif self.reader:
self._doReadOp()
elif self.writer:
self._doWriteOp()
else:
self.outWriteEvent()
except:
self._clear()
raise | [
"def",
"inWriteEvent",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_checkAssert",
"(",
")",
"if",
"self",
".",
"handshaker",
":",
"self",
".",
"_doHandshakeOp",
"(",
")",
"elif",
"self",
".",
"closer",
":",
"self",
".",
"_doCloseOp",
"(",
")",
"elif",
"self",
".",
"reader",
":",
"self",
".",
"_doReadOp",
"(",
")",
"elif",
"self",
".",
"writer",
":",
"self",
".",
"_doWriteOp",
"(",
")",
"else",
":",
"self",
".",
"outWriteEvent",
"(",
")",
"except",
":",
"self",
".",
"_clear",
"(",
")",
"raise"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/tlslite/tlslite/integration/AsyncStateMachine.py#L137-L153 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/column_accessor.py | python | ColumnAccessor._pad_key | (self, key: Any, pad_value="") | return key + (pad_value,) * (self.nlevels - len(key)) | Pad the provided key to a length equal to the number
of levels. | Pad the provided key to a length equal to the number
of levels. | [
"Pad",
"the",
"provided",
"key",
"to",
"a",
"length",
"equal",
"to",
"the",
"number",
"of",
"levels",
"."
] | def _pad_key(self, key: Any, pad_value="") -> Any:
"""
Pad the provided key to a length equal to the number
of levels.
"""
if not self.multiindex:
return key
if not isinstance(key, tuple):
key = (key,)
return key + (pad_value,) * (self.nlevels - len(key)) | [
"def",
"_pad_key",
"(",
"self",
",",
"key",
":",
"Any",
",",
"pad_value",
"=",
"\"\"",
")",
"->",
"Any",
":",
"if",
"not",
"self",
".",
"multiindex",
":",
"return",
"key",
"if",
"not",
"isinstance",
"(",
"key",
",",
"tuple",
")",
":",
"key",
"=",
"(",
"key",
",",
")",
"return",
"key",
"+",
"(",
"pad_value",
",",
")",
"*",
"(",
"self",
".",
"nlevels",
"-",
"len",
"(",
"key",
")",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column_accessor.py#L454-L463 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/autograd.py | python | HardSigmoid.forward | (self, x) | return singa.ReLU(ans) | Args:
x (CTensor): matrix
Returns:
a CTensor for the result | Args:
x (CTensor): matrix
Returns:
a CTensor for the result | [
"Args",
":",
"x",
"(",
"CTensor",
")",
":",
"matrix",
"Returns",
":",
"a",
"CTensor",
"for",
"the",
"result"
] | def forward(self, x):
"""
Args:
x (CTensor): matrix
Returns:
a CTensor for the result
"""
x = singa.AddFloat(singa.MultFloat(x, self.alpha), self.gamma)
if training:
self.cache = x
x = singa.ReLU(x)
mask1 = singa.LTFloat(x, 1.0)
mask2 = singa.GEFloat(x, 1.0)
ans = singa.__add__(singa.__mul__(x, mask1), mask2)
return singa.ReLU(ans) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"singa",
".",
"AddFloat",
"(",
"singa",
".",
"MultFloat",
"(",
"x",
",",
"self",
".",
"alpha",
")",
",",
"self",
".",
"gamma",
")",
"if",
"training",
":",
"self",
".",
"cache",
"=",
"x",
"x",
"=",
"singa",
".",
"ReLU",
"(",
"x",
")",
"mask1",
"=",
"singa",
".",
"LTFloat",
"(",
"x",
",",
"1.0",
")",
"mask2",
"=",
"singa",
".",
"GEFloat",
"(",
"x",
",",
"1.0",
")",
"ans",
"=",
"singa",
".",
"__add__",
"(",
"singa",
".",
"__mul__",
"(",
"x",
",",
"mask1",
")",
",",
"mask2",
")",
"return",
"singa",
".",
"ReLU",
"(",
"ans",
")"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L3182-L3198 | |
cyberfire/tensorflow-mtcnn | 82a39f0f632cfe253369a1390fde97efe6ce778e | detect_face.py | python | Network.feed | (self, *args) | return self | Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers. | Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers. | [
"Set",
"the",
"input",
"(",
"s",
")",
"for",
"the",
"next",
"operation",
"by",
"replacing",
"the",
"terminal",
"nodes",
".",
"The",
"arguments",
"can",
"be",
"either",
"layer",
"names",
"or",
"the",
"actual",
"layers",
"."
] | def feed(self, *args):
'''Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
'''
assert len(args) != 0
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, string_types):
try:
fed_layer = self.layers[fed_layer]
except KeyError:
raise KeyError('Unknown layer name fed: %s' % fed_layer)
self.terminals.append(fed_layer)
return self | [
"def",
"feed",
"(",
"self",
",",
"*",
"args",
")",
":",
"assert",
"len",
"(",
"args",
")",
"!=",
"0",
"self",
".",
"terminals",
"=",
"[",
"]",
"for",
"fed_layer",
"in",
"args",
":",
"if",
"isinstance",
"(",
"fed_layer",
",",
"string_types",
")",
":",
"try",
":",
"fed_layer",
"=",
"self",
".",
"layers",
"[",
"fed_layer",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Unknown layer name fed: %s'",
"%",
"fed_layer",
")",
"self",
".",
"terminals",
".",
"append",
"(",
"fed_layer",
")",
"return",
"self"
] | https://github.com/cyberfire/tensorflow-mtcnn/blob/82a39f0f632cfe253369a1390fde97efe6ce778e/detect_face.py#L97-L110 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/manager.py | python | Manager.construct | (self, properties = [], targets = []) | Constructs the dependency graph.
properties: the build properties.
targets: the targets to consider. If none is specified, uses all. | Constructs the dependency graph.
properties: the build properties.
targets: the targets to consider. If none is specified, uses all. | [
"Constructs",
"the",
"dependency",
"graph",
".",
"properties",
":",
"the",
"build",
"properties",
".",
"targets",
":",
"the",
"targets",
"to",
"consider",
".",
"If",
"none",
"is",
"specified",
"uses",
"all",
"."
] | def construct (self, properties = [], targets = []):
""" Constructs the dependency graph.
properties: the build properties.
targets: the targets to consider. If none is specified, uses all.
"""
if not targets:
for name, project in self.projects ().projects ():
targets.append (project.target ())
property_groups = build_request.expand_no_defaults (properties)
virtual_targets = []
build_prop_sets = []
for p in property_groups:
build_prop_sets.append (property_set.create (feature.split (p)))
if not build_prop_sets:
build_prop_sets = [property_set.empty ()]
for build_properties in build_prop_sets:
for target in targets:
result = target.generate (build_properties)
virtual_targets.extend (result.targets ())
actual_targets = []
for virtual_target in virtual_targets:
actual_targets.extend (virtual_target.actualize ()) | [
"def",
"construct",
"(",
"self",
",",
"properties",
"=",
"[",
"]",
",",
"targets",
"=",
"[",
"]",
")",
":",
"if",
"not",
"targets",
":",
"for",
"name",
",",
"project",
"in",
"self",
".",
"projects",
"(",
")",
".",
"projects",
"(",
")",
":",
"targets",
".",
"append",
"(",
"project",
".",
"target",
"(",
")",
")",
"property_groups",
"=",
"build_request",
".",
"expand_no_defaults",
"(",
"properties",
")",
"virtual_targets",
"=",
"[",
"]",
"build_prop_sets",
"=",
"[",
"]",
"for",
"p",
"in",
"property_groups",
":",
"build_prop_sets",
".",
"append",
"(",
"property_set",
".",
"create",
"(",
"feature",
".",
"split",
"(",
"p",
")",
")",
")",
"if",
"not",
"build_prop_sets",
":",
"build_prop_sets",
"=",
"[",
"property_set",
".",
"empty",
"(",
")",
"]",
"for",
"build_properties",
"in",
"build_prop_sets",
":",
"for",
"target",
"in",
"targets",
":",
"result",
"=",
"target",
".",
"generate",
"(",
"build_properties",
")",
"virtual_targets",
".",
"extend",
"(",
"result",
".",
"targets",
"(",
")",
")",
"actual_targets",
"=",
"[",
"]",
"for",
"virtual_target",
"in",
"virtual_targets",
":",
"actual_targets",
".",
"extend",
"(",
"virtual_target",
".",
"actualize",
"(",
")",
")"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/manager.py#L83-L109 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | contrib/misc/performance/graphite/bareos-graphite-poller.py | python | sendEvent | (url, eventPayload) | return 0 | Send a single event to Carbon via http/json
Parameters
url: the carbon api url to receive events
eventPayLoad: event data in json format | Send a single event to Carbon via http/json
Parameters
url: the carbon api url to receive events
eventPayLoad: event data in json format | [
"Send",
"a",
"single",
"event",
"to",
"Carbon",
"via",
"http",
"/",
"json",
"Parameters",
"url",
":",
"the",
"carbon",
"api",
"url",
"to",
"receive",
"events",
"eventPayLoad",
":",
"event",
"data",
"in",
"json",
"format"
] | def sendEvent(url, eventPayload):
'''
Send a single event to Carbon via http/json
Parameters
url: the carbon api url to receive events
eventPayLoad: event data in json format
'''
logger.debug("send eventdata %s to %s" % (json.dumps(eventPayload), url))
r = requests.post(url, data=json.dumps(eventPayload))
if r.status_code != 200:
logger.error("http post for event failed with code %d and reason: %s" % (r.statuscode, r.reason))
return 1
logger.debug(r.text)
return 0 | [
"def",
"sendEvent",
"(",
"url",
",",
"eventPayload",
")",
":",
"logger",
".",
"debug",
"(",
"\"send eventdata %s to %s\"",
"%",
"(",
"json",
".",
"dumps",
"(",
"eventPayload",
")",
",",
"url",
")",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"eventPayload",
")",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"logger",
".",
"error",
"(",
"\"http post for event failed with code %d and reason: %s\"",
"%",
"(",
"r",
".",
"statuscode",
",",
"r",
".",
"reason",
")",
")",
"return",
"1",
"logger",
".",
"debug",
"(",
"r",
".",
"text",
")",
"return",
"0"
] | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/contrib/misc/performance/graphite/bareos-graphite-poller.py#L70-L83 | |
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | scripts/cpp_lint.py | python | _FunctionState.Check | (self, error, filename, linenum) | Report if too many lines in function body.
Args:
error: The function to call with any errors found.
filename: The name of the current file.
linenum: The number of the line to check. | Report if too many lines in function body. | [
"Report",
"if",
"too",
"many",
"lines",
"in",
"function",
"body",
"."
] | def Check(self, error, filename, linenum):
"""Report if too many lines in function body.
Args:
error: The function to call with any errors found.
filename: The name of the current file.
linenum: The number of the line to check.
"""
if Match(r'T(EST|est)', self.current_function):
base_trigger = self._TEST_TRIGGER
else:
base_trigger = self._NORMAL_TRIGGER
trigger = base_trigger * 2**_VerboseLevel()
if self.lines_in_function > trigger:
error_level = int(math.log(self.lines_in_function / base_trigger, 2))
# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
if error_level > 5:
error_level = 5
error(filename, linenum, 'readability/fn_size', error_level,
'Small and focused functions are preferred:'
' %s has %d non-comment lines'
' (error triggered by exceeding %d lines).' % (
self.current_function, self.lines_in_function, trigger)) | [
"def",
"Check",
"(",
"self",
",",
"error",
",",
"filename",
",",
"linenum",
")",
":",
"if",
"Match",
"(",
"r'T(EST|est)'",
",",
"self",
".",
"current_function",
")",
":",
"base_trigger",
"=",
"self",
".",
"_TEST_TRIGGER",
"else",
":",
"base_trigger",
"=",
"self",
".",
"_NORMAL_TRIGGER",
"trigger",
"=",
"base_trigger",
"*",
"2",
"**",
"_VerboseLevel",
"(",
")",
"if",
"self",
".",
"lines_in_function",
">",
"trigger",
":",
"error_level",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"self",
".",
"lines_in_function",
"/",
"base_trigger",
",",
"2",
")",
")",
"# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...",
"if",
"error_level",
">",
"5",
":",
"error_level",
"=",
"5",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/fn_size'",
",",
"error_level",
",",
"'Small and focused functions are preferred:'",
"' %s has %d non-comment lines'",
"' (error triggered by exceeding %d lines).'",
"%",
"(",
"self",
".",
"current_function",
",",
"self",
".",
"lines_in_function",
",",
"trigger",
")",
")"
] | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L836-L859 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | tools/coreml/converter/_layers.py | python | convert_convolution | (net, node, module, builder) | Convert a convolution layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object. | Convert a convolution layer from mxnet to coreml. | [
"Convert",
"a",
"convolution",
"layer",
"from",
"mxnet",
"to",
"coreml",
"."
] | def convert_convolution(net, node, module, builder):
"""Convert a convolution layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attrs(node)
inputs = node['inputs']
args, _ = module.get_params()
if 'no_bias' in param.keys():
has_bias = not literal_eval(param['no_bias'])
else:
has_bias = True
if 'pad' in param.keys() and literal_eval(param['pad']) != (0, 0):
pad = literal_eval(param['pad'])
builder.add_padding(
name=name+"_pad",
left=pad[1],
right=pad[1],
top=pad[0],
bottom=pad[0],
value=0,
input_name=input_name,
output_name=name+"_pad_output")
input_name = name+"_pad_output"
border_mode = "valid"
n_filters = int(param['num_filter'])
n_groups = int(param['num_group']) if 'num_group' in param else 1
W = args[_get_node_name(net, inputs[1][0])].asnumpy()
if has_bias:
Wb = args[_get_node_name(net, inputs[2][0])].asnumpy()
else:
Wb = None
channels = W.shape[1]
stride_height = 1
stride_width = 1
if 'stride' in param.keys():
stride_height, stride_width = literal_eval(param['stride'])
kernel_height, kernel_width = literal_eval(param['kernel'])
W = W.transpose((2, 3, 1, 0))
builder.add_convolution(
name=name,
kernel_channels=channels,
output_channels=n_filters,
height=kernel_height,
width=kernel_width,
stride_height=stride_height,
stride_width=stride_width,
border_mode=border_mode,
groups=n_groups,
W=W,
b=Wb,
has_bias=has_bias,
is_deconv=False,
output_shape=None,
input_name=input_name,
output_name=output_name) | [
"def",
"convert_convolution",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attrs",
"(",
"node",
")",
"inputs",
"=",
"node",
"[",
"'inputs'",
"]",
"args",
",",
"_",
"=",
"module",
".",
"get_params",
"(",
")",
"if",
"'no_bias'",
"in",
"param",
".",
"keys",
"(",
")",
":",
"has_bias",
"=",
"not",
"literal_eval",
"(",
"param",
"[",
"'no_bias'",
"]",
")",
"else",
":",
"has_bias",
"=",
"True",
"if",
"'pad'",
"in",
"param",
".",
"keys",
"(",
")",
"and",
"literal_eval",
"(",
"param",
"[",
"'pad'",
"]",
")",
"!=",
"(",
"0",
",",
"0",
")",
":",
"pad",
"=",
"literal_eval",
"(",
"param",
"[",
"'pad'",
"]",
")",
"builder",
".",
"add_padding",
"(",
"name",
"=",
"name",
"+",
"\"_pad\"",
",",
"left",
"=",
"pad",
"[",
"1",
"]",
",",
"right",
"=",
"pad",
"[",
"1",
"]",
",",
"top",
"=",
"pad",
"[",
"0",
"]",
",",
"bottom",
"=",
"pad",
"[",
"0",
"]",
",",
"value",
"=",
"0",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"name",
"+",
"\"_pad_output\"",
")",
"input_name",
"=",
"name",
"+",
"\"_pad_output\"",
"border_mode",
"=",
"\"valid\"",
"n_filters",
"=",
"int",
"(",
"param",
"[",
"'num_filter'",
"]",
")",
"n_groups",
"=",
"int",
"(",
"param",
"[",
"'num_group'",
"]",
")",
"if",
"'num_group'",
"in",
"param",
"else",
"1",
"W",
"=",
"args",
"[",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"]",
".",
"asnumpy",
"(",
")",
"if",
"has_bias",
":",
"Wb",
"=",
"args",
"[",
"_get_node_name",
"(",
"net",
",",
"inputs",
"[",
"2",
"]",
"[",
"0",
"]",
")",
"]",
".",
"asnumpy",
"(",
")",
"else",
":",
"Wb",
"=",
"None",
"channels",
"=",
"W",
".",
"shape",
"[",
"1",
"]",
"stride_height",
"=",
"1",
"stride_width",
"=",
"1",
"if",
"'stride'",
"in",
"param",
".",
"keys",
"(",
")",
":",
"stride_height",
",",
"stride_width",
"=",
"literal_eval",
"(",
"param",
"[",
"'stride'",
"]",
")",
"kernel_height",
",",
"kernel_width",
"=",
"literal_eval",
"(",
"param",
"[",
"'kernel'",
"]",
")",
"W",
"=",
"W",
".",
"transpose",
"(",
"(",
"2",
",",
"3",
",",
"1",
",",
"0",
")",
")",
"builder",
".",
"add_convolution",
"(",
"name",
"=",
"name",
",",
"kernel_channels",
"=",
"channels",
",",
"output_channels",
"=",
"n_filters",
",",
"height",
"=",
"kernel_height",
",",
"width",
"=",
"kernel_width",
",",
"stride_height",
"=",
"stride_height",
",",
"stride_width",
"=",
"stride_width",
",",
"border_mode",
"=",
"border_mode",
",",
"groups",
"=",
"n_groups",
",",
"W",
"=",
"W",
",",
"b",
"=",
"Wb",
",",
"has_bias",
"=",
"has_bias",
",",
"is_deconv",
"=",
"False",
",",
"output_shape",
"=",
"None",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/coreml/converter/_layers.py#L337-L415 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/encoders.py | python | encode_7or8bit | (msg) | Set the Content-Transfer-Encoding header to 7bit or 8bit. | Set the Content-Transfer-Encoding header to 7bit or 8bit. | [
"Set",
"the",
"Content",
"-",
"Transfer",
"-",
"Encoding",
"header",
"to",
"7bit",
"or",
"8bit",
"."
] | def encode_7or8bit(msg):
"""Set the Content-Transfer-Encoding header to 7bit or 8bit."""
orig = msg.get_payload(decode=True)
if orig is None:
# There's no payload. For backwards compatibility we use 7bit
msg['Content-Transfer-Encoding'] = '7bit'
return
# We play a trick to make this go fast. If decoding from ASCII succeeds,
# we know the data must be 7bit, otherwise treat it as 8bit.
try:
orig.decode('ascii')
except UnicodeError:
msg['Content-Transfer-Encoding'] = '8bit'
else:
msg['Content-Transfer-Encoding'] = '7bit' | [
"def",
"encode_7or8bit",
"(",
"msg",
")",
":",
"orig",
"=",
"msg",
".",
"get_payload",
"(",
"decode",
"=",
"True",
")",
"if",
"orig",
"is",
"None",
":",
"# There's no payload. For backwards compatibility we use 7bit",
"msg",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"'7bit'",
"return",
"# We play a trick to make this go fast. If decoding from ASCII succeeds,",
"# we know the data must be 7bit, otherwise treat it as 8bit.",
"try",
":",
"orig",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"UnicodeError",
":",
"msg",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"'8bit'",
"else",
":",
"msg",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"'7bit'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/encoders.py#L50-L64 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/de2/nyan_subprocessor.py | python | DE2NyanSubprocessor._create_nyan_members | (cls, full_data_set) | Fill nyan member values of the API objects. | Fill nyan member values of the API objects. | [
"Fill",
"nyan",
"member",
"values",
"of",
"the",
"API",
"objects",
"."
] | def _create_nyan_members(cls, full_data_set):
"""
Fill nyan member values of the API objects.
"""
for unit_line in full_data_set.unit_lines.values():
unit_line.create_nyan_members()
for building_line in full_data_set.building_lines.values():
building_line.create_nyan_members()
for ambient_group in full_data_set.ambient_groups.values():
ambient_group.create_nyan_members()
for variant_group in full_data_set.variant_groups.values():
variant_group.create_nyan_members()
for tech_group in full_data_set.tech_groups.values():
tech_group.create_nyan_members()
for terrain_group in full_data_set.terrain_groups.values():
terrain_group.create_nyan_members()
for civ_group in full_data_set.civ_groups.values():
civ_group.create_nyan_members() | [
"def",
"_create_nyan_members",
"(",
"cls",
",",
"full_data_set",
")",
":",
"for",
"unit_line",
"in",
"full_data_set",
".",
"unit_lines",
".",
"values",
"(",
")",
":",
"unit_line",
".",
"create_nyan_members",
"(",
")",
"for",
"building_line",
"in",
"full_data_set",
".",
"building_lines",
".",
"values",
"(",
")",
":",
"building_line",
".",
"create_nyan_members",
"(",
")",
"for",
"ambient_group",
"in",
"full_data_set",
".",
"ambient_groups",
".",
"values",
"(",
")",
":",
"ambient_group",
".",
"create_nyan_members",
"(",
")",
"for",
"variant_group",
"in",
"full_data_set",
".",
"variant_groups",
".",
"values",
"(",
")",
":",
"variant_group",
".",
"create_nyan_members",
"(",
")",
"for",
"tech_group",
"in",
"full_data_set",
".",
"tech_groups",
".",
"values",
"(",
")",
":",
"tech_group",
".",
"create_nyan_members",
"(",
")",
"for",
"terrain_group",
"in",
"full_data_set",
".",
"terrain_groups",
".",
"values",
"(",
")",
":",
"terrain_group",
".",
"create_nyan_members",
"(",
")",
"for",
"civ_group",
"in",
"full_data_set",
".",
"civ_groups",
".",
"values",
"(",
")",
":",
"civ_group",
".",
"create_nyan_members",
"(",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/de2/nyan_subprocessor.py#L104-L127 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/persist/persistencemanager.py | python | PersistenceManager.Unregister | (self, window) | return True | Unregister the object, this is called by :class:`PersistenceManager` itself so there is
usually no need to do it explicitly.
:param `window`: an instance of :class:`Window`, which must have been previously
registered with :meth:`~PersistenceManager.Register`.
:note: For the persistent windows this is done automatically (via :meth:`~PersistenceManager.SaveAndUnregister`)
when the window is destroyed so you only need to call this function explicitly if you
are using custom persistent objects or if you want to prevent the object properties
from being saved.
:note: This deletes the associated :class:`PersistentObject`. | Unregister the object, this is called by :class:`PersistenceManager` itself so there is
usually no need to do it explicitly. | [
"Unregister",
"the",
"object",
"this",
"is",
"called",
"by",
":",
"class",
":",
"PersistenceManager",
"itself",
"so",
"there",
"is",
"usually",
"no",
"need",
"to",
"do",
"it",
"explicitly",
"."
] | def Unregister(self, window):
"""
Unregister the object, this is called by :class:`PersistenceManager` itself so there is
usually no need to do it explicitly.
:param `window`: an instance of :class:`Window`, which must have been previously
registered with :meth:`~PersistenceManager.Register`.
:note: For the persistent windows this is done automatically (via :meth:`~PersistenceManager.SaveAndUnregister`)
when the window is destroyed so you only need to call this function explicitly if you
are using custom persistent objects or if you want to prevent the object properties
from being saved.
:note: This deletes the associated :class:`PersistentObject`.
"""
if not self.Find(window):
return False
name = window.GetName()
self._persistentObjects.pop(name)
return True | [
"def",
"Unregister",
"(",
"self",
",",
"window",
")",
":",
"if",
"not",
"self",
".",
"Find",
"(",
"window",
")",
":",
"return",
"False",
"name",
"=",
"window",
".",
"GetName",
"(",
")",
"self",
".",
"_persistentObjects",
".",
"pop",
"(",
"name",
")",
"return",
"True"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/persist/persistencemanager.py#L475-L497 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListCtrl.SetGradientStyle | (self, vertical=0) | Sets the gradient style for gradient-style selections.
:param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
gradient-style selections. | Sets the gradient style for gradient-style selections. | [
"Sets",
"the",
"gradient",
"style",
"for",
"gradient",
"-",
"style",
"selections",
"."
] | def SetGradientStyle(self, vertical=0):
"""
Sets the gradient style for gradient-style selections.
:param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
gradient-style selections.
"""
self._mainWin.SetGradientStyle(vertical) | [
"def",
"SetGradientStyle",
"(",
"self",
",",
"vertical",
"=",
"0",
")",
":",
"self",
".",
"_mainWin",
".",
"SetGradientStyle",
"(",
"vertical",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L13207-L13215 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | unique | (ar, return_index=False, return_inverse=False, return_counts=False, axis=None) | return _npi.unique(ar, return_index, return_inverse, return_counts, axis) | Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional
outputs in addition to the unique elements:
* the indices of the input array that give the unique values
* the indices of the unique array that reconstruct the input array
* the number of times each unique value comes up in the input array
Parameters
----------
ar : _Symbol
Input array. Unless `axis` is specified, this will be flattened if it
is not already 1-D.
return_index : bool, optional
If True, also return the indices of `ar` (along the specified axis,
if provided, or in the flattened array) that result in the unique array.
return_inverse : bool, optional
If True, also return the indices of the unique array (for the specified
axis, if provided) that can be used to reconstruct `ar`.
return_counts : bool, optional
If True, also return the number of times each unique item appears
in `ar`.
axis : int or None, optional
The axis to operate on. If None, `ar` will be flattened. If an integer,
the subarrays indexed by the given axis will be flattened and treated
as the elements of a 1-D array with the dimension of the given axis,
see the notes for more details. The default is None.
Returns
-------
unique : _Symbol
The sorted unique values.
unique_indices : _Symbol, optional
The indices of the first occurrences of the unique values in the
original array. Only provided if `return_index` is True.
unique_inverse : _Symbol, optional
The indices to reconstruct the original array from the
unique array. Only provided if `return_inverse` is True.
unique_counts : _Symbol, optional
The number of times each of the unique values comes up in the
original array. Only provided if `return_counts` is True.
Notes
-----
When an axis is specified the subarrays indexed by the axis are sorted.
This is done by making the specified axis the first dimension of the array
and then flattening the subarrays in C order. The flattened subarrays are
then viewed as a structured type with each element given a label, with the
effect that we end up with a 1-D array of structured types that can be
treated in the same way as any other 1-D array. The result is that the
flattened subarrays are sorted in lexicographic order starting with the
first element. | Find the unique elements of an array. | [
"Find",
"the",
"unique",
"elements",
"of",
"an",
"array",
"."
] | def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None):
"""
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional
outputs in addition to the unique elements:
* the indices of the input array that give the unique values
* the indices of the unique array that reconstruct the input array
* the number of times each unique value comes up in the input array
Parameters
----------
ar : _Symbol
Input array. Unless `axis` is specified, this will be flattened if it
is not already 1-D.
return_index : bool, optional
If True, also return the indices of `ar` (along the specified axis,
if provided, or in the flattened array) that result in the unique array.
return_inverse : bool, optional
If True, also return the indices of the unique array (for the specified
axis, if provided) that can be used to reconstruct `ar`.
return_counts : bool, optional
If True, also return the number of times each unique item appears
in `ar`.
axis : int or None, optional
The axis to operate on. If None, `ar` will be flattened. If an integer,
the subarrays indexed by the given axis will be flattened and treated
as the elements of a 1-D array with the dimension of the given axis,
see the notes for more details. The default is None.
Returns
-------
unique : _Symbol
The sorted unique values.
unique_indices : _Symbol, optional
The indices of the first occurrences of the unique values in the
original array. Only provided if `return_index` is True.
unique_inverse : _Symbol, optional
The indices to reconstruct the original array from the
unique array. Only provided if `return_inverse` is True.
unique_counts : _Symbol, optional
The number of times each of the unique values comes up in the
original array. Only provided if `return_counts` is True.
Notes
-----
When an axis is specified the subarrays indexed by the axis are sorted.
This is done by making the specified axis the first dimension of the array
and then flattening the subarrays in C order. The flattened subarrays are
then viewed as a structured type with each element given a label, with the
effect that we end up with a 1-D array of structured types that can be
treated in the same way as any other 1-D array. The result is that the
flattened subarrays are sorted in lexicographic order starting with the
first element.
"""
return _npi.unique(ar, return_index, return_inverse, return_counts, axis) | [
"def",
"unique",
"(",
"ar",
",",
"return_index",
"=",
"False",
",",
"return_inverse",
"=",
"False",
",",
"return_counts",
"=",
"False",
",",
"axis",
"=",
"None",
")",
":",
"return",
"_npi",
".",
"unique",
"(",
"ar",
",",
"return_index",
",",
"return_inverse",
",",
"return_counts",
",",
"axis",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L6008-L6064 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/math_grad.py | python | _MaximumGrad | (op, grad) | return _MaximumMinimumGrad(op, grad, math_ops.greater_equal) | Returns grad*(x > y, x <= y) with type of grad. | Returns grad*(x > y, x <= y) with type of grad. | [
"Returns",
"grad",
"*",
"(",
"x",
">",
"y",
"x",
"<",
"=",
"y",
")",
"with",
"type",
"of",
"grad",
"."
] | def _MaximumGrad(op, grad):
"""Returns grad*(x > y, x <= y) with type of grad."""
return _MaximumMinimumGrad(op, grad, math_ops.greater_equal) | [
"def",
"_MaximumGrad",
"(",
"op",
",",
"grad",
")",
":",
"return",
"_MaximumMinimumGrad",
"(",
"op",
",",
"grad",
",",
"math_ops",
".",
"greater_equal",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_grad.py#L813-L815 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | Group.GetGroupNames | (self, *args) | return _gdal.Group_GetGroupNames(self, *args) | r"""GetGroupNames(Group self, char ** options=None) -> char ** | r"""GetGroupNames(Group self, char ** options=None) -> char ** | [
"r",
"GetGroupNames",
"(",
"Group",
"self",
"char",
"**",
"options",
"=",
"None",
")",
"-",
">",
"char",
"**"
] | def GetGroupNames(self, *args):
r"""GetGroupNames(Group self, char ** options=None) -> char **"""
return _gdal.Group_GetGroupNames(self, *args) | [
"def",
"GetGroupNames",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"Group_GetGroupNames",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2607-L2609 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dygraph/dygraph_to_static/function_spec.py | python | FunctionSpec.unified_args_and_kwargs | (self, args, kwargs) | return tuple(args), kwargs | Moves kwargs with default value into arguments list to keep `args` contain the same length
value as function definition.
For example:
Given function definition: `def foo(x, a=1, b=2)`,
when calling it by `foo(23)`, the args is `[23]`, kwargs is `{a=1, b=2}`.
In this function, it will return args with `[23, 1, 2]`, kwargs with `{}`
Args:
args(tuple): tuple of input arguments value of decorated function.
kwargs(dict): dict of input keyword arguments value of decorated function.
Return:
New arguments tuple containing default kwargs value. | Moves kwargs with default value into arguments list to keep `args` contain the same length
value as function definition. | [
"Moves",
"kwargs",
"with",
"default",
"value",
"into",
"arguments",
"list",
"to",
"keep",
"args",
"contain",
"the",
"same",
"length",
"value",
"as",
"function",
"definition",
"."
] | def unified_args_and_kwargs(self, args, kwargs):
"""
Moves kwargs with default value into arguments list to keep `args` contain the same length
value as function definition.
For example:
Given function definition: `def foo(x, a=1, b=2)`,
when calling it by `foo(23)`, the args is `[23]`, kwargs is `{a=1, b=2}`.
In this function, it will return args with `[23, 1, 2]`, kwargs with `{}`
Args:
args(tuple): tuple of input arguments value of decorated function.
kwargs(dict): dict of input keyword arguments value of decorated function.
Return:
New arguments tuple containing default kwargs value.
"""
if len(self._arg_names) < len(args):
error_msg = "The decorated function `{}` requires {} arguments: {}, but received {} with {}.".format(
self._dygraph_function.__name__,
len(self._arg_names), self._arg_names, len(args), args)
if args and inspect.isclass(args[0]):
error_msg += "\n\tMaybe the function has more than one decorator, we don't support this for now."
raise NotImplementedError(error_msg)
else:
raise ValueError(error_msg)
args = list(args)
for i in six.moves.range(len(args), len(self._arg_names)):
arg_name = self._arg_names[i]
if arg_name in kwargs:
args.append(kwargs[arg_name])
del kwargs[arg_name]
else:
if arg_name not in self._default_kwargs:
raise ValueError(
"`{}()` requires `{}` arguments, but not found in input `args`: {} and `kwargs`: {}.".
format(self._dygraph_function.__name__, arg_name, args,
kwargs))
args.append(self._default_kwargs[arg_name])
return tuple(args), kwargs | [
"def",
"unified_args_and_kwargs",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"len",
"(",
"self",
".",
"_arg_names",
")",
"<",
"len",
"(",
"args",
")",
":",
"error_msg",
"=",
"\"The decorated function `{}` requires {} arguments: {}, but received {} with {}.\"",
".",
"format",
"(",
"self",
".",
"_dygraph_function",
".",
"__name__",
",",
"len",
"(",
"self",
".",
"_arg_names",
")",
",",
"self",
".",
"_arg_names",
",",
"len",
"(",
"args",
")",
",",
"args",
")",
"if",
"args",
"and",
"inspect",
".",
"isclass",
"(",
"args",
"[",
"0",
"]",
")",
":",
"error_msg",
"+=",
"\"\\n\\tMaybe the function has more than one decorator, we don't support this for now.\"",
"raise",
"NotImplementedError",
"(",
"error_msg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"error_msg",
")",
"args",
"=",
"list",
"(",
"args",
")",
"for",
"i",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"len",
"(",
"args",
")",
",",
"len",
"(",
"self",
".",
"_arg_names",
")",
")",
":",
"arg_name",
"=",
"self",
".",
"_arg_names",
"[",
"i",
"]",
"if",
"arg_name",
"in",
"kwargs",
":",
"args",
".",
"append",
"(",
"kwargs",
"[",
"arg_name",
"]",
")",
"del",
"kwargs",
"[",
"arg_name",
"]",
"else",
":",
"if",
"arg_name",
"not",
"in",
"self",
".",
"_default_kwargs",
":",
"raise",
"ValueError",
"(",
"\"`{}()` requires `{}` arguments, but not found in input `args`: {} and `kwargs`: {}.\"",
".",
"format",
"(",
"self",
".",
"_dygraph_function",
".",
"__name__",
",",
"arg_name",
",",
"args",
",",
"kwargs",
")",
")",
"args",
".",
"append",
"(",
"self",
".",
"_default_kwargs",
"[",
"arg_name",
"]",
")",
"return",
"tuple",
"(",
"args",
")",
",",
"kwargs"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/function_spec.py#L56-L99 | |
OAID/Caffe-HRT | aae71e498ab842c6f92bcc23fc668423615a4d65 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | PascalMultilabelDataLayerSync.backward | (self, top, propagate_down, bottom) | These layers does not back propagate | These layers does not back propagate | [
"These",
"layers",
"does",
"not",
"back",
"propagate"
] | def backward(self, top, propagate_down, bottom):
"""
These layers does not back propagate
"""
pass | [
"def",
"backward",
"(",
"self",
",",
"top",
",",
"propagate_down",
",",
"bottom",
")",
":",
"pass"
] | https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L74-L78 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/calibration.py | python | _SigmoidCalibration.predict | (self, T) | return 1. / (1. + np.exp(self.a_ * T + self.b_)) | Predict new data by linear interpolation.
Parameters
----------
T : array-like, shape (n_samples,)
Data to predict from.
Returns
-------
T_ : array, shape (n_samples,)
The predicted data. | Predict new data by linear interpolation. | [
"Predict",
"new",
"data",
"by",
"linear",
"interpolation",
"."
] | def predict(self, T):
"""Predict new data by linear interpolation.
Parameters
----------
T : array-like, shape (n_samples,)
Data to predict from.
Returns
-------
T_ : array, shape (n_samples,)
The predicted data.
"""
T = column_or_1d(T)
return 1. / (1. + np.exp(self.a_ * T + self.b_)) | [
"def",
"predict",
"(",
"self",
",",
"T",
")",
":",
"T",
"=",
"column_or_1d",
"(",
"T",
")",
"return",
"1.",
"/",
"(",
"1.",
"+",
"np",
".",
"exp",
"(",
"self",
".",
"a_",
"*",
"T",
"+",
"self",
".",
"b_",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/calibration.py#L493-L507 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/cookielib.py | python | request_path | (request) | return req_path | request-URI, as defined by RFC 2965. | request-URI, as defined by RFC 2965. | [
"request",
"-",
"URI",
"as",
"defined",
"by",
"RFC",
"2965",
"."
] | def request_path(request):
"""request-URI, as defined by RFC 2965."""
url = request.get_full_url()
#scheme, netloc, path, parameters, query, frag = urlparse.urlparse(url)
#req_path = escape_path("".join(urlparse.urlparse(url)[2:]))
path, parameters, query, frag = urlparse.urlparse(url)[2:]
if parameters:
path = "%s;%s" % (path, parameters)
path = escape_path(path)
req_path = urlparse.urlunparse(("", "", path, "", query, frag))
if not req_path.startswith("/"):
# fix bad RFC 2396 absoluteURI
req_path = "/"+req_path
return req_path | [
"def",
"request_path",
"(",
"request",
")",
":",
"url",
"=",
"request",
".",
"get_full_url",
"(",
")",
"#scheme, netloc, path, parameters, query, frag = urlparse.urlparse(url)",
"#req_path = escape_path(\"\".join(urlparse.urlparse(url)[2:]))",
"path",
",",
"parameters",
",",
"query",
",",
"frag",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"[",
"2",
":",
"]",
"if",
"parameters",
":",
"path",
"=",
"\"%s;%s\"",
"%",
"(",
"path",
",",
"parameters",
")",
"path",
"=",
"escape_path",
"(",
"path",
")",
"req_path",
"=",
"urlparse",
".",
"urlunparse",
"(",
"(",
"\"\"",
",",
"\"\"",
",",
"path",
",",
"\"\"",
",",
"query",
",",
"frag",
")",
")",
"if",
"not",
"req_path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"# fix bad RFC 2396 absoluteURI",
"req_path",
"=",
"\"/\"",
"+",
"req_path",
"return",
"req_path"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/cookielib.py#L603-L616 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/core.py | python | MaskedArray.__int__ | (self) | return int(self.item()) | Convert to int. | Convert to int. | [
"Convert",
"to",
"int",
"."
] | def __int__(self):
"""
Convert to int.
"""
if self.size > 1:
raise TypeError("Only length-1 arrays can be converted "
"to Python scalars")
elif self._mask:
raise MaskError('Cannot convert masked element to a Python int.')
return int(self.item()) | [
"def",
"__int__",
"(",
"self",
")",
":",
"if",
"self",
".",
"size",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"Only length-1 arrays can be converted \"",
"\"to Python scalars\"",
")",
"elif",
"self",
".",
"_mask",
":",
"raise",
"MaskError",
"(",
"'Cannot convert masked element to a Python int.'",
")",
"return",
"int",
"(",
"self",
".",
"item",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L4375-L4385 | |
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/sanitizers/sancov_formatter.py | python | write_instrumented | (options) | Implements the 'all' action of this tool. | Implements the 'all' action of this tool. | [
"Implements",
"the",
"all",
"action",
"of",
"this",
"tool",
"."
] | def write_instrumented(options):
"""Implements the 'all' action of this tool."""
exe_list = list(executables(options.build_dir))
logging.info('Reading instrumented lines from %d executables.',
len(exe_list))
pool = Pool(CPUS)
try:
results = pool.imap_unordered(get_instrumented_lines, exe_list)
finally:
pool.close()
# Merge multiprocessing results and prepare output data.
data = merge_instrumented_line_results(exe_list, results)
logging.info('Read data from %d executables, which covers %d files.',
len(data['tests']), len(data['files']))
logging.info('Writing results to %s', options.json_output)
# Write json output.
with open(options.json_output, 'w') as f:
json.dump(data, f, sort_keys=True) | [
"def",
"write_instrumented",
"(",
"options",
")",
":",
"exe_list",
"=",
"list",
"(",
"executables",
"(",
"options",
".",
"build_dir",
")",
")",
"logging",
".",
"info",
"(",
"'Reading instrumented lines from %d executables.'",
",",
"len",
"(",
"exe_list",
")",
")",
"pool",
"=",
"Pool",
"(",
"CPUS",
")",
"try",
":",
"results",
"=",
"pool",
".",
"imap_unordered",
"(",
"get_instrumented_lines",
",",
"exe_list",
")",
"finally",
":",
"pool",
".",
"close",
"(",
")",
"# Merge multiprocessing results and prepare output data.",
"data",
"=",
"merge_instrumented_line_results",
"(",
"exe_list",
",",
"results",
")",
"logging",
".",
"info",
"(",
"'Read data from %d executables, which covers %d files.'",
",",
"len",
"(",
"data",
"[",
"'tests'",
"]",
")",
",",
"len",
"(",
"data",
"[",
"'files'",
"]",
")",
")",
"logging",
".",
"info",
"(",
"'Writing results to %s'",
",",
"options",
".",
"json_output",
")",
"# Write json output.",
"with",
"open",
"(",
"options",
".",
"json_output",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"data",
",",
"f",
",",
"sort_keys",
"=",
"True",
")"
] | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/sanitizers/sancov_formatter.py#L218-L238 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py3/pygments/formatters/img.py | python | ImageFormatter._paint_line_number_bg | (self, im) | Paint the line number background on the image. | Paint the line number background on the image. | [
"Paint",
"the",
"line",
"number",
"background",
"on",
"the",
"image",
"."
] | def _paint_line_number_bg(self, im):
"""
Paint the line number background on the image.
"""
if not self.line_numbers:
return
if self.line_number_fg is None:
return
draw = ImageDraw.Draw(im)
recth = im.size[-1]
rectw = self.image_pad + self.line_number_width - self.line_number_pad
draw.rectangle([(0, 0), (rectw, recth)],
fill=self.line_number_bg)
if self.line_number_separator:
draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)
del draw | [
"def",
"_paint_line_number_bg",
"(",
"self",
",",
"im",
")",
":",
"if",
"not",
"self",
".",
"line_numbers",
":",
"return",
"if",
"self",
".",
"line_number_fg",
"is",
"None",
":",
"return",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"im",
")",
"recth",
"=",
"im",
".",
"size",
"[",
"-",
"1",
"]",
"rectw",
"=",
"self",
".",
"image_pad",
"+",
"self",
".",
"line_number_width",
"-",
"self",
".",
"line_number_pad",
"draw",
".",
"rectangle",
"(",
"[",
"(",
"0",
",",
"0",
")",
",",
"(",
"rectw",
",",
"recth",
")",
"]",
",",
"fill",
"=",
"self",
".",
"line_number_bg",
")",
"if",
"self",
".",
"line_number_separator",
":",
"draw",
".",
"line",
"(",
"[",
"(",
"rectw",
",",
"0",
")",
",",
"(",
"rectw",
",",
"recth",
")",
"]",
",",
"fill",
"=",
"self",
".",
"line_number_fg",
")",
"del",
"draw"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/formatters/img.py#L548-L563 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/altgraph/altgraph/GraphAlgo.py | python | dijkstra | (graph, start, end=None) | return (D,P) | Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the end node.
Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.
This code does not verify this property for all edges (only the edges examined until the end
vertex is reached), but will correctly compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.
*Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004* | Dijkstra's algorithm for shortest paths | [
"Dijkstra",
"s",
"algorithm",
"for",
"shortest",
"paths"
] | def dijkstra(graph, start, end=None):
"""
Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the end node.
Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.
This code does not verify this property for all edges (only the edges examined until the end
vertex is reached), but will correctly compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.
*Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004*
"""
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = _priorityDictionary() # estimated distances of non-final vertices
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in graph.out_nbrs(v):
edge_id = graph.edge_by_node(v,w)
vwLength = D[v] + graph.edge_data(edge_id)
if w in D:
if vwLength < D[w]:
raise GraphError("Dijkstra: found better path to already-final vertex")
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return (D,P) | [
"def",
"dijkstra",
"(",
"graph",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"D",
"=",
"{",
"}",
"# dictionary of final distances",
"P",
"=",
"{",
"}",
"# dictionary of predecessors",
"Q",
"=",
"_priorityDictionary",
"(",
")",
"# estimated distances of non-final vertices",
"Q",
"[",
"start",
"]",
"=",
"0",
"for",
"v",
"in",
"Q",
":",
"D",
"[",
"v",
"]",
"=",
"Q",
"[",
"v",
"]",
"if",
"v",
"==",
"end",
":",
"break",
"for",
"w",
"in",
"graph",
".",
"out_nbrs",
"(",
"v",
")",
":",
"edge_id",
"=",
"graph",
".",
"edge_by_node",
"(",
"v",
",",
"w",
")",
"vwLength",
"=",
"D",
"[",
"v",
"]",
"+",
"graph",
".",
"edge_data",
"(",
"edge_id",
")",
"if",
"w",
"in",
"D",
":",
"if",
"vwLength",
"<",
"D",
"[",
"w",
"]",
":",
"raise",
"GraphError",
"(",
"\"Dijkstra: found better path to already-final vertex\"",
")",
"elif",
"w",
"not",
"in",
"Q",
"or",
"vwLength",
"<",
"Q",
"[",
"w",
"]",
":",
"Q",
"[",
"w",
"]",
"=",
"vwLength",
"P",
"[",
"w",
"]",
"=",
"v",
"return",
"(",
"D",
",",
"P",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/GraphAlgo.py#L7-L44 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/tools/clang/utils/check_cfc/check_cfc.py | python | replace_output_file | (args, new_name) | return args | Replaces the specified name of an output file with the specified name.
Assumes that the output file name is specified in the command line args. | Replaces the specified name of an output file with the specified name.
Assumes that the output file name is specified in the command line args. | [
"Replaces",
"the",
"specified",
"name",
"of",
"an",
"output",
"file",
"with",
"the",
"specified",
"name",
".",
"Assumes",
"that",
"the",
"output",
"file",
"name",
"is",
"specified",
"in",
"the",
"command",
"line",
"args",
"."
] | def replace_output_file(args, new_name):
"""Replaces the specified name of an output file with the specified name.
Assumes that the output file name is specified in the command line args."""
replaceidx = None
attached = False
for idx, val in enumerate(args):
if val == '-o':
replaceidx = idx + 1
attached = False
elif val.startswith('-o'):
replaceidx = idx
attached = True
if replaceidx is None:
raise Exception
replacement = new_name
if attached == True:
replacement = '-o' + new_name
args[replaceidx] = replacement
return args | [
"def",
"replace_output_file",
"(",
"args",
",",
"new_name",
")",
":",
"replaceidx",
"=",
"None",
"attached",
"=",
"False",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"val",
"==",
"'-o'",
":",
"replaceidx",
"=",
"idx",
"+",
"1",
"attached",
"=",
"False",
"elif",
"val",
".",
"startswith",
"(",
"'-o'",
")",
":",
"replaceidx",
"=",
"idx",
"attached",
"=",
"True",
"if",
"replaceidx",
"is",
"None",
":",
"raise",
"Exception",
"replacement",
"=",
"new_name",
"if",
"attached",
"==",
"True",
":",
"replacement",
"=",
"'-o'",
"+",
"new_name",
"args",
"[",
"replaceidx",
"]",
"=",
"replacement",
"return",
"args"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/utils/check_cfc/check_cfc.py#L151-L170 | |
vesoft-inc/nebula | 25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35 | .linters/cpp/cpplint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L1315-L1317 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/utility.py | python | ArrayManager.turnover | (self) | return self.turnover_array | Get trading turnover time series. | Get trading turnover time series. | [
"Get",
"trading",
"turnover",
"time",
"series",
"."
] | def turnover(self) -> np.ndarray:
"""
Get trading turnover time series.
"""
return self.turnover_array | [
"def",
"turnover",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"self",
".",
"turnover_array"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/utility.py#L516-L520 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/driver.py | python | _make_mem_finalizer | (dtor) | return mem_finalize | finalises memory
Parameters:
dtor a function that will delete/free held memory from a reference
Returns:
Finalising function | finalises memory
Parameters:
dtor a function that will delete/free held memory from a reference | [
"finalises",
"memory",
"Parameters",
":",
"dtor",
"a",
"function",
"that",
"will",
"delete",
"/",
"free",
"held",
"memory",
"from",
"a",
"reference"
] | def _make_mem_finalizer(dtor):
"""
finalises memory
Parameters:
dtor a function that will delete/free held memory from a reference
Returns:
Finalising function
"""
def mem_finalize(context, handle):
allocations = context.allocations
sync = hsa.implicit_sync
def core():
_logger.info("Current allocations: %s", allocations)
if allocations:
_logger.info("Attempting delete on %s" % handle.value)
del allocations[handle.value]
sync() # implicit sync
dtor(handle)
return core
return mem_finalize | [
"def",
"_make_mem_finalizer",
"(",
"dtor",
")",
":",
"def",
"mem_finalize",
"(",
"context",
",",
"handle",
")",
":",
"allocations",
"=",
"context",
".",
"allocations",
"sync",
"=",
"hsa",
".",
"implicit_sync",
"def",
"core",
"(",
")",
":",
"_logger",
".",
"info",
"(",
"\"Current allocations: %s\"",
",",
"allocations",
")",
"if",
"allocations",
":",
"_logger",
".",
"info",
"(",
"\"Attempting delete on %s\"",
"%",
"handle",
".",
"value",
")",
"del",
"allocations",
"[",
"handle",
".",
"value",
"]",
"sync",
"(",
")",
"# implicit sync",
"dtor",
"(",
"handle",
")",
"return",
"core",
"return",
"mem_finalize"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/hsadrv/driver.py#L1400-L1422 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/combo.py | python | ComboCtrl.UseAltPopupWindow | (*args, **kwargs) | return _combo.ComboCtrl_UseAltPopupWindow(*args, **kwargs) | UseAltPopupWindow(self, bool enable=True)
Enable or disable usage of an alternative popup window, which
guarantees ability to focus the popup control, and allows common
native controls to function normally. This alternative popup window is
usually a wxDialog, and as such, when it is shown, its parent
top-level window will appear as if the focus has been lost from it. | UseAltPopupWindow(self, bool enable=True) | [
"UseAltPopupWindow",
"(",
"self",
"bool",
"enable",
"=",
"True",
")"
] | def UseAltPopupWindow(*args, **kwargs):
"""
UseAltPopupWindow(self, bool enable=True)
Enable or disable usage of an alternative popup window, which
guarantees ability to focus the popup control, and allows common
native controls to function normally. This alternative popup window is
usually a wxDialog, and as such, when it is shown, its parent
top-level window will appear as if the focus has been lost from it.
"""
return _combo.ComboCtrl_UseAltPopupWindow(*args, **kwargs) | [
"def",
"UseAltPopupWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboCtrl_UseAltPopupWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L386-L396 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py3/more_itertools/recipes.py | python | ncycles | (iterable, n) | return chain.from_iterable(repeat(tuple(iterable), n)) | Returns the sequence elements *n* times
>>> list(ncycles(["a", "b"], 3))
['a', 'b', 'a', 'b', 'a', 'b'] | Returns the sequence elements *n* times | [
"Returns",
"the",
"sequence",
"elements",
"*",
"n",
"*",
"times"
] | def ncycles(iterable, n):
"""Returns the sequence elements *n* times
>>> list(ncycles(["a", "b"], 3))
['a', 'b', 'a', 'b', 'a', 'b']
"""
return chain.from_iterable(repeat(tuple(iterable), n)) | [
"def",
"ncycles",
"(",
"iterable",
",",
"n",
")",
":",
"return",
"chain",
".",
"from_iterable",
"(",
"repeat",
"(",
"tuple",
"(",
"iterable",
")",
",",
"n",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py3/more_itertools/recipes.py#L202-L209 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.unbind | (self, sequence, funcid=None) | Unbind for this widget for event SEQUENCE the
function identified with FUNCID. | Unbind for this widget for event SEQUENCE the
function identified with FUNCID. | [
"Unbind",
"for",
"this",
"widget",
"for",
"event",
"SEQUENCE",
"the",
"function",
"identified",
"with",
"FUNCID",
"."
] | def unbind(self, sequence, funcid=None):
"""Unbind for this widget for event SEQUENCE the
function identified with FUNCID."""
self.tk.call('bind', self._w, sequence, '')
if funcid:
self.deletecommand(funcid) | [
"def",
"unbind",
"(",
"self",
",",
"sequence",
",",
"funcid",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'bind'",
",",
"self",
".",
"_w",
",",
"sequence",
",",
"''",
")",
"if",
"funcid",
":",
"self",
".",
"deletecommand",
"(",
"funcid",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1037-L1042 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py | python | SMTPHandler.emit | (self, record) | Emit a record.
Format the record and send it to the specified addressees. | Emit a record. | [
"Emit",
"a",
"record",
"."
] | def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
from email.message import EmailMessage
import email.utils
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
msg = EmailMessage()
msg['From'] = self.fromaddr
msg['To'] = ','.join(self.toaddrs)
msg['Subject'] = self.getSubject(record)
msg['Date'] = email.utils.localtime()
msg.set_content(self.format(record))
if self.username:
if self.secure is not None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.send_message(msg)
smtp.quit()
except Exception:
self.handleError(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"import",
"smtplib",
"from",
"email",
".",
"message",
"import",
"EmailMessage",
"import",
"email",
".",
"utils",
"port",
"=",
"self",
".",
"mailport",
"if",
"not",
"port",
":",
"port",
"=",
"smtplib",
".",
"SMTP_PORT",
"smtp",
"=",
"smtplib",
".",
"SMTP",
"(",
"self",
".",
"mailhost",
",",
"port",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"msg",
"=",
"EmailMessage",
"(",
")",
"msg",
"[",
"'From'",
"]",
"=",
"self",
".",
"fromaddr",
"msg",
"[",
"'To'",
"]",
"=",
"','",
".",
"join",
"(",
"self",
".",
"toaddrs",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"self",
".",
"getSubject",
"(",
"record",
")",
"msg",
"[",
"'Date'",
"]",
"=",
"email",
".",
"utils",
".",
"localtime",
"(",
")",
"msg",
".",
"set_content",
"(",
"self",
".",
"format",
"(",
"record",
")",
")",
"if",
"self",
".",
"username",
":",
"if",
"self",
".",
"secure",
"is",
"not",
"None",
":",
"smtp",
".",
"ehlo",
"(",
")",
"smtp",
".",
"starttls",
"(",
"*",
"self",
".",
"secure",
")",
"smtp",
".",
"ehlo",
"(",
")",
"smtp",
".",
"login",
"(",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"smtp",
".",
"send_message",
"(",
"msg",
")",
"smtp",
".",
"quit",
"(",
")",
"except",
"Exception",
":",
"self",
".",
"handleError",
"(",
"record",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py#L994-L1024 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py | python | QuantileTransformer._transform_col | (self, X_col, quantiles, inverse) | return X_col | Private function to transform a single feature | Private function to transform a single feature | [
"Private",
"function",
"to",
"transform",
"a",
"single",
"feature"
] | def _transform_col(self, X_col, quantiles, inverse):
"""Private function to transform a single feature"""
output_distribution = self.output_distribution
if not inverse:
lower_bound_x = quantiles[0]
upper_bound_x = quantiles[-1]
lower_bound_y = 0
upper_bound_y = 1
else:
lower_bound_x = 0
upper_bound_x = 1
lower_bound_y = quantiles[0]
upper_bound_y = quantiles[-1]
# for inverse transform, match a uniform distribution
with np.errstate(invalid='ignore'): # hide NaN comparison warnings
if output_distribution == 'normal':
X_col = stats.norm.cdf(X_col)
# else output distribution is already a uniform distribution
# find index for lower and higher bounds
with np.errstate(invalid='ignore'): # hide NaN comparison warnings
if output_distribution == 'normal':
lower_bounds_idx = (X_col - BOUNDS_THRESHOLD <
lower_bound_x)
upper_bounds_idx = (X_col + BOUNDS_THRESHOLD >
upper_bound_x)
if output_distribution == 'uniform':
lower_bounds_idx = (X_col == lower_bound_x)
upper_bounds_idx = (X_col == upper_bound_x)
isfinite_mask = ~np.isnan(X_col)
X_col_finite = X_col[isfinite_mask]
if not inverse:
# Interpolate in one direction and in the other and take the
# mean. This is in case of repeated values in the features
# and hence repeated quantiles
#
# If we don't do this, only one extreme of the duplicated is
# used (the upper when we do ascending, and the
# lower for descending). We take the mean of these two
X_col[isfinite_mask] = .5 * (
np.interp(X_col_finite, quantiles, self.references_)
- np.interp(-X_col_finite, -quantiles[::-1],
-self.references_[::-1]))
else:
X_col[isfinite_mask] = np.interp(X_col_finite,
self.references_, quantiles)
X_col[upper_bounds_idx] = upper_bound_y
X_col[lower_bounds_idx] = lower_bound_y
# for forward transform, match the output distribution
if not inverse:
with np.errstate(invalid='ignore'): # hide NaN comparison warnings
if output_distribution == 'normal':
X_col = stats.norm.ppf(X_col)
# find the value to clip the data to avoid mapping to
# infinity. Clip such that the inverse transform will be
# consistent
clip_min = stats.norm.ppf(BOUNDS_THRESHOLD - np.spacing(1))
clip_max = stats.norm.ppf(1 - (BOUNDS_THRESHOLD -
np.spacing(1)))
X_col = np.clip(X_col, clip_min, clip_max)
# else output distribution is uniform and the ppf is the
# identity function so we let X_col unchanged
return X_col | [
"def",
"_transform_col",
"(",
"self",
",",
"X_col",
",",
"quantiles",
",",
"inverse",
")",
":",
"output_distribution",
"=",
"self",
".",
"output_distribution",
"if",
"not",
"inverse",
":",
"lower_bound_x",
"=",
"quantiles",
"[",
"0",
"]",
"upper_bound_x",
"=",
"quantiles",
"[",
"-",
"1",
"]",
"lower_bound_y",
"=",
"0",
"upper_bound_y",
"=",
"1",
"else",
":",
"lower_bound_x",
"=",
"0",
"upper_bound_x",
"=",
"1",
"lower_bound_y",
"=",
"quantiles",
"[",
"0",
"]",
"upper_bound_y",
"=",
"quantiles",
"[",
"-",
"1",
"]",
"# for inverse transform, match a uniform distribution",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"# hide NaN comparison warnings",
"if",
"output_distribution",
"==",
"'normal'",
":",
"X_col",
"=",
"stats",
".",
"norm",
".",
"cdf",
"(",
"X_col",
")",
"# else output distribution is already a uniform distribution",
"# find index for lower and higher bounds",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"# hide NaN comparison warnings",
"if",
"output_distribution",
"==",
"'normal'",
":",
"lower_bounds_idx",
"=",
"(",
"X_col",
"-",
"BOUNDS_THRESHOLD",
"<",
"lower_bound_x",
")",
"upper_bounds_idx",
"=",
"(",
"X_col",
"+",
"BOUNDS_THRESHOLD",
">",
"upper_bound_x",
")",
"if",
"output_distribution",
"==",
"'uniform'",
":",
"lower_bounds_idx",
"=",
"(",
"X_col",
"==",
"lower_bound_x",
")",
"upper_bounds_idx",
"=",
"(",
"X_col",
"==",
"upper_bound_x",
")",
"isfinite_mask",
"=",
"~",
"np",
".",
"isnan",
"(",
"X_col",
")",
"X_col_finite",
"=",
"X_col",
"[",
"isfinite_mask",
"]",
"if",
"not",
"inverse",
":",
"# Interpolate in one direction and in the other and take the",
"# mean. This is in case of repeated values in the features",
"# and hence repeated quantiles",
"#",
"# If we don't do this, only one extreme of the duplicated is",
"# used (the upper when we do ascending, and the",
"# lower for descending). We take the mean of these two",
"X_col",
"[",
"isfinite_mask",
"]",
"=",
".5",
"*",
"(",
"np",
".",
"interp",
"(",
"X_col_finite",
",",
"quantiles",
",",
"self",
".",
"references_",
")",
"-",
"np",
".",
"interp",
"(",
"-",
"X_col_finite",
",",
"-",
"quantiles",
"[",
":",
":",
"-",
"1",
"]",
",",
"-",
"self",
".",
"references_",
"[",
":",
":",
"-",
"1",
"]",
")",
")",
"else",
":",
"X_col",
"[",
"isfinite_mask",
"]",
"=",
"np",
".",
"interp",
"(",
"X_col_finite",
",",
"self",
".",
"references_",
",",
"quantiles",
")",
"X_col",
"[",
"upper_bounds_idx",
"]",
"=",
"upper_bound_y",
"X_col",
"[",
"lower_bounds_idx",
"]",
"=",
"lower_bound_y",
"# for forward transform, match the output distribution",
"if",
"not",
"inverse",
":",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"# hide NaN comparison warnings",
"if",
"output_distribution",
"==",
"'normal'",
":",
"X_col",
"=",
"stats",
".",
"norm",
".",
"ppf",
"(",
"X_col",
")",
"# find the value to clip the data to avoid mapping to",
"# infinity. Clip such that the inverse transform will be",
"# consistent",
"clip_min",
"=",
"stats",
".",
"norm",
".",
"ppf",
"(",
"BOUNDS_THRESHOLD",
"-",
"np",
".",
"spacing",
"(",
"1",
")",
")",
"clip_max",
"=",
"stats",
".",
"norm",
".",
"ppf",
"(",
"1",
"-",
"(",
"BOUNDS_THRESHOLD",
"-",
"np",
".",
"spacing",
"(",
"1",
")",
")",
")",
"X_col",
"=",
"np",
".",
"clip",
"(",
"X_col",
",",
"clip_min",
",",
"clip_max",
")",
"# else output distribution is uniform and the ppf is the",
"# identity function so we let X_col unchanged",
"return",
"X_col"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py#L2372-L2439 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py | python | ParserElement.__rand__ | (self, other ) | return other & self | Implementation of & operator when left operand is not a C{L{ParserElement}} | Implementation of & operator when left operand is not a C{L{ParserElement}} | [
"Implementation",
"of",
"&",
"operator",
"when",
"left",
"operand",
"is",
"not",
"a",
"C",
"{",
"L",
"{",
"ParserElement",
"}}"
] | def __rand__(self, other ):
"""
Implementation of & operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"&",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py#L2008-L2018 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/Optimize.py | python | EarlyReplaceBuiltinCalls._handle_simple_function_frozenset | (self, node, pos_args) | return node | Replace frozenset([...]) by frozenset((...)) as tuples are more efficient. | Replace frozenset([...]) by frozenset((...)) as tuples are more efficient. | [
"Replace",
"frozenset",
"(",
"[",
"...",
"]",
")",
"by",
"frozenset",
"((",
"...",
"))",
"as",
"tuples",
"are",
"more",
"efficient",
"."
] | def _handle_simple_function_frozenset(self, node, pos_args):
"""Replace frozenset([...]) by frozenset((...)) as tuples are more efficient.
"""
if len(pos_args) != 1:
return node
if pos_args[0].is_sequence_constructor and not pos_args[0].args:
del pos_args[0]
elif isinstance(pos_args[0], ExprNodes.ListNode):
pos_args[0] = pos_args[0].as_tuple()
return node | [
"def",
"_handle_simple_function_frozenset",
"(",
"self",
",",
"node",
",",
"pos_args",
")",
":",
"if",
"len",
"(",
"pos_args",
")",
"!=",
"1",
":",
"return",
"node",
"if",
"pos_args",
"[",
"0",
"]",
".",
"is_sequence_constructor",
"and",
"not",
"pos_args",
"[",
"0",
"]",
".",
"args",
":",
"del",
"pos_args",
"[",
"0",
"]",
"elif",
"isinstance",
"(",
"pos_args",
"[",
"0",
"]",
",",
"ExprNodes",
".",
"ListNode",
")",
":",
"pos_args",
"[",
"0",
"]",
"=",
"pos_args",
"[",
"0",
"]",
".",
"as_tuple",
"(",
")",
"return",
"node"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/Optimize.py#L1896-L1905 | |
ufal/udpipe | e51f02d2744cdfd4a29efc1320644ea04d535f0b | doc/t2t_docsys/txt2tags.py | python | ConfigLines.parse_line | (self, line='', keyname='', target='') | return [target, name, value] | Detects %!key:val config lines and extract data from it | Detects %!key:val config lines and extract data from it | [
"Detects",
"%!key",
":",
"val",
"config",
"lines",
"and",
"extract",
"data",
"from",
"it"
] | def parse_line(self, line='', keyname='', target=''):
"Detects %!key:val config lines and extract data from it"
empty = ['', '', '']
if not line: return empty
no_target = ['target', 'includeconf']
re_name = keyname or '[a-z]+'
re_target = target or '[a-z]*'
# XXX TODO <value>\S.+? requires TWO chars, breaks %!include:a
cfgregex = re.compile("""
^%%!\s* # leading id with opt spaces
(?P<name>%s)\s* # config name
(\((?P<target>%s)\))? # optional target spec inside ()
\s*:\s* # key:value delimiter with opt spaces
(?P<value>\S.+?) # config value
\s*$ # rstrip() spaces and hit EOL
"""%(re_name, re_target), re.I+re.VERBOSE)
prepostregex = re.compile("""
# ---[ PATTERN ]---
^( "([^"]*)" # "double quoted" or
| '([^']*)' # 'single quoted' or
| ([^\s]+) # single_word
)
\s+ # separated by spaces
# ---[ REPLACE ]---
( "([^"]*)" # "double quoted" or
| '([^']*)' # 'single quoted' or
| (.*) # anything
)
\s*$
""", re.VERBOSE)
guicolors = re.compile("^([^\s]+\s+){3}[^\s]+") # 4 tokens
# Give me a match or get out
match = cfgregex.match(line)
if not match: return empty
# Save information about this config
name = (match.group('name') or '').lower()
target = (match.group('target') or 'all').lower()
value = match.group('value')
# %!keyword(target) not allowed for these
if name in no_target and match.group('target'):
Error(
_("You can't use (target) with %s") % ('%!' + name)
+ "\n%s" % line)
# Force no_target keywords to be valid for all targets
if name in no_target:
target = 'all'
# Special config for GUI colors
if name == 'guicolors':
valmatch = guicolors.search(value)
if not valmatch: return empty
value = re.split('\s+', value)
# Special config with two quoted values (%!preproc: "foo" 'bar')
if name == 'preproc' or name == 'postproc':
valmatch = prepostregex.search(value)
if not valmatch: return empty
getval = valmatch.group
patt = getval(2) or getval(3) or getval(4) or ''
repl = getval(6) or getval(7) or getval(8) or ''
value = (patt, repl)
return [target, name, value] | [
"def",
"parse_line",
"(",
"self",
",",
"line",
"=",
"''",
",",
"keyname",
"=",
"''",
",",
"target",
"=",
"''",
")",
":",
"empty",
"=",
"[",
"''",
",",
"''",
",",
"''",
"]",
"if",
"not",
"line",
":",
"return",
"empty",
"no_target",
"=",
"[",
"'target'",
",",
"'includeconf'",
"]",
"re_name",
"=",
"keyname",
"or",
"'[a-z]+'",
"re_target",
"=",
"target",
"or",
"'[a-z]*'",
"# XXX TODO <value>\\S.+? requires TWO chars, breaks %!include:a",
"cfgregex",
"=",
"re",
".",
"compile",
"(",
"\"\"\"\n\t\t\t^%%!\\s*\t\t # leading id with opt spaces\n\t\t\t(?P<name>%s)\\s* # config name\n\t\t\t(\\((?P<target>%s)\\))? # optional target spec inside ()\n\t\t\t\\s*:\\s*\t\t # key:value delimiter with opt spaces\n\t\t\t(?P<value>\\S.+?) # config value\n\t\t\t\\s*$\t\t # rstrip() spaces and hit EOL\n\t\t\t\"\"\"",
"%",
"(",
"re_name",
",",
"re_target",
")",
",",
"re",
".",
"I",
"+",
"re",
".",
"VERBOSE",
")",
"prepostregex",
"=",
"re",
".",
"compile",
"(",
"\"\"\"\n\t\t\t\t\t # ---[ PATTERN ]---\n\t\t\t^( \"([^\"]*)\"\t # \"double quoted\" or\n\t\t\t| '([^']*)'\t # 'single quoted' or\n\t\t\t| ([^\\s]+)\t # single_word\n\t\t\t)\n\t\t\t\\s+\t\t # separated by spaces\n\n\t\t\t\t\t # ---[ REPLACE ]---\n\t\t\t( \"([^\"]*)\"\t # \"double quoted\" or\n\t\t\t| '([^']*)'\t # 'single quoted' or\n\t\t\t| (.*)\t\t # anything\n\t\t\t)\n\t\t\t\\s*$\n\t\t\t\"\"\"",
",",
"re",
".",
"VERBOSE",
")",
"guicolors",
"=",
"re",
".",
"compile",
"(",
"\"^([^\\s]+\\s+){3}[^\\s]+\"",
")",
"# 4 tokens",
"# Give me a match or get out",
"match",
"=",
"cfgregex",
".",
"match",
"(",
"line",
")",
"if",
"not",
"match",
":",
"return",
"empty",
"# Save information about this config",
"name",
"=",
"(",
"match",
".",
"group",
"(",
"'name'",
")",
"or",
"''",
")",
".",
"lower",
"(",
")",
"target",
"=",
"(",
"match",
".",
"group",
"(",
"'target'",
")",
"or",
"'all'",
")",
".",
"lower",
"(",
")",
"value",
"=",
"match",
".",
"group",
"(",
"'value'",
")",
"# %!keyword(target) not allowed for these",
"if",
"name",
"in",
"no_target",
"and",
"match",
".",
"group",
"(",
"'target'",
")",
":",
"Error",
"(",
"_",
"(",
"\"You can't use (target) with %s\"",
")",
"%",
"(",
"'%!'",
"+",
"name",
")",
"+",
"\"\\n%s\"",
"%",
"line",
")",
"# Force no_target keywords to be valid for all targets",
"if",
"name",
"in",
"no_target",
":",
"target",
"=",
"'all'",
"# Special config for GUI colors",
"if",
"name",
"==",
"'guicolors'",
":",
"valmatch",
"=",
"guicolors",
".",
"search",
"(",
"value",
")",
"if",
"not",
"valmatch",
":",
"return",
"empty",
"value",
"=",
"re",
".",
"split",
"(",
"'\\s+'",
",",
"value",
")",
"# Special config with two quoted values (%!preproc: \"foo\" 'bar')",
"if",
"name",
"==",
"'preproc'",
"or",
"name",
"==",
"'postproc'",
":",
"valmatch",
"=",
"prepostregex",
".",
"search",
"(",
"value",
")",
"if",
"not",
"valmatch",
":",
"return",
"empty",
"getval",
"=",
"valmatch",
".",
"group",
"patt",
"=",
"getval",
"(",
"2",
")",
"or",
"getval",
"(",
"3",
")",
"or",
"getval",
"(",
"4",
")",
"or",
"''",
"repl",
"=",
"getval",
"(",
"6",
")",
"or",
"getval",
"(",
"7",
")",
"or",
"getval",
"(",
"8",
")",
"or",
"''",
"value",
"=",
"(",
"patt",
",",
"repl",
")",
"return",
"[",
"target",
",",
"name",
",",
"value",
"]"
] | https://github.com/ufal/udpipe/blob/e51f02d2744cdfd4a29efc1320644ea04d535f0b/doc/t2t_docsys/txt2tags.py#L2992-L3058 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/sparse.py | python | BaseSparseNDArray.check_format | (self, full_check=True) | Check whether the NDArray format is valid.
Parameters
----------
full_check : bool, optional
If `True`, rigorous check, O(N) operations. Otherwise
basic check, O(1) operations (default True). | Check whether the NDArray format is valid. | [
"Check",
"whether",
"the",
"NDArray",
"format",
"is",
"valid",
"."
] | def check_format(self, full_check=True):
"""Check whether the NDArray format is valid.
Parameters
----------
full_check : bool, optional
If `True`, rigorous check, O(N) operations. Otherwise
basic check, O(1) operations (default True).
"""
check_call(_LIB.MXNDArraySyncCheckFormat(self.handle, ctypes.c_bool(full_check))) | [
"def",
"check_format",
"(",
"self",
",",
"full_check",
"=",
"True",
")",
":",
"check_call",
"(",
"_LIB",
".",
"MXNDArraySyncCheckFormat",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"c_bool",
"(",
"full_check",
")",
")",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/sparse.py#L266-L275 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | InfoBar.SetShowHideEffects | (*args, **kwargs) | return _controls_.InfoBar_SetShowHideEffects(*args, **kwargs) | SetShowHideEffects(self, int showEffect, int hideEffect) | SetShowHideEffects(self, int showEffect, int hideEffect) | [
"SetShowHideEffects",
"(",
"self",
"int",
"showEffect",
"int",
"hideEffect",
")"
] | def SetShowHideEffects(*args, **kwargs):
"""SetShowHideEffects(self, int showEffect, int hideEffect)"""
return _controls_.InfoBar_SetShowHideEffects(*args, **kwargs) | [
"def",
"SetShowHideEffects",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"InfoBar_SetShowHideEffects",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7824-L7826 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Tools/scripts/analyze_dxp.py | python | has_pairs | (profile) | return len(profile) > 0 and isinstance(profile[0], list) | Returns True if the Python that produced the argument profile
was built with -DDXPAIRS. | Returns True if the Python that produced the argument profile
was built with -DDXPAIRS. | [
"Returns",
"True",
"if",
"the",
"Python",
"that",
"produced",
"the",
"argument",
"profile",
"was",
"built",
"with",
"-",
"DDXPAIRS",
"."
] | def has_pairs(profile):
"""Returns True if the Python that produced the argument profile
was built with -DDXPAIRS."""
return len(profile) > 0 and isinstance(profile[0], list) | [
"def",
"has_pairs",
"(",
"profile",
")",
":",
"return",
"len",
"(",
"profile",
")",
">",
"0",
"and",
"isinstance",
"(",
"profile",
"[",
"0",
"]",
",",
"list",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Tools/scripts/analyze_dxp.py#L39-L43 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/launch_utils.py | python | add_arguments | (argname, type, default, help, argparser, **kwargs) | Add argparse's argument.
Usage:
.. code-block:: python
parser = argparse.ArgumentParser()
add_argument("name", str, "Jonh", "User name.", parser)
args = parser.parse_args() | Add argparse's argument.
Usage:
.. code-block:: python
parser = argparse.ArgumentParser()
add_argument("name", str, "Jonh", "User name.", parser)
args = parser.parse_args() | [
"Add",
"argparse",
"s",
"argument",
".",
"Usage",
":",
"..",
"code",
"-",
"block",
"::",
"python",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"()",
"add_argument",
"(",
"name",
"str",
"Jonh",
"User",
"name",
".",
"parser",
")",
"args",
"=",
"parser",
".",
"parse_args",
"()"
] | def add_arguments(argname, type, default, help, argparser, **kwargs):
"""Add argparse's argument.
Usage:
.. code-block:: python
parser = argparse.ArgumentParser()
add_argument("name", str, "Jonh", "User name.", parser)
args = parser.parse_args()
"""
type = strtobool if type == bool else type
argparser.add_argument(
"--" + argname,
default=default,
type=type,
help=help + ' Default: %(default)s.',
**kwargs) | [
"def",
"add_arguments",
"(",
"argname",
",",
"type",
",",
"default",
",",
"help",
",",
"argparser",
",",
"*",
"*",
"kwargs",
")",
":",
"type",
"=",
"strtobool",
"if",
"type",
"==",
"bool",
"else",
"type",
"argparser",
".",
"add_argument",
"(",
"\"--\"",
"+",
"argname",
",",
"default",
"=",
"default",
",",
"type",
"=",
"type",
",",
"help",
"=",
"help",
"+",
"' Default: %(default)s.'",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/launch_utils.py#L360-L374 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/interpolate/polyint.py | python | _Interpolator1DWithDerivatives.derivative | (self, x, der=1) | return self._finish_y(y[der], x_shape) | Evaluate one derivative of the polynomial at the point x
Parameters
----------
x : array_like
Point or points at which to evaluate the derivatives
der : integer, optional
Which derivative to extract. This number includes the
function value as 0th derivative.
Returns
-------
d : ndarray
Derivative interpolated at the x-points. Shape of d is
determined by replacing the interpolation axis in the
original array with the shape of x.
Notes
-----
This is computed by evaluating all derivatives up to the desired
one (using self.derivatives()) and then discarding the rest. | Evaluate one derivative of the polynomial at the point x | [
"Evaluate",
"one",
"derivative",
"of",
"the",
"polynomial",
"at",
"the",
"point",
"x"
] | def derivative(self, x, der=1):
"""
Evaluate one derivative of the polynomial at the point x
Parameters
----------
x : array_like
Point or points at which to evaluate the derivatives
der : integer, optional
Which derivative to extract. This number includes the
function value as 0th derivative.
Returns
-------
d : ndarray
Derivative interpolated at the x-points. Shape of d is
determined by replacing the interpolation axis in the
original array with the shape of x.
Notes
-----
This is computed by evaluating all derivatives up to the desired
one (using self.derivatives()) and then discarding the rest.
"""
x, x_shape = self._prepare_x(x)
y = self._evaluate_derivatives(x, der+1)
return self._finish_y(y[der], x_shape) | [
"def",
"derivative",
"(",
"self",
",",
"x",
",",
"der",
"=",
"1",
")",
":",
"x",
",",
"x_shape",
"=",
"self",
".",
"_prepare_x",
"(",
"x",
")",
"y",
"=",
"self",
".",
"_evaluate_derivatives",
"(",
"x",
",",
"der",
"+",
"1",
")",
"return",
"self",
".",
"_finish_y",
"(",
"y",
"[",
"der",
"]",
",",
"x_shape",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/polyint.py#L190-L218 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py | python | assert_bool | (dist, attr, value) | Verify that value is True, False, 0, or 1 | Verify that value is True, False, 0, or 1 | [
"Verify",
"that",
"value",
"is",
"True",
"False",
"0",
"or",
"1"
] | def assert_bool(dist, attr, value):
"""Verify that value is True, False, 0, or 1"""
if bool(value) != value:
tmpl = "{attr!r} must be a boolean value (got {value!r})"
raise DistutilsSetupError(tmpl.format(attr=attr, value=value)) | [
"def",
"assert_bool",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"if",
"bool",
"(",
"value",
")",
"!=",
"value",
":",
"tmpl",
"=",
"\"{attr!r} must be a boolean value (got {value!r})\"",
"raise",
"DistutilsSetupError",
"(",
"tmpl",
".",
"format",
"(",
"attr",
"=",
"attr",
",",
"value",
"=",
"value",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py#L265-L269 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | FlagValues.RegisteredFlags | (self) | return list(self.FlagDict()) | Returns: a list of the names and short names of all registered flags. | Returns: a list of the names and short names of all registered flags. | [
"Returns",
":",
"a",
"list",
"of",
"the",
"names",
"and",
"short",
"names",
"of",
"all",
"registered",
"flags",
"."
] | def RegisteredFlags(self):
"""Returns: a list of the names and short names of all registered flags."""
return list(self.FlagDict()) | [
"def",
"RegisteredFlags",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"FlagDict",
"(",
")",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1341-L1343 | |
facebook/watchman | 0917460c71b000b96be9b9575d77f06f2f6053bb | build/fbcode_builder/getdeps/fetcher.py | python | ShipitPathMap._minimize_roots | (self) | compute the de-duplicated set of roots within fbsource.
We take the shortest common directory prefix to make this
determination | compute the de-duplicated set of roots within fbsource.
We take the shortest common directory prefix to make this
determination | [
"compute",
"the",
"de",
"-",
"duplicated",
"set",
"of",
"roots",
"within",
"fbsource",
".",
"We",
"take",
"the",
"shortest",
"common",
"directory",
"prefix",
"to",
"make",
"this",
"determination"
] | def _minimize_roots(self):
"""compute the de-duplicated set of roots within fbsource.
We take the shortest common directory prefix to make this
determination"""
self.roots.sort(key=len)
minimized = []
for r in self.roots:
add_this_entry = True
for existing in minimized:
if r.startswith(existing + "/"):
add_this_entry = False
break
if add_this_entry:
minimized.append(r)
self.roots = minimized | [
"def",
"_minimize_roots",
"(",
"self",
")",
":",
"self",
".",
"roots",
".",
"sort",
"(",
"key",
"=",
"len",
")",
"minimized",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"roots",
":",
"add_this_entry",
"=",
"True",
"for",
"existing",
"in",
"minimized",
":",
"if",
"r",
".",
"startswith",
"(",
"existing",
"+",
"\"/\"",
")",
":",
"add_this_entry",
"=",
"False",
"break",
"if",
"add_this_entry",
":",
"minimized",
".",
"append",
"(",
"r",
")",
"self",
".",
"roots",
"=",
"minimized"
] | https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/build/fbcode_builder/getdeps/fetcher.py#L411-L427 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiDockingGuideWindow.__init__ | (self, parent, rect, direction=0, center=False, useAero=False) | Default class constructor. Used internally, do not call it in your code!
:param `parent`: the :class:`AuiManager` parent;
:param Rect `rect`: the window rect;
:param integer `direction`: one of ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, ``wx.RIGHT``,
``wx.CENTER``;
:param bool `center`: whether the calling class is a :class:`AuiCenterDockingGuide`;
:param bool `useAero`: whether to use the new Aero-style bitmaps or Whidbey-style bitmaps
for the docking guide. | Default class constructor. Used internally, do not call it in your code! | [
"Default",
"class",
"constructor",
".",
"Used",
"internally",
"do",
"not",
"call",
"it",
"in",
"your",
"code!"
] | def __init__(self, parent, rect, direction=0, center=False, useAero=False):
"""
Default class constructor. Used internally, do not call it in your code!
:param `parent`: the :class:`AuiManager` parent;
:param Rect `rect`: the window rect;
:param integer `direction`: one of ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, ``wx.RIGHT``,
``wx.CENTER``;
:param bool `center`: whether the calling class is a :class:`AuiCenterDockingGuide`;
:param bool `useAero`: whether to use the new Aero-style bitmaps or Whidbey-style bitmaps
for the docking guide.
"""
wx.Window.__init__(self, parent, -1, rect.GetPosition(), rect.GetSize(), wx.NO_BORDER)
self._direction = direction
self._center = center
self._valid = True
self._useAero = useAero
self._bmp_unfocus, self._bmp_focus = GetDockingImage(direction, useAero, center)
self._currentImage = self._bmp_unfocus
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_PAINT, self.OnPaint) | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"rect",
",",
"direction",
"=",
"0",
",",
"center",
"=",
"False",
",",
"useAero",
"=",
"False",
")",
":",
"wx",
".",
"Window",
".",
"__init__",
"(",
"self",
",",
"parent",
",",
"-",
"1",
",",
"rect",
".",
"GetPosition",
"(",
")",
",",
"rect",
".",
"GetSize",
"(",
")",
",",
"wx",
".",
"NO_BORDER",
")",
"self",
".",
"_direction",
"=",
"direction",
"self",
".",
"_center",
"=",
"center",
"self",
".",
"_valid",
"=",
"True",
"self",
".",
"_useAero",
"=",
"useAero",
"self",
".",
"_bmp_unfocus",
",",
"self",
".",
"_bmp_focus",
"=",
"GetDockingImage",
"(",
"direction",
",",
"useAero",
",",
"center",
")",
"self",
".",
"_currentImage",
"=",
"self",
".",
"_bmp_unfocus",
"self",
".",
"SetBackgroundStyle",
"(",
"wx",
".",
"BG_STYLE_CUSTOM",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_ERASE_BACKGROUND",
",",
"self",
".",
"OnEraseBackground",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_PAINT",
",",
"self",
".",
"OnPaint",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L1926-L1952 | ||
snyball/Hawck | 625d840a9ac6f15d067d8307e2bd1a6930693a8b | hawck-ui/hawck_ui/privesc.py | python | SudoMethod.getcmd | (self, expl: str, user: str, what: List[str]) | return full_cmd | Get full command for this sudo method. | Get full command for this sudo method. | [
"Get",
"full",
"command",
"for",
"this",
"sudo",
"method",
"."
] | def getcmd(self, expl: str, user: str, what: List[str]) -> List[str]:
"""
Get full command for this sudo method.
"""
full_cmd = [self.cmd]
full_cmd.extend(self.base_flags)
if not self.options["user"]:
full_cmd.append(user)
else:
full_cmd.extend([self.options["user"], user,])
# if "message" in self.options:
# full_cmd.extend([self.options["message"], expl])
# full_cmd.append("--")
full_cmd.extend(what)
return full_cmd | [
"def",
"getcmd",
"(",
"self",
",",
"expl",
":",
"str",
",",
"user",
":",
"str",
",",
"what",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"full_cmd",
"=",
"[",
"self",
".",
"cmd",
"]",
"full_cmd",
".",
"extend",
"(",
"self",
".",
"base_flags",
")",
"if",
"not",
"self",
".",
"options",
"[",
"\"user\"",
"]",
":",
"full_cmd",
".",
"append",
"(",
"user",
")",
"else",
":",
"full_cmd",
".",
"extend",
"(",
"[",
"self",
".",
"options",
"[",
"\"user\"",
"]",
",",
"user",
",",
"]",
")",
"# if \"message\" in self.options:",
"# full_cmd.extend([self.options[\"message\"], expl])",
"# full_cmd.append(\"--\")",
"full_cmd",
".",
"extend",
"(",
"what",
")",
"return",
"full_cmd"
] | https://github.com/snyball/Hawck/blob/625d840a9ac6f15d067d8307e2bd1a6930693a8b/hawck-ui/hawck_ui/privesc.py#L73-L87 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py | python | CollectedLinks.__init__ | (
self,
files, # type: List[Link]
find_links, # type: List[Link]
project_urls, # type: List[Link]
) | :param files: Links from file locations.
:param find_links: Links from find_links.
:param project_urls: URLs to HTML project pages, as described by
the PEP 503 simple repository API. | [] | def __init__(
self,
files, # type: List[Link]
find_links, # type: List[Link]
project_urls, # type: List[Link]
):
# type: (...) -> None
"""
:param files: Links from file locations.
:param find_links: Links from find_links.
:param project_urls: URLs to HTML project pages, as described by
the PEP 503 simple repository API.
"""
self.files = files
self.find_links = find_links
self.project_urls = project_urls | [
"def",
"__init__",
"(",
"self",
",",
"files",
",",
"# type: List[Link]",
"find_links",
",",
"# type: List[Link]",
"project_urls",
",",
"# type: List[Link]",
")",
":",
"# type: (...) -> None",
"self",
".",
"files",
"=",
"files",
"self",
".",
"find_links",
"=",
"find_links",
"self",
".",
"project_urls",
"=",
"project_urls"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py#L1087-L1117 | |||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configDialog.py | python | ConfigDialog.SaveNewKeySet | (self,keySetName,keySet) | save a newly created core key set.
keySetName - string, the name of the new key set
keySet - dictionary containing the new key set | save a newly created core key set.
keySetName - string, the name of the new key set
keySet - dictionary containing the new key set | [
"save",
"a",
"newly",
"created",
"core",
"key",
"set",
".",
"keySetName",
"-",
"string",
"the",
"name",
"of",
"the",
"new",
"key",
"set",
"keySet",
"-",
"dictionary",
"containing",
"the",
"new",
"key",
"set"
] | def SaveNewKeySet(self,keySetName,keySet):
"""
save a newly created core key set.
keySetName - string, the name of the new key set
keySet - dictionary containing the new key set
"""
if not idleConf.userCfg['keys'].has_section(keySetName):
idleConf.userCfg['keys'].add_section(keySetName)
for event in keySet.keys():
value=keySet[event]
idleConf.userCfg['keys'].SetOption(keySetName,event,value) | [
"def",
"SaveNewKeySet",
"(",
"self",
",",
"keySetName",
",",
"keySet",
")",
":",
"if",
"not",
"idleConf",
".",
"userCfg",
"[",
"'keys'",
"]",
".",
"has_section",
"(",
"keySetName",
")",
":",
"idleConf",
".",
"userCfg",
"[",
"'keys'",
"]",
".",
"add_section",
"(",
"keySetName",
")",
"for",
"event",
"in",
"keySet",
".",
"keys",
"(",
")",
":",
"value",
"=",
"keySet",
"[",
"event",
"]",
"idleConf",
".",
"userCfg",
"[",
"'keys'",
"]",
".",
"SetOption",
"(",
"keySetName",
",",
"event",
",",
"value",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configDialog.py#L1067-L1077 | ||
AngoraFuzzer/Angora | 80e81c8590077bc0ac069dbd367da8ce405ff618 | llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py | python | GetPreviousNonBlankLine | (clean_lines, linenum) | return ('', -1) | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line. | Return the most recent non-blank line and its line number. | [
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] | def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | [
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",
"(",
"prevline",
")",
":",
"# if not a blank line...",
"return",
"(",
"prevline",
",",
"prevlinenum",
")",
"prevlinenum",
"-=",
"1",
"return",
"(",
"''",
",",
"-",
"1",
")"
] | https://github.com/AngoraFuzzer/Angora/blob/80e81c8590077bc0ac069dbd367da8ce405ff618/llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py#L2544-L2564 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/support/parse_khhttpd_access_log.py | python | Quad2GCS | (addr_list, x_coord, y_coord, xy_range) | Drill down through quad-tree to get final x,y coords. | Drill down through quad-tree to get final x,y coords. | [
"Drill",
"down",
"through",
"quad",
"-",
"tree",
"to",
"get",
"final",
"x",
"y",
"coords",
"."
] | def Quad2GCS(addr_list, x_coord, y_coord, xy_range):
'''Drill down through quad-tree to get final x,y coords.'''
if not addr_list:
new_coords = (x_coord, y_coord)
return new_coords
else:
tile_addr = addr_list.pop()
new_range = xy_range/2
if tile_addr == '0':
x_coord -= new_range
y_coord -= new_range
if tile_addr == '1':
x_coord += new_range
y_coord -= new_range
if tile_addr == '2':
x_coord += new_range
y_coord += new_range
if tile_addr == '3':
x_coord -= new_range
y_coord += new_range
return Quad2GCS(addr_list, x_coord, y_coord, new_range) | [
"def",
"Quad2GCS",
"(",
"addr_list",
",",
"x_coord",
",",
"y_coord",
",",
"xy_range",
")",
":",
"if",
"not",
"addr_list",
":",
"new_coords",
"=",
"(",
"x_coord",
",",
"y_coord",
")",
"return",
"new_coords",
"else",
":",
"tile_addr",
"=",
"addr_list",
".",
"pop",
"(",
")",
"new_range",
"=",
"xy_range",
"/",
"2",
"if",
"tile_addr",
"==",
"'0'",
":",
"x_coord",
"-=",
"new_range",
"y_coord",
"-=",
"new_range",
"if",
"tile_addr",
"==",
"'1'",
":",
"x_coord",
"+=",
"new_range",
"y_coord",
"-=",
"new_range",
"if",
"tile_addr",
"==",
"'2'",
":",
"x_coord",
"+=",
"new_range",
"y_coord",
"+=",
"new_range",
"if",
"tile_addr",
"==",
"'3'",
":",
"x_coord",
"-=",
"new_range",
"y_coord",
"+=",
"new_range",
"return",
"Quad2GCS",
"(",
"addr_list",
",",
"x_coord",
",",
"y_coord",
",",
"new_range",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/support/parse_khhttpd_access_log.py#L133-L153 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/profiler/parser/step_trace_parser.py | python | AscendStepTraceParser._save_step_trace_to_result | (self, ts_tracks, skip_step) | Save step trace data to result. | Save step trace data to result. | [
"Save",
"step",
"trace",
"data",
"to",
"result",
"."
] | def _save_step_trace_to_result(self, ts_tracks, skip_step):
"""Save step trace data to result."""
step_trace = {'reduce': defaultdict(list)}
for ts_track in ts_tracks:
if ts_track['rptType'] != STEP_TRACE_RPT_TYPE:
continue
step_trace['start'] = step_trace.get('end', '-')
self._construct_step_trace(ts_track, step_trace)
if step_trace.get('end'):
if not skip_step:
self._record_trace_event(step_trace)
skip_step = False
start_time = step_trace.get('end', '-')
step_trace.clear()
step_trace['start'] = start_time
step_trace['reduce'] = defaultdict(list) | [
"def",
"_save_step_trace_to_result",
"(",
"self",
",",
"ts_tracks",
",",
"skip_step",
")",
":",
"step_trace",
"=",
"{",
"'reduce'",
":",
"defaultdict",
"(",
"list",
")",
"}",
"for",
"ts_track",
"in",
"ts_tracks",
":",
"if",
"ts_track",
"[",
"'rptType'",
"]",
"!=",
"STEP_TRACE_RPT_TYPE",
":",
"continue",
"step_trace",
"[",
"'start'",
"]",
"=",
"step_trace",
".",
"get",
"(",
"'end'",
",",
"'-'",
")",
"self",
".",
"_construct_step_trace",
"(",
"ts_track",
",",
"step_trace",
")",
"if",
"step_trace",
".",
"get",
"(",
"'end'",
")",
":",
"if",
"not",
"skip_step",
":",
"self",
".",
"_record_trace_event",
"(",
"step_trace",
")",
"skip_step",
"=",
"False",
"start_time",
"=",
"step_trace",
".",
"get",
"(",
"'end'",
",",
"'-'",
")",
"step_trace",
".",
"clear",
"(",
")",
"step_trace",
"[",
"'start'",
"]",
"=",
"start_time",
"step_trace",
"[",
"'reduce'",
"]",
"=",
"defaultdict",
"(",
"list",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/step_trace_parser.py#L563-L579 | ||
nsnam/ns-3-dev-git | efdb2e21f45c0a87a60b47c547b68fa140a7b686 | utils/grid.py | python | TimelineEvent.get_events_bounds | (self, start, end) | return(s, e + 1) | ! Get Events Bounds
@param self this object
@param start starting event
@param end ending event
@return event bounds | ! Get Events Bounds | [
"!",
"Get",
"Events",
"Bounds"
] | def get_events_bounds(self, start, end):
"""! Get Events Bounds
@param self this object
@param start starting event
@param end ending event
@return event bounds
"""
s = self.__search(start)
e = self.__search(end)
return(s, e + 1) | [
"def",
"get_events_bounds",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"s",
"=",
"self",
".",
"__search",
"(",
"start",
")",
"e",
"=",
"self",
".",
"__search",
"(",
"end",
")",
"return",
"(",
"s",
",",
"e",
"+",
"1",
")"
] | https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/utils/grid.py#L230-L239 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | PhysicsTools/Heppy/python/physicsobjects/Muon.py | python | Muon.looseId | ( self ) | return self.physObj.isLooseMuon() | Loose ID as recommended by mu POG. | Loose ID as recommended by mu POG. | [
"Loose",
"ID",
"as",
"recommended",
"by",
"mu",
"POG",
"."
] | def looseId( self ):
'''Loose ID as recommended by mu POG.'''
return self.physObj.isLooseMuon() | [
"def",
"looseId",
"(",
"self",
")",
":",
"return",
"self",
".",
"physObj",
".",
"isLooseMuon",
"(",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/Heppy/python/physicsobjects/Muon.py#L15-L17 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/turtle.py | python | TurtleScreenBase._type | (self, item) | return self.cv.type(item) | Return 'line' or 'polygon' or 'image' depending on
type of item. | Return 'line' or 'polygon' or 'image' depending on
type of item. | [
"Return",
"line",
"or",
"polygon",
"or",
"image",
"depending",
"on",
"type",
"of",
"item",
"."
] | def _type(self, item):
"""Return 'line' or 'polygon' or 'image' depending on
type of item.
"""
return self.cv.type(item) | [
"def",
"_type",
"(",
"self",
",",
"item",
")",
":",
"return",
"self",
".",
"cv",
".",
"type",
"(",
"item",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L747-L751 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/session.py | python | Session.get_available_regions | (self, service_name, partition_name='aws',
allow_non_regional=False) | return results | Lists the region and endpoint names of a particular partition.
:type service_name: string
:param service_name: Name of a service to list endpoint for (e.g., s3).
This parameter accepts a service name (e.g., "elb") or endpoint
prefix (e.g., "elasticloadbalancing").
:type partition_name: string
:param partition_name: Name of the partition to limit endpoints to.
(e.g., aws for the public AWS endpoints, aws-cn for AWS China
endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.
:type allow_non_regional: bool
:param allow_non_regional: Set to True to include endpoints that are
not regional endpoints (e.g., s3-external-1,
fips-us-gov-west-1, etc).
:return: Returns a list of endpoint names (e.g., ["us-east-1"]). | Lists the region and endpoint names of a particular partition. | [
"Lists",
"the",
"region",
"and",
"endpoint",
"names",
"of",
"a",
"particular",
"partition",
"."
] | def get_available_regions(self, service_name, partition_name='aws',
allow_non_regional=False):
"""Lists the region and endpoint names of a particular partition.
:type service_name: string
:param service_name: Name of a service to list endpoint for (e.g., s3).
This parameter accepts a service name (e.g., "elb") or endpoint
prefix (e.g., "elasticloadbalancing").
:type partition_name: string
:param partition_name: Name of the partition to limit endpoints to.
(e.g., aws for the public AWS endpoints, aws-cn for AWS China
endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.
:type allow_non_regional: bool
:param allow_non_regional: Set to True to include endpoints that are
not regional endpoints (e.g., s3-external-1,
fips-us-gov-west-1, etc).
:return: Returns a list of endpoint names (e.g., ["us-east-1"]).
"""
resolver = self._get_internal_component('endpoint_resolver')
results = []
try:
service_data = self.get_service_data(service_name)
endpoint_prefix = service_data['metadata'].get(
'endpointPrefix', service_name)
results = resolver.get_available_endpoints(
endpoint_prefix, partition_name, allow_non_regional)
except UnknownServiceError:
pass
return results | [
"def",
"get_available_regions",
"(",
"self",
",",
"service_name",
",",
"partition_name",
"=",
"'aws'",
",",
"allow_non_regional",
"=",
"False",
")",
":",
"resolver",
"=",
"self",
".",
"_get_internal_component",
"(",
"'endpoint_resolver'",
")",
"results",
"=",
"[",
"]",
"try",
":",
"service_data",
"=",
"self",
".",
"get_service_data",
"(",
"service_name",
")",
"endpoint_prefix",
"=",
"service_data",
"[",
"'metadata'",
"]",
".",
"get",
"(",
"'endpointPrefix'",
",",
"service_name",
")",
"results",
"=",
"resolver",
".",
"get_available_endpoints",
"(",
"endpoint_prefix",
",",
"partition_name",
",",
"allow_non_regional",
")",
"except",
"UnknownServiceError",
":",
"pass",
"return",
"results"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/session.py#L877-L907 | |
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | priority_queue/maxheap.py | python | MaxHeap.get_max | (self) | return self.data[1] | get_max returns the maximum value (i.e. root) in the heap,
without removing it. Returns None, if the heap is empty. | get_max returns the maximum value (i.e. root) in the heap,
without removing it. Returns None, if the heap is empty. | [
"get_max",
"returns",
"the",
"maximum",
"value",
"(",
"i",
".",
"e",
".",
"root",
")",
"in",
"the",
"heap",
"without",
"removing",
"it",
".",
"Returns",
"None",
"if",
"the",
"heap",
"is",
"empty",
"."
] | def get_max(self):
""" get_max returns the maximum value (i.e. root) in the heap,
without removing it. Returns None, if the heap is empty.
"""
if self.is_empty():
return None
return self.data[1] | [
"def",
"get_max",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
"return",
"None",
"return",
"self",
".",
"data",
"[",
"1",
"]"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/priority_queue/maxheap.py#L28-L34 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/blocks/robotcontroller.py | python | RobotControllerIO.sensorNames | (self) | return self.inputs.keys() | Returns the list of sensor names (including clock and time step) | Returns the list of sensor names (including clock and time step) | [
"Returns",
"the",
"list",
"of",
"sensor",
"names",
"(",
"including",
"clock",
"and",
"time",
"step",
")"
] | def sensorNames(self):
"""Returns the list of sensor names (including clock and time step)"""
return self.inputs.keys() | [
"def",
"sensorNames",
"(",
"self",
")",
":",
"return",
"self",
".",
"inputs",
".",
"keys",
"(",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/blocks/robotcontroller.py#L171-L173 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/base.py | python | check_call | (ret) | Check the return value of C API call.
This function will raise an exception when an error occurs.
Wrap every API call with this function.
Parameters
----------
ret : int
return value from API calls. | Check the return value of C API call. | [
"Check",
"the",
"return",
"value",
"of",
"C",
"API",
"call",
"."
] | def check_call(ret):
"""Check the return value of C API call.
This function will raise an exception when an error occurs.
Wrap every API call with this function.
Parameters
----------
ret : int
return value from API calls.
"""
if ret != 0:
raise get_last_ffi_error() | [
"def",
"check_call",
"(",
"ret",
")",
":",
"if",
"ret",
"!=",
"0",
":",
"raise",
"get_last_ffi_error",
"(",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/base.py#L241-L253 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/dist.py | python | Distribution._move_install_requirements_markers | (self) | Move requirements in `install_requires` that are using environment
markers `extras_require`. | Move requirements in `install_requires` that are using environment
markers `extras_require`. | [
"Move",
"requirements",
"in",
"install_requires",
"that",
"are",
"using",
"environment",
"markers",
"extras_require",
"."
] | def _move_install_requirements_markers(self):
"""
Move requirements in `install_requires` that are using environment
markers `extras_require`.
"""
# divide the install_requires into two sets, simple ones still
# handled by install_requires and more complex ones handled
# by extras_require.
def is_simple_req(req):
return not req.marker
spec_inst_reqs = getattr(self, 'install_requires', None) or ()
inst_reqs = list(pkg_resources.parse_requirements(spec_inst_reqs))
simple_reqs = filter(is_simple_req, inst_reqs)
complex_reqs = filterfalse(is_simple_req, inst_reqs)
self.install_requires = list(map(str, simple_reqs))
for r in complex_reqs:
self._tmp_extras_require[':' + str(r.marker)].append(r)
self.extras_require = dict(
(k, [str(r) for r in map(self._clean_req, v)])
for k, v in self._tmp_extras_require.items()
) | [
"def",
"_move_install_requirements_markers",
"(",
"self",
")",
":",
"# divide the install_requires into two sets, simple ones still",
"# handled by install_requires and more complex ones handled",
"# by extras_require.",
"def",
"is_simple_req",
"(",
"req",
")",
":",
"return",
"not",
"req",
".",
"marker",
"spec_inst_reqs",
"=",
"getattr",
"(",
"self",
",",
"'install_requires'",
",",
"None",
")",
"or",
"(",
")",
"inst_reqs",
"=",
"list",
"(",
"pkg_resources",
".",
"parse_requirements",
"(",
"spec_inst_reqs",
")",
")",
"simple_reqs",
"=",
"filter",
"(",
"is_simple_req",
",",
"inst_reqs",
")",
"complex_reqs",
"=",
"filterfalse",
"(",
"is_simple_req",
",",
"inst_reqs",
")",
"self",
".",
"install_requires",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"simple_reqs",
")",
")",
"for",
"r",
"in",
"complex_reqs",
":",
"self",
".",
"_tmp_extras_require",
"[",
"':'",
"+",
"str",
"(",
"r",
".",
"marker",
")",
"]",
".",
"append",
"(",
"r",
")",
"self",
".",
"extras_require",
"=",
"dict",
"(",
"(",
"k",
",",
"[",
"str",
"(",
"r",
")",
"for",
"r",
"in",
"map",
"(",
"self",
".",
"_clean_req",
",",
"v",
")",
"]",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_tmp_extras_require",
".",
"items",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/dist.py#L401-L425 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/packager_enterprise.py | python | make_deb_repo | (repo, distro, build_os) | Make the Debian repo. | Make the Debian repo. | [
"Make",
"the",
"Debian",
"repo",
"."
] | def make_deb_repo(repo, distro, build_os):
"""Make the Debian repo."""
# Note: the Debian repository Packages files must be generated
# very carefully in order to be usable.
oldpwd = os.getcwd()
os.chdir(repo + "../../../../../../")
try:
dirs = {
os.path.dirname(deb)[2:]
for deb in packager.backtick(["find", ".", "-name", "*.deb"]).decode('utf-8').split()
}
for directory in dirs:
st = packager.backtick(["dpkg-scanpackages", directory, "/dev/null"])
with open(directory + "/Packages", "wb") as fh:
fh.write(st)
bt = packager.backtick(["gzip", "-9c", directory + "/Packages"])
with open(directory + "/Packages.gz", "wb") as fh:
fh.write(bt)
finally:
os.chdir(oldpwd)
# Notes: the Release{,.gpg} files must live in a special place,
# and must be created after all the Packages.gz files have been
# done.
s1 = """Origin: mongodb
Label: mongodb
Suite: %s
Codename: %s/mongodb-enterprise
Architectures: amd64 ppc64el s390x arm64
Components: %s
Description: MongoDB packages
""" % (distro.repo_os_version(build_os), distro.repo_os_version(build_os), distro.repo_component())
if os.path.exists(repo + "../../Release"):
os.unlink(repo + "../../Release")
if os.path.exists(repo + "../../Release.gpg"):
os.unlink(repo + "../../Release.gpg")
oldpwd = os.getcwd()
os.chdir(repo + "../../")
s2 = packager.backtick(["apt-ftparchive", "release", "."])
try:
with open("Release", 'wb') as fh:
fh.write(s1.encode('utf-8'))
fh.write(s2)
finally:
os.chdir(oldpwd) | [
"def",
"make_deb_repo",
"(",
"repo",
",",
"distro",
",",
"build_os",
")",
":",
"# Note: the Debian repository Packages files must be generated",
"# very carefully in order to be usable.",
"oldpwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"repo",
"+",
"\"../../../../../../\"",
")",
"try",
":",
"dirs",
"=",
"{",
"os",
".",
"path",
".",
"dirname",
"(",
"deb",
")",
"[",
"2",
":",
"]",
"for",
"deb",
"in",
"packager",
".",
"backtick",
"(",
"[",
"\"find\"",
",",
"\".\"",
",",
"\"-name\"",
",",
"\"*.deb\"",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"split",
"(",
")",
"}",
"for",
"directory",
"in",
"dirs",
":",
"st",
"=",
"packager",
".",
"backtick",
"(",
"[",
"\"dpkg-scanpackages\"",
",",
"directory",
",",
"\"/dev/null\"",
"]",
")",
"with",
"open",
"(",
"directory",
"+",
"\"/Packages\"",
",",
"\"wb\"",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"st",
")",
"bt",
"=",
"packager",
".",
"backtick",
"(",
"[",
"\"gzip\"",
",",
"\"-9c\"",
",",
"directory",
"+",
"\"/Packages\"",
"]",
")",
"with",
"open",
"(",
"directory",
"+",
"\"/Packages.gz\"",
",",
"\"wb\"",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"bt",
")",
"finally",
":",
"os",
".",
"chdir",
"(",
"oldpwd",
")",
"# Notes: the Release{,.gpg} files must live in a special place,",
"# and must be created after all the Packages.gz files have been",
"# done.",
"s1",
"=",
"\"\"\"Origin: mongodb\nLabel: mongodb\nSuite: %s\nCodename: %s/mongodb-enterprise\nArchitectures: amd64 ppc64el s390x arm64\nComponents: %s\nDescription: MongoDB packages\n\"\"\"",
"%",
"(",
"distro",
".",
"repo_os_version",
"(",
"build_os",
")",
",",
"distro",
".",
"repo_os_version",
"(",
"build_os",
")",
",",
"distro",
".",
"repo_component",
"(",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"repo",
"+",
"\"../../Release\"",
")",
":",
"os",
".",
"unlink",
"(",
"repo",
"+",
"\"../../Release\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"repo",
"+",
"\"../../Release.gpg\"",
")",
":",
"os",
".",
"unlink",
"(",
"repo",
"+",
"\"../../Release.gpg\"",
")",
"oldpwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"repo",
"+",
"\"../../\"",
")",
"s2",
"=",
"packager",
".",
"backtick",
"(",
"[",
"\"apt-ftparchive\"",
",",
"\"release\"",
",",
"\".\"",
"]",
")",
"try",
":",
"with",
"open",
"(",
"\"Release\"",
",",
"'wb'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"s1",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"fh",
".",
"write",
"(",
"s2",
")",
"finally",
":",
"os",
".",
"chdir",
"(",
"oldpwd",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/packager_enterprise.py#L278-L321 | ||
LUX-Core/lux | 4e1ff7d34a9c76312135ddc869db09149c35170e | contrib/devtools/github-merge.py | python | git_config_get | (option, default=None) | Get named configuration option from git repository. | Get named configuration option from git repository. | [
"Get",
"named",
"configuration",
"option",
"from",
"git",
"repository",
"."
] | def git_config_get(option, default=None):
'''
Get named configuration option from git repository.
'''
try:
return subprocess.check_output([GIT,'config','--get',option]).rstrip().decode('utf-8')
except subprocess.CalledProcessError as e:
return default | [
"def",
"git_config_get",
"(",
"option",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"[",
"GIT",
",",
"'config'",
",",
"'--get'",
",",
"option",
"]",
")",
".",
"rstrip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"return",
"default"
] | https://github.com/LUX-Core/lux/blob/4e1ff7d34a9c76312135ddc869db09149c35170e/contrib/devtools/github-merge.py#L42-L49 | ||
microsoft/LightGBM | 904b2d5158703c4900b68008617951dd2f9ff21b | python-package/lightgbm/dask.py | python | _DaskLGBMModel.client_ | (self) | return _get_dask_client(client=self.client) | :obj:`dask.distributed.Client`: Dask client.
This property can be passed in the constructor or updated
with ``model.set_params(client=client)``. | :obj:`dask.distributed.Client`: Dask client. | [
":",
"obj",
":",
"dask",
".",
"distributed",
".",
"Client",
":",
"Dask",
"client",
"."
] | def client_(self) -> Client:
""":obj:`dask.distributed.Client`: Dask client.
This property can be passed in the constructor or updated
with ``model.set_params(client=client)``.
"""
if not getattr(self, "fitted_", False):
raise LGBMNotFittedError('Cannot access property client_ before calling fit().')
return _get_dask_client(client=self.client) | [
"def",
"client_",
"(",
"self",
")",
"->",
"Client",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"\"fitted_\"",
",",
"False",
")",
":",
"raise",
"LGBMNotFittedError",
"(",
"'Cannot access property client_ before calling fit().'",
")",
"return",
"_get_dask_client",
"(",
"client",
"=",
"self",
".",
"client",
")"
] | https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/dask.py#L1006-L1015 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/processing/algs/qgis/voronoi.py | python | cmp | (a, b) | return (b < a) - (a < b) | Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero if x == y and strictly
positive if x > y.
In python 2 cmp() was a built in function but in python 3 is gone. | Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero if x == y and strictly
positive if x > y. | [
"Compare",
"the",
"two",
"objects",
"x",
"and",
"y",
"and",
"return",
"an",
"integer",
"according",
"to",
"the",
"outcome",
".",
"The",
"return",
"value",
"is",
"negative",
"if",
"x",
"<",
"y",
"zero",
"if",
"x",
"==",
"y",
"and",
"strictly",
"positive",
"if",
"x",
">",
"y",
"."
] | def cmp(a, b):
"""Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero if x == y and strictly
positive if x > y.
In python 2 cmp() was a built in function but in python 3 is gone.
"""
return (b < a) - (a < b) | [
"def",
"cmp",
"(",
"a",
",",
"b",
")",
":",
"return",
"(",
"b",
"<",
"a",
")",
"-",
"(",
"a",
"<",
"b",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/algs/qgis/voronoi.py#L890-L897 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/descriptor_pool.py | python | DescriptorPool.FindExtensionByNumber | (self, message_descriptor, number) | Gets the extension of the specified message with the specified number.
Extensions have to be registered to this pool by calling :func:`Add` or
:func:`AddExtensionDescriptor`.
Args:
message_descriptor (Descriptor): descriptor of the extended message.
number (int): Number of the extension field.
Returns:
FieldDescriptor: The descriptor for the extension.
Raises:
KeyError: when no extension with the given number is known for the
specified message. | Gets the extension of the specified message with the specified number. | [
"Gets",
"the",
"extension",
"of",
"the",
"specified",
"message",
"with",
"the",
"specified",
"number",
"."
] | def FindExtensionByNumber(self, message_descriptor, number):
"""Gets the extension of the specified message with the specified number.
Extensions have to be registered to this pool by calling :func:`Add` or
:func:`AddExtensionDescriptor`.
Args:
message_descriptor (Descriptor): descriptor of the extended message.
number (int): Number of the extension field.
Returns:
FieldDescriptor: The descriptor for the extension.
Raises:
KeyError: when no extension with the given number is known for the
specified message.
"""
try:
return self._extensions_by_number[message_descriptor][number]
except KeyError:
self._TryLoadExtensionFromDB(message_descriptor, number)
return self._extensions_by_number[message_descriptor][number] | [
"def",
"FindExtensionByNumber",
"(",
"self",
",",
"message_descriptor",
",",
"number",
")",
":",
"try",
":",
"return",
"self",
".",
"_extensions_by_number",
"[",
"message_descriptor",
"]",
"[",
"number",
"]",
"except",
"KeyError",
":",
"self",
".",
"_TryLoadExtensionFromDB",
"(",
"message_descriptor",
",",
"number",
")",
"return",
"self",
".",
"_extensions_by_number",
"[",
"message_descriptor",
"]",
"[",
"number",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/descriptor_pool.py#L596-L617 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/protobuf/python/google/protobuf/message.py | python | Message.__str__ | (self) | Outputs a human-readable representation of the message. | Outputs a human-readable representation of the message. | [
"Outputs",
"a",
"human",
"-",
"readable",
"representation",
"of",
"the",
"message",
"."
] | def __str__(self):
"""Outputs a human-readable representation of the message."""
raise NotImplementedError | [
"def",
"__str__",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/message.py#L86-L88 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py | python | Style.theme_create | (self, themename, parent=None, settings=None) | Creates a new theme.
It is an error if themename already exists. If parent is
specified, the new theme will inherit styles, elements and
layouts from the specified parent theme. If settings are present,
they are expected to have the same syntax used for theme_settings. | Creates a new theme. | [
"Creates",
"a",
"new",
"theme",
"."
] | def theme_create(self, themename, parent=None, settings=None):
"""Creates a new theme.
It is an error if themename already exists. If parent is
specified, the new theme will inherit styles, elements and
layouts from the specified parent theme. If settings are present,
they are expected to have the same syntax used for theme_settings."""
script = _script_from_settings(settings) if settings else ''
if parent:
self.tk.call(self._name, "theme", "create", themename,
"-parent", parent, "-settings", script)
else:
self.tk.call(self._name, "theme", "create", themename,
"-settings", script) | [
"def",
"theme_create",
"(",
"self",
",",
"themename",
",",
"parent",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"script",
"=",
"_script_from_settings",
"(",
"settings",
")",
"if",
"settings",
"else",
"''",
"if",
"parent",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_name",
",",
"\"theme\"",
",",
"\"create\"",
",",
"themename",
",",
"\"-parent\"",
",",
"parent",
",",
"\"-settings\"",
",",
"script",
")",
"else",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_name",
",",
"\"theme\"",
",",
"\"create\"",
",",
"themename",
",",
"\"-settings\"",
",",
"script",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py#L479-L493 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py | python | _create_handle_data_proto | (shape_proto, dtype_enum) | return variant_shape_and_type_data | Create handle data based on shape and dtype protos. | Create handle data based on shape and dtype protos. | [
"Create",
"handle",
"data",
"based",
"on",
"shape",
"and",
"dtype",
"protos",
"."
] | def _create_handle_data_proto(shape_proto, dtype_enum):
"""Create handle data based on shape and dtype protos."""
variant_shape_and_type_data = \
cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData()
variant_shape_and_type_data.is_set = True
# NOTE(ebrevdo): shape_and_type lacks append() in some versions of protobuf.
variant_shape_and_type_data.shape_and_type.extend([
cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType(
shape=shape_proto, dtype=dtype_enum)
])
return variant_shape_and_type_data | [
"def",
"_create_handle_data_proto",
"(",
"shape_proto",
",",
"dtype_enum",
")",
":",
"variant_shape_and_type_data",
"=",
"cpp_shape_inference_pb2",
".",
"CppShapeInferenceResult",
".",
"HandleData",
"(",
")",
"variant_shape_and_type_data",
".",
"is_set",
"=",
"True",
"# NOTE(ebrevdo): shape_and_type lacks append() in some versions of protobuf.",
"variant_shape_and_type_data",
".",
"shape_and_type",
".",
"extend",
"(",
"[",
"cpp_shape_inference_pb2",
".",
"CppShapeInferenceResult",
".",
"HandleShapeAndType",
"(",
"shape",
"=",
"shape_proto",
",",
"dtype",
"=",
"dtype_enum",
")",
"]",
")",
"return",
"variant_shape_and_type_data"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py#L53-L63 | |
deepmodeling/deepmd-kit | 159e45d248b0429844fb6a8cb3b3a201987c8d79 | deepmd/utils/path.py | python | DPH5Path.load_numpy | (self) | return self.root[self.name][:] | Load NumPy array.
Returns
-------
np.ndarray
loaded NumPy array | Load NumPy array.
Returns
-------
np.ndarray
loaded NumPy array | [
"Load",
"NumPy",
"array",
".",
"Returns",
"-------",
"np",
".",
"ndarray",
"loaded",
"NumPy",
"array"
] | def load_numpy(self) -> np.ndarray:
"""Load NumPy array.
Returns
-------
np.ndarray
loaded NumPy array
"""
return self.root[self.name][:] | [
"def",
"load_numpy",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"self",
".",
"root",
"[",
"self",
".",
"name",
"]",
"[",
":",
"]"
] | https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/utils/path.py#L239-L247 | |
google/shaka-packager | e1b0c7c45431327fd3ce193514a5407d07b39b22 | packager/third_party/protobuf/python/google/protobuf/text_format.py | python | Tokenizer.ConsumeIdentifierOrNumber | (self) | return result | Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed. | Consumes protocol message field identifier. | [
"Consumes",
"protocol",
"message",
"field",
"identifier",
"."
] | def ConsumeIdentifierOrNumber(self):
"""Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed.
"""
result = self.token
if not self._IDENTIFIER_OR_NUMBER.match(result):
raise self.ParseError('Expected identifier or number.')
self.NextToken()
return result | [
"def",
"ConsumeIdentifierOrNumber",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"token",
"if",
"not",
"self",
".",
"_IDENTIFIER_OR_NUMBER",
".",
"match",
"(",
"result",
")",
":",
"raise",
"self",
".",
"ParseError",
"(",
"'Expected identifier or number.'",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/text_format.py#L1080-L1093 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/serialjava.py | python | Serial.cd | (self) | Read terminal status line: Carrier Detect | Read terminal status line: Carrier Detect | [
"Read",
"terminal",
"status",
"line",
":",
"Carrier",
"Detect"
] | def cd(self):
"""Read terminal status line: Carrier Detect"""
if not self.sPort:
raise portNotOpenError
self.sPort.isCD() | [
"def",
"cd",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"sPort",
":",
"raise",
"portNotOpenError",
"self",
".",
"sPort",
".",
"isCD",
"(",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/serialjava.py#L245-L249 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/mathtls.py | python | MAC_SSL.digest | (self) | return h.digest() | Return the hash value of this hashing object.
This returns a string containing 8-bit data. The object is
not altered in any way by this function; you can continue
updating the object after calling this function. | Return the hash value of this hashing object. | [
"Return",
"the",
"hash",
"value",
"of",
"this",
"hashing",
"object",
"."
] | def digest(self):
"""Return the hash value of this hashing object.
This returns a string containing 8-bit data. The object is
not altered in any way by this function; you can continue
updating the object after calling this function.
"""
h = self.outer.copy()
h.update(self.inner.digest())
return h.digest() | [
"def",
"digest",
"(",
"self",
")",
":",
"h",
"=",
"self",
".",
"outer",
".",
"copy",
"(",
")",
"h",
".",
"update",
"(",
"self",
".",
"inner",
".",
"digest",
"(",
")",
")",
"return",
"h",
".",
"digest",
"(",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/mathtls.py#L165-L174 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/device.py | python | Device.empty_cache | (self) | Empties the memory cache for the current device.
MXNet utilizes a memory pool to avoid excessive allocations.
Calling empty_cache will empty the memory pool of the
device. This will only free the memory of the unreferenced data.
Examples
-------
>>> ctx = mx.gpu(0)
>>> arr = mx.np.ones((200,200), ctx=ctx)
>>> del arr
>>> ctx.empty_cache() # forces release of memory allocated for arr | Empties the memory cache for the current device. | [
"Empties",
"the",
"memory",
"cache",
"for",
"the",
"current",
"device",
"."
] | def empty_cache(self):
"""Empties the memory cache for the current device.
MXNet utilizes a memory pool to avoid excessive allocations.
Calling empty_cache will empty the memory pool of the
device. This will only free the memory of the unreferenced data.
Examples
-------
>>> ctx = mx.gpu(0)
>>> arr = mx.np.ones((200,200), ctx=ctx)
>>> del arr
>>> ctx.empty_cache() # forces release of memory allocated for arr
"""
dev_type = ctypes.c_int(self.device_typeid)
dev_id = ctypes.c_int(self.device_id)
check_call(_LIB.MXStorageEmptyCache(dev_type, dev_id)) | [
"def",
"empty_cache",
"(",
"self",
")",
":",
"dev_type",
"=",
"ctypes",
".",
"c_int",
"(",
"self",
".",
"device_typeid",
")",
"dev_id",
"=",
"ctypes",
".",
"c_int",
"(",
"self",
".",
"device_id",
")",
"check_call",
"(",
"_LIB",
".",
"MXStorageEmptyCache",
"(",
"dev_type",
",",
"dev_id",
")",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/device.py#L120-L136 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.