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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | AboutDialogInfo._GetWebSiteURL | (*args, **kwargs) | return _misc_.AboutDialogInfo__GetWebSiteURL(*args, **kwargs) | _GetWebSiteURL(self) -> String | _GetWebSiteURL(self) -> String | [
"_GetWebSiteURL",
"(",
"self",
")",
"-",
">",
"String"
] | def _GetWebSiteURL(*args, **kwargs):
"""_GetWebSiteURL(self) -> String"""
return _misc_.AboutDialogInfo__GetWebSiteURL(*args, **kwargs) | [
"def",
"_GetWebSiteURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"AboutDialogInfo__GetWebSiteURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6767-L6769 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/python/op_hint.py | python | _LiteAggregateOperand.aggregate_and_return_name_for_input | (self, out_graphdef) | This adds the nodes to out_graphdef and returns an aggregated output.
In particular, if you have 4 inputs to a hint stub, this will be the
node that you can use as an output. I.e. you have 4 timesteps from a
static rnn, then a fused UnidirectionalLSTM will expect 1 input with
all 4 time steps. So here we make a pack and return the output name of
that pack.
Args:
out_graphdef: A graphdef that is ready to have this input added.
Returns:
The name of a pack that aggregates this node. | This adds the nodes to out_graphdef and returns an aggregated output. | [
"This",
"adds",
"the",
"nodes",
"to",
"out_graphdef",
"and",
"returns",
"an",
"aggregated",
"output",
"."
] | def aggregate_and_return_name_for_input(self, out_graphdef):
"""This adds the nodes to out_graphdef and returns an aggregated output.
In particular, if you have 4 inputs to a hint stub, this will be the
node that you can use as an output. I.e. you have 4 timesteps from a
static rnn, then a fused UnidirectionalLSTM will expect 1 input with
all 4 time steps. So here we make a pack and return the output name of
that pack.
Args:
out_graphdef: A graphdef that is ready to have this input added.
Returns:
The name of a pack that aggregates this node.
"""
flattened = self.flatten_nodes()
if (self.aggregation == OpHint.AGGREGATE_FIRST) or (
self.aggregation == OpHint.AGGREGATE_LAST):
assert len(flattened) == 1
if len(flattened) == 1 and self.aggregation != OpHint.AGGREGATE_STACK:
return _tensor_name_base(flattened[0].name)
else:
new_node = _node_def_pb2.NodeDef()
new_node.op = "Pack"
new_node.name = "OpHintStack-%s" % flattened[0].name
new_node.attr["N"].i = len(flattened)
new_node.attr["T"].type = flattened[0].attr["T"].type
for discrete in flattened:
new_node.input.append(_tensor_name_base(discrete.name))
out_graphdef.node.extend([new_node])
return new_node.name | [
"def",
"aggregate_and_return_name_for_input",
"(",
"self",
",",
"out_graphdef",
")",
":",
"flattened",
"=",
"self",
".",
"flatten_nodes",
"(",
")",
"if",
"(",
"self",
".",
"aggregation",
"==",
"OpHint",
".",
"AGGREGATE_FIRST",
")",
"or",
"(",
"self",
".",
"aggregation",
"==",
"OpHint",
".",
"AGGREGATE_LAST",
")",
":",
"assert",
"len",
"(",
"flattened",
")",
"==",
"1",
"if",
"len",
"(",
"flattened",
")",
"==",
"1",
"and",
"self",
".",
"aggregation",
"!=",
"OpHint",
".",
"AGGREGATE_STACK",
":",
"return",
"_tensor_name_base",
"(",
"flattened",
"[",
"0",
"]",
".",
"name",
")",
"else",
":",
"new_node",
"=",
"_node_def_pb2",
".",
"NodeDef",
"(",
")",
"new_node",
".",
"op",
"=",
"\"Pack\"",
"new_node",
".",
"name",
"=",
"\"OpHintStack-%s\"",
"%",
"flattened",
"[",
"0",
"]",
".",
"name",
"new_node",
".",
"attr",
"[",
"\"N\"",
"]",
".",
"i",
"=",
"len",
"(",
"flattened",
")",
"new_node",
".",
"attr",
"[",
"\"T\"",
"]",
".",
"type",
"=",
"flattened",
"[",
"0",
"]",
".",
"attr",
"[",
"\"T\"",
"]",
".",
"type",
"for",
"discrete",
"in",
"flattened",
":",
"new_node",
".",
"input",
".",
"append",
"(",
"_tensor_name_base",
"(",
"discrete",
".",
"name",
")",
")",
"out_graphdef",
".",
"node",
".",
"extend",
"(",
"[",
"new_node",
"]",
")",
"return",
"new_node",
".",
"name"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/op_hint.py#L583-L613 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/toolchain/apple/linker_driver.py | python | LinkerDriver.run | (self) | Runs the linker driver, separating out the main compiler driver's
arguments from the ones handled by this class. It then invokes the
required tools, starting with the compiler driver to produce the linker
output. | Runs the linker driver, separating out the main compiler driver's
arguments from the ones handled by this class. It then invokes the
required tools, starting with the compiler driver to produce the linker
output. | [
"Runs",
"the",
"linker",
"driver",
"separating",
"out",
"the",
"main",
"compiler",
"driver",
"s",
"arguments",
"from",
"the",
"ones",
"handled",
"by",
"this",
"class",
".",
"It",
"then",
"invokes",
"the",
"required",
"tools",
"starting",
"with",
"the",
"compiler",
"driver",
"to",
"produce",
"the",
"linker",
"output",
"."
] | def run(self):
"""Runs the linker driver, separating out the main compiler driver's
arguments from the ones handled by this class. It then invokes the
required tools, starting with the compiler driver to produce the linker
output.
"""
# Collect arguments to the linker driver (this script) and remove them
# from the arguments being passed to the compiler driver.
linker_driver_actions = {}
compiler_driver_args = []
for index, arg in enumerate(self._args[1:]):
if arg.startswith(LINKER_DRIVER_ARG_PREFIX):
# Convert driver actions into a map of name => lambda to invoke.
driver_action = self._process_driver_arg(arg)
assert driver_action[0] not in linker_driver_actions
linker_driver_actions[driver_action[0]] = driver_action[1]
else:
compiler_driver_args.append(arg)
if self._get_linker_output() is None:
raise ValueError(
'Could not find path to linker output (-o or --output)')
linker_driver_outputs = [self._get_linker_output()]
try:
# Zero the mtime in OSO fields for deterministic builds.
# https://crbug.com/330262.
env = os.environ.copy()
env['ZERO_AR_DATE'] = '1'
# Run the linker by invoking the compiler driver.
subprocess.check_call(compiler_driver_args, env=env)
# Run the linker driver actions, in the order specified by the
# actions list.
for action in self._actions:
name = action[0]
if name in linker_driver_actions:
linker_driver_outputs += linker_driver_actions[name]()
except:
# If a linker driver action failed, remove all the outputs to make
# the build step atomic.
map(_remove_path, linker_driver_outputs)
# Re-report the original failure.
raise | [
"def",
"run",
"(",
"self",
")",
":",
"# Collect arguments to the linker driver (this script) and remove them",
"# from the arguments being passed to the compiler driver.",
"linker_driver_actions",
"=",
"{",
"}",
"compiler_driver_args",
"=",
"[",
"]",
"for",
"index",
",",
"arg",
"in",
"enumerate",
"(",
"self",
".",
"_args",
"[",
"1",
":",
"]",
")",
":",
"if",
"arg",
".",
"startswith",
"(",
"LINKER_DRIVER_ARG_PREFIX",
")",
":",
"# Convert driver actions into a map of name => lambda to invoke.",
"driver_action",
"=",
"self",
".",
"_process_driver_arg",
"(",
"arg",
")",
"assert",
"driver_action",
"[",
"0",
"]",
"not",
"in",
"linker_driver_actions",
"linker_driver_actions",
"[",
"driver_action",
"[",
"0",
"]",
"]",
"=",
"driver_action",
"[",
"1",
"]",
"else",
":",
"compiler_driver_args",
".",
"append",
"(",
"arg",
")",
"if",
"self",
".",
"_get_linker_output",
"(",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Could not find path to linker output (-o or --output)'",
")",
"linker_driver_outputs",
"=",
"[",
"self",
".",
"_get_linker_output",
"(",
")",
"]",
"try",
":",
"# Zero the mtime in OSO fields for deterministic builds.",
"# https://crbug.com/330262.",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
"[",
"'ZERO_AR_DATE'",
"]",
"=",
"'1'",
"# Run the linker by invoking the compiler driver.",
"subprocess",
".",
"check_call",
"(",
"compiler_driver_args",
",",
"env",
"=",
"env",
")",
"# Run the linker driver actions, in the order specified by the",
"# actions list.",
"for",
"action",
"in",
"self",
".",
"_actions",
":",
"name",
"=",
"action",
"[",
"0",
"]",
"if",
"name",
"in",
"linker_driver_actions",
":",
"linker_driver_outputs",
"+=",
"linker_driver_actions",
"[",
"name",
"]",
"(",
")",
"except",
":",
"# If a linker driver action failed, remove all the outputs to make",
"# the build step atomic.",
"map",
"(",
"_remove_path",
",",
"linker_driver_outputs",
")",
"# Re-report the original failure.",
"raise"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/toolchain/apple/linker_driver.py#L85-L130 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_trimex.py | python | Trimex.GetResources | (self) | return {'Pixmap': 'Draft_Trimex',
'Accel': "T, R",
'MenuText': QT_TRANSLATE_NOOP("Draft_Trimex", "Trimex"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Trimex",
"Trims or extends the selected object, or extrudes single"
+ " faces.\nCTRL snaps, SHIFT constrains to current segment"
+ " or to normal, ALT inverts.")} | Set icon, menu and tooltip. | Set icon, menu and tooltip. | [
"Set",
"icon",
"menu",
"and",
"tooltip",
"."
] | def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_Trimex',
'Accel': "T, R",
'MenuText': QT_TRANSLATE_NOOP("Draft_Trimex", "Trimex"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Trimex",
"Trims or extends the selected object, or extrudes single"
+ " faces.\nCTRL snaps, SHIFT constrains to current segment"
+ " or to normal, ALT inverts.")} | [
"def",
"GetResources",
"(",
"self",
")",
":",
"return",
"{",
"'Pixmap'",
":",
"'Draft_Trimex'",
",",
"'Accel'",
":",
"\"T, R\"",
",",
"'MenuText'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Trimex\"",
",",
"\"Trimex\"",
")",
",",
"'ToolTip'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Trimex\"",
",",
"\"Trims or extends the selected object, or extrudes single\"",
"+",
"\" faces.\\nCTRL snaps, SHIFT constrains to current segment\"",
"+",
"\" or to normal, ALT inverts.\"",
")",
"}"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trimex.py#L71-L80 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/bucket.py | python | Bucket.set_canned_acl | (self, acl_str, key_name='', headers=None,
version_id=None, generation=None, if_generation=None,
if_metageneration=None) | return self._set_acl_helper(acl_str, key_name, headers, query_args,
generation, if_generation,
if_metageneration, canned=True) | Sets a bucket's or objects's ACL using a predefined (canned) value.
:type acl_str: string
:param acl_str: A canned ACL string. See
:data:`~.gs.acl.CannedACLStrings`.
:type key_name: string
:param key_name: A key name within the bucket to set the ACL for. If not
specified, the ACL for the bucket will be set.
:type headers: dict
:param headers: Additional headers to set during the request.
:type version_id: string
:param version_id: Unused in this subclass.
:type generation: int
:param generation: If specified, sets the ACL for a specific generation
of a versioned object. If not specified, the current version is
modified.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the acl
will only be updated if its current generation number is this value.
:type if_metageneration: int
:param if_metageneration: (optional) If set to a metageneration number,
the acl will only be updated if its current metageneration number is
this value. | Sets a bucket's or objects's ACL using a predefined (canned) value. | [
"Sets",
"a",
"bucket",
"s",
"or",
"objects",
"s",
"ACL",
"using",
"a",
"predefined",
"(",
"canned",
")",
"value",
"."
] | def set_canned_acl(self, acl_str, key_name='', headers=None,
version_id=None, generation=None, if_generation=None,
if_metageneration=None):
"""Sets a bucket's or objects's ACL using a predefined (canned) value.
:type acl_str: string
:param acl_str: A canned ACL string. See
:data:`~.gs.acl.CannedACLStrings`.
:type key_name: string
:param key_name: A key name within the bucket to set the ACL for. If not
specified, the ACL for the bucket will be set.
:type headers: dict
:param headers: Additional headers to set during the request.
:type version_id: string
:param version_id: Unused in this subclass.
:type generation: int
:param generation: If specified, sets the ACL for a specific generation
of a versioned object. If not specified, the current version is
modified.
:type if_generation: int
:param if_generation: (optional) If set to a generation number, the acl
will only be updated if its current generation number is this value.
:type if_metageneration: int
:param if_metageneration: (optional) If set to a metageneration number,
the acl will only be updated if its current metageneration number is
this value.
"""
if acl_str not in CannedACLStrings:
raise ValueError("Provided canned ACL string (%s) is not valid."
% acl_str)
query_args = STANDARD_ACL
return self._set_acl_helper(acl_str, key_name, headers, query_args,
generation, if_generation,
if_metageneration, canned=True) | [
"def",
"set_canned_acl",
"(",
"self",
",",
"acl_str",
",",
"key_name",
"=",
"''",
",",
"headers",
"=",
"None",
",",
"version_id",
"=",
"None",
",",
"generation",
"=",
"None",
",",
"if_generation",
"=",
"None",
",",
"if_metageneration",
"=",
"None",
")",
":",
"if",
"acl_str",
"not",
"in",
"CannedACLStrings",
":",
"raise",
"ValueError",
"(",
"\"Provided canned ACL string (%s) is not valid.\"",
"%",
"acl_str",
")",
"query_args",
"=",
"STANDARD_ACL",
"return",
"self",
".",
"_set_acl_helper",
"(",
"acl_str",
",",
"key_name",
",",
"headers",
",",
"query_args",
",",
"generation",
",",
"if_generation",
",",
"if_metageneration",
",",
"canned",
"=",
"True",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/bucket.py#L489-L528 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | utils/vim-lldb/python-vim-lldb/vim_panes.py | python | PaneLayout.hide | (self, panes=[]) | Hide panes specified. If empty list provided, hide all. | Hide panes specified. If empty list provided, hide all. | [
"Hide",
"panes",
"specified",
".",
"If",
"empty",
"list",
"provided",
"hide",
"all",
"."
] | def hide(self, panes=[]):
""" Hide panes specified. If empty list provided, hide all. """
for name in self.panes:
if name in panes or len(panes) == 0:
self.panes[name].destroy() | [
"def",
"hide",
"(",
"self",
",",
"panes",
"=",
"[",
"]",
")",
":",
"for",
"name",
"in",
"self",
".",
"panes",
":",
"if",
"name",
"in",
"panes",
"or",
"len",
"(",
"panes",
")",
"==",
"0",
":",
"self",
".",
"panes",
"[",
"name",
"]",
".",
"destroy",
"(",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/vim_panes.py#L212-L216 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py | python | Driver.implicit_sync | (self) | Implicit synchronization for all asynchronous streams
across all devices. | Implicit synchronization for all asynchronous streams
across all devices. | [
"Implicit",
"synchronization",
"for",
"all",
"asynchronous",
"streams",
"across",
"all",
"devices",
"."
] | def implicit_sync(self):
"""
Implicit synchronization for all asynchronous streams
across all devices.
"""
_logger.info("implicit sync")
for st in self._active_streams:
st.synchronize() | [
"def",
"implicit_sync",
"(",
"self",
")",
":",
"_logger",
".",
"info",
"(",
"\"implicit sync\"",
")",
"for",
"st",
"in",
"self",
".",
"_active_streams",
":",
"st",
".",
"synchronize",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/driver.py#L347-L354 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_trackers.py | python | rectangleTracker.getSize | (self) | return ((DraftVecUtils.project(diag, self.u)).Length,
(DraftVecUtils.project(diag, self.v)).Length) | Return (length, width) of the rectangle. | Return (length, width) of the rectangle. | [
"Return",
"(",
"length",
"width",
")",
"of",
"the",
"rectangle",
"."
] | def getSize(self):
"""Return (length, width) of the rectangle."""
p1 = Vector(self.coords.point.getValues()[0].getValue())
p2 = Vector(self.coords.point.getValues()[2].getValue())
diag = p2.sub(p1)
return ((DraftVecUtils.project(diag, self.u)).Length,
(DraftVecUtils.project(diag, self.v)).Length) | [
"def",
"getSize",
"(",
"self",
")",
":",
"p1",
"=",
"Vector",
"(",
"self",
".",
"coords",
".",
"point",
".",
"getValues",
"(",
")",
"[",
"0",
"]",
".",
"getValue",
"(",
")",
")",
"p2",
"=",
"Vector",
"(",
"self",
".",
"coords",
".",
"point",
".",
"getValues",
"(",
")",
"[",
"2",
"]",
".",
"getValue",
"(",
")",
")",
"diag",
"=",
"p2",
".",
"sub",
"(",
"p1",
")",
"return",
"(",
"(",
"DraftVecUtils",
".",
"project",
"(",
"diag",
",",
"self",
".",
"u",
")",
")",
".",
"Length",
",",
"(",
"DraftVecUtils",
".",
"project",
"(",
"diag",
",",
"self",
".",
"v",
")",
")",
".",
"Length",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trackers.py#L292-L298 | |
KhronosGroup/SPIRV-LLVM | 1eb85593f3fe2c39379b9a9b088d51eda4f42b8b | bindings/python/llvm/disassembler.py | python | Disassembler.get_instruction | (self, source, pc=0) | return (result, out_str.value) | Obtain the next instruction from an input source.
The input source should be a str or bytearray or something that
represents a sequence of bytes.
This function will start reading bytes from the beginning of the
source.
The pc argument specifies the address that the first byte is at.
This returns a 2-tuple of:
long number of bytes read. 0 if no instruction was read.
str representation of instruction. This will be the assembly that
represents the instruction. | Obtain the next instruction from an input source. | [
"Obtain",
"the",
"next",
"instruction",
"from",
"an",
"input",
"source",
"."
] | def get_instruction(self, source, pc=0):
"""Obtain the next instruction from an input source.
The input source should be a str or bytearray or something that
represents a sequence of bytes.
This function will start reading bytes from the beginning of the
source.
The pc argument specifies the address that the first byte is at.
This returns a 2-tuple of:
long number of bytes read. 0 if no instruction was read.
str representation of instruction. This will be the assembly that
represents the instruction.
"""
buf = cast(c_char_p(source), POINTER(c_ubyte))
out_str = cast((c_byte * 255)(), c_char_p)
result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)),
c_uint64(pc), out_str, 255)
return (result, out_str.value) | [
"def",
"get_instruction",
"(",
"self",
",",
"source",
",",
"pc",
"=",
"0",
")",
":",
"buf",
"=",
"cast",
"(",
"c_char_p",
"(",
"source",
")",
",",
"POINTER",
"(",
"c_ubyte",
")",
")",
"out_str",
"=",
"cast",
"(",
"(",
"c_byte",
"*",
"255",
")",
"(",
")",
",",
"c_char_p",
")",
"result",
"=",
"lib",
".",
"LLVMDisasmInstruction",
"(",
"self",
",",
"buf",
",",
"c_uint64",
"(",
"len",
"(",
"source",
")",
")",
",",
"c_uint64",
"(",
"pc",
")",
",",
"out_str",
",",
"255",
")",
"return",
"(",
"result",
",",
"out_str",
".",
"value",
")"
] | https://github.com/KhronosGroup/SPIRV-LLVM/blob/1eb85593f3fe2c39379b9a9b088d51eda4f42b8b/bindings/python/llvm/disassembler.py#L84-L107 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel._get_closest_point_distance_brute | (self, points) | return dist | Return the distance between the two closest points. | Return the distance between the two closest points. | [
"Return",
"the",
"distance",
"between",
"the",
"two",
"closest",
"points",
"."
] | def _get_closest_point_distance_brute(self, points):
"""Return the distance between the two closest points."""
point_count = len(points)
dist = sys.float_info.max
for i in range(1, point_count):
for j in range(i):
dist = min(dist, self._distance_between(points[i],
points[j]))
return dist | [
"def",
"_get_closest_point_distance_brute",
"(",
"self",
",",
"points",
")",
":",
"point_count",
"=",
"len",
"(",
"points",
")",
"dist",
"=",
"sys",
".",
"float_info",
".",
"max",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"point_count",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
")",
":",
"dist",
"=",
"min",
"(",
"dist",
",",
"self",
".",
"_distance_between",
"(",
"points",
"[",
"i",
"]",
",",
"points",
"[",
"j",
"]",
")",
")",
"return",
"dist"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L8430-L8438 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mimify.py | python | mimify_part | (ifile, ofile, is_mime) | Convert an 8bit part of a MIME mail message to quoted-printable. | Convert an 8bit part of a MIME mail message to quoted-printable. | [
"Convert",
"an",
"8bit",
"part",
"of",
"a",
"MIME",
"mail",
"message",
"to",
"quoted",
"-",
"printable",
"."
] | def mimify_part(ifile, ofile, is_mime):
"""Convert an 8bit part of a MIME mail message to quoted-printable."""
has_cte = is_qp = is_base64 = 0
multipart = None
must_quote_body = must_quote_header = has_iso_chars = 0
header = []
header_end = ''
message = []
message_end = ''
# read header
hfile = HeaderFile(ifile)
while 1:
line = hfile.readline()
if not line:
break
if not must_quote_header and iso_char.search(line):
must_quote_header = 1
if mv.match(line):
is_mime = 1
if cte.match(line):
has_cte = 1
if qp.match(line):
is_qp = 1
elif base64_re.match(line):
is_base64 = 1
mp_res = mp.match(line)
if mp_res:
multipart = '--' + mp_res.group(1)
if he.match(line):
header_end = line
break
header.append(line)
# read body
while 1:
line = ifile.readline()
if not line:
break
if multipart:
if line == multipart + '--\n':
message_end = line
break
if line == multipart + '\n':
message_end = line
break
if is_base64:
message.append(line)
continue
if is_qp:
while line[-2:] == '=\n':
line = line[:-2]
newline = ifile.readline()
if newline[:len(QUOTE)] == QUOTE:
newline = newline[len(QUOTE):]
line = line + newline
line = mime_decode(line)
message.append(line)
if not has_iso_chars:
if iso_char.search(line):
has_iso_chars = must_quote_body = 1
if not must_quote_body:
if len(line) > MAXLEN:
must_quote_body = 1
# convert and output header and body
for line in header:
if must_quote_header:
line = mime_encode_header(line)
chrset_res = chrset.match(line)
if chrset_res:
if has_iso_chars:
# change us-ascii into iso-8859-1
if chrset_res.group(2).lower() == 'us-ascii':
line = '%s%s%s' % (chrset_res.group(1),
CHARSET,
chrset_res.group(3))
else:
# change iso-8859-* into us-ascii
line = '%sus-ascii%s' % chrset_res.group(1, 3)
if has_cte and cte.match(line):
line = 'Content-Transfer-Encoding: '
if is_base64:
line = line + 'base64\n'
elif must_quote_body:
line = line + 'quoted-printable\n'
else:
line = line + '7bit\n'
ofile.write(line)
if (must_quote_header or must_quote_body) and not is_mime:
ofile.write('Mime-Version: 1.0\n')
ofile.write('Content-Type: text/plain; ')
if has_iso_chars:
ofile.write('charset="%s"\n' % CHARSET)
else:
ofile.write('charset="us-ascii"\n')
if must_quote_body and not has_cte:
ofile.write('Content-Transfer-Encoding: quoted-printable\n')
ofile.write(header_end)
for line in message:
if must_quote_body:
line = mime_encode(line, 0)
ofile.write(line)
ofile.write(message_end)
line = message_end
while multipart:
if line == multipart + '--\n':
# read bit after the end of the last part
while 1:
line = ifile.readline()
if not line:
return
if must_quote_body:
line = mime_encode(line, 0)
ofile.write(line)
if line == multipart + '\n':
nifile = File(ifile, multipart)
mimify_part(nifile, ofile, 1)
line = nifile.peek
if not line:
# premature end of file
break
ofile.write(line)
continue
# unexpectedly no multipart separator--copy rest of file
while 1:
line = ifile.readline()
if not line:
return
if must_quote_body:
line = mime_encode(line, 0)
ofile.write(line) | [
"def",
"mimify_part",
"(",
"ifile",
",",
"ofile",
",",
"is_mime",
")",
":",
"has_cte",
"=",
"is_qp",
"=",
"is_base64",
"=",
"0",
"multipart",
"=",
"None",
"must_quote_body",
"=",
"must_quote_header",
"=",
"has_iso_chars",
"=",
"0",
"header",
"=",
"[",
"]",
"header_end",
"=",
"''",
"message",
"=",
"[",
"]",
"message_end",
"=",
"''",
"# read header",
"hfile",
"=",
"HeaderFile",
"(",
"ifile",
")",
"while",
"1",
":",
"line",
"=",
"hfile",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"if",
"not",
"must_quote_header",
"and",
"iso_char",
".",
"search",
"(",
"line",
")",
":",
"must_quote_header",
"=",
"1",
"if",
"mv",
".",
"match",
"(",
"line",
")",
":",
"is_mime",
"=",
"1",
"if",
"cte",
".",
"match",
"(",
"line",
")",
":",
"has_cte",
"=",
"1",
"if",
"qp",
".",
"match",
"(",
"line",
")",
":",
"is_qp",
"=",
"1",
"elif",
"base64_re",
".",
"match",
"(",
"line",
")",
":",
"is_base64",
"=",
"1",
"mp_res",
"=",
"mp",
".",
"match",
"(",
"line",
")",
"if",
"mp_res",
":",
"multipart",
"=",
"'--'",
"+",
"mp_res",
".",
"group",
"(",
"1",
")",
"if",
"he",
".",
"match",
"(",
"line",
")",
":",
"header_end",
"=",
"line",
"break",
"header",
".",
"append",
"(",
"line",
")",
"# read body",
"while",
"1",
":",
"line",
"=",
"ifile",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"if",
"multipart",
":",
"if",
"line",
"==",
"multipart",
"+",
"'--\\n'",
":",
"message_end",
"=",
"line",
"break",
"if",
"line",
"==",
"multipart",
"+",
"'\\n'",
":",
"message_end",
"=",
"line",
"break",
"if",
"is_base64",
":",
"message",
".",
"append",
"(",
"line",
")",
"continue",
"if",
"is_qp",
":",
"while",
"line",
"[",
"-",
"2",
":",
"]",
"==",
"'=\\n'",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
"newline",
"=",
"ifile",
".",
"readline",
"(",
")",
"if",
"newline",
"[",
":",
"len",
"(",
"QUOTE",
")",
"]",
"==",
"QUOTE",
":",
"newline",
"=",
"newline",
"[",
"len",
"(",
"QUOTE",
")",
":",
"]",
"line",
"=",
"line",
"+",
"newline",
"line",
"=",
"mime_decode",
"(",
"line",
")",
"message",
".",
"append",
"(",
"line",
")",
"if",
"not",
"has_iso_chars",
":",
"if",
"iso_char",
".",
"search",
"(",
"line",
")",
":",
"has_iso_chars",
"=",
"must_quote_body",
"=",
"1",
"if",
"not",
"must_quote_body",
":",
"if",
"len",
"(",
"line",
")",
">",
"MAXLEN",
":",
"must_quote_body",
"=",
"1",
"# convert and output header and body",
"for",
"line",
"in",
"header",
":",
"if",
"must_quote_header",
":",
"line",
"=",
"mime_encode_header",
"(",
"line",
")",
"chrset_res",
"=",
"chrset",
".",
"match",
"(",
"line",
")",
"if",
"chrset_res",
":",
"if",
"has_iso_chars",
":",
"# change us-ascii into iso-8859-1",
"if",
"chrset_res",
".",
"group",
"(",
"2",
")",
".",
"lower",
"(",
")",
"==",
"'us-ascii'",
":",
"line",
"=",
"'%s%s%s'",
"%",
"(",
"chrset_res",
".",
"group",
"(",
"1",
")",
",",
"CHARSET",
",",
"chrset_res",
".",
"group",
"(",
"3",
")",
")",
"else",
":",
"# change iso-8859-* into us-ascii",
"line",
"=",
"'%sus-ascii%s'",
"%",
"chrset_res",
".",
"group",
"(",
"1",
",",
"3",
")",
"if",
"has_cte",
"and",
"cte",
".",
"match",
"(",
"line",
")",
":",
"line",
"=",
"'Content-Transfer-Encoding: '",
"if",
"is_base64",
":",
"line",
"=",
"line",
"+",
"'base64\\n'",
"elif",
"must_quote_body",
":",
"line",
"=",
"line",
"+",
"'quoted-printable\\n'",
"else",
":",
"line",
"=",
"line",
"+",
"'7bit\\n'",
"ofile",
".",
"write",
"(",
"line",
")",
"if",
"(",
"must_quote_header",
"or",
"must_quote_body",
")",
"and",
"not",
"is_mime",
":",
"ofile",
".",
"write",
"(",
"'Mime-Version: 1.0\\n'",
")",
"ofile",
".",
"write",
"(",
"'Content-Type: text/plain; '",
")",
"if",
"has_iso_chars",
":",
"ofile",
".",
"write",
"(",
"'charset=\"%s\"\\n'",
"%",
"CHARSET",
")",
"else",
":",
"ofile",
".",
"write",
"(",
"'charset=\"us-ascii\"\\n'",
")",
"if",
"must_quote_body",
"and",
"not",
"has_cte",
":",
"ofile",
".",
"write",
"(",
"'Content-Transfer-Encoding: quoted-printable\\n'",
")",
"ofile",
".",
"write",
"(",
"header_end",
")",
"for",
"line",
"in",
"message",
":",
"if",
"must_quote_body",
":",
"line",
"=",
"mime_encode",
"(",
"line",
",",
"0",
")",
"ofile",
".",
"write",
"(",
"line",
")",
"ofile",
".",
"write",
"(",
"message_end",
")",
"line",
"=",
"message_end",
"while",
"multipart",
":",
"if",
"line",
"==",
"multipart",
"+",
"'--\\n'",
":",
"# read bit after the end of the last part",
"while",
"1",
":",
"line",
"=",
"ifile",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"return",
"if",
"must_quote_body",
":",
"line",
"=",
"mime_encode",
"(",
"line",
",",
"0",
")",
"ofile",
".",
"write",
"(",
"line",
")",
"if",
"line",
"==",
"multipart",
"+",
"'\\n'",
":",
"nifile",
"=",
"File",
"(",
"ifile",
",",
"multipart",
")",
"mimify_part",
"(",
"nifile",
",",
"ofile",
",",
"1",
")",
"line",
"=",
"nifile",
".",
"peek",
"if",
"not",
"line",
":",
"# premature end of file",
"break",
"ofile",
".",
"write",
"(",
"line",
")",
"continue",
"# unexpectedly no multipart separator--copy rest of file",
"while",
"1",
":",
"line",
"=",
"ifile",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"return",
"if",
"must_quote_body",
":",
"line",
"=",
"mime_encode",
"(",
"line",
",",
"0",
")",
"ofile",
".",
"write",
"(",
"line",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mimify.py#L280-L413 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py | python | ParserElement.suppress | ( self ) | return Suppress( self ) | Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output. | Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output. | [
"Suppresses",
"the",
"output",
"of",
"this",
"C",
"{",
"ParserElement",
"}",
";",
"useful",
"to",
"keep",
"punctuation",
"from",
"cluttering",
"up",
"returned",
"output",
"."
] | def suppress( self ):
"""
Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output.
"""
return Suppress( self ) | [
"def",
"suppress",
"(",
"self",
")",
":",
"return",
"Suppress",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L2045-L2050 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Data.py | python | Data.set_blob | (self, blob) | Sets the blob with data. | Sets the blob with data. | [
"Sets",
"the",
"blob",
"with",
"data",
"."
] | def set_blob(self, blob):
"""Sets the blob with data.
"""
self._internal.set_blob(blob._internal) | [
"def",
"set_blob",
"(",
"self",
",",
"blob",
")",
":",
"self",
".",
"_internal",
".",
"set_blob",
"(",
"blob",
".",
"_internal",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Data.py#L47-L50 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/misc.py | python | pairwise | (iterable) | return zip_longest(iterable, iterable) | Return paired elements.
For example:
s -> (s0, s1), (s2, s3), (s4, s5), ... | Return paired elements. | [
"Return",
"paired",
"elements",
"."
] | def pairwise(iterable):
# type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]
"""
Return paired elements.
For example:
s -> (s0, s1), (s2, s3), (s4, s5), ...
"""
iterable = iter(iterable)
return zip_longest(iterable, iterable) | [
"def",
"pairwise",
"(",
"iterable",
")",
":",
"# type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"return",
"zip_longest",
"(",
"iterable",
",",
"iterable",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/misc.py#L903-L912 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/msvc.py | python | validate_vars | (env) | Validate the PCH and PCHSTOP construction variables. | Validate the PCH and PCHSTOP construction variables. | [
"Validate",
"the",
"PCH",
"and",
"PCHSTOP",
"construction",
"variables",
"."
] | def validate_vars(env):
"""Validate the PCH and PCHSTOP construction variables."""
if 'PCH' in env and env['PCH']:
if 'PCHSTOP' not in env:
raise SCons.Errors.UserError("The PCHSTOP construction must be defined if PCH is defined.")
if not SCons.Util.is_String(env['PCHSTOP']):
raise SCons.Errors.UserError("The PCHSTOP construction variable must be a string: %r"%env['PCHSTOP']) | [
"def",
"validate_vars",
"(",
"env",
")",
":",
"if",
"'PCH'",
"in",
"env",
"and",
"env",
"[",
"'PCH'",
"]",
":",
"if",
"'PCHSTOP'",
"not",
"in",
"env",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"The PCHSTOP construction must be defined if PCH is defined.\"",
")",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_String",
"(",
"env",
"[",
"'PCHSTOP'",
"]",
")",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"The PCHSTOP construction variable must be a string: %r\"",
"%",
"env",
"[",
"'PCHSTOP'",
"]",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/msvc.py#L54-L60 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Wrapping/Generators/Python/itk/support/extras.py | python | set_nthreads | (number_of_threads: int) | Support convenient set of the number of threads.
Use example (in python):
import itk
itk.set_nthreads(4) ## use 4 threads | Support convenient set of the number of threads.
Use example (in python):
import itk
itk.set_nthreads(4) ## use 4 threads | [
"Support",
"convenient",
"set",
"of",
"the",
"number",
"of",
"threads",
".",
"Use",
"example",
"(",
"in",
"python",
")",
":",
"import",
"itk",
"itk",
".",
"set_nthreads",
"(",
"4",
")",
"##",
"use",
"4",
"threads"
] | def set_nthreads(number_of_threads: int) -> None:
"""
Support convenient set of the number of threads.
Use example (in python):
import itk
itk.set_nthreads(4) ## use 4 threads
"""
assert number_of_threads > 0, (
"Please set a positive number of threads instead of %d" % number_of_threads
)
import itk
threader = itk.MultiThreaderBase.New()
threader.SetGlobalDefaultNumberOfThreads(number_of_threads) | [
"def",
"set_nthreads",
"(",
"number_of_threads",
":",
"int",
")",
"->",
"None",
":",
"assert",
"number_of_threads",
">",
"0",
",",
"(",
"\"Please set a positive number of threads instead of %d\"",
"%",
"number_of_threads",
")",
"import",
"itk",
"threader",
"=",
"itk",
".",
"MultiThreaderBase",
".",
"New",
"(",
")",
"threader",
".",
"SetGlobalDefaultNumberOfThreads",
"(",
"number_of_threads",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Wrapping/Generators/Python/itk/support/extras.py#L135-L149 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/groupby/groupby.py | python | GroupBy.cummax | (self) | return self.agg("cummax") | Get the column-wise cumulative maximum value in each group. | Get the column-wise cumulative maximum value in each group. | [
"Get",
"the",
"column",
"-",
"wise",
"cumulative",
"maximum",
"value",
"in",
"each",
"group",
"."
] | def cummax(self):
"""Get the column-wise cumulative maximum value in each group."""
return self.agg("cummax") | [
"def",
"cummax",
"(",
"self",
")",
":",
"return",
"self",
".",
"agg",
"(",
"\"cummax\"",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/groupby/groupby.py#L1029-L1031 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/session_ops.py | python | TensorHandle._get_reader_key | (handle) | return handle_parts[0] + ";" + handle_parts[-1] | The graph key for reader. | The graph key for reader. | [
"The",
"graph",
"key",
"for",
"reader",
"."
] | def _get_reader_key(handle):
"""The graph key for reader."""
handle_parts = str(handle).split(";")
return handle_parts[0] + ";" + handle_parts[-1] | [
"def",
"_get_reader_key",
"(",
"handle",
")",
":",
"handle_parts",
"=",
"str",
"(",
"handle",
")",
".",
"split",
"(",
"\";\"",
")",
"return",
"handle_parts",
"[",
"0",
"]",
"+",
"\";\"",
"+",
"handle_parts",
"[",
"-",
"1",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/session_ops.py#L104-L107 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/xapian/xapian-maintainer-tools/audit.py | python | SourceChecker.join_slashed_lines | (self, lines) | return newlines | Join lines terminated with \ together | Join lines terminated with \ together | [
"Join",
"lines",
"terminated",
"with",
"\\",
"together"
] | def join_slashed_lines(self, lines):
"Join lines terminated with \ together"
newlines = []
had_slash = False
for line in lines:
if had_slash:
newlines[-1] += line
else:
newlines.append(line)
had_slash = False
if line.endswith('\\'):
had_slash = True
newlines[-1] = newlines[-1][:-1]
return newlines | [
"def",
"join_slashed_lines",
"(",
"self",
",",
"lines",
")",
":",
"newlines",
"=",
"[",
"]",
"had_slash",
"=",
"False",
"for",
"line",
"in",
"lines",
":",
"if",
"had_slash",
":",
"newlines",
"[",
"-",
"1",
"]",
"+=",
"line",
"else",
":",
"newlines",
".",
"append",
"(",
"line",
")",
"had_slash",
"=",
"False",
"if",
"line",
".",
"endswith",
"(",
"'\\\\'",
")",
":",
"had_slash",
"=",
"True",
"newlines",
"[",
"-",
"1",
"]",
"=",
"newlines",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"return",
"newlines"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/xapian/xapian-maintainer-tools/audit.py#L292-L306 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/internal/well_known_types.py | python | Any.TypeName | (self) | return self.type_url.split('/')[-1] | Returns the protobuf type name of the inner message. | Returns the protobuf type name of the inner message. | [
"Returns",
"the",
"protobuf",
"type",
"name",
"of",
"the",
"inner",
"message",
"."
] | def TypeName(self):
"""Returns the protobuf type name of the inner message."""
# Only last part is to be used: b/25630112
return self.type_url.split('/')[-1] | [
"def",
"TypeName",
"(",
"self",
")",
":",
"# Only last part is to be used: b/25630112",
"return",
"self",
".",
"type_url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/well_known_types.py#L82-L85 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Misc.winfo_class | (self) | return self.tk.call('winfo', 'class', self._w) | Return window class name of this widget. | Return window class name of this widget. | [
"Return",
"window",
"class",
"name",
"of",
"this",
"widget",
"."
] | def winfo_class(self):
"""Return window class name of this widget."""
return self.tk.call('winfo', 'class', self._w) | [
"def",
"winfo_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'class'",
",",
"self",
".",
"_w",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L968-L970 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/indexes/datetimelike.py | python | DatetimeIndexOpsMixin._summary | (self, name=None) | return result | Return a summarized representation.
Parameters
----------
name : str
name to use in the summary representation
Returns
-------
String with a summarized representation of the index | Return a summarized representation. | [
"Return",
"a",
"summarized",
"representation",
"."
] | def _summary(self, name=None):
"""
Return a summarized representation.
Parameters
----------
name : str
name to use in the summary representation
Returns
-------
String with a summarized representation of the index
"""
formatter = self._formatter_func
if len(self) > 0:
index_summary = ', %s to %s' % (formatter(self[0]),
formatter(self[-1]))
else:
index_summary = ''
if name is None:
name = type(self).__name__
result = '%s: %s entries%s' % (printing.pprint_thing(name),
len(self), index_summary)
if self.freq:
result += '\nFreq: %s' % self.freqstr
# display as values, not quoted
result = result.replace("'", "")
return result | [
"def",
"_summary",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"formatter",
"=",
"self",
".",
"_formatter_func",
"if",
"len",
"(",
"self",
")",
">",
"0",
":",
"index_summary",
"=",
"', %s to %s'",
"%",
"(",
"formatter",
"(",
"self",
"[",
"0",
"]",
")",
",",
"formatter",
"(",
"self",
"[",
"-",
"1",
"]",
")",
")",
"else",
":",
"index_summary",
"=",
"''",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"result",
"=",
"'%s: %s entries%s'",
"%",
"(",
"printing",
".",
"pprint_thing",
"(",
"name",
")",
",",
"len",
"(",
"self",
")",
",",
"index_summary",
")",
"if",
"self",
".",
"freq",
":",
"result",
"+=",
"'\\nFreq: %s'",
"%",
"self",
".",
"freqstr",
"# display as values, not quoted",
"result",
"=",
"result",
".",
"replace",
"(",
"\"'\"",
",",
"\"\"",
")",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/datetimelike.py#L548-L577 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathSlot.py | python | ObjectSlot._processFeature | (self, obj, shape, sub, pNum) | return False | _processFeature(obj, shape, sub, pNum)...
This function analyzes a shape and returns a three item tuple containing:
working point,
shape orientation/slope,
shape category as face, edge, or vert. | _processFeature(obj, shape, sub, pNum)...
This function analyzes a shape and returns a three item tuple containing:
working point,
shape orientation/slope,
shape category as face, edge, or vert. | [
"_processFeature",
"(",
"obj",
"shape",
"sub",
"pNum",
")",
"...",
"This",
"function",
"analyzes",
"a",
"shape",
"and",
"returns",
"a",
"three",
"item",
"tuple",
"containing",
":",
"working",
"point",
"shape",
"orientation",
"/",
"slope",
"shape",
"category",
"as",
"face",
"edge",
"or",
"vert",
"."
] | def _processFeature(self, obj, shape, sub, pNum):
"""_processFeature(obj, shape, sub, pNum)...
This function analyzes a shape and returns a three item tuple containing:
working point,
shape orientation/slope,
shape category as face, edge, or vert."""
p = None
dYdX = None
cat = sub[:4]
PathLog.debug('sub-feature is {}'.format(cat))
Ref = getattr(obj, 'Reference' + str(pNum))
if cat == 'Face':
BE = self._getBottomEdge(shape)
if BE:
self.bottomEdges.append(BE)
# calculate slope of face
V0 = shape.Vertexes[0]
v1 = shape.CenterOfMass
temp = FreeCAD.Vector(v1.x - V0.X, v1.y - V0.Y, 0.0)
dYdX = self._normalizeVector(temp)
# Determine normal vector for face
norm = shape.normalAt(0.0, 0.0)
# FreeCAD.Console.PrintMessage('{} normal {}.\n'.format(sub, norm))
if norm.z != 0:
msg = translate('PathSlot',
'The selected face is not oriented vertically:')
FreeCAD.Console.PrintError(msg + ' {}.\n'.format(sub))
return False
if Ref == 'Center of Mass':
comS = shape.CenterOfMass
p = FreeCAD.Vector(comS.x, comS.y, 0.0)
elif Ref == 'Center of BoundBox':
comS = shape.BoundBox.Center
p = FreeCAD.Vector(comS.x, comS.y, 0.0)
elif Ref == 'Lowest Point':
p = self._getLowestPoint(shape)
elif Ref == 'Highest Point':
p = self._getHighestPoint(shape)
elif cat == 'Edge':
featDetIdx = pNum - 1
if shape.Curve.TypeId == 'Part::GeomCircle':
self.featureDetails[featDetIdx] = "arc"
# calculate slope between end vertexes
v0 = shape.Edges[0].Vertexes[0]
v1 = shape.Edges[0].Vertexes[1]
temp = FreeCAD.Vector(v1.X - v0.X, v1.Y - v0.Y, 0.0)
dYdX = self._normalizeVector(temp)
if Ref == 'Center of Mass':
comS = shape.CenterOfMass
p = FreeCAD.Vector(comS.x, comS.y, 0.0)
elif Ref == 'Center of BoundBox':
comS = shape.BoundBox.Center
p = FreeCAD.Vector(comS.x, comS.y, 0.0)
elif Ref == 'Lowest Point':
p = self._findLowestPointOnEdge(shape)
elif Ref == 'Highest Point':
p = self._findHighestPointOnEdge(shape)
elif cat == 'Vert':
V = shape.Vertexes[0]
p = FreeCAD.Vector(V.X, V.Y, 0.0)
if p:
return (p, dYdX, cat)
return False | [
"def",
"_processFeature",
"(",
"self",
",",
"obj",
",",
"shape",
",",
"sub",
",",
"pNum",
")",
":",
"p",
"=",
"None",
"dYdX",
"=",
"None",
"cat",
"=",
"sub",
"[",
":",
"4",
"]",
"PathLog",
".",
"debug",
"(",
"'sub-feature is {}'",
".",
"format",
"(",
"cat",
")",
")",
"Ref",
"=",
"getattr",
"(",
"obj",
",",
"'Reference'",
"+",
"str",
"(",
"pNum",
")",
")",
"if",
"cat",
"==",
"'Face'",
":",
"BE",
"=",
"self",
".",
"_getBottomEdge",
"(",
"shape",
")",
"if",
"BE",
":",
"self",
".",
"bottomEdges",
".",
"append",
"(",
"BE",
")",
"# calculate slope of face",
"V0",
"=",
"shape",
".",
"Vertexes",
"[",
"0",
"]",
"v1",
"=",
"shape",
".",
"CenterOfMass",
"temp",
"=",
"FreeCAD",
".",
"Vector",
"(",
"v1",
".",
"x",
"-",
"V0",
".",
"X",
",",
"v1",
".",
"y",
"-",
"V0",
".",
"Y",
",",
"0.0",
")",
"dYdX",
"=",
"self",
".",
"_normalizeVector",
"(",
"temp",
")",
"# Determine normal vector for face",
"norm",
"=",
"shape",
".",
"normalAt",
"(",
"0.0",
",",
"0.0",
")",
"# FreeCAD.Console.PrintMessage('{} normal {}.\\n'.format(sub, norm))",
"if",
"norm",
".",
"z",
"!=",
"0",
":",
"msg",
"=",
"translate",
"(",
"'PathSlot'",
",",
"'The selected face is not oriented vertically:'",
")",
"FreeCAD",
".",
"Console",
".",
"PrintError",
"(",
"msg",
"+",
"' {}.\\n'",
".",
"format",
"(",
"sub",
")",
")",
"return",
"False",
"if",
"Ref",
"==",
"'Center of Mass'",
":",
"comS",
"=",
"shape",
".",
"CenterOfMass",
"p",
"=",
"FreeCAD",
".",
"Vector",
"(",
"comS",
".",
"x",
",",
"comS",
".",
"y",
",",
"0.0",
")",
"elif",
"Ref",
"==",
"'Center of BoundBox'",
":",
"comS",
"=",
"shape",
".",
"BoundBox",
".",
"Center",
"p",
"=",
"FreeCAD",
".",
"Vector",
"(",
"comS",
".",
"x",
",",
"comS",
".",
"y",
",",
"0.0",
")",
"elif",
"Ref",
"==",
"'Lowest Point'",
":",
"p",
"=",
"self",
".",
"_getLowestPoint",
"(",
"shape",
")",
"elif",
"Ref",
"==",
"'Highest Point'",
":",
"p",
"=",
"self",
".",
"_getHighestPoint",
"(",
"shape",
")",
"elif",
"cat",
"==",
"'Edge'",
":",
"featDetIdx",
"=",
"pNum",
"-",
"1",
"if",
"shape",
".",
"Curve",
".",
"TypeId",
"==",
"'Part::GeomCircle'",
":",
"self",
".",
"featureDetails",
"[",
"featDetIdx",
"]",
"=",
"\"arc\"",
"# calculate slope between end vertexes",
"v0",
"=",
"shape",
".",
"Edges",
"[",
"0",
"]",
".",
"Vertexes",
"[",
"0",
"]",
"v1",
"=",
"shape",
".",
"Edges",
"[",
"0",
"]",
".",
"Vertexes",
"[",
"1",
"]",
"temp",
"=",
"FreeCAD",
".",
"Vector",
"(",
"v1",
".",
"X",
"-",
"v0",
".",
"X",
",",
"v1",
".",
"Y",
"-",
"v0",
".",
"Y",
",",
"0.0",
")",
"dYdX",
"=",
"self",
".",
"_normalizeVector",
"(",
"temp",
")",
"if",
"Ref",
"==",
"'Center of Mass'",
":",
"comS",
"=",
"shape",
".",
"CenterOfMass",
"p",
"=",
"FreeCAD",
".",
"Vector",
"(",
"comS",
".",
"x",
",",
"comS",
".",
"y",
",",
"0.0",
")",
"elif",
"Ref",
"==",
"'Center of BoundBox'",
":",
"comS",
"=",
"shape",
".",
"BoundBox",
".",
"Center",
"p",
"=",
"FreeCAD",
".",
"Vector",
"(",
"comS",
".",
"x",
",",
"comS",
".",
"y",
",",
"0.0",
")",
"elif",
"Ref",
"==",
"'Lowest Point'",
":",
"p",
"=",
"self",
".",
"_findLowestPointOnEdge",
"(",
"shape",
")",
"elif",
"Ref",
"==",
"'Highest Point'",
":",
"p",
"=",
"self",
".",
"_findHighestPointOnEdge",
"(",
"shape",
")",
"elif",
"cat",
"==",
"'Vert'",
":",
"V",
"=",
"shape",
".",
"Vertexes",
"[",
"0",
"]",
"p",
"=",
"FreeCAD",
".",
"Vector",
"(",
"V",
".",
"X",
",",
"V",
".",
"Y",
",",
"0.0",
")",
"if",
"p",
":",
"return",
"(",
"p",
",",
"dYdX",
",",
"cat",
")",
"return",
"False"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathSlot.py#L1165-L1234 | |
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/bindings-generator/clang/cindex.py | python | Cursor.get_children_array | (self) | return children | Return an iterator for accessing the children of this cursor. | Return an iterator for accessing the children of this cursor. | [
"Return",
"an",
"iterator",
"for",
"accessing",
"the",
"children",
"of",
"this",
"cursor",
"."
] | def get_children_array(self):
"""Return an iterator for accessing the children of this cursor."""
# FIXME: Expose iteration from CIndex, PR6125.
def visitor(child, parent, children):
# FIXME: Document this assertion in API.
# FIXME: There should just be an isNull method.
assert child != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
child._tu = self._tu
children.append(child)
return 1 # continue
children = []
conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
children)
return children | [
"def",
"get_children_array",
"(",
"self",
")",
":",
"# FIXME: Expose iteration from CIndex, PR6125.",
"def",
"visitor",
"(",
"child",
",",
"parent",
",",
"children",
")",
":",
"# FIXME: Document this assertion in API.",
"# FIXME: There should just be an isNull method.",
"assert",
"child",
"!=",
"conf",
".",
"lib",
".",
"clang_getNullCursor",
"(",
")",
"# Create reference to TU so it isn't GC'd before Cursor.",
"child",
".",
"_tu",
"=",
"self",
".",
"_tu",
"children",
".",
"append",
"(",
"child",
")",
"return",
"1",
"# continue",
"children",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_visitChildren",
"(",
"self",
",",
"callbacks",
"[",
"'cursor_visit'",
"]",
"(",
"visitor",
")",
",",
"children",
")",
"return",
"children"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L1457-L1473 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | driver/python/pysequoiadb/client.py | python | client.disconnect | (self) | disconnect to current server.
Exceptions:
pysequoiadb.error.SDBBaseError | disconnect to current server. | [
"disconnect",
"to",
"current",
"server",
"."
] | def disconnect(self):
"""disconnect to current server.
Exceptions:
pysequoiadb.error.SDBBaseError
"""
rc = sdb.sdb_disconnect(self._client)
raise_if_error(rc, "Failed to disconnect")
# success to disconnect
self.__host = self.HOST
self.__service = self.PSW
self.__connected = False | [
"def",
"disconnect",
"(",
"self",
")",
":",
"rc",
"=",
"sdb",
".",
"sdb_disconnect",
"(",
"self",
".",
"_client",
")",
"raise_if_error",
"(",
"rc",
",",
"\"Failed to disconnect\"",
")",
"# success to disconnect",
"self",
".",
"__host",
"=",
"self",
".",
"HOST",
"self",
".",
"__service",
"=",
"self",
".",
"PSW",
"self",
".",
"__connected",
"=",
"False"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/client.py#L401-L413 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/name_expansion.py | python | _NameExpansionIterator.__iter__ | (self) | Iterates over all source URLs passed to the iterator.
For each src url, expands wildcards, object-less bucket names,
subdir bucket names, and directory names, and generates a flat listing of
all the matching objects/files.
You should instantiate this object using the static factory function
NameExpansionIterator, because consumers of this iterator need the
PluralityCheckableIterator wrapper built by that function.
Yields:
gslib.name_expansion.NameExpansionResult.
Raises:
CommandException: if errors encountered. | Iterates over all source URLs passed to the iterator. | [
"Iterates",
"over",
"all",
"source",
"URLs",
"passed",
"to",
"the",
"iterator",
"."
] | def __iter__(self):
"""Iterates over all source URLs passed to the iterator.
For each src url, expands wildcards, object-less bucket names,
subdir bucket names, and directory names, and generates a flat listing of
all the matching objects/files.
You should instantiate this object using the static factory function
NameExpansionIterator, because consumers of this iterator need the
PluralityCheckableIterator wrapper built by that function.
Yields:
gslib.name_expansion.NameExpansionResult.
Raises:
CommandException: if errors encountered.
"""
for url_str in self.url_strs:
storage_url = StorageUrlFromString(url_str)
if storage_url.IsFileUrl() and storage_url.IsStream():
if self.url_strs.has_plurality:
raise CommandException('Multiple URL strings are not supported '
'with streaming ("-") URLs.')
yield NameExpansionResult(storage_url, False, False, storage_url)
continue
# Step 1: Expand any explicitly specified wildcards. The output from this
# step is an iterator of BucketListingRef.
# Starting with gs://buck*/abc* this step would expand to gs://bucket/abcd
src_names_bucket = False
if (storage_url.IsCloudUrl() and storage_url.IsBucket()
and not self.recursion_requested):
# UNIX commands like rm and cp will omit directory references.
# If url_str refers only to buckets and we are not recursing,
# then produce references of type BUCKET, because they are guaranteed
# to pass through Step 2 and be omitted in Step 3.
post_step1_iter = PluralityCheckableIterator(
self.WildcardIterator(url_str).IterBuckets(
bucket_fields=['id']))
else:
# Get a list of objects and prefixes, expanding the top level for
# any listed buckets. If our source is a bucket, however, we need
# to treat all of the top level expansions as names_container=True.
post_step1_iter = PluralityCheckableIterator(
self.WildcardIterator(url_str).IterAll(
bucket_listing_fields=['name'],
expand_top_level_buckets=True))
if storage_url.IsCloudUrl() and storage_url.IsBucket():
src_names_bucket = True
# Step 2: Expand bucket subdirs. The output from this
# step is an iterator of (names_container, BucketListingRef).
# Starting with gs://bucket/abcd this step would expand to:
# iter([(True, abcd/o1.txt), (True, abcd/o2.txt)]).
subdir_exp_wildcard = self._flatness_wildcard[self.recursion_requested]
if self.recursion_requested:
post_step2_iter = _ImplicitBucketSubdirIterator(
self, post_step1_iter, subdir_exp_wildcard)
else:
post_step2_iter = _NonContainerTuplifyIterator(post_step1_iter)
post_step2_iter = PluralityCheckableIterator(post_step2_iter)
# Because we actually perform and check object listings here, this will
# raise if url_args includes a non-existent object. However,
# plurality_checkable_iterator will buffer the exception for us, not
# raising it until the iterator is actually asked to yield the first
# result.
if post_step2_iter.IsEmpty():
if self.continue_on_error:
try:
raise CommandException('No URLs matched: %s' % url_str)
except CommandException, e:
# Yield a specialized tuple of (exception, stack_trace) to
# the wrapping PluralityCheckableIterator.
yield (e, sys.exc_info()[2])
else:
raise CommandException('No URLs matched: %s' % url_str)
# Step 3. Omit any directories, buckets, or bucket subdirectories for
# non-recursive expansions.
post_step3_iter = PluralityCheckableIterator(_OmitNonRecursiveIterator(
post_step2_iter, self.recursion_requested, self.command_name,
self.cmd_supports_recursion, self.logger))
src_url_expands_to_multi = post_step3_iter.HasPlurality()
is_multi_source_request = (self.url_strs.has_plurality
or src_url_expands_to_multi)
# Step 4. Expand directories and buckets. This step yields the iterated
# values. Starting with gs://bucket this step would expand to:
# [abcd/o1.txt, abcd/o2.txt, xyz/o1.txt, xyz/o2.txt]
# Starting with file://dir this step would expand to:
# [dir/a.txt, dir/b.txt, dir/c/]
for (names_container, blr) in post_step3_iter:
src_names_container = src_names_bucket or names_container
if blr.IsObject():
yield NameExpansionResult(
storage_url, is_multi_source_request, src_names_container,
blr.storage_url)
else:
# Use implicit wildcarding to do the enumeration.
# At this point we are guaranteed that:
# - Recursion has been requested because non-object entries are
# filtered in step 3 otherwise.
# - This is a prefix or bucket subdirectory because only
# non-recursive iterations product bucket references.
expanded_url = StorageUrlFromString(blr.url_string)
if expanded_url.IsFileUrl():
# Convert dir to implicit recursive wildcard.
url_to_iterate = '%s%s%s' % (blr, os.sep, subdir_exp_wildcard)
else:
# Convert subdir to implicit recursive wildcard.
url_to_iterate = expanded_url.CreatePrefixUrl(
wildcard_suffix=subdir_exp_wildcard)
wc_iter = PluralityCheckableIterator(
self.WildcardIterator(url_to_iterate).IterObjects(
bucket_listing_fields=['name']))
src_url_expands_to_multi = (src_url_expands_to_multi
or wc_iter.HasPlurality())
is_multi_source_request = (self.url_strs.has_plurality
or src_url_expands_to_multi)
# This will be a flattened listing of all underlying objects in the
# subdir.
for blr in wc_iter:
yield NameExpansionResult(
storage_url, is_multi_source_request, True, blr.storage_url) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"url_str",
"in",
"self",
".",
"url_strs",
":",
"storage_url",
"=",
"StorageUrlFromString",
"(",
"url_str",
")",
"if",
"storage_url",
".",
"IsFileUrl",
"(",
")",
"and",
"storage_url",
".",
"IsStream",
"(",
")",
":",
"if",
"self",
".",
"url_strs",
".",
"has_plurality",
":",
"raise",
"CommandException",
"(",
"'Multiple URL strings are not supported '",
"'with streaming (\"-\") URLs.'",
")",
"yield",
"NameExpansionResult",
"(",
"storage_url",
",",
"False",
",",
"False",
",",
"storage_url",
")",
"continue",
"# Step 1: Expand any explicitly specified wildcards. The output from this",
"# step is an iterator of BucketListingRef.",
"# Starting with gs://buck*/abc* this step would expand to gs://bucket/abcd",
"src_names_bucket",
"=",
"False",
"if",
"(",
"storage_url",
".",
"IsCloudUrl",
"(",
")",
"and",
"storage_url",
".",
"IsBucket",
"(",
")",
"and",
"not",
"self",
".",
"recursion_requested",
")",
":",
"# UNIX commands like rm and cp will omit directory references.",
"# If url_str refers only to buckets and we are not recursing,",
"# then produce references of type BUCKET, because they are guaranteed",
"# to pass through Step 2 and be omitted in Step 3.",
"post_step1_iter",
"=",
"PluralityCheckableIterator",
"(",
"self",
".",
"WildcardIterator",
"(",
"url_str",
")",
".",
"IterBuckets",
"(",
"bucket_fields",
"=",
"[",
"'id'",
"]",
")",
")",
"else",
":",
"# Get a list of objects and prefixes, expanding the top level for",
"# any listed buckets. If our source is a bucket, however, we need",
"# to treat all of the top level expansions as names_container=True.",
"post_step1_iter",
"=",
"PluralityCheckableIterator",
"(",
"self",
".",
"WildcardIterator",
"(",
"url_str",
")",
".",
"IterAll",
"(",
"bucket_listing_fields",
"=",
"[",
"'name'",
"]",
",",
"expand_top_level_buckets",
"=",
"True",
")",
")",
"if",
"storage_url",
".",
"IsCloudUrl",
"(",
")",
"and",
"storage_url",
".",
"IsBucket",
"(",
")",
":",
"src_names_bucket",
"=",
"True",
"# Step 2: Expand bucket subdirs. The output from this",
"# step is an iterator of (names_container, BucketListingRef).",
"# Starting with gs://bucket/abcd this step would expand to:",
"# iter([(True, abcd/o1.txt), (True, abcd/o2.txt)]).",
"subdir_exp_wildcard",
"=",
"self",
".",
"_flatness_wildcard",
"[",
"self",
".",
"recursion_requested",
"]",
"if",
"self",
".",
"recursion_requested",
":",
"post_step2_iter",
"=",
"_ImplicitBucketSubdirIterator",
"(",
"self",
",",
"post_step1_iter",
",",
"subdir_exp_wildcard",
")",
"else",
":",
"post_step2_iter",
"=",
"_NonContainerTuplifyIterator",
"(",
"post_step1_iter",
")",
"post_step2_iter",
"=",
"PluralityCheckableIterator",
"(",
"post_step2_iter",
")",
"# Because we actually perform and check object listings here, this will",
"# raise if url_args includes a non-existent object. However,",
"# plurality_checkable_iterator will buffer the exception for us, not",
"# raising it until the iterator is actually asked to yield the first",
"# result.",
"if",
"post_step2_iter",
".",
"IsEmpty",
"(",
")",
":",
"if",
"self",
".",
"continue_on_error",
":",
"try",
":",
"raise",
"CommandException",
"(",
"'No URLs matched: %s'",
"%",
"url_str",
")",
"except",
"CommandException",
",",
"e",
":",
"# Yield a specialized tuple of (exception, stack_trace) to",
"# the wrapping PluralityCheckableIterator.",
"yield",
"(",
"e",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"else",
":",
"raise",
"CommandException",
"(",
"'No URLs matched: %s'",
"%",
"url_str",
")",
"# Step 3. Omit any directories, buckets, or bucket subdirectories for",
"# non-recursive expansions.",
"post_step3_iter",
"=",
"PluralityCheckableIterator",
"(",
"_OmitNonRecursiveIterator",
"(",
"post_step2_iter",
",",
"self",
".",
"recursion_requested",
",",
"self",
".",
"command_name",
",",
"self",
".",
"cmd_supports_recursion",
",",
"self",
".",
"logger",
")",
")",
"src_url_expands_to_multi",
"=",
"post_step3_iter",
".",
"HasPlurality",
"(",
")",
"is_multi_source_request",
"=",
"(",
"self",
".",
"url_strs",
".",
"has_plurality",
"or",
"src_url_expands_to_multi",
")",
"# Step 4. Expand directories and buckets. This step yields the iterated",
"# values. Starting with gs://bucket this step would expand to:",
"# [abcd/o1.txt, abcd/o2.txt, xyz/o1.txt, xyz/o2.txt]",
"# Starting with file://dir this step would expand to:",
"# [dir/a.txt, dir/b.txt, dir/c/]",
"for",
"(",
"names_container",
",",
"blr",
")",
"in",
"post_step3_iter",
":",
"src_names_container",
"=",
"src_names_bucket",
"or",
"names_container",
"if",
"blr",
".",
"IsObject",
"(",
")",
":",
"yield",
"NameExpansionResult",
"(",
"storage_url",
",",
"is_multi_source_request",
",",
"src_names_container",
",",
"blr",
".",
"storage_url",
")",
"else",
":",
"# Use implicit wildcarding to do the enumeration.",
"# At this point we are guaranteed that:",
"# - Recursion has been requested because non-object entries are",
"# filtered in step 3 otherwise.",
"# - This is a prefix or bucket subdirectory because only",
"# non-recursive iterations product bucket references.",
"expanded_url",
"=",
"StorageUrlFromString",
"(",
"blr",
".",
"url_string",
")",
"if",
"expanded_url",
".",
"IsFileUrl",
"(",
")",
":",
"# Convert dir to implicit recursive wildcard.",
"url_to_iterate",
"=",
"'%s%s%s'",
"%",
"(",
"blr",
",",
"os",
".",
"sep",
",",
"subdir_exp_wildcard",
")",
"else",
":",
"# Convert subdir to implicit recursive wildcard.",
"url_to_iterate",
"=",
"expanded_url",
".",
"CreatePrefixUrl",
"(",
"wildcard_suffix",
"=",
"subdir_exp_wildcard",
")",
"wc_iter",
"=",
"PluralityCheckableIterator",
"(",
"self",
".",
"WildcardIterator",
"(",
"url_to_iterate",
")",
".",
"IterObjects",
"(",
"bucket_listing_fields",
"=",
"[",
"'name'",
"]",
")",
")",
"src_url_expands_to_multi",
"=",
"(",
"src_url_expands_to_multi",
"or",
"wc_iter",
".",
"HasPlurality",
"(",
")",
")",
"is_multi_source_request",
"=",
"(",
"self",
".",
"url_strs",
".",
"has_plurality",
"or",
"src_url_expands_to_multi",
")",
"# This will be a flattened listing of all underlying objects in the",
"# subdir.",
"for",
"blr",
"in",
"wc_iter",
":",
"yield",
"NameExpansionResult",
"(",
"storage_url",
",",
"is_multi_source_request",
",",
"True",
",",
"blr",
".",
"storage_url",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/name_expansion.py#L151-L280 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/ccompiler.py | python | CCompiler._fix_lib_args | (self, libraries, library_dirs, runtime_library_dirs) | return (libraries, library_dirs, runtime_library_dirs) | Typecheck and fix up some of the arguments supplied to the
'link_*' methods. Specifically: ensure that all arguments are
lists, and augment them with their permanent versions
(eg. 'self.libraries' augments 'libraries'). Return a tuple with
fixed versions of all arguments. | Typecheck and fix up some of the arguments supplied to the
'link_*' methods. Specifically: ensure that all arguments are
lists, and augment them with their permanent versions
(eg. 'self.libraries' augments 'libraries'). Return a tuple with
fixed versions of all arguments. | [
"Typecheck",
"and",
"fix",
"up",
"some",
"of",
"the",
"arguments",
"supplied",
"to",
"the",
"link_",
"*",
"methods",
".",
"Specifically",
":",
"ensure",
"that",
"all",
"arguments",
"are",
"lists",
"and",
"augment",
"them",
"with",
"their",
"permanent",
"versions",
"(",
"eg",
".",
"self",
".",
"libraries",
"augments",
"libraries",
")",
".",
"Return",
"a",
"tuple",
"with",
"fixed",
"versions",
"of",
"all",
"arguments",
"."
] | def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
"""Typecheck and fix up some of the arguments supplied to the
'link_*' methods. Specifically: ensure that all arguments are
lists, and augment them with their permanent versions
(eg. 'self.libraries' augments 'libraries'). Return a tuple with
fixed versions of all arguments.
"""
if libraries is None:
libraries = self.libraries
elif isinstance(libraries, (list, tuple)):
libraries = list (libraries) + (self.libraries or [])
else:
raise TypeError(
"'libraries' (if supplied) must be a list of strings")
if library_dirs is None:
library_dirs = self.library_dirs
elif isinstance(library_dirs, (list, tuple)):
library_dirs = list (library_dirs) + (self.library_dirs or [])
else:
raise TypeError(
"'library_dirs' (if supplied) must be a list of strings")
if runtime_library_dirs is None:
runtime_library_dirs = self.runtime_library_dirs
elif isinstance(runtime_library_dirs, (list, tuple)):
runtime_library_dirs = (list(runtime_library_dirs) +
(self.runtime_library_dirs or []))
else:
raise TypeError("'runtime_library_dirs' (if supplied) "
"must be a list of strings")
return (libraries, library_dirs, runtime_library_dirs) | [
"def",
"_fix_lib_args",
"(",
"self",
",",
"libraries",
",",
"library_dirs",
",",
"runtime_library_dirs",
")",
":",
"if",
"libraries",
"is",
"None",
":",
"libraries",
"=",
"self",
".",
"libraries",
"elif",
"isinstance",
"(",
"libraries",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"libraries",
"=",
"list",
"(",
"libraries",
")",
"+",
"(",
"self",
".",
"libraries",
"or",
"[",
"]",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"'libraries' (if supplied) must be a list of strings\"",
")",
"if",
"library_dirs",
"is",
"None",
":",
"library_dirs",
"=",
"self",
".",
"library_dirs",
"elif",
"isinstance",
"(",
"library_dirs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"library_dirs",
"=",
"list",
"(",
"library_dirs",
")",
"+",
"(",
"self",
".",
"library_dirs",
"or",
"[",
"]",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"'library_dirs' (if supplied) must be a list of strings\"",
")",
"if",
"runtime_library_dirs",
"is",
"None",
":",
"runtime_library_dirs",
"=",
"self",
".",
"runtime_library_dirs",
"elif",
"isinstance",
"(",
"runtime_library_dirs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"runtime_library_dirs",
"=",
"(",
"list",
"(",
"runtime_library_dirs",
")",
"+",
"(",
"self",
".",
"runtime_library_dirs",
"or",
"[",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"'runtime_library_dirs' (if supplied) \"",
"\"must be a list of strings\"",
")",
"return",
"(",
"libraries",
",",
"library_dirs",
",",
"runtime_library_dirs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/ccompiler.py#L427-L459 | |
CNugteren/CLBlast | 4500a03440e2cc54998c0edab366babf5e504d67 | scripts/generator/generator/routine.py | python | Routine.buffer_def_wrapper_cuda | (self, name, flavour) | return [] | As above but for CUDA | As above but for CUDA | [
"As",
"above",
"but",
"for",
"CUDA"
] | def buffer_def_wrapper_cuda(self, name, flavour):
"""As above but for CUDA"""
prefix = "const " if name in self.inputs else ""
if name in self.inputs or name in self.outputs:
a = [prefix + flavour.buffer_type + "* " + name + "_buffer"]
b = ["const size_t " + name + "_offset"]
c = ["const size_t " + name + "_" + self.postfix(name)] if name not in self.buffers_without_ld_inc() else []
return [", ".join(a + b + c)]
return [] | [
"def",
"buffer_def_wrapper_cuda",
"(",
"self",
",",
"name",
",",
"flavour",
")",
":",
"prefix",
"=",
"\"const \"",
"if",
"name",
"in",
"self",
".",
"inputs",
"else",
"\"\"",
"if",
"name",
"in",
"self",
".",
"inputs",
"or",
"name",
"in",
"self",
".",
"outputs",
":",
"a",
"=",
"[",
"prefix",
"+",
"flavour",
".",
"buffer_type",
"+",
"\"* \"",
"+",
"name",
"+",
"\"_buffer\"",
"]",
"b",
"=",
"[",
"\"const size_t \"",
"+",
"name",
"+",
"\"_offset\"",
"]",
"c",
"=",
"[",
"\"const size_t \"",
"+",
"name",
"+",
"\"_\"",
"+",
"self",
".",
"postfix",
"(",
"name",
")",
"]",
"if",
"name",
"not",
"in",
"self",
".",
"buffers_without_ld_inc",
"(",
")",
"else",
"[",
"]",
"return",
"[",
"\", \"",
".",
"join",
"(",
"a",
"+",
"b",
"+",
"c",
")",
"]",
"return",
"[",
"]"
] | https://github.com/CNugteren/CLBlast/blob/4500a03440e2cc54998c0edab366babf5e504d67/scripts/generator/generator/routine.py#L291-L299 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_basic.py | python | Shape.GetTextColour | (self, regionId = 0) | return self._regions[regionId].GetColour() | Get the colour for the specified text region. | Get the colour for the specified text region. | [
"Get",
"the",
"colour",
"for",
"the",
"specified",
"text",
"region",
"."
] | def GetTextColour(self, regionId = 0):
"""Get the colour for the specified text region."""
if regionId >= len(self._regions):
return ""
return self._regions[regionId].GetColour() | [
"def",
"GetTextColour",
"(",
"self",
",",
"regionId",
"=",
"0",
")",
":",
"if",
"regionId",
">=",
"len",
"(",
"self",
".",
"_regions",
")",
":",
"return",
"\"\"",
"return",
"self",
".",
"_regions",
"[",
"regionId",
"]",
".",
"GetColour",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L648-L652 | |
vgteam/vg | cf4d516a5e9ee5163c783e4437ddf16b18a4b561 | scripts/filter_variants_on_repeats.py | python | main | (args) | return 0 | Parses command line arguments and do the work of the program.
"args" specifies the program arguments, with args[0] being the executable
name. The return value should be used as the program's exit code. | Parses command line arguments and do the work of the program.
"args" specifies the program arguments, with args[0] being the executable
name. The return value should be used as the program's exit code. | [
"Parses",
"command",
"line",
"arguments",
"and",
"do",
"the",
"work",
"of",
"the",
"program",
".",
"args",
"specifies",
"the",
"program",
"arguments",
"with",
"args",
"[",
"0",
"]",
"being",
"the",
"executable",
"name",
".",
"The",
"return",
"value",
"should",
"be",
"used",
"as",
"the",
"program",
"s",
"exit",
"code",
"."
] | def main(args):
"""
Parses command line arguments and do the work of the program.
"args" specifies the program arguments, with args[0] being the executable
name. The return value should be used as the program's exit code.
"""
options = parse_args(args) # This holds the nicely-parsed options object
# Make a repeat database
db = RepeatDb(options.assembly, options.contig, options.start, options.end)
# Strip "chr" from the contig.
# TODO: figure out if we need to
short_contig = (options.contig[3:] if len(options.contig) > 3
else options.contig)
# Read the input VCF
reader = vcf.Reader(options.vcf)
# Make a writer for the passing records
writer = vcf.Writer(options.out_vcf, reader)
# Track statistics
total_variants = 0
kept_variants = 0
non_snp_variants = 0
for variant in reader.fetch(short_contig, options.start, options.end):
# For each variant in our region
# Count it
total_variants += 1
# See how numerous it should be
count = db.get_copies("chr" + variant.CHROM, variant.POS)
# And how common it is
frequency = variant.INFO["AF"][0]
if variant.is_snp:
# SNPs are modeled
# What's the minimum frequency to get more true than fake hits?
min_frequency = (count * options.error_rate /
(3 - 2 * options.error_rate))
# Should we keep it?
keep = (frequency >= min_frequency)
sys.stderr.write(
"{} {}:{} has {} copies, frequency {:.4f} vs. {:.4f}\n".format(
"☑" if keep else "☐", variant.CHROM, variant.POS, count,
frequency, min_frequency))
else:
# We have to keep everything that's not a SNP because we have no
# error model
keep = True
sys.stderr.write(
"{} {}:{} has {} copies, frequency {:.4f} (non-SNP)\n".format(
"☑" if keep else "☐", variant.CHROM, variant.POS, count,
frequency))
non_snp_variants += 1
if keep:
# Pass the variants we're keeping
writer.write_record(variant)
# Count it
kept_variants += 1
sys.stderr.write("Finished! Kept {} ({} non-SNP) / {} variants\n".format(
kept_variants, non_snp_variants, total_variants))
return 0 | [
"def",
"main",
"(",
"args",
")",
":",
"options",
"=",
"parse_args",
"(",
"args",
")",
"# This holds the nicely-parsed options object",
"# Make a repeat database",
"db",
"=",
"RepeatDb",
"(",
"options",
".",
"assembly",
",",
"options",
".",
"contig",
",",
"options",
".",
"start",
",",
"options",
".",
"end",
")",
"# Strip \"chr\" from the contig.",
"# TODO: figure out if we need to",
"short_contig",
"=",
"(",
"options",
".",
"contig",
"[",
"3",
":",
"]",
"if",
"len",
"(",
"options",
".",
"contig",
")",
">",
"3",
"else",
"options",
".",
"contig",
")",
"# Read the input VCF",
"reader",
"=",
"vcf",
".",
"Reader",
"(",
"options",
".",
"vcf",
")",
"# Make a writer for the passing records",
"writer",
"=",
"vcf",
".",
"Writer",
"(",
"options",
".",
"out_vcf",
",",
"reader",
")",
"# Track statistics",
"total_variants",
"=",
"0",
"kept_variants",
"=",
"0",
"non_snp_variants",
"=",
"0",
"for",
"variant",
"in",
"reader",
".",
"fetch",
"(",
"short_contig",
",",
"options",
".",
"start",
",",
"options",
".",
"end",
")",
":",
"# For each variant in our region",
"# Count it",
"total_variants",
"+=",
"1",
"# See how numerous it should be",
"count",
"=",
"db",
".",
"get_copies",
"(",
"\"chr\"",
"+",
"variant",
".",
"CHROM",
",",
"variant",
".",
"POS",
")",
"# And how common it is",
"frequency",
"=",
"variant",
".",
"INFO",
"[",
"\"AF\"",
"]",
"[",
"0",
"]",
"if",
"variant",
".",
"is_snp",
":",
"# SNPs are modeled",
"# What's the minimum frequency to get more true than fake hits?",
"min_frequency",
"=",
"(",
"count",
"*",
"options",
".",
"error_rate",
"/",
"(",
"3",
"-",
"2",
"*",
"options",
".",
"error_rate",
")",
")",
"# Should we keep it?",
"keep",
"=",
"(",
"frequency",
">=",
"min_frequency",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"{} {}:{} has {} copies, frequency {:.4f} vs. {:.4f}\\n\"",
".",
"format",
"(",
"\"☑\" i",
" k",
"ep e",
"se \"",
"\", va",
"r",
"ant.CHR",
"O",
"M, va",
"r",
"ant.POS",
",",
" co",
"u",
"t,",
"",
"frequency",
",",
"min_frequency",
")",
")",
"else",
":",
"# We have to keep everything that's not a SNP because we have no",
"# error model",
"keep",
"=",
"True",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"{} {}:{} has {} copies, frequency {:.4f} (non-SNP)\\n\"",
".",
"format",
"(",
"\"☑\" i",
" k",
"ep e",
"se \"",
"\", va",
"r",
"ant.CHR",
"O",
"M, va",
"r",
"ant.POS",
",",
" co",
"u",
"t,",
"",
"frequency",
")",
")",
"non_snp_variants",
"+=",
"1",
"if",
"keep",
":",
"# Pass the variants we're keeping",
"writer",
".",
"write_record",
"(",
"variant",
")",
"# Count it",
"kept_variants",
"+=",
"1",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Finished! Kept {} ({} non-SNP) / {} variants\\n\"",
".",
"format",
"(",
"kept_variants",
",",
"non_snp_variants",
",",
"total_variants",
")",
")",
"return",
"0"
] | https://github.com/vgteam/vg/blob/cf4d516a5e9ee5163c783e4437ddf16b18a4b561/scripts/filter_variants_on_repeats.py#L130-L205 | |
moranzcw/LeetCode-NOTES | 49a7e33b83d8d9ce449c758717f74a69e72f808e | update.py | python | pop_up_box | () | 使用tkinter弹出输入框输入数字, 具有确定输入和清除功能, 可在函数内直接调用num(文本框的值)使用 | 使用tkinter弹出输入框输入数字, 具有确定输入和清除功能, 可在函数内直接调用num(文本框的值)使用 | [
"使用tkinter弹出输入框输入数字",
"具有确定输入和清除功能",
"可在函数内直接调用num",
"(",
"文本框的值",
")",
"使用"
] | def pop_up_box():
"""
使用tkinter弹出输入框输入数字, 具有确定输入和清除功能, 可在函数内直接调用num(文本框的值)使用
"""
def inputstr():
nonlocal title
nonlocal code
title = get_title(entry.get())
if title == None:
tkinter.messagebox.showinfo(title='更新失败',message='更新失败')
return
code = text.get('0.0',tkinter.END)
save(title,code)
mess = '粘贴到readme:\n'+'['+title+'](Algorithms/'+title+'/solution.cpp)'
tkinter.messagebox.showinfo(title='更新完成',message=mess) # return ok
def clearstr():
entry.delete(0,tkinter.END)
text.delete('0.0',tkinter.END)
pass
title = ''
code = ''
root = tkinter.Tk(className='输入代码') # 弹出框框名
root.geometry('500x400') # 设置弹出框的大小 w x h
entry = tkinter.Entry(root)
entry.pack() # 将entry"打上去"
text = tkinter.Text(root, height=15) # 这即是输入框中的内容
text.pack()
btn1 = tkinter.Button(root, text='Input', command=inputstr) # 按下此按钮(Input), 触发inputint函数
btn2 = tkinter.Button(root, text='Clear', command=clearstr)
# 按钮定位
btn1.pack(side='bottom')
btn2.pack(side='bottom')
# 上述完成之后, 开始真正弹出弹出框
root.mainloop() | [
"def",
"pop_up_box",
"(",
")",
":",
"def",
"inputstr",
"(",
")",
":",
"nonlocal",
"title",
"nonlocal",
"code",
"title",
"=",
"get_title",
"(",
"entry",
".",
"get",
"(",
")",
")",
"if",
"title",
"==",
"None",
":",
"tkinter",
".",
"messagebox",
".",
"showinfo",
"(",
"title",
"=",
"'更新失败',message",
"=",
"'更新失败')",
"",
"",
"",
"return",
"code",
"=",
"text",
".",
"get",
"(",
"'0.0'",
",",
"tkinter",
".",
"END",
")",
"save",
"(",
"title",
",",
"code",
")",
"mess",
"=",
"'粘贴到readme:\\n'+'['+t",
"i",
"tle",
"+",
"'](Al",
"g",
"orithms/'+title",
"+",
"'/sol",
"u",
"tion.cpp)'",
"tkinter",
".",
"messagebox",
".",
"showinfo",
"(",
"title",
"=",
"'更新完成',message",
"=",
"mess) ",
"#",
" ret",
"u",
" ok",
"def",
"clearstr",
"(",
")",
":",
"entry",
".",
"delete",
"(",
"0",
",",
"tkinter",
".",
"END",
")",
"text",
".",
"delete",
"(",
"'0.0'",
",",
"tkinter",
".",
"END",
")",
"pass",
"title",
"=",
"''",
"code",
"=",
"''",
"root",
"=",
"tkinter",
".",
"Tk",
"(",
"className",
"=",
"'输入代码') # 弹出框",
"框",
"",
"root",
".",
"geometry",
"(",
"'500x400'",
")",
"# 设置弹出框的大小 w x h",
"entry",
"=",
"tkinter",
".",
"Entry",
"(",
"root",
")",
"entry",
".",
"pack",
"(",
")",
"# 将entry\"打上去\"",
"text",
"=",
"tkinter",
".",
"Text",
"(",
"root",
",",
"height",
"=",
"15",
")",
"# 这即是输入框中的内容",
"text",
".",
"pack",
"(",
")",
"btn1",
"=",
"tkinter",
".",
"Button",
"(",
"root",
",",
"text",
"=",
"'Input'",
",",
"command",
"=",
"inputstr",
")",
"# 按下此按钮(Input), 触发inputint函数",
"btn2",
"=",
"tkinter",
".",
"Button",
"(",
"root",
",",
"text",
"=",
"'Clear'",
",",
"command",
"=",
"clearstr",
")",
"# 按钮定位",
"btn1",
".",
"pack",
"(",
"side",
"=",
"'bottom'",
")",
"btn2",
".",
"pack",
"(",
"side",
"=",
"'bottom'",
")",
"# 上述完成之后, 开始真正弹出弹出框",
"root",
".",
"mainloop",
"(",
")"
] | https://github.com/moranzcw/LeetCode-NOTES/blob/49a7e33b83d8d9ce449c758717f74a69e72f808e/update.py#L27-L66 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/pytables.py | python | Table.index_cols | (self) | return [(i.axis, i.cname) for i in self.index_axes] | return a list of my index cols | return a list of my index cols | [
"return",
"a",
"list",
"of",
"my",
"index",
"cols"
] | def index_cols(self):
"""return a list of my index cols"""
# Note: each `i.cname` below is assured to be a str.
return [(i.axis, i.cname) for i in self.index_axes] | [
"def",
"index_cols",
"(",
"self",
")",
":",
"# Note: each `i.cname` below is assured to be a str.",
"return",
"[",
"(",
"i",
".",
"axis",
",",
"i",
".",
"cname",
")",
"for",
"i",
"in",
"self",
".",
"index_axes",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L3450-L3453 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/html5parser.py | python | HTMLParser.documentEncoding | (self) | return self.tokenizer.stream.charEncoding[0].name | Name of the character encoding that was used to decode the input stream, or
:obj:`None` if that is not determined yet | Name of the character encoding that was used to decode the input stream, or
:obj:`None` if that is not determined yet | [
"Name",
"of",
"the",
"character",
"encoding",
"that",
"was",
"used",
"to",
"decode",
"the",
"input",
"stream",
"or",
":",
"obj",
":",
"None",
"if",
"that",
"is",
"not",
"determined",
"yet"
] | def documentEncoding(self):
"""Name of the character encoding that was used to decode the input stream, or
:obj:`None` if that is not determined yet
"""
if not hasattr(self, 'tokenizer'):
return None
return self.tokenizer.stream.charEncoding[0].name | [
"def",
"documentEncoding",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'tokenizer'",
")",
":",
"return",
"None",
"return",
"self",
".",
"tokenizer",
".",
"stream",
".",
"charEncoding",
"[",
"0",
"]",
".",
"name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/html5parser.py#L173-L180 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite_e.py | python | hermeval2d | (x, y, c) | return pu._valnd(hermeval, c, x, y) | Evaluate a 2-D HermiteE series at points (x, y).
This function returns the values:
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y)
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.
If `c` is a 1-D array a one is implicitly appended to its shape to make
it 2-D. The shape of the result will be c.shape[2:] + x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points `(x, y)`,
where `x` and `y` must have the same shape. If `x` or `y` is a list
or tuple, it is first converted to an ndarray, otherwise it is left
unchanged and if it isn't an ndarray it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term
of multi-degree i,j is contained in ``c[i,j]``. If `c` has
dimension greater than two the remaining indices enumerate multiple
sets of coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points formed with
pairs of corresponding values from `x` and `y`.
See Also
--------
hermeval, hermegrid2d, hermeval3d, hermegrid3d
Notes
-----
.. versionadded:: 1.7.0 | Evaluate a 2-D HermiteE series at points (x, y). | [
"Evaluate",
"a",
"2",
"-",
"D",
"HermiteE",
"series",
"at",
"points",
"(",
"x",
"y",
")",
"."
] | def hermeval2d(x, y, c):
"""
Evaluate a 2-D HermiteE series at points (x, y).
This function returns the values:
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y)
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.
If `c` is a 1-D array a one is implicitly appended to its shape to make
it 2-D. The shape of the result will be c.shape[2:] + x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points `(x, y)`,
where `x` and `y` must have the same shape. If `x` or `y` is a list
or tuple, it is first converted to an ndarray, otherwise it is left
unchanged and if it isn't an ndarray it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term
of multi-degree i,j is contained in ``c[i,j]``. If `c` has
dimension greater than two the remaining indices enumerate multiple
sets of coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points formed with
pairs of corresponding values from `x` and `y`.
See Also
--------
hermeval, hermegrid2d, hermeval3d, hermegrid3d
Notes
-----
.. versionadded:: 1.7.0
"""
return pu._valnd(hermeval, c, x, y) | [
"def",
"hermeval2d",
"(",
"x",
",",
"y",
",",
"c",
")",
":",
"return",
"pu",
".",
"_valnd",
"(",
"hermeval",
",",
"c",
",",
"x",
",",
"y",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite_e.py#L870-L916 | |
Jack-Cherish/Algorithm | ab3e0f05ff15972f282b6122b73dfa0e84b5960b | Sort Algorithms.py | python | SelectSort | (input_list) | return sorted_list | 函数说明:简单选择排序(升序)
Website:
http://cuijiahua.com
Parameters:
input_list - 待排序列表
Returns:
sorted_list - 升序排序好的列表 | 函数说明:简单选择排序(升序)
Website:
http://cuijiahua.com
Parameters:
input_list - 待排序列表
Returns:
sorted_list - 升序排序好的列表 | [
"函数说明",
":",
"简单选择排序(升序)",
"Website",
":",
"http",
":",
"//",
"cuijiahua",
".",
"com",
"Parameters",
":",
"input_list",
"-",
"待排序列表",
"Returns",
":",
"sorted_list",
"-",
"升序排序好的列表"
] | def SelectSort(input_list):
'''
函数说明:简单选择排序(升序)
Website:
http://cuijiahua.com
Parameters:
input_list - 待排序列表
Returns:
sorted_list - 升序排序好的列表
'''
if len(input_list) == 0:
return []
sorted_list = input_list
length = len(sorted_list)
for i in range(length):
min_index = i
for j in range(i + 1, length):
if sorted_list[min_index] > sorted_list[j]:
min_index = j
temp = sorted_list[i]
sorted_list[i] = sorted_list[min_index]
sorted_list[min_index] = temp
return sorted_list | [
"def",
"SelectSort",
"(",
"input_list",
")",
":",
"if",
"len",
"(",
"input_list",
")",
"==",
"0",
":",
"return",
"[",
"]",
"sorted_list",
"=",
"input_list",
"length",
"=",
"len",
"(",
"sorted_list",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"min_index",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"length",
")",
":",
"if",
"sorted_list",
"[",
"min_index",
"]",
">",
"sorted_list",
"[",
"j",
"]",
":",
"min_index",
"=",
"j",
"temp",
"=",
"sorted_list",
"[",
"i",
"]",
"sorted_list",
"[",
"i",
"]",
"=",
"sorted_list",
"[",
"min_index",
"]",
"sorted_list",
"[",
"min_index",
"]",
"=",
"temp",
"return",
"sorted_list"
] | https://github.com/Jack-Cherish/Algorithm/blob/ab3e0f05ff15972f282b6122b73dfa0e84b5960b/Sort Algorithms.py#L165-L187 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py | python | X509.has_expired | (self) | return not_after < datetime.datetime.utcnow() | Check whether the certificate has expired.
:return: ``True`` if the certificate has expired, ``False`` otherwise.
:rtype: bool | Check whether the certificate has expired. | [
"Check",
"whether",
"the",
"certificate",
"has",
"expired",
"."
] | def has_expired(self):
"""
Check whether the certificate has expired.
:return: ``True`` if the certificate has expired, ``False`` otherwise.
:rtype: bool
"""
time_string = _native(self.get_notAfter())
not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
return not_after < datetime.datetime.utcnow() | [
"def",
"has_expired",
"(",
"self",
")",
":",
"time_string",
"=",
"_native",
"(",
"self",
".",
"get_notAfter",
"(",
")",
")",
"not_after",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"time_string",
",",
"\"%Y%m%d%H%M%SZ\"",
")",
"return",
"not_after",
"<",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L1323-L1333 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/nn_ops.py | python | SparseApplyFtrl.__init__ | (self, lr, l1, l2, lr_power, use_locking=False) | Initialize SparseApplyFtrl. | Initialize SparseApplyFtrl. | [
"Initialize",
"SparseApplyFtrl",
"."
] | def __init__(self, lr, l1, l2, lr_power, use_locking=False):
"""Initialize SparseApplyFtrl."""
validator.check_value_type("lr", lr, [float], self.name)
validator.check_value_type("l1", l1, [float], self.name)
validator.check_value_type("l2", l2, [float], self.name)
validator.check_value_type("lr_power", lr_power, [float], self.name)
self.lr = validator.check_positive_float(lr, "lr", self.name)
self.l1 = validator.check_non_negative_float(l1, "l1", self.name)
self.l2 = validator.check_non_negative_float(l2, "l2", self.name)
self.lr_power = validator.check_number("lr_power", lr_power, 0, Rel.LE, self.name)
self.use_locking = validator.check_value_type("use_locking", use_locking, [bool], self.name)
self.init_prim_io_names(inputs=['var', 'accum', 'linear', 'grad', 'indices'],
outputs=['var', 'accum', 'linear'])
self.add_prim_attr('side_effect_mem', True) | [
"def",
"__init__",
"(",
"self",
",",
"lr",
",",
"l1",
",",
"l2",
",",
"lr_power",
",",
"use_locking",
"=",
"False",
")",
":",
"validator",
".",
"check_value_type",
"(",
"\"lr\"",
",",
"lr",
",",
"[",
"float",
"]",
",",
"self",
".",
"name",
")",
"validator",
".",
"check_value_type",
"(",
"\"l1\"",
",",
"l1",
",",
"[",
"float",
"]",
",",
"self",
".",
"name",
")",
"validator",
".",
"check_value_type",
"(",
"\"l2\"",
",",
"l2",
",",
"[",
"float",
"]",
",",
"self",
".",
"name",
")",
"validator",
".",
"check_value_type",
"(",
"\"lr_power\"",
",",
"lr_power",
",",
"[",
"float",
"]",
",",
"self",
".",
"name",
")",
"self",
".",
"lr",
"=",
"validator",
".",
"check_positive_float",
"(",
"lr",
",",
"\"lr\"",
",",
"self",
".",
"name",
")",
"self",
".",
"l1",
"=",
"validator",
".",
"check_non_negative_float",
"(",
"l1",
",",
"\"l1\"",
",",
"self",
".",
"name",
")",
"self",
".",
"l2",
"=",
"validator",
".",
"check_non_negative_float",
"(",
"l2",
",",
"\"l2\"",
",",
"self",
".",
"name",
")",
"self",
".",
"lr_power",
"=",
"validator",
".",
"check_number",
"(",
"\"lr_power\"",
",",
"lr_power",
",",
"0",
",",
"Rel",
".",
"LE",
",",
"self",
".",
"name",
")",
"self",
".",
"use_locking",
"=",
"validator",
".",
"check_value_type",
"(",
"\"use_locking\"",
",",
"use_locking",
",",
"[",
"bool",
"]",
",",
"self",
".",
"name",
")",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'var'",
",",
"'accum'",
",",
"'linear'",
",",
"'grad'",
",",
"'indices'",
"]",
",",
"outputs",
"=",
"[",
"'var'",
",",
"'accum'",
",",
"'linear'",
"]",
")",
"self",
".",
"add_prim_attr",
"(",
"'side_effect_mem'",
",",
"True",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/nn_ops.py#L6591-L6604 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | Appearance.refresh | (self, deep: "bool"=True) | return _robotsim.Appearance_refresh(self, deep) | r"""
refresh(Appearance self, bool deep=True)
call this to rebuild internal buffers, e.g., when the OpenGL context changes. If
deep=True, the entire data structure will be revised. Use this for streaming
data, for example. | r"""
refresh(Appearance self, bool deep=True) | [
"r",
"refresh",
"(",
"Appearance",
"self",
"bool",
"deep",
"=",
"True",
")"
] | def refresh(self, deep: "bool"=True) -> "void":
r"""
refresh(Appearance self, bool deep=True)
call this to rebuild internal buffers, e.g., when the OpenGL context changes. If
deep=True, the entire data structure will be revised. Use this for streaming
data, for example.
"""
return _robotsim.Appearance_refresh(self, deep) | [
"def",
"refresh",
"(",
"self",
",",
"deep",
":",
"\"bool\"",
"=",
"True",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"Appearance_refresh",
"(",
"self",
",",
"deep",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L2787-L2797 | |
EricLYang/courseRepo | 60679ec7ec130fe0cff9d26b704f1e286e5fde13 | 3_class/mono-slam/build/catkin_generated/installspace/_setup_util.py | python | _prefix_env_variable | (environ, name, paths, subfolders) | return prefix_str | Return the prefix to prepend to the environment variable NAME, adding any path in NEW_PATHS_STR without creating duplicate or empty items. | Return the prefix to prepend to the environment variable NAME, adding any path in NEW_PATHS_STR without creating duplicate or empty items. | [
"Return",
"the",
"prefix",
"to",
"prepend",
"to",
"the",
"environment",
"variable",
"NAME",
"adding",
"any",
"path",
"in",
"NEW_PATHS_STR",
"without",
"creating",
"duplicate",
"or",
"empty",
"items",
"."
] | def _prefix_env_variable(environ, name, paths, subfolders):
'''
Return the prefix to prepend to the environment variable NAME, adding any path in NEW_PATHS_STR without creating duplicate or empty items.
'''
value = environ[name] if name in environ else ''
environ_paths = [path for path in value.split(os.pathsep) if path]
checked_paths = []
for path in paths:
if not isinstance(subfolders, list):
subfolders = [subfolders]
for subfolder in subfolders:
path_tmp = path
if subfolder:
path_tmp = os.path.join(path_tmp, subfolder)
# skip nonexistent paths
if not os.path.exists(path_tmp):
continue
# exclude any path already in env and any path we already added
if path_tmp not in environ_paths and path_tmp not in checked_paths:
checked_paths.append(path_tmp)
prefix_str = os.pathsep.join(checked_paths)
if prefix_str != '' and environ_paths:
prefix_str += os.pathsep
return prefix_str | [
"def",
"_prefix_env_variable",
"(",
"environ",
",",
"name",
",",
"paths",
",",
"subfolders",
")",
":",
"value",
"=",
"environ",
"[",
"name",
"]",
"if",
"name",
"in",
"environ",
"else",
"''",
"environ_paths",
"=",
"[",
"path",
"for",
"path",
"in",
"value",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"if",
"path",
"]",
"checked_paths",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"if",
"not",
"isinstance",
"(",
"subfolders",
",",
"list",
")",
":",
"subfolders",
"=",
"[",
"subfolders",
"]",
"for",
"subfolder",
"in",
"subfolders",
":",
"path_tmp",
"=",
"path",
"if",
"subfolder",
":",
"path_tmp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_tmp",
",",
"subfolder",
")",
"# skip nonexistent paths",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path_tmp",
")",
":",
"continue",
"# exclude any path already in env and any path we already added",
"if",
"path_tmp",
"not",
"in",
"environ_paths",
"and",
"path_tmp",
"not",
"in",
"checked_paths",
":",
"checked_paths",
".",
"append",
"(",
"path_tmp",
")",
"prefix_str",
"=",
"os",
".",
"pathsep",
".",
"join",
"(",
"checked_paths",
")",
"if",
"prefix_str",
"!=",
"''",
"and",
"environ_paths",
":",
"prefix_str",
"+=",
"os",
".",
"pathsep",
"return",
"prefix_str"
] | https://github.com/EricLYang/courseRepo/blob/60679ec7ec130fe0cff9d26b704f1e286e5fde13/3_class/mono-slam/build/catkin_generated/installspace/_setup_util.py#L150-L173 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/selectionDataModel.py | python | SelectionDataModel.removeInactivePrims | (self) | Remove all inactive prims | Remove all inactive prims | [
"Remove",
"all",
"inactive",
"prims"
] | def removeInactivePrims(self):
"""Remove all inactive prims"""
for prim in self.getPrims():
if not prim.IsActive():
self.removePrim(prim) | [
"def",
"removeInactivePrims",
"(",
"self",
")",
":",
"for",
"prim",
"in",
"self",
".",
"getPrims",
"(",
")",
":",
"if",
"not",
"prim",
".",
"IsActive",
"(",
")",
":",
"self",
".",
"removePrim",
"(",
"prim",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L757-L761 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/email/parser.py | python | BytesParser.__init__ | (self, *args, **kw) | Parser of binary RFC 2822 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
The input must be formatted as a block of RFC 2822 headers and header
continuation lines, optionally preceded by a `Unix-from' header. The
header block is terminated either by the end of the input or by a
blank line.
_class is the class to instantiate for new message objects when they
must be created. This class must have a constructor that can take
zero arguments. Default is Message.Message. | Parser of binary RFC 2822 and MIME email messages. | [
"Parser",
"of",
"binary",
"RFC",
"2822",
"and",
"MIME",
"email",
"messages",
"."
] | def __init__(self, *args, **kw):
"""Parser of binary RFC 2822 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
The input must be formatted as a block of RFC 2822 headers and header
continuation lines, optionally preceded by a `Unix-from' header. The
header block is terminated either by the end of the input or by a
blank line.
_class is the class to instantiate for new message objects when they
must be created. This class must have a constructor that can take
zero arguments. Default is Message.Message.
"""
self.parser = Parser(*args, **kw) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"parser",
"=",
"Parser",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/parser.py#L81-L97 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/xmlreader.py | python | XMLReader.getProperty | (self, name) | Looks up and returns the value of a SAX2 property. | Looks up and returns the value of a SAX2 property. | [
"Looks",
"up",
"and",
"returns",
"the",
"value",
"of",
"a",
"SAX2",
"property",
"."
] | def getProperty(self, name):
"Looks up and returns the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name) | [
"def",
"getProperty",
"(",
"self",
",",
"name",
")",
":",
"raise",
"SAXNotRecognizedException",
"(",
"\"Property '%s' not recognized\"",
"%",
"name",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/xmlreader.py#L83-L85 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L1937-L1939 | |
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | scripts/cpp_lint.py | python | _NestingState.SeenOpenBrace | (self) | return (not self.stack) or self.stack[-1].seen_open_brace | Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace. | Check if we have seen the opening brace for the innermost block. | [
"Check",
"if",
"we",
"have",
"seen",
"the",
"opening",
"brace",
"for",
"the",
"innermost",
"block",
"."
] | def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace | [
"def",
"SeenOpenBrace",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"stack",
")",
"or",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"seen_open_brace"
] | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L1935-L1942 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/GettextCommon.py | python | _detect_xgettext | (env) | return None | Detects *xgettext(1)* binary | Detects *xgettext(1)* binary | [
"Detects",
"*",
"xgettext",
"(",
"1",
")",
"*",
"binary"
] | def _detect_xgettext(env):
""" Detects *xgettext(1)* binary """
if 'XGETTEXT' in env:
return env['XGETTEXT']
xgettext = env.Detect('xgettext');
if xgettext:
return xgettext
raise SCons.Errors.StopError(XgettextNotFound, "Could not detect xgettext")
return None | [
"def",
"_detect_xgettext",
"(",
"env",
")",
":",
"if",
"'XGETTEXT'",
"in",
"env",
":",
"return",
"env",
"[",
"'XGETTEXT'",
"]",
"xgettext",
"=",
"env",
".",
"Detect",
"(",
"'xgettext'",
")",
"if",
"xgettext",
":",
"return",
"xgettext",
"raise",
"SCons",
".",
"Errors",
".",
"StopError",
"(",
"XgettextNotFound",
",",
"\"Could not detect xgettext\"",
")",
"return",
"None"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/GettextCommon.py#L389-L397 | |
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/internal/enum_type_wrapper.py | python | EnumTypeWrapper.items | (self) | return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file. | Return a list of the (name, value) pairs of the enum. | [
"Return",
"a",
"list",
"of",
"the",
"(",
"name",
"value",
")",
"pairs",
"of",
"the",
"enum",
"."
] | def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"value_descriptor",
".",
"name",
",",
"value_descriptor",
".",
"number",
")",
"for",
"value_descriptor",
"in",
"self",
".",
"_enum_type",
".",
"values",
"]"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/enum_type_wrapper.py#L83-L89 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManager.DoDropRow | (self, panes, target, dock_direction, dock_layer, dock_row) | return self.ProcessDockResult(target, drop) | Insert a row in the interface before dropping.
:param `panes`: a list of :class:`AuiPaneInfo` classes;
:param AuiPaneInfo `target`: the target pane;
:param integer `dock_direction`: the docking direction;
:param integer `dock_layer`: the docking layer;
:param integer `dock_row`: the docking row. | Insert a row in the interface before dropping. | [
"Insert",
"a",
"row",
"in",
"the",
"interface",
"before",
"dropping",
"."
] | def DoDropRow(self, panes, target, dock_direction, dock_layer, dock_row):
"""
Insert a row in the interface before dropping.
:param `panes`: a list of :class:`AuiPaneInfo` classes;
:param AuiPaneInfo `target`: the target pane;
:param integer `dock_direction`: the docking direction;
:param integer `dock_layer`: the docking layer;
:param integer `dock_row`: the docking row.
"""
drop = self.CopyTarget(target)
panes = DoInsertDockRow(panes, dock_direction, dock_layer, dock_row)
drop.Dock().Direction(dock_direction).Layer(dock_layer).Row(dock_row).Position(0)
return self.ProcessDockResult(target, drop) | [
"def",
"DoDropRow",
"(",
"self",
",",
"panes",
",",
"target",
",",
"dock_direction",
",",
"dock_layer",
",",
"dock_row",
")",
":",
"drop",
"=",
"self",
".",
"CopyTarget",
"(",
"target",
")",
"panes",
"=",
"DoInsertDockRow",
"(",
"panes",
",",
"dock_direction",
",",
"dock_layer",
",",
"dock_row",
")",
"drop",
".",
"Dock",
"(",
")",
".",
"Direction",
"(",
"dock_direction",
")",
".",
"Layer",
"(",
"dock_layer",
")",
".",
"Row",
"(",
"dock_row",
")",
".",
"Position",
"(",
"0",
")",
"return",
"self",
".",
"ProcessDockResult",
"(",
"target",
",",
"drop",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L8040-L8055 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBar.GetToolLongHelp | (*args, **kwargs) | return _aui.AuiToolBar_GetToolLongHelp(*args, **kwargs) | GetToolLongHelp(self, int toolId) -> String | GetToolLongHelp(self, int toolId) -> String | [
"GetToolLongHelp",
"(",
"self",
"int",
"toolId",
")",
"-",
">",
"String"
] | def GetToolLongHelp(*args, **kwargs):
"""GetToolLongHelp(self, int toolId) -> String"""
return _aui.AuiToolBar_GetToolLongHelp(*args, **kwargs) | [
"def",
"GetToolLongHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBar_GetToolLongHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L2242-L2244 | |
VowpalWabbit/vowpal_wabbit | 866b8fa88ff85a957c7eb72065ea44518b9ba416 | python/vowpalwabbit/pyvw.py | python | Workspace.get_weight | (self, index, offset=0) | return pylibvw.vw.get_weight(self, index, offset) | Get the weight at a particular position in the (learned) weight
vector.
Args:
index (int): position in the learned weight vector
offset (int): By default is 0
Returns:
float: Weight at the given index | Get the weight at a particular position in the (learned) weight
vector. | [
"Get",
"the",
"weight",
"at",
"a",
"particular",
"position",
"in",
"the",
"(",
"learned",
")",
"weight",
"vector",
"."
] | def get_weight(self, index, offset=0) -> float:
"""Get the weight at a particular position in the (learned) weight
vector.
Args:
index (int): position in the learned weight vector
offset (int): By default is 0
Returns:
float: Weight at the given index
"""
return pylibvw.vw.get_weight(self, index, offset) | [
"def",
"get_weight",
"(",
"self",
",",
"index",
",",
"offset",
"=",
"0",
")",
"->",
"float",
":",
"return",
"pylibvw",
".",
"vw",
".",
"get_weight",
"(",
"self",
",",
"index",
",",
"offset",
")"
] | https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/pyvw.py#L532-L543 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cgutils.py | python | for_range_slice_generic | (builder, start, stop, step) | A helper wrapper for for_range_slice(). This is a context manager which
yields two for_range_slice()-alike context managers, the first for
the positive step case, the second for the negative step case.
Use:
with for_range_slice_generic(...) as (pos_range, neg_range):
with pos_range as (idx, count):
...
with neg_range as (idx, count):
... | A helper wrapper for for_range_slice(). This is a context manager which
yields two for_range_slice()-alike context managers, the first for
the positive step case, the second for the negative step case. | [
"A",
"helper",
"wrapper",
"for",
"for_range_slice",
"()",
".",
"This",
"is",
"a",
"context",
"manager",
"which",
"yields",
"two",
"for_range_slice",
"()",
"-",
"alike",
"context",
"managers",
"the",
"first",
"for",
"the",
"positive",
"step",
"case",
"the",
"second",
"for",
"the",
"negative",
"step",
"case",
"."
] | def for_range_slice_generic(builder, start, stop, step):
"""
A helper wrapper for for_range_slice(). This is a context manager which
yields two for_range_slice()-alike context managers, the first for
the positive step case, the second for the negative step case.
Use:
with for_range_slice_generic(...) as (pos_range, neg_range):
with pos_range as (idx, count):
...
with neg_range as (idx, count):
...
"""
intp = start.type
is_pos_step = builder.icmp_signed('>=', step, ir.Constant(intp, 0))
pos_for_range = for_range_slice(builder, start, stop, step, intp, inc=True)
neg_for_range = for_range_slice(builder, start, stop, step, intp, inc=False)
@contextmanager
def cm_cond(cond, inner_cm):
with cond:
with inner_cm as value:
yield value
with builder.if_else(is_pos_step, likely=True) as (then, otherwise):
yield cm_cond(then, pos_for_range), cm_cond(otherwise, neg_for_range) | [
"def",
"for_range_slice_generic",
"(",
"builder",
",",
"start",
",",
"stop",
",",
"step",
")",
":",
"intp",
"=",
"start",
".",
"type",
"is_pos_step",
"=",
"builder",
".",
"icmp_signed",
"(",
"'>='",
",",
"step",
",",
"ir",
".",
"Constant",
"(",
"intp",
",",
"0",
")",
")",
"pos_for_range",
"=",
"for_range_slice",
"(",
"builder",
",",
"start",
",",
"stop",
",",
"step",
",",
"intp",
",",
"inc",
"=",
"True",
")",
"neg_for_range",
"=",
"for_range_slice",
"(",
"builder",
",",
"start",
",",
"stop",
",",
"step",
",",
"intp",
",",
"inc",
"=",
"False",
")",
"@",
"contextmanager",
"def",
"cm_cond",
"(",
"cond",
",",
"inner_cm",
")",
":",
"with",
"cond",
":",
"with",
"inner_cm",
"as",
"value",
":",
"yield",
"value",
"with",
"builder",
".",
"if_else",
"(",
"is_pos_step",
",",
"likely",
"=",
"True",
")",
"as",
"(",
"then",
",",
"otherwise",
")",
":",
"yield",
"cm_cond",
"(",
"then",
",",
"pos_for_range",
")",
",",
"cm_cond",
"(",
"otherwise",
",",
"neg_for_range",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cgutils.py#L555-L581 | ||
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/benchtracker/server_db.py | python | get_csv_data | () | Return a zipped archive of csv files for selected tasks | Return a zipped archive of csv files for selected tasks | [
"Return",
"a",
"zipped",
"archive",
"of",
"csv",
"files",
"for",
"selected",
"tasks"
] | def get_csv_data():
"""Return a zipped archive of csv files for selected tasks"""
(exception, payload) = parse_data()
if exception:
return payload
else:
(database, tasks, params, data) = payload
memory_file = BytesIO()
with zipfile.ZipFile(memory_file, "a", zipfile.ZIP_DEFLATED) as zf:
t = 0
for csvf in d.export_data_csv(params, data):
# characters the filesystem might complain about (/|) are replaced
zf.writestr(
"benchmark_results/" + tasks[t].replace("/", ".").replace("|", "__"),
csvf.getvalue(),
)
t += 1
# prepare to send over network
memory_file.seek(0)
return send_file(
memory_file, attachment_filename="benchmark_results.zip", as_attachment=True
) | [
"def",
"get_csv_data",
"(",
")",
":",
"(",
"exception",
",",
"payload",
")",
"=",
"parse_data",
"(",
")",
"if",
"exception",
":",
"return",
"payload",
"else",
":",
"(",
"database",
",",
"tasks",
",",
"params",
",",
"data",
")",
"=",
"payload",
"memory_file",
"=",
"BytesIO",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"memory_file",
",",
"\"a\"",
",",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"as",
"zf",
":",
"t",
"=",
"0",
"for",
"csvf",
"in",
"d",
".",
"export_data_csv",
"(",
"params",
",",
"data",
")",
":",
"# characters the filesystem might complain about (/|) are replaced",
"zf",
".",
"writestr",
"(",
"\"benchmark_results/\"",
"+",
"tasks",
"[",
"t",
"]",
".",
"replace",
"(",
"\"/\"",
",",
"\".\"",
")",
".",
"replace",
"(",
"\"|\"",
",",
"\"__\"",
")",
",",
"csvf",
".",
"getvalue",
"(",
")",
",",
")",
"t",
"+=",
"1",
"# prepare to send over network",
"memory_file",
".",
"seek",
"(",
"0",
")",
"return",
"send_file",
"(",
"memory_file",
",",
"attachment_filename",
"=",
"\"benchmark_results.zip\"",
",",
"as_attachment",
"=",
"True",
")"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/benchtracker/server_db.py#L171-L193 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_vim.py | python | EditraCommander.PrevIdent | (self, repeat=1) | Find the previous occurrence of identifier under cursor | Find the previous occurrence of identifier under cursor | [
"Find",
"the",
"previous",
"occurrence",
"of",
"identifier",
"under",
"cursor"
] | def PrevIdent(self, repeat=1):
"""Find the previous occurrence of identifier under cursor"""
self._NextIdent(repeat, back=True) | [
"def",
"PrevIdent",
"(",
"self",
",",
"repeat",
"=",
"1",
")",
":",
"self",
".",
"_NextIdent",
"(",
"repeat",
",",
"back",
"=",
"True",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_vim.py#L542-L544 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_field_common.py | python | _restore_pmap_field_pickle | (key_type, value_type, data) | return _restore_pickle(type_, data) | Unpickling function for auto-generated PMap field types. | Unpickling function for auto-generated PMap field types. | [
"Unpickling",
"function",
"for",
"auto",
"-",
"generated",
"PMap",
"field",
"types",
"."
] | def _restore_pmap_field_pickle(key_type, value_type, data):
"""Unpickling function for auto-generated PMap field types."""
type_ = _pmap_field_types[key_type, value_type]
return _restore_pickle(type_, data) | [
"def",
"_restore_pmap_field_pickle",
"(",
"key_type",
",",
"value_type",
",",
"data",
")",
":",
"type_",
"=",
"_pmap_field_types",
"[",
"key_type",
",",
"value_type",
"]",
"return",
"_restore_pickle",
"(",
"type_",
",",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_field_common.py#L279-L282 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/sessions.py | python | Session.patch | (self, url, data=None, **kwargs) | return self.request('PATCH', url, data=data, **kwargs) | r"""Sends a PATCH request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response | r"""Sends a PATCH request. Returns :class:`Response` object. | [
"r",
"Sends",
"a",
"PATCH",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def patch(self, url, data=None, **kwargs):
r"""Sends a PATCH request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PATCH', url, data=data, **kwargs) | [
"def",
"patch",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'PATCH'",
",",
"url",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/sessions.py#L592-L602 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/drivers/win32/windowing.py | python | MoveAndSizeWindow | (wnd, position=None, size=None, child=None) | Moves and/or resizes a window.
Repositions and resizes a window. If a child window is provided,
the parent window is resized so the child window has the given size
Args:
wnd: handle of the frame window
position: new location for the frame window
size: new size for the frame window (or the child window)
child: handle of the child window
Returns:
None | Moves and/or resizes a window. | [
"Moves",
"and",
"/",
"or",
"resizes",
"a",
"window",
"."
] | def MoveAndSizeWindow(wnd, position=None, size=None, child=None):
"""Moves and/or resizes a window.
Repositions and resizes a window. If a child window is provided,
the parent window is resized so the child window has the given size
Args:
wnd: handle of the frame window
position: new location for the frame window
size: new size for the frame window (or the child window)
child: handle of the child window
Returns:
None
"""
rect = win32gui.GetWindowRect(wnd)
if position is None: position = (rect[0], rect[1])
if size is None:
size = (rect[2]-rect[0], rect[3]-rect[1])
elif child is not None:
child_rect = win32gui.GetWindowRect(child)
slop = (rect[2]-rect[0]-child_rect[2]+child_rect[0],
rect[3]-rect[1]-child_rect[3]+child_rect[1])
size = (size[0]+slop[0], size[1]+slop[1])
win32gui.MoveWindow(wnd, # window to move
position[0], # new x coord
position[1], # new y coord
size[0], # new width
size[1], # new height
True) | [
"def",
"MoveAndSizeWindow",
"(",
"wnd",
",",
"position",
"=",
"None",
",",
"size",
"=",
"None",
",",
"child",
"=",
"None",
")",
":",
"rect",
"=",
"win32gui",
".",
"GetWindowRect",
"(",
"wnd",
")",
"if",
"position",
"is",
"None",
":",
"position",
"=",
"(",
"rect",
"[",
"0",
"]",
",",
"rect",
"[",
"1",
"]",
")",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"(",
"rect",
"[",
"2",
"]",
"-",
"rect",
"[",
"0",
"]",
",",
"rect",
"[",
"3",
"]",
"-",
"rect",
"[",
"1",
"]",
")",
"elif",
"child",
"is",
"not",
"None",
":",
"child_rect",
"=",
"win32gui",
".",
"GetWindowRect",
"(",
"child",
")",
"slop",
"=",
"(",
"rect",
"[",
"2",
"]",
"-",
"rect",
"[",
"0",
"]",
"-",
"child_rect",
"[",
"2",
"]",
"+",
"child_rect",
"[",
"0",
"]",
",",
"rect",
"[",
"3",
"]",
"-",
"rect",
"[",
"1",
"]",
"-",
"child_rect",
"[",
"3",
"]",
"+",
"child_rect",
"[",
"1",
"]",
")",
"size",
"=",
"(",
"size",
"[",
"0",
"]",
"+",
"slop",
"[",
"0",
"]",
",",
"size",
"[",
"1",
"]",
"+",
"slop",
"[",
"1",
"]",
")",
"win32gui",
".",
"MoveWindow",
"(",
"wnd",
",",
"# window to move",
"position",
"[",
"0",
"]",
",",
"# new x coord",
"position",
"[",
"1",
"]",
",",
"# new y coord",
"size",
"[",
"0",
"]",
",",
"# new width",
"size",
"[",
"1",
"]",
",",
"# new height",
"True",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/drivers/win32/windowing.py#L254-L285 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/distribution_util.py | python | assert_integer_form | (
x, data=None, summarize=None, message=None, name="assert_integer_form") | return check_ops.assert_equal(
x, math_ops.cast(math_ops.round(casted_x), x.dtype),
data=data, summarize=summarize, message=message, name=name) | Assert that x has integer components (or floats equal to integers).
Args:
x: Numeric `Tensor`
data: The tensors to print out if the condition is `False`. Defaults to
error message and first few entries of `x` and `y`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional).
Returns:
Op raising `InvalidArgumentError` if round(x) != x. | Assert that x has integer components (or floats equal to integers). | [
"Assert",
"that",
"x",
"has",
"integer",
"components",
"(",
"or",
"floats",
"equal",
"to",
"integers",
")",
"."
] | def assert_integer_form(
x, data=None, summarize=None, message=None, name="assert_integer_form"):
"""Assert that x has integer components (or floats equal to integers).
Args:
x: Numeric `Tensor`
data: The tensors to print out if the condition is `False`. Defaults to
error message and first few entries of `x` and `y`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional).
Returns:
Op raising `InvalidArgumentError` if round(x) != x.
"""
message = message or "x has non-integer components"
x = ops.convert_to_tensor(x, name="x")
casted_x = math_ops.to_int64(x)
return check_ops.assert_equal(
x, math_ops.cast(math_ops.round(casted_x), x.dtype),
data=data, summarize=summarize, message=message, name=name) | [
"def",
"assert_integer_form",
"(",
"x",
",",
"data",
"=",
"None",
",",
"summarize",
"=",
"None",
",",
"message",
"=",
"None",
",",
"name",
"=",
"\"assert_integer_form\"",
")",
":",
"message",
"=",
"message",
"or",
"\"x has non-integer components\"",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
"=",
"\"x\"",
")",
"casted_x",
"=",
"math_ops",
".",
"to_int64",
"(",
"x",
")",
"return",
"check_ops",
".",
"assert_equal",
"(",
"x",
",",
"math_ops",
".",
"cast",
"(",
"math_ops",
".",
"round",
"(",
"casted_x",
")",
",",
"x",
".",
"dtype",
")",
",",
"data",
"=",
"data",
",",
"summarize",
"=",
"summarize",
",",
"message",
"=",
"message",
",",
"name",
"=",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/distribution_util.py#L69-L90 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/dashboard/services/ceph_service.py | python | CephService.get_smart_data_by_host | (hostname) | return smart_data | Get the SMART data of all devices on the given host, regardless
of the daemon (osd, mon, ...).
:param hostname: The name of the host.
:return: A dictionary containing the SMART data of every device
on the given host. The device name is used as the key in the
dictionary. | Get the SMART data of all devices on the given host, regardless
of the daemon (osd, mon, ...).
:param hostname: The name of the host.
:return: A dictionary containing the SMART data of every device
on the given host. The device name is used as the key in the
dictionary. | [
"Get",
"the",
"SMART",
"data",
"of",
"all",
"devices",
"on",
"the",
"given",
"host",
"regardless",
"of",
"the",
"daemon",
"(",
"osd",
"mon",
"...",
")",
".",
":",
"param",
"hostname",
":",
"The",
"name",
"of",
"the",
"host",
".",
":",
"return",
":",
"A",
"dictionary",
"containing",
"the",
"SMART",
"data",
"of",
"every",
"device",
"on",
"the",
"given",
"host",
".",
"The",
"device",
"name",
"is",
"used",
"as",
"the",
"key",
"in",
"the",
"dictionary",
"."
] | def get_smart_data_by_host(hostname):
# type: (str) -> dict
"""
Get the SMART data of all devices on the given host, regardless
of the daemon (osd, mon, ...).
:param hostname: The name of the host.
:return: A dictionary containing the SMART data of every device
on the given host. The device name is used as the key in the
dictionary.
"""
devices = CephService.get_devices_by_host(hostname)
smart_data = {} # type: dict
if devices:
for device in devices:
if device['devid'] not in smart_data:
smart_data.update(
CephService._get_smart_data_by_device(device))
else:
logger.debug('[SMART] could not retrieve device list from host %s', hostname)
return smart_data | [
"def",
"get_smart_data_by_host",
"(",
"hostname",
")",
":",
"# type: (str) -> dict",
"devices",
"=",
"CephService",
".",
"get_devices_by_host",
"(",
"hostname",
")",
"smart_data",
"=",
"{",
"}",
"# type: dict",
"if",
"devices",
":",
"for",
"device",
"in",
"devices",
":",
"if",
"device",
"[",
"'devid'",
"]",
"not",
"in",
"smart_data",
":",
"smart_data",
".",
"update",
"(",
"CephService",
".",
"_get_smart_data_by_device",
"(",
"device",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'[SMART] could not retrieve device list from host %s'",
",",
"hostname",
")",
"return",
"smart_data"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/services/ceph_service.py#L301-L320 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/graphdata.py | python | GraphData.get_sampled_neighbors | (self, node_list, neighbor_nums, neighbor_types, strategy=SamplingStrategy.RANDOM) | return self._graph_data.get_sampled_neighbors(
node_list, neighbor_nums, neighbor_types, DE_C_INTER_SAMPLING_STRATEGY[strategy]).as_array() | Get sampled neighbor information.
The api supports multi-hop neighbor sampling. That is, the previous sampling result is used as the input of
next-hop sampling. A maximum of 6-hop are allowed.
The sampling result is tiled into a list in the format of [input node, 1-hop sampling result,
2-hop sampling result ...]
Args:
node_list (Union[list, numpy.ndarray]): The given list of nodes.
neighbor_nums (Union[list, numpy.ndarray]): Number of neighbors sampled per hop.
neighbor_types (Union[list, numpy.ndarray]): Neighbor type sampled per hop.
strategy (SamplingStrategy, optional): Sampling strategy (default=SamplingStrategy.RANDOM).
It can be any of [SamplingStrategy.RANDOM, SamplingStrategy.EDGE_WEIGHT].
- SamplingStrategy.RANDOM, random sampling with replacement.
- SamplingStrategy.EDGE_WEIGHT, sampling with edge weight as probability.
Returns:
numpy.ndarray, array of neighbors.
Examples:
>>> nodes = graph_dataset.get_all_nodes(node_type=1)
>>> neighbors = graph_dataset.get_sampled_neighbors(node_list=nodes, neighbor_nums=[2, 2],
... neighbor_types=[2, 1])
Raises:
TypeError: If `node_list` is not list or ndarray.
TypeError: If `neighbor_nums` is not list or ndarray.
TypeError: If `neighbor_types` is not list or ndarray. | Get sampled neighbor information. | [
"Get",
"sampled",
"neighbor",
"information",
"."
] | def get_sampled_neighbors(self, node_list, neighbor_nums, neighbor_types, strategy=SamplingStrategy.RANDOM):
"""
Get sampled neighbor information.
The api supports multi-hop neighbor sampling. That is, the previous sampling result is used as the input of
next-hop sampling. A maximum of 6-hop are allowed.
The sampling result is tiled into a list in the format of [input node, 1-hop sampling result,
2-hop sampling result ...]
Args:
node_list (Union[list, numpy.ndarray]): The given list of nodes.
neighbor_nums (Union[list, numpy.ndarray]): Number of neighbors sampled per hop.
neighbor_types (Union[list, numpy.ndarray]): Neighbor type sampled per hop.
strategy (SamplingStrategy, optional): Sampling strategy (default=SamplingStrategy.RANDOM).
It can be any of [SamplingStrategy.RANDOM, SamplingStrategy.EDGE_WEIGHT].
- SamplingStrategy.RANDOM, random sampling with replacement.
- SamplingStrategy.EDGE_WEIGHT, sampling with edge weight as probability.
Returns:
numpy.ndarray, array of neighbors.
Examples:
>>> nodes = graph_dataset.get_all_nodes(node_type=1)
>>> neighbors = graph_dataset.get_sampled_neighbors(node_list=nodes, neighbor_nums=[2, 2],
... neighbor_types=[2, 1])
Raises:
TypeError: If `node_list` is not list or ndarray.
TypeError: If `neighbor_nums` is not list or ndarray.
TypeError: If `neighbor_types` is not list or ndarray.
"""
if not isinstance(strategy, SamplingStrategy):
raise TypeError("Wrong input type for strategy, should be enum of 'SamplingStrategy'.")
if self._working_mode == 'server':
raise Exception("This method is not supported when working mode is server.")
return self._graph_data.get_sampled_neighbors(
node_list, neighbor_nums, neighbor_types, DE_C_INTER_SAMPLING_STRATEGY[strategy]).as_array() | [
"def",
"get_sampled_neighbors",
"(",
"self",
",",
"node_list",
",",
"neighbor_nums",
",",
"neighbor_types",
",",
"strategy",
"=",
"SamplingStrategy",
".",
"RANDOM",
")",
":",
"if",
"not",
"isinstance",
"(",
"strategy",
",",
"SamplingStrategy",
")",
":",
"raise",
"TypeError",
"(",
"\"Wrong input type for strategy, should be enum of 'SamplingStrategy'.\"",
")",
"if",
"self",
".",
"_working_mode",
"==",
"'server'",
":",
"raise",
"Exception",
"(",
"\"This method is not supported when working mode is server.\"",
")",
"return",
"self",
".",
"_graph_data",
".",
"get_sampled_neighbors",
"(",
"node_list",
",",
"neighbor_nums",
",",
"neighbor_types",
",",
"DE_C_INTER_SAMPLING_STRATEGY",
"[",
"strategy",
"]",
")",
".",
"as_array",
"(",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/graphdata.py#L341-L379 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/aws_utils.py | python | ArnParser.arn | (self) | return self.__arn | The source ARN. | The source ARN. | [
"The",
"source",
"ARN",
"."
] | def arn(self):
"""The source ARN."""
return self.__arn | [
"def",
"arn",
"(",
"self",
")",
":",
"return",
"self",
".",
"__arn"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/aws_utils.py#L398-L400 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | syzygy/build/get_syzygy_binaries.py | python | _CleanState | (output_dir, state, dry_run=False) | return deleted | Cleans up files/directories in |output_dir| that are referenced by
the given |state|. Raises an error if there are local changes. Returns a
dictionary of files that were deleted. | Cleans up files/directories in |output_dir| that are referenced by
the given |state|. Raises an error if there are local changes. Returns a
dictionary of files that were deleted. | [
"Cleans",
"up",
"files",
"/",
"directories",
"in",
"|output_dir|",
"that",
"are",
"referenced",
"by",
"the",
"given",
"|state|",
".",
"Raises",
"an",
"error",
"if",
"there",
"are",
"local",
"changes",
".",
"Returns",
"a",
"dictionary",
"of",
"files",
"that",
"were",
"deleted",
"."
] | def _CleanState(output_dir, state, dry_run=False):
"""Cleans up files/directories in |output_dir| that are referenced by
the given |state|. Raises an error if there are local changes. Returns a
dictionary of files that were deleted.
"""
_LOGGER.debug('Deleting files from previous installation.')
deleted = {}
# Generate a list of files to delete, relative to |output_dir|.
contents = state['contents']
files = sorted(contents.keys())
# Try to delete the files. Keep track of directories to delete as well.
dirs = {}
for relpath in files:
fullpath = os.path.join(output_dir, relpath)
fulldir = os.path.dirname(fullpath)
dirs[fulldir] = True
if os.path.exists(fullpath):
# If somehow the file has become a directory complain about it.
if os.path.isdir(fullpath):
raise Exception('Directory exists where file expected: %s' % fullpath)
# Double check that the file doesn't have local changes. If it does
# then refuse to delete it.
if relpath in contents:
stored_md5 = contents[relpath]
actual_md5 = _Md5(fullpath)
if actual_md5 != stored_md5:
raise Exception('File has local changes: %s' % fullpath)
# The file is unchanged so it can safely be deleted.
_LOGGER.debug('Deleting file "%s".', fullpath)
deleted[relpath] = True
if not dry_run:
os.unlink(fullpath)
# Sort directories from longest name to shortest. This lets us remove empty
# directories from the most nested paths first.
dirs = sorted(dirs.keys(), key=lambda x: len(x), reverse=True)
for p in dirs:
if os.path.exists(p) and _DirIsEmpty(p):
_LOGGER.debug('Deleting empty directory "%s".', p)
if not dry_run:
_RmTree(p)
return deleted | [
"def",
"_CleanState",
"(",
"output_dir",
",",
"state",
",",
"dry_run",
"=",
"False",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Deleting files from previous installation.'",
")",
"deleted",
"=",
"{",
"}",
"# Generate a list of files to delete, relative to |output_dir|.",
"contents",
"=",
"state",
"[",
"'contents'",
"]",
"files",
"=",
"sorted",
"(",
"contents",
".",
"keys",
"(",
")",
")",
"# Try to delete the files. Keep track of directories to delete as well.",
"dirs",
"=",
"{",
"}",
"for",
"relpath",
"in",
"files",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"relpath",
")",
"fulldir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fullpath",
")",
"dirs",
"[",
"fulldir",
"]",
"=",
"True",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fullpath",
")",
":",
"# If somehow the file has become a directory complain about it.",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullpath",
")",
":",
"raise",
"Exception",
"(",
"'Directory exists where file expected: %s'",
"%",
"fullpath",
")",
"# Double check that the file doesn't have local changes. If it does",
"# then refuse to delete it.",
"if",
"relpath",
"in",
"contents",
":",
"stored_md5",
"=",
"contents",
"[",
"relpath",
"]",
"actual_md5",
"=",
"_Md5",
"(",
"fullpath",
")",
"if",
"actual_md5",
"!=",
"stored_md5",
":",
"raise",
"Exception",
"(",
"'File has local changes: %s'",
"%",
"fullpath",
")",
"# The file is unchanged so it can safely be deleted.",
"_LOGGER",
".",
"debug",
"(",
"'Deleting file \"%s\".'",
",",
"fullpath",
")",
"deleted",
"[",
"relpath",
"]",
"=",
"True",
"if",
"not",
"dry_run",
":",
"os",
".",
"unlink",
"(",
"fullpath",
")",
"# Sort directories from longest name to shortest. This lets us remove empty",
"# directories from the most nested paths first.",
"dirs",
"=",
"sorted",
"(",
"dirs",
".",
"keys",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
",",
"reverse",
"=",
"True",
")",
"for",
"p",
"in",
"dirs",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
"and",
"_DirIsEmpty",
"(",
"p",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Deleting empty directory \"%s\".'",
",",
"p",
")",
"if",
"not",
"dry_run",
":",
"_RmTree",
"(",
"p",
")",
"return",
"deleted"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/syzygy/build/get_syzygy_binaries.py#L200-L246 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/server.py | python | ROSLaunchNode.start | (self) | Startup roslaunch server XML-RPC services
@raise RLException: if server fails to start | Startup roslaunch server XML-RPC services | [
"Startup",
"roslaunch",
"server",
"XML",
"-",
"RPC",
"services"
] | def start(self):
"""
Startup roslaunch server XML-RPC services
@raise RLException: if server fails to start
"""
logger = logging.getLogger('roslaunch.server')
logger.info("starting roslaunch XML-RPC server")
super(ROSLaunchNode, self).start()
# wait for node thread to initialize
timeout_t = time.time() + _STARTUP_TIMEOUT
logger.info("waiting for roslaunch XML-RPC server to initialize")
while not self.uri and time.time() < timeout_t:
time.sleep(0.01)
if not self.uri:
raise RLException("XML-RPC initialization failed")
# Make sure our xmlrpc server is actually up. We've seen very
# odd cases where remote nodes are unable to contact the
# server but have been unable to prove this is the cause.
server_up = False
while not server_up and time.time() < timeout_t:
try:
code, msg, val = ServerProxy(self.uri).get_pid()
if val != os.getpid():
raise RLException("Server at [%s] did not respond with correct PID. There appears to be something wrong with the networking configuration"%self.uri)
server_up = True
except IOError:
# presumably this can occur if we call in a small time
# interval between the server socket port being
# assigned and the XMLRPC server initializing, but it
# is highly unlikely and unconfirmed
time.sleep(0.1)
except socket.error as e:
if e.errno == 113:
p = urlparse(self.uri)
raise RLException("Unable to contact the address [%s], which should be local.\nThis is generally caused by:\n * bad local network configuration\n * bad ROS_IP environment variable\n * bad ROS_HOSTNAME environment variable\nCan you ping %s?"%(self.uri, p.hostname))
else:
time.sleep(0.1)
if not server_up:
p = urlparse(self.uri)
raise RLException("""Unable to contact my own server at [%s].
This usually means that the network is not configured properly.
A common cause is that the machine cannot ping itself. Please check
for errors by running:
\tping %s
For more tips, please see
\thttp://www.ros.org/wiki/ROS/NetworkSetup
"""%(self.uri, p.hostname))
printlog_bold("started roslaunch server %s"%(self.uri)) | [
"def",
"start",
"(",
"self",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'roslaunch.server'",
")",
"logger",
".",
"info",
"(",
"\"starting roslaunch XML-RPC server\"",
")",
"super",
"(",
"ROSLaunchNode",
",",
"self",
")",
".",
"start",
"(",
")",
"# wait for node thread to initialize",
"timeout_t",
"=",
"time",
".",
"time",
"(",
")",
"+",
"_STARTUP_TIMEOUT",
"logger",
".",
"info",
"(",
"\"waiting for roslaunch XML-RPC server to initialize\"",
")",
"while",
"not",
"self",
".",
"uri",
"and",
"time",
".",
"time",
"(",
")",
"<",
"timeout_t",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"not",
"self",
".",
"uri",
":",
"raise",
"RLException",
"(",
"\"XML-RPC initialization failed\"",
")",
"# Make sure our xmlrpc server is actually up. We've seen very",
"# odd cases where remote nodes are unable to contact the",
"# server but have been unable to prove this is the cause.",
"server_up",
"=",
"False",
"while",
"not",
"server_up",
"and",
"time",
".",
"time",
"(",
")",
"<",
"timeout_t",
":",
"try",
":",
"code",
",",
"msg",
",",
"val",
"=",
"ServerProxy",
"(",
"self",
".",
"uri",
")",
".",
"get_pid",
"(",
")",
"if",
"val",
"!=",
"os",
".",
"getpid",
"(",
")",
":",
"raise",
"RLException",
"(",
"\"Server at [%s] did not respond with correct PID. There appears to be something wrong with the networking configuration\"",
"%",
"self",
".",
"uri",
")",
"server_up",
"=",
"True",
"except",
"IOError",
":",
"# presumably this can occur if we call in a small time",
"# interval between the server socket port being",
"# assigned and the XMLRPC server initializing, but it",
"# is highly unlikely and unconfirmed",
"time",
".",
"sleep",
"(",
"0.1",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"113",
":",
"p",
"=",
"urlparse",
"(",
"self",
".",
"uri",
")",
"raise",
"RLException",
"(",
"\"Unable to contact the address [%s], which should be local.\\nThis is generally caused by:\\n * bad local network configuration\\n * bad ROS_IP environment variable\\n * bad ROS_HOSTNAME environment variable\\nCan you ping %s?\"",
"%",
"(",
"self",
".",
"uri",
",",
"p",
".",
"hostname",
")",
")",
"else",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"if",
"not",
"server_up",
":",
"p",
"=",
"urlparse",
"(",
"self",
".",
"uri",
")",
"raise",
"RLException",
"(",
"\"\"\"Unable to contact my own server at [%s].\nThis usually means that the network is not configured properly.\n\nA common cause is that the machine cannot ping itself. Please check\nfor errors by running:\n\n\\tping %s\n\nFor more tips, please see\n\n\\thttp://www.ros.org/wiki/ROS/NetworkSetup\n\"\"\"",
"%",
"(",
"self",
".",
"uri",
",",
"p",
".",
"hostname",
")",
")",
"printlog_bold",
"(",
"\"started roslaunch server %s\"",
"%",
"(",
"self",
".",
"uri",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/server.py#L353-L406 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/fields.py | python | RequestField.render_headers | (self) | return u"\r\n".join(lines) | Renders the headers for this request field. | Renders the headers for this request field. | [
"Renders",
"the",
"headers",
"for",
"this",
"request",
"field",
"."
] | def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append(u"%s: %s" % (sort_key, self.headers[sort_key]))
for header_name, header_value in self.headers.items():
if header_name not in sort_keys:
if header_value:
lines.append(u"%s: %s" % (header_name, header_value))
lines.append(u"\r\n")
return u"\r\n".join(lines) | [
"def",
"render_headers",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"sort_keys",
"=",
"[",
"\"Content-Disposition\"",
",",
"\"Content-Type\"",
",",
"\"Content-Location\"",
"]",
"for",
"sort_key",
"in",
"sort_keys",
":",
"if",
"self",
".",
"headers",
".",
"get",
"(",
"sort_key",
",",
"False",
")",
":",
"lines",
".",
"append",
"(",
"u\"%s: %s\"",
"%",
"(",
"sort_key",
",",
"self",
".",
"headers",
"[",
"sort_key",
"]",
")",
")",
"for",
"header_name",
",",
"header_value",
"in",
"self",
".",
"headers",
".",
"items",
"(",
")",
":",
"if",
"header_name",
"not",
"in",
"sort_keys",
":",
"if",
"header_value",
":",
"lines",
".",
"append",
"(",
"u\"%s: %s\"",
"%",
"(",
"header_name",
",",
"header_value",
")",
")",
"lines",
".",
"append",
"(",
"u\"\\r\\n\"",
")",
"return",
"u\"\\r\\n\"",
".",
"join",
"(",
"lines",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/fields.py#L229-L246 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_style.py | python | StyleMgr.StyleDefault | (self) | Clears the editor styles to default
@postcondition: style is reset to default | Clears the editor styles to default
@postcondition: style is reset to default | [
"Clears",
"the",
"editor",
"styles",
"to",
"default",
"@postcondition",
":",
"style",
"is",
"reset",
"to",
"default"
] | def StyleDefault(self):
"""Clears the editor styles to default
@postcondition: style is reset to default
"""
self.StyleClearAll()
self.SetCaretForeground(wx.BLACK)
self.Colourise(0, -1) | [
"def",
"StyleDefault",
"(",
"self",
")",
":",
"self",
".",
"StyleClearAll",
"(",
")",
"self",
".",
"SetCaretForeground",
"(",
"wx",
".",
"BLACK",
")",
"self",
".",
"Colourise",
"(",
"0",
",",
"-",
"1",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_style.py#L917-L924 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/tpu/tpu_sharding.py | python | ShardingPolicy.set_number_of_partitions | (self, number_of_partitions) | Sets the number of partitions for the current policy.
If the policy has been frozen then shard_dimension must match the
existing setting.
Args:
number_of_partitions: The number of partitions to use in the policy.
Raises:
ValueError: If the policy has been frozen and shard_dimension
differs from the frozen value. | Sets the number of partitions for the current policy. | [
"Sets",
"the",
"number",
"of",
"partitions",
"for",
"the",
"current",
"policy",
"."
] | def set_number_of_partitions(self, number_of_partitions):
"""Sets the number of partitions for the current policy.
If the policy has been frozen then shard_dimension must match the
existing setting.
Args:
number_of_partitions: The number of partitions to use in the policy.
Raises:
ValueError: If the policy has been frozen and shard_dimension
differs from the frozen value.
"""
if self._frozen:
if self._number_of_partitions != number_of_partitions:
raise ValueError(
f"Can't set number_of_partitions to {number_of_partitions} since "
f"it has been frozen to use {self._number_of_partitions}.")
else:
self._number_of_partitions = number_of_partitions | [
"def",
"set_number_of_partitions",
"(",
"self",
",",
"number_of_partitions",
")",
":",
"if",
"self",
".",
"_frozen",
":",
"if",
"self",
".",
"_number_of_partitions",
"!=",
"number_of_partitions",
":",
"raise",
"ValueError",
"(",
"f\"Can't set number_of_partitions to {number_of_partitions} since \"",
"f\"it has been frozen to use {self._number_of_partitions}.\"",
")",
"else",
":",
"self",
".",
"_number_of_partitions",
"=",
"number_of_partitions"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/tpu_sharding.py#L94-L113 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/contrib/_securetransport/low_level.py | python | _is_cert | (item) | return CoreFoundation.CFGetTypeID(item) == expected | Returns True if a given CFTypeRef is a certificate. | Returns True if a given CFTypeRef is a certificate. | [
"Returns",
"True",
"if",
"a",
"given",
"CFTypeRef",
"is",
"a",
"certificate",
"."
] | def _is_cert(item):
"""
Returns True if a given CFTypeRef is a certificate.
"""
expected = Security.SecCertificateGetTypeID()
return CoreFoundation.CFGetTypeID(item) == expected | [
"def",
"_is_cert",
"(",
"item",
")",
":",
"expected",
"=",
"Security",
".",
"SecCertificateGetTypeID",
"(",
")",
"return",
"CoreFoundation",
".",
"CFGetTypeID",
"(",
"item",
")",
"==",
"expected"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/contrib/_securetransport/low_level.py#L150-L155 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Script/Interactive.py | python | SConsInteractiveCmd.do_clean | (self, argv) | return self.do_build(['build', '--clean'] + argv[1:]) | \
clean [TARGETS] Clean (remove) the specified TARGETS
and their dependencies. 'c' is a synonym. | \
clean [TARGETS] Clean (remove) the specified TARGETS
and their dependencies. 'c' is a synonym. | [
"\\",
"clean",
"[",
"TARGETS",
"]",
"Clean",
"(",
"remove",
")",
"the",
"specified",
"TARGETS",
"and",
"their",
"dependencies",
".",
"c",
"is",
"a",
"synonym",
"."
] | def do_clean(self, argv):
"""\
clean [TARGETS] Clean (remove) the specified TARGETS
and their dependencies. 'c' is a synonym.
"""
return self.do_build(['build', '--clean'] + argv[1:]) | [
"def",
"do_clean",
"(",
"self",
",",
"argv",
")",
":",
"return",
"self",
".",
"do_build",
"(",
"[",
"'build'",
",",
"'--clean'",
"]",
"+",
"argv",
"[",
"1",
":",
"]",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Script/Interactive.py#L267-L272 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | PhotoImage.blank | (self) | Display a transparent image. | Display a transparent image. | [
"Display",
"a",
"transparent",
"image",
"."
] | def blank(self):
"""Display a transparent image."""
self.tk.call(self.name, 'blank') | [
"def",
"blank",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"name",
",",
"'blank'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3307-L3309 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_osx_support.py | python | _find_appropriate_compiler | (_config_vars) | return _config_vars | Find appropriate C compiler for extension module builds | Find appropriate C compiler for extension module builds | [
"Find",
"appropriate",
"C",
"compiler",
"for",
"extension",
"module",
"builds"
] | def _find_appropriate_compiler(_config_vars):
"""Find appropriate C compiler for extension module builds"""
# Issue #13590:
# The OSX location for the compiler varies between OSX
# (or rather Xcode) releases. With older releases (up-to 10.5)
# the compiler is in /usr/bin, with newer releases the compiler
# can only be found inside Xcode.app if the "Command Line Tools"
# are not installed.
#
# Futhermore, the compiler that can be used varies between
# Xcode releases. Upto Xcode 4 it was possible to use 'gcc-4.2'
# as the compiler, after that 'clang' should be used because
# gcc-4.2 is either not present, or a copy of 'llvm-gcc' that
# miscompiles Python.
# skip checks if the compiler was overriden with a CC env variable
if 'CC' in os.environ:
return _config_vars
# The CC config var might contain additional arguments.
# Ignore them while searching.
cc = oldcc = _config_vars['CC'].split()[0]
if not _find_executable(cc):
# Compiler is not found on the shell search PATH.
# Now search for clang, first on PATH (if the Command LIne
# Tools have been installed in / or if the user has provided
# another location via CC). If not found, try using xcrun
# to find an uninstalled clang (within a selected Xcode).
# NOTE: Cannot use subprocess here because of bootstrap
# issues when building Python itself (and os.popen is
# implemented on top of subprocess and is therefore not
# usable as well)
cc = _find_build_tool('clang')
elif os.path.basename(cc).startswith('gcc'):
# Compiler is GCC, check if it is LLVM-GCC
data = _read_output("'%s' --version"
% (cc.replace("'", "'\"'\"'"),))
if 'llvm-gcc' in data:
# Found LLVM-GCC, fall back to clang
cc = _find_build_tool('clang')
if not cc:
raise SystemError(
"Cannot locate working compiler")
if cc != oldcc:
# Found a replacement compiler.
# Modify config vars using new compiler, if not already explictly
# overriden by an env variable, preserving additional arguments.
for cv in _COMPILER_CONFIG_VARS:
if cv in _config_vars and cv not in os.environ:
cv_split = _config_vars[cv].split()
cv_split[0] = cc if cv != 'CXX' else cc + '++'
_save_modified_value(_config_vars, cv, ' '.join(cv_split))
return _config_vars | [
"def",
"_find_appropriate_compiler",
"(",
"_config_vars",
")",
":",
"# Issue #13590:",
"# The OSX location for the compiler varies between OSX",
"# (or rather Xcode) releases. With older releases (up-to 10.5)",
"# the compiler is in /usr/bin, with newer releases the compiler",
"# can only be found inside Xcode.app if the \"Command Line Tools\"",
"# are not installed.",
"#",
"# Futhermore, the compiler that can be used varies between",
"# Xcode releases. Upto Xcode 4 it was possible to use 'gcc-4.2'",
"# as the compiler, after that 'clang' should be used because",
"# gcc-4.2 is either not present, or a copy of 'llvm-gcc' that",
"# miscompiles Python.",
"# skip checks if the compiler was overriden with a CC env variable",
"if",
"'CC'",
"in",
"os",
".",
"environ",
":",
"return",
"_config_vars",
"# The CC config var might contain additional arguments.",
"# Ignore them while searching.",
"cc",
"=",
"oldcc",
"=",
"_config_vars",
"[",
"'CC'",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]",
"if",
"not",
"_find_executable",
"(",
"cc",
")",
":",
"# Compiler is not found on the shell search PATH.",
"# Now search for clang, first on PATH (if the Command LIne",
"# Tools have been installed in / or if the user has provided",
"# another location via CC). If not found, try using xcrun",
"# to find an uninstalled clang (within a selected Xcode).",
"# NOTE: Cannot use subprocess here because of bootstrap",
"# issues when building Python itself (and os.popen is",
"# implemented on top of subprocess and is therefore not",
"# usable as well)",
"cc",
"=",
"_find_build_tool",
"(",
"'clang'",
")",
"elif",
"os",
".",
"path",
".",
"basename",
"(",
"cc",
")",
".",
"startswith",
"(",
"'gcc'",
")",
":",
"# Compiler is GCC, check if it is LLVM-GCC",
"data",
"=",
"_read_output",
"(",
"\"'%s' --version\"",
"%",
"(",
"cc",
".",
"replace",
"(",
"\"'\"",
",",
"\"'\\\"'\\\"'\"",
")",
",",
")",
")",
"if",
"'llvm-gcc'",
"in",
"data",
":",
"# Found LLVM-GCC, fall back to clang",
"cc",
"=",
"_find_build_tool",
"(",
"'clang'",
")",
"if",
"not",
"cc",
":",
"raise",
"SystemError",
"(",
"\"Cannot locate working compiler\"",
")",
"if",
"cc",
"!=",
"oldcc",
":",
"# Found a replacement compiler.",
"# Modify config vars using new compiler, if not already explictly",
"# overriden by an env variable, preserving additional arguments.",
"for",
"cv",
"in",
"_COMPILER_CONFIG_VARS",
":",
"if",
"cv",
"in",
"_config_vars",
"and",
"cv",
"not",
"in",
"os",
".",
"environ",
":",
"cv_split",
"=",
"_config_vars",
"[",
"cv",
"]",
".",
"split",
"(",
")",
"cv_split",
"[",
"0",
"]",
"=",
"cc",
"if",
"cv",
"!=",
"'CXX'",
"else",
"cc",
"+",
"'++'",
"_save_modified_value",
"(",
"_config_vars",
",",
"cv",
",",
"' '",
".",
"join",
"(",
"cv_split",
")",
")",
"return",
"_config_vars"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_osx_support.py#L144-L203 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/distributions/python/ops/operator_pd_vdvt_update.py | python | OperatorPDSqrtVDVTUpdate.get_shape | (self) | return self._operator.get_shape() | Static `TensorShape` of entire operator.
If this operator represents the batch matrix `A` with
`A.shape = [N1,...,Nn, k, k]`, then this returns
`TensorShape([N1,...,Nn, k, k])`
Returns:
`TensorShape`, statically determined, may be undefined. | Static `TensorShape` of entire operator. | [
"Static",
"TensorShape",
"of",
"entire",
"operator",
"."
] | def get_shape(self):
"""Static `TensorShape` of entire operator.
If this operator represents the batch matrix `A` with
`A.shape = [N1,...,Nn, k, k]`, then this returns
`TensorShape([N1,...,Nn, k, k])`
Returns:
`TensorShape`, statically determined, may be undefined.
"""
return self._operator.get_shape() | [
"def",
"get_shape",
"(",
"self",
")",
":",
"return",
"self",
".",
"_operator",
".",
"get_shape",
"(",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/operator_pd_vdvt_update.py#L279-L289 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/ndarray.py | python | modulo | (lhs, rhs) | return _ufunc_helper(
lhs,
rhs,
op.broadcast_mod,
operator.mod,
_internal._mod_scalar,
_internal._rmod_scalar) | Returns element-wise modulo of the input arrays with broadcasting.
Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.array
First array in modulo.
rhs : scalar or mxnet.ndarray.array
Second array in modulo.
The arrays to be taken modulo. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
The element-wise modulo of the input arrays.
Examples
--------
>>> x = mx.nd.ones((2,3))*6
>>> y = mx.nd.ones((2,1))*4
>>> x.asnumpy()
array([[ 6., 6., 6.],
[ 6., 6., 6.]], dtype=float32)
>>> y.asnumpy()
array([[ 4.],
[ 4.]], dtype=float32)
>>> x%5
<NDArray 2x3 @cpu(0)>
>>> (x%5).asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (x%y).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
>>> mx.nd.modulo(x,y).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32) | Returns element-wise modulo of the input arrays with broadcasting. | [
"Returns",
"element",
"-",
"wise",
"modulo",
"of",
"the",
"input",
"arrays",
"with",
"broadcasting",
"."
] | def modulo(lhs, rhs):
"""Returns element-wise modulo of the input arrays with broadcasting.
Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.array
First array in modulo.
rhs : scalar or mxnet.ndarray.array
Second array in modulo.
The arrays to be taken modulo. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
The element-wise modulo of the input arrays.
Examples
--------
>>> x = mx.nd.ones((2,3))*6
>>> y = mx.nd.ones((2,1))*4
>>> x.asnumpy()
array([[ 6., 6., 6.],
[ 6., 6., 6.]], dtype=float32)
>>> y.asnumpy()
array([[ 4.],
[ 4.]], dtype=float32)
>>> x%5
<NDArray 2x3 @cpu(0)>
>>> (x%5).asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (x%y).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
>>> mx.nd.modulo(x,y).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_mod,
operator.mod,
_internal._mod_scalar,
_internal._rmod_scalar) | [
"def",
"modulo",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"return",
"_ufunc_helper",
"(",
"lhs",
",",
"rhs",
",",
"op",
".",
"broadcast_mod",
",",
"operator",
".",
"mod",
",",
"_internal",
".",
"_mod_scalar",
",",
"_internal",
".",
"_rmod_scalar",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L3901-L3954 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Grid.grid_remove | (self) | Unmap this widget but remember the grid options. | Unmap this widget but remember the grid options. | [
"Unmap",
"this",
"widget",
"but",
"remember",
"the",
"grid",
"options",
"."
] | def grid_remove(self):
"""Unmap this widget but remember the grid options."""
self.tk.call('grid', 'remove', self._w) | [
"def",
"grid_remove",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'grid'",
",",
"'remove'",
",",
"self",
".",
"_w",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L1971-L1973 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | Argument.WriteDestinationInitalizationValidation | (self, file, func) | Writes the client side destintion initialization validation. | Writes the client side destintion initialization validation. | [
"Writes",
"the",
"client",
"side",
"destintion",
"initialization",
"validation",
"."
] | def WriteDestinationInitalizationValidation(self, file, func):
"""Writes the client side destintion initialization validation."""
pass | [
"def",
"WriteDestinationInitalizationValidation",
"(",
"self",
",",
"file",
",",
"func",
")",
":",
"pass"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5833-L5835 | ||
rampageX/firmware-mod-kit | c94cd6aeee50d92ec5280a6dba6d74828fd3606b | src/binwalk-2.1.1/src/binwalk/core/display.py | python | Display._fix_unicode | (self, line) | return bytes2str(line.encode('ascii', 'ignore')) | This is a hack, there must be a better way to handle it.
In Python3, if the environment variable LANG=C is set, indicating
that the terminal is ASCII only, but unicode characters need to be
printed to the screen or to a file (e.g., file path, magic result
format string), then an UnicodeEncodError exception will be raised.
This converts the given line to ASCII, ignoring conversion errors,
and returns a str. | This is a hack, there must be a better way to handle it.
In Python3, if the environment variable LANG=C is set, indicating
that the terminal is ASCII only, but unicode characters need to be
printed to the screen or to a file (e.g., file path, magic result
format string), then an UnicodeEncodError exception will be raised. | [
"This",
"is",
"a",
"hack",
"there",
"must",
"be",
"a",
"better",
"way",
"to",
"handle",
"it",
".",
"In",
"Python3",
"if",
"the",
"environment",
"variable",
"LANG",
"=",
"C",
"is",
"set",
"indicating",
"that",
"the",
"terminal",
"is",
"ASCII",
"only",
"but",
"unicode",
"characters",
"need",
"to",
"be",
"printed",
"to",
"the",
"screen",
"or",
"to",
"a",
"file",
"(",
"e",
".",
"g",
".",
"file",
"path",
"magic",
"result",
"format",
"string",
")",
"then",
"an",
"UnicodeEncodError",
"exception",
"will",
"be",
"raised",
"."
] | def _fix_unicode(self, line):
'''
This is a hack, there must be a better way to handle it.
In Python3, if the environment variable LANG=C is set, indicating
that the terminal is ASCII only, but unicode characters need to be
printed to the screen or to a file (e.g., file path, magic result
format string), then an UnicodeEncodError exception will be raised.
This converts the given line to ASCII, ignoring conversion errors,
and returns a str.
'''
return bytes2str(line.encode('ascii', 'ignore')) | [
"def",
"_fix_unicode",
"(",
"self",
",",
"line",
")",
":",
"return",
"bytes2str",
"(",
"line",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
")"
] | https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/core/display.py#L36-L47 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | PhysicsTools/Heppy/python/physicsobjects/Electron.py | python | Electron.edz | (self) | return self.gsfTrack().dzError() | returns the uncertainty on dxz (from gsf track) | returns the uncertainty on dxz (from gsf track) | [
"returns",
"the",
"uncertainty",
"on",
"dxz",
"(",
"from",
"gsf",
"track",
")"
] | def edz(self):
'''returns the uncertainty on dxz (from gsf track)'''
return self.gsfTrack().dzError() | [
"def",
"edz",
"(",
"self",
")",
":",
"return",
"self",
".",
"gsfTrack",
"(",
")",
".",
"dzError",
"(",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/Heppy/python/physicsobjects/Electron.py#L396-L398 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/threading.py | python | _Condition.notifyAll | (self) | Wake up all threads waiting on this condition.
If the calling thread has not acquired the lock when this method
is called, a RuntimeError is raised. | Wake up all threads waiting on this condition. | [
"Wake",
"up",
"all",
"threads",
"waiting",
"on",
"this",
"condition",
"."
] | def notifyAll(self):
"""Wake up all threads waiting on this condition.
If the calling thread has not acquired the lock when this method
is called, a RuntimeError is raised.
"""
self.notify(len(self.__waiters)) | [
"def",
"notifyAll",
"(",
"self",
")",
":",
"self",
".",
"notify",
"(",
"len",
"(",
"self",
".",
"__waiters",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/threading.py#L399-L406 | ||
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/internal/input_stream.py | python | InputStreamBuffer.ReadVarUInt32 | (self) | return i | Reads a varint from the stream, interprets this varint
as an unsigned, 32-bit integer, and returns the integer. | Reads a varint from the stream, interprets this varint
as an unsigned, 32-bit integer, and returns the integer. | [
"Reads",
"a",
"varint",
"from",
"the",
"stream",
"interprets",
"this",
"varint",
"as",
"an",
"unsigned",
"32",
"-",
"bit",
"integer",
"and",
"returns",
"the",
"integer",
"."
] | def ReadVarUInt32(self):
"""Reads a varint from the stream, interprets this varint
as an unsigned, 32-bit integer, and returns the integer.
"""
i = self.ReadVarUInt64()
if i > wire_format.UINT32_MAX:
raise message.DecodeError('Value out of range for uint32: %d' % i)
return i | [
"def",
"ReadVarUInt32",
"(",
"self",
")",
":",
"i",
"=",
"self",
".",
"ReadVarUInt64",
"(",
")",
"if",
"i",
">",
"wire_format",
".",
"UINT32_MAX",
":",
"raise",
"message",
".",
"DecodeError",
"(",
"'Value out of range for uint32: %d'",
"%",
"i",
")",
"return",
"i"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/input_stream.py#L178-L185 | |
ukoethe/vigra | 093d57d15c8c237adf1704d96daa6393158ce299 | vigranumpy/lib/arraytypes.py | python | ImagePyramid.channelIndex | (self) | return getattr(self[self._highestLevel], 'channelIndex', self.ndim) | The channel dimension of the images in this pyramid.
If the images have no axistags, or no channel axis is
specified, this defaults to 'ndim'. | The channel dimension of the images in this pyramid.
If the images have no axistags, or no channel axis is
specified, this defaults to 'ndim'. | [
"The",
"channel",
"dimension",
"of",
"the",
"images",
"in",
"this",
"pyramid",
".",
"If",
"the",
"images",
"have",
"no",
"axistags",
"or",
"no",
"channel",
"axis",
"is",
"specified",
"this",
"defaults",
"to",
"ndim",
"."
] | def channelIndex(self):
'''The channel dimension of the images in this pyramid.
If the images have no axistags, or no channel axis is
specified, this defaults to 'ndim'.
'''
return getattr(self[self._highestLevel], 'channelIndex', self.ndim) | [
"def",
"channelIndex",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
"[",
"self",
".",
"_highestLevel",
"]",
",",
"'channelIndex'",
",",
"self",
".",
"ndim",
")"
] | https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L1990-L1995 | |
mapsme/omim | 1892903b63f2c85b16ed4966d21fe76aba06b9ba | tools/python/maps_generator/checks/check.py | python | Check.check | (self) | Performs a logic of the check. | Performs a logic of the check. | [
"Performs",
"a",
"logic",
"of",
"the",
"check",
"."
] | def check(self):
"""
Performs a logic of the check.
"""
pass | [
"def",
"check",
"(",
"self",
")",
":",
"pass"
] | https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/tools/python/maps_generator/checks/check.py#L76-L80 | ||
vesoft-inc/nebula | 25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35 | .linters/cpp/cpplint.py | python | FlagCxx11Features | (filename, clean_lines, linenum, error) | Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Flag those c++11 features that we only allow in certain places. | [
"Flag",
"those",
"c",
"++",
"11",
"features",
"that",
"we",
"only",
"allow",
"in",
"certain",
"places",
"."
] | def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++ TR1 headers.
if include and include.group(1).startswith('tr1/'):
error(filename, linenum, 'build/c++tr1', 5,
('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
# Flag unapproved C++11 headers.
if include and include.group(1) in ('cfenv',
'condition_variable',
'fenv.h',
'future',
'mutex',
'thread',
'chrono',
'ratio',
'regex',
'system_error',
):
error(filename, linenum, 'build/c++11', 5,
('<%s> is an unapproved C++11 header.') % include.group(1))
# The only place where we need to worry about C++11 keywords and library
# features in preprocessor directives is in macro definitions.
if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
# These are classes and free functions. The classes are always
# mentioned as std::*, but we only catch the free functions if
# they're not found by ADL. They're alphabetical by header.
for top_name in (
# type_traits
'alignment_of',
'aligned_union',
):
if Search(r'\bstd::%s\b' % top_name, line):
error(filename, linenum, 'build/c++11', 5,
('std::%s is an unapproved C++11 class or function. Send c-style '
'an example of where it would make your code more readable, and '
'they may let you use it.') % top_name) | [
"def",
"FlagCxx11Features",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"include",
"=",
"Match",
"(",
"r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'",
",",
"line",
")",
"# Flag unapproved C++ TR1 headers.",
"if",
"include",
"and",
"include",
".",
"group",
"(",
"1",
")",
".",
"startswith",
"(",
"'tr1/'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++tr1'",
",",
"5",
",",
"(",
"'C++ TR1 headers such as <%s> are unapproved.'",
")",
"%",
"include",
".",
"group",
"(",
"1",
")",
")",
"# Flag unapproved C++11 headers.",
"if",
"include",
"and",
"include",
".",
"group",
"(",
"1",
")",
"in",
"(",
"'cfenv'",
",",
"'condition_variable'",
",",
"'fenv.h'",
",",
"'future'",
",",
"'mutex'",
",",
"'thread'",
",",
"'chrono'",
",",
"'ratio'",
",",
"'regex'",
",",
"'system_error'",
",",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++11'",
",",
"5",
",",
"(",
"'<%s> is an unapproved C++11 header.'",
")",
"%",
"include",
".",
"group",
"(",
"1",
")",
")",
"# The only place where we need to worry about C++11 keywords and library",
"# features in preprocessor directives is in macro definitions.",
"if",
"Match",
"(",
"r'\\s*#'",
",",
"line",
")",
"and",
"not",
"Match",
"(",
"r'\\s*#\\s*define\\b'",
",",
"line",
")",
":",
"return",
"# These are classes and free functions. The classes are always",
"# mentioned as std::*, but we only catch the free functions if",
"# they're not found by ADL. They're alphabetical by header.",
"for",
"top_name",
"in",
"(",
"# type_traits",
"'alignment_of'",
",",
"'aligned_union'",
",",
")",
":",
"if",
"Search",
"(",
"r'\\bstd::%s\\b'",
"%",
"top_name",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/c++11'",
",",
"5",
",",
"(",
"'std::%s is an unapproved C++11 class or function. Send c-style '",
"'an example of where it would make your code more readable, and '",
"'they may let you use it.'",
")",
"%",
"top_name",
")"
] | https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L6111-L6160 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/dist.py | python | Distribution.include | (self, **attrs) | Add items to distribution that are named in keyword arguments
For example, 'dist.include(py_modules=["x"])' would add 'x' to
the distribution's 'py_modules' attribute, if it was not already
there.
Currently, this method only supports inclusion for attributes that are
lists or tuples. If you need to add support for adding to other
attributes in this or a subclass, you can add an '_include_X' method,
where 'X' is the name of the attribute. The method will be called with
the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
will try to call 'dist._include_foo({"bar":"baz"})', which can then
handle whatever special inclusion logic is needed. | Add items to distribution that are named in keyword arguments | [
"Add",
"items",
"to",
"distribution",
"that",
"are",
"named",
"in",
"keyword",
"arguments"
] | def include(self, **attrs):
"""Add items to distribution that are named in keyword arguments
For example, 'dist.include(py_modules=["x"])' would add 'x' to
the distribution's 'py_modules' attribute, if it was not already
there.
Currently, this method only supports inclusion for attributes that are
lists or tuples. If you need to add support for adding to other
attributes in this or a subclass, you can add an '_include_X' method,
where 'X' is the name of the attribute. The method will be called with
the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
will try to call 'dist._include_foo({"bar":"baz"})', which can then
handle whatever special inclusion logic is needed.
"""
for k, v in attrs.items():
include = getattr(self, '_include_' + k, None)
if include:
include(v)
else:
self._include_misc(k, v) | [
"def",
"include",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"include",
"=",
"getattr",
"(",
"self",
",",
"'_include_'",
"+",
"k",
",",
"None",
")",
"if",
"include",
":",
"include",
"(",
"v",
")",
"else",
":",
"self",
".",
"_include_misc",
"(",
"k",
",",
"v",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/dist.py#L785-L805 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/tool/transl2tc.py | python | TranslationToTc.Setup | (self, globopt, args) | return self.rc2grd.ParseOptions(args) | Sets the instance up for use. | Sets the instance up for use. | [
"Sets",
"the",
"instance",
"up",
"for",
"use",
"."
] | def Setup(self, globopt, args):
'''Sets the instance up for use.
'''
self.SetOptions(globopt)
self.rc2grd = rc2grd.Rc2Grd()
self.rc2grd.SetOptions(globopt)
self.limits = None
if len(args) and args[0] == '-l':
self.limits = util.ReadFile(args[1], util.RAW_TEXT).split('\n')
args = args[2:]
return self.rc2grd.ParseOptions(args) | [
"def",
"Setup",
"(",
"self",
",",
"globopt",
",",
"args",
")",
":",
"self",
".",
"SetOptions",
"(",
"globopt",
")",
"self",
".",
"rc2grd",
"=",
"rc2grd",
".",
"Rc2Grd",
"(",
")",
"self",
".",
"rc2grd",
".",
"SetOptions",
"(",
"globopt",
")",
"self",
".",
"limits",
"=",
"None",
"if",
"len",
"(",
"args",
")",
"and",
"args",
"[",
"0",
"]",
"==",
"'-l'",
":",
"self",
".",
"limits",
"=",
"util",
".",
"ReadFile",
"(",
"args",
"[",
"1",
"]",
",",
"util",
".",
"RAW_TEXT",
")",
".",
"split",
"(",
"'\\n'",
")",
"args",
"=",
"args",
"[",
"2",
":",
"]",
"return",
"self",
".",
"rc2grd",
".",
"ParseOptions",
"(",
"args",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/tool/transl2tc.py#L53-L63 | |
jiaxiang-wu/quantized-cnn | 4d020e17026df90e40111d219e3eb74e0afb1588 | cpplint.py | python | CheckCStyleCast | (filename, clean_lines, linenum, cast_type, pattern, error) | return True | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
line = clean_lines.elided[linenum]
match = Search(pattern, line)
if not match:
return False
# Exclude lines with keywords that tend to look like casts
context = line[0:match.start(1) - 1]
if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
return False
# Try expanding current context to see if we one level of
# parentheses inside a macro.
if linenum > 0:
for i in xrange(linenum - 1, max(0, linenum - 5), -1):
context = clean_lines.elided[i] + context
if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
return False
# operator++(int) and operator--(int)
if context.endswith(' operator++') or context.endswith(' operator--'):
return False
# A single unnamed argument for a function tends to look like old
# style cast. If we see those, don't issue warnings for deprecated
# casts, instead issue warnings for unnamed arguments where
# appropriate.
#
# These are things that we want warnings for, since the style guide
# explicitly require all parameters to be named:
# Function(int);
# Function(int) {
# ConstMember(int) const;
# ConstMember(int) const {
# ExceptionMember(int) throw (...);
# ExceptionMember(int) throw (...) {
# PureVirtual(int) = 0;
# [](int) -> bool {
#
# These are functions of some sort, where the compiler would be fine
# if they had named parameters, but people often omit those
# identifiers to reduce clutter:
# (FunctionPointer)(int);
# (FunctionPointer)(int) = value;
# Function((function_pointer_arg)(int))
# Function((function_pointer_arg)(int), int param)
# <TemplateArgument(int)>;
# <(FunctionPointerTemplateArgument)(int)>;
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
remainder):
# Looks like an unnamed parameter.
# Don't warn on any kind of template arguments.
if Match(r'^\s*>', remainder):
return False
# Don't warn on assignments to function pointers, but keep warnings for
# unnamed parameters to pure virtual functions. Note that this pattern
# will also pass on assignments of "0" to function pointers, but the
# preferred values for those would be "nullptr" or "NULL".
matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
if matched_zero and matched_zero.group(1) != '0':
return False
# Don't warn on function pointer declarations. For this we need
# to check what came before the "(type)" string.
if Match(r'.*\)\s*$', line[0:match.start(0)]):
return False
# Don't warn if the parameter is named with block comments, e.g.:
# Function(int /*unused_param*/);
raw_line = clean_lines.raw_lines[linenum]
if '/*' in raw_line:
return False
# Passed all filters, issue warning here.
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"# Exclude lines with keywords that tend to look like casts",
"context",
"=",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
"if",
"Match",
"(",
"r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$'",
",",
"context",
")",
":",
"return",
"False",
"# Try expanding current context to see if we one level of",
"# parentheses inside a macro.",
"if",
"linenum",
">",
"0",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
"-",
"1",
",",
"max",
"(",
"0",
",",
"linenum",
"-",
"5",
")",
",",
"-",
"1",
")",
":",
"context",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"+",
"context",
"if",
"Match",
"(",
"r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$'",
",",
"context",
")",
":",
"return",
"False",
"# operator++(int) and operator--(int)",
"if",
"context",
".",
"endswith",
"(",
"' operator++'",
")",
"or",
"context",
".",
"endswith",
"(",
"' operator--'",
")",
":",
"return",
"False",
"# A single unnamed argument for a function tends to look like old",
"# style cast. If we see those, don't issue warnings for deprecated",
"# casts, instead issue warnings for unnamed arguments where",
"# appropriate.",
"#",
"# These are things that we want warnings for, since the style guide",
"# explicitly require all parameters to be named:",
"# Function(int);",
"# Function(int) {",
"# ConstMember(int) const;",
"# ConstMember(int) const {",
"# ExceptionMember(int) throw (...);",
"# ExceptionMember(int) throw (...) {",
"# PureVirtual(int) = 0;",
"# [](int) -> bool {",
"#",
"# These are functions of some sort, where the compiler would be fine",
"# if they had named parameters, but people often omit those",
"# identifiers to reduce clutter:",
"# (FunctionPointer)(int);",
"# (FunctionPointer)(int) = value;",
"# Function((function_pointer_arg)(int))",
"# Function((function_pointer_arg)(int), int param)",
"# <TemplateArgument(int)>;",
"# <(FunctionPointerTemplateArgument)(int)>;",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"0",
")",
":",
"]",
"if",
"Match",
"(",
"r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)'",
",",
"remainder",
")",
":",
"# Looks like an unnamed parameter.",
"# Don't warn on any kind of template arguments.",
"if",
"Match",
"(",
"r'^\\s*>'",
",",
"remainder",
")",
":",
"return",
"False",
"# Don't warn on assignments to function pointers, but keep warnings for",
"# unnamed parameters to pure virtual functions. Note that this pattern",
"# will also pass on assignments of \"0\" to function pointers, but the",
"# preferred values for those would be \"nullptr\" or \"NULL\".",
"matched_zero",
"=",
"Match",
"(",
"r'^\\s=\\s*(\\S+)\\s*;'",
",",
"remainder",
")",
"if",
"matched_zero",
"and",
"matched_zero",
".",
"group",
"(",
"1",
")",
"!=",
"'0'",
":",
"return",
"False",
"# Don't warn on function pointer declarations. For this we need",
"# to check what came before the \"(type)\" string.",
"if",
"Match",
"(",
"r'.*\\)\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"0",
")",
"]",
")",
":",
"return",
"False",
"# Don't warn if the parameter is named with block comments, e.g.:",
"# Function(int /*unused_param*/);",
"raw_line",
"=",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
"if",
"'/*'",
"in",
"raw_line",
":",
"return",
"False",
"# Passed all filters, issue warning here.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/function'",
",",
"3",
",",
"'All parameters should be named in a function'",
")",
"return",
"True",
"# At this point, all that should be left is actual casts.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using C-style cast. Use %s<%s>(...) instead'",
"%",
"(",
"cast_type",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"True"
] | https://github.com/jiaxiang-wu/quantized-cnn/blob/4d020e17026df90e40111d219e3eb74e0afb1588/cpplint.py#L5337-L5438 | |
vxl/vxl | f7358571ada5a4b4823fb86976d55f8d6500ce64 | contrib/brl/bseg/boxm2/pyscripts/boxm2_scene_adaptor.py | python | rewriteScenePath | (boxm2_dir, scene_file) | Rewrites a given scene XML file with a new scene_paths element
that points to its containing directory.
:param boxm2_dir: The directory containing the given scene file.
:param scene_file: Relative path from `boxm2_dir` to the given
XML file to modify. | Rewrites a given scene XML file with a new scene_paths element
that points to its containing directory. | [
"Rewrites",
"a",
"given",
"scene",
"XML",
"file",
"with",
"a",
"new",
"scene_paths",
"element",
"that",
"points",
"to",
"its",
"containing",
"directory",
"."
] | def rewriteScenePath(boxm2_dir, scene_file):
"""Rewrites a given scene XML file with a new scene_paths element
that points to its containing directory.
:param boxm2_dir: The directory containing the given scene file.
:param scene_file: Relative path from `boxm2_dir` to the given
XML file to modify.
"""
abs_name = os.path.join(boxm2_dir, scene_file)
if os.path.isfile(abs_name):
tree = ElementTree()
tree.parse(abs_name)
root = tree.getroot()
for path in root.iter('scene_paths'):
path.set('path', boxm2_dir + '/')
tree.write(abs_name) | [
"def",
"rewriteScenePath",
"(",
"boxm2_dir",
",",
"scene_file",
")",
":",
"abs_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"boxm2_dir",
",",
"scene_file",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"abs_name",
")",
":",
"tree",
"=",
"ElementTree",
"(",
")",
"tree",
".",
"parse",
"(",
"abs_name",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"for",
"path",
"in",
"root",
".",
"iter",
"(",
"'scene_paths'",
")",
":",
"path",
".",
"set",
"(",
"'path'",
",",
"boxm2_dir",
"+",
"'/'",
")",
"tree",
".",
"write",
"(",
"abs_name",
")"
] | https://github.com/vxl/vxl/blob/f7358571ada5a4b4823fb86976d55f8d6500ce64/contrib/brl/bseg/boxm2/pyscripts/boxm2_scene_adaptor.py#L842-L858 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py | python | Mailbox.iterkeys | (self) | Return an iterator over keys. | Return an iterator over keys. | [
"Return",
"an",
"iterator",
"over",
"keys",
"."
] | def iterkeys(self):
"""Return an iterator over keys."""
raise NotImplementedError('Method must be implemented by subclass') | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Method must be implemented by subclass'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py#L97-L99 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/layers/loss.py | python | npair_loss | (anchor, positive, labels, l2_reg=0.002) | return l2loss + celoss | Npair loss requires paired data. Npair loss has two parts: the first part is L2
regularizer on the embedding vector; the second part is cross entropy loss which
takes the similarity matrix of anchor and positive as logits.
For more information, please refer to:
`Improved Deep Metric Learning with Multi class N pair Loss Objective <http://www.nec-labs.com/uploads/images/Department-Images/MediaAnalytics/papers/nips16_npairmetriclearning.pdf>`_
Args:
anchor(Tensor): embedding vector for the anchor image. shape=[batch_size, embedding_dims],
the data type is float32 or float64.
positive(Tensor): embedding vector for the positive image. shape=[batch_size, embedding_dims],
the data type is float32 or float64.
labels(Tensor): 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64.
l2_reg(float32): L2 regularization term on embedding vector, default: 0.002.
Returns:
A Tensor representing the npair loss, the data type is the same as anchor, the shape is [1].
Examples:
.. code-block:: python
import paddle
DATATYPE = "float32"
anchor = paddle.rand(shape=(18, 6), dtype=DATATYPE)
positive = paddle.rand(shape=(18, 6), dtype=DATATYPE)
labels = paddle.rand(shape=(18,), dtype=DATATYPE)
npair_loss = paddle.nn.functional.npair_loss(anchor, positive, labels, l2_reg = 0.002)
print(npair_loss) | Npair loss requires paired data. Npair loss has two parts: the first part is L2
regularizer on the embedding vector; the second part is cross entropy loss which
takes the similarity matrix of anchor and positive as logits.
For more information, please refer to:
`Improved Deep Metric Learning with Multi class N pair Loss Objective <http://www.nec-labs.com/uploads/images/Department-Images/MediaAnalytics/papers/nips16_npairmetriclearning.pdf>`_
Args:
anchor(Tensor): embedding vector for the anchor image. shape=[batch_size, embedding_dims],
the data type is float32 or float64.
positive(Tensor): embedding vector for the positive image. shape=[batch_size, embedding_dims],
the data type is float32 or float64.
labels(Tensor): 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64.
l2_reg(float32): L2 regularization term on embedding vector, default: 0.002. | [
"Npair",
"loss",
"requires",
"paired",
"data",
".",
"Npair",
"loss",
"has",
"two",
"parts",
":",
"the",
"first",
"part",
"is",
"L2",
"regularizer",
"on",
"the",
"embedding",
"vector",
";",
"the",
"second",
"part",
"is",
"cross",
"entropy",
"loss",
"which",
"takes",
"the",
"similarity",
"matrix",
"of",
"anchor",
"and",
"positive",
"as",
"logits",
".",
"For",
"more",
"information",
"please",
"refer",
"to",
":",
"Improved",
"Deep",
"Metric",
"Learning",
"with",
"Multi",
"class",
"N",
"pair",
"Loss",
"Objective",
"<http",
":",
"//",
"www",
".",
"nec",
"-",
"labs",
".",
"com",
"/",
"uploads",
"/",
"images",
"/",
"Department",
"-",
"Images",
"/",
"MediaAnalytics",
"/",
"papers",
"/",
"nips16_npairmetriclearning",
".",
"pdf",
">",
"_",
"Args",
":",
"anchor",
"(",
"Tensor",
")",
":",
"embedding",
"vector",
"for",
"the",
"anchor",
"image",
".",
"shape",
"=",
"[",
"batch_size",
"embedding_dims",
"]",
"the",
"data",
"type",
"is",
"float32",
"or",
"float64",
".",
"positive",
"(",
"Tensor",
")",
":",
"embedding",
"vector",
"for",
"the",
"positive",
"image",
".",
"shape",
"=",
"[",
"batch_size",
"embedding_dims",
"]",
"the",
"data",
"type",
"is",
"float32",
"or",
"float64",
".",
"labels",
"(",
"Tensor",
")",
":",
"1",
"-",
"D",
"tensor",
".",
"shape",
"=",
"[",
"batch_size",
"]",
"the",
"data",
"type",
"is",
"float32",
"or",
"float64",
"or",
"int64",
".",
"l2_reg",
"(",
"float32",
")",
":",
"L2",
"regularization",
"term",
"on",
"embedding",
"vector",
"default",
":",
"0",
".",
"002",
"."
] | def npair_loss(anchor, positive, labels, l2_reg=0.002):
"""
Npair loss requires paired data. Npair loss has two parts: the first part is L2
regularizer on the embedding vector; the second part is cross entropy loss which
takes the similarity matrix of anchor and positive as logits.
For more information, please refer to:
`Improved Deep Metric Learning with Multi class N pair Loss Objective <http://www.nec-labs.com/uploads/images/Department-Images/MediaAnalytics/papers/nips16_npairmetriclearning.pdf>`_
Args:
anchor(Tensor): embedding vector for the anchor image. shape=[batch_size, embedding_dims],
the data type is float32 or float64.
positive(Tensor): embedding vector for the positive image. shape=[batch_size, embedding_dims],
the data type is float32 or float64.
labels(Tensor): 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64.
l2_reg(float32): L2 regularization term on embedding vector, default: 0.002.
Returns:
A Tensor representing the npair loss, the data type is the same as anchor, the shape is [1].
Examples:
.. code-block:: python
import paddle
DATATYPE = "float32"
anchor = paddle.rand(shape=(18, 6), dtype=DATATYPE)
positive = paddle.rand(shape=(18, 6), dtype=DATATYPE)
labels = paddle.rand(shape=(18,), dtype=DATATYPE)
npair_loss = paddle.nn.functional.npair_loss(anchor, positive, labels, l2_reg = 0.002)
print(npair_loss)
"""
check_variable_and_dtype(anchor, 'anchor', ['float32', 'float64'],
'npair_loss')
check_variable_and_dtype(positive, 'positive', ['float32', 'float64'],
'positive')
check_variable_and_dtype(labels, 'labels', ['float32', 'float64', 'int64'],
'labels')
Beta = 0.25
batch_size = labels.shape[0]
labels = nn.reshape(labels, shape=[batch_size, 1])
labels = paddle.tile(labels, repeat_times=[1, batch_size])
labels = equal(labels, nn.transpose(labels, perm=[1, 0])).astype('float32')
labels = labels / nn.reduce_sum(labels, dim=1, keep_dim=True)
l2loss = nn.reduce_mean(nn.reduce_sum(square(anchor), 1)) \
+ nn.reduce_mean(nn.reduce_sum(square(positive), 1))
l2loss = l2loss * Beta * l2_reg
similarity_matrix = paddle.matmul(
anchor, positive, transpose_x=False, transpose_y=True)
softmax_ce = softmax_with_cross_entropy(
logits=similarity_matrix, label=labels, soft_label=True)
cross_entropy = nn.reduce_sum(labels * softmax_ce, 0)
celoss = nn.reduce_mean(cross_entropy)
return l2loss + celoss | [
"def",
"npair_loss",
"(",
"anchor",
",",
"positive",
",",
"labels",
",",
"l2_reg",
"=",
"0.002",
")",
":",
"check_variable_and_dtype",
"(",
"anchor",
",",
"'anchor'",
",",
"[",
"'float32'",
",",
"'float64'",
"]",
",",
"'npair_loss'",
")",
"check_variable_and_dtype",
"(",
"positive",
",",
"'positive'",
",",
"[",
"'float32'",
",",
"'float64'",
"]",
",",
"'positive'",
")",
"check_variable_and_dtype",
"(",
"labels",
",",
"'labels'",
",",
"[",
"'float32'",
",",
"'float64'",
",",
"'int64'",
"]",
",",
"'labels'",
")",
"Beta",
"=",
"0.25",
"batch_size",
"=",
"labels",
".",
"shape",
"[",
"0",
"]",
"labels",
"=",
"nn",
".",
"reshape",
"(",
"labels",
",",
"shape",
"=",
"[",
"batch_size",
",",
"1",
"]",
")",
"labels",
"=",
"paddle",
".",
"tile",
"(",
"labels",
",",
"repeat_times",
"=",
"[",
"1",
",",
"batch_size",
"]",
")",
"labels",
"=",
"equal",
"(",
"labels",
",",
"nn",
".",
"transpose",
"(",
"labels",
",",
"perm",
"=",
"[",
"1",
",",
"0",
"]",
")",
")",
".",
"astype",
"(",
"'float32'",
")",
"labels",
"=",
"labels",
"/",
"nn",
".",
"reduce_sum",
"(",
"labels",
",",
"dim",
"=",
"1",
",",
"keep_dim",
"=",
"True",
")",
"l2loss",
"=",
"nn",
".",
"reduce_mean",
"(",
"nn",
".",
"reduce_sum",
"(",
"square",
"(",
"anchor",
")",
",",
"1",
")",
")",
"+",
"nn",
".",
"reduce_mean",
"(",
"nn",
".",
"reduce_sum",
"(",
"square",
"(",
"positive",
")",
",",
"1",
")",
")",
"l2loss",
"=",
"l2loss",
"*",
"Beta",
"*",
"l2_reg",
"similarity_matrix",
"=",
"paddle",
".",
"matmul",
"(",
"anchor",
",",
"positive",
",",
"transpose_x",
"=",
"False",
",",
"transpose_y",
"=",
"True",
")",
"softmax_ce",
"=",
"softmax_with_cross_entropy",
"(",
"logits",
"=",
"similarity_matrix",
",",
"label",
"=",
"labels",
",",
"soft_label",
"=",
"True",
")",
"cross_entropy",
"=",
"nn",
".",
"reduce_sum",
"(",
"labels",
"*",
"softmax_ce",
",",
"0",
")",
"celoss",
"=",
"nn",
".",
"reduce_mean",
"(",
"cross_entropy",
")",
"return",
"l2loss",
"+",
"celoss"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/loss.py#L1666-L1730 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py | python | KeyProcessor._get_matches | (self, key_presses: List[KeyPress]) | return [b for b in self._bindings.get_bindings_for_keys(keys) if b.filter()] | For a list of :class:`KeyPress` instances. Give the matching handlers
that would handle this. | For a list of :class:`KeyPress` instances. Give the matching handlers
that would handle this. | [
"For",
"a",
"list",
"of",
":",
"class",
":",
"KeyPress",
"instances",
".",
"Give",
"the",
"matching",
"handlers",
"that",
"would",
"handle",
"this",
"."
] | def _get_matches(self, key_presses: List[KeyPress]) -> List[Binding]:
"""
For a list of :class:`KeyPress` instances. Give the matching handlers
that would handle this.
"""
keys = tuple(k.key for k in key_presses)
# Try match, with mode flag
return [b for b in self._bindings.get_bindings_for_keys(keys) if b.filter()] | [
"def",
"_get_matches",
"(",
"self",
",",
"key_presses",
":",
"List",
"[",
"KeyPress",
"]",
")",
"->",
"List",
"[",
"Binding",
"]",
":",
"keys",
"=",
"tuple",
"(",
"k",
".",
"key",
"for",
"k",
"in",
"key_presses",
")",
"# Try match, with mode flag",
"return",
"[",
"b",
"for",
"b",
"in",
"self",
".",
"_bindings",
".",
"get_bindings_for_keys",
"(",
"keys",
")",
"if",
"b",
".",
"filter",
"(",
")",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py#L119-L127 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/unix_events.py | python | AbstractChildWatcher.add_child_handler | (self, pid, callback, *args) | Register a new child handler.
Arrange for callback(pid, returncode, *args) to be called when
process 'pid' terminates. Specifying another callback for the same
process replaces the previous handler.
Note: callback() must be thread-safe. | Register a new child handler. | [
"Register",
"a",
"new",
"child",
"handler",
"."
] | def add_child_handler(self, pid, callback, *args):
"""Register a new child handler.
Arrange for callback(pid, returncode, *args) to be called when
process 'pid' terminates. Specifying another callback for the same
process replaces the previous handler.
Note: callback() must be thread-safe.
"""
raise NotImplementedError() | [
"def",
"add_child_handler",
"(",
"self",
",",
"pid",
",",
"callback",
",",
"*",
"args",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/unix_events.py#L809-L818 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sgraph.py | python | _edge_list_to_sframe | (ls, src_column_name, dst_column_name) | return sf | Convert a list of edges into an SFrame. | Convert a list of edges into an SFrame. | [
"Convert",
"a",
"list",
"of",
"edges",
"into",
"an",
"SFrame",
"."
] | def _edge_list_to_sframe(ls, src_column_name, dst_column_name):
"""
Convert a list of edges into an SFrame.
"""
sf = SFrame()
if type(ls) == list:
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
sf[src_column_name] = [e.src_vid for e in ls]
sf[dst_column_name] = [e.dst_vid for e in ls]
for c in cols:
sf[c] = [e.attr.get(c) for e in ls]
elif type(ls) == Edge:
sf[src_column_name] = [ls.src_vid]
sf[dst_column_name] = [ls.dst_vid]
else:
raise TypeError('Edges type {} is Not supported.'.format(type(ls)))
return sf | [
"def",
"_edge_list_to_sframe",
"(",
"ls",
",",
"src_column_name",
",",
"dst_column_name",
")",
":",
"sf",
"=",
"SFrame",
"(",
")",
"if",
"type",
"(",
"ls",
")",
"==",
"list",
":",
"cols",
"=",
"reduce",
"(",
"set",
".",
"union",
",",
"(",
"set",
"(",
"v",
".",
"attr",
".",
"keys",
"(",
")",
")",
"for",
"v",
"in",
"ls",
")",
")",
"sf",
"[",
"src_column_name",
"]",
"=",
"[",
"e",
".",
"src_vid",
"for",
"e",
"in",
"ls",
"]",
"sf",
"[",
"dst_column_name",
"]",
"=",
"[",
"e",
".",
"dst_vid",
"for",
"e",
"in",
"ls",
"]",
"for",
"c",
"in",
"cols",
":",
"sf",
"[",
"c",
"]",
"=",
"[",
"e",
".",
"attr",
".",
"get",
"(",
"c",
")",
"for",
"e",
"in",
"ls",
"]",
"elif",
"type",
"(",
"ls",
")",
"==",
"Edge",
":",
"sf",
"[",
"src_column_name",
"]",
"=",
"[",
"ls",
".",
"src_vid",
"]",
"sf",
"[",
"dst_column_name",
"]",
"=",
"[",
"ls",
".",
"dst_vid",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"'Edges type {} is Not supported.'",
".",
"format",
"(",
"type",
"(",
"ls",
")",
")",
")",
"return",
"sf"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sgraph.py#L1404-L1424 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/Editra.py | python | Main | () | Configures and Runs an instance of Editra
@summary: Parses command line options, loads the user profile, creates
an instance of Editra and starts the main loop. | Configures and Runs an instance of Editra
@summary: Parses command line options, loads the user profile, creates
an instance of Editra and starts the main loop. | [
"Configures",
"and",
"Runs",
"an",
"instance",
"of",
"Editra",
"@summary",
":",
"Parses",
"command",
"line",
"options",
"loads",
"the",
"user",
"profile",
"creates",
"an",
"instance",
"of",
"Editra",
"and",
"starts",
"the",
"main",
"loop",
"."
] | def Main():
"""Configures and Runs an instance of Editra
@summary: Parses command line options, loads the user profile, creates
an instance of Editra and starts the main loop.
"""
opts, args = ProcessCommandLine()
if '-p' in opts:
p_file = opts['-p']
opts.pop('-p')
if not len(p_file):
# Fall back to default output file
p_file = "editra.prof"
import hotshot
prof = hotshot.Profile(p_file)
prof.runcall(_Main, opts, args)
prof.close()
else:
_Main(opts, args) | [
"def",
"Main",
"(",
")",
":",
"opts",
",",
"args",
"=",
"ProcessCommandLine",
"(",
")",
"if",
"'-p'",
"in",
"opts",
":",
"p_file",
"=",
"opts",
"[",
"'-p'",
"]",
"opts",
".",
"pop",
"(",
"'-p'",
")",
"if",
"not",
"len",
"(",
"p_file",
")",
":",
"# Fall back to default output file",
"p_file",
"=",
"\"editra.prof\"",
"import",
"hotshot",
"prof",
"=",
"hotshot",
".",
"Profile",
"(",
"p_file",
")",
"prof",
".",
"runcall",
"(",
"_Main",
",",
"opts",
",",
"args",
")",
"prof",
".",
"close",
"(",
")",
"else",
":",
"_Main",
"(",
"opts",
",",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/Editra.py#L1058-L1079 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/utils/emulator.py | python | LaunchEmulator | (avd_name, abi, kill_and_launch=True, enable_kvm=False,
sdcard_size=DEFAULT_SDCARD_SIZE,
storage_size=DEFAULT_STORAGE_SIZE, headless=False) | return emulator | Launch an existing emulator with name avd_name.
Args:
avd_name: name of existing emulator
abi: the emulator target platform
headless: running emulator with no ui
Returns:
emulator object. | Launch an existing emulator with name avd_name. | [
"Launch",
"an",
"existing",
"emulator",
"with",
"name",
"avd_name",
"."
] | def LaunchEmulator(avd_name, abi, kill_and_launch=True, enable_kvm=False,
sdcard_size=DEFAULT_SDCARD_SIZE,
storage_size=DEFAULT_STORAGE_SIZE, headless=False):
"""Launch an existing emulator with name avd_name.
Args:
avd_name: name of existing emulator
abi: the emulator target platform
headless: running emulator with no ui
Returns:
emulator object.
"""
logging.info('Specified emulator named avd_name=%s launched', avd_name)
emulator = Emulator(avd_name, abi, enable_kvm=enable_kvm,
sdcard_size=sdcard_size, storage_size=storage_size,
headless=headless)
emulator.Launch(kill_all_emulators=kill_and_launch)
emulator.ConfirmLaunch(True)
return emulator | [
"def",
"LaunchEmulator",
"(",
"avd_name",
",",
"abi",
",",
"kill_and_launch",
"=",
"True",
",",
"enable_kvm",
"=",
"False",
",",
"sdcard_size",
"=",
"DEFAULT_SDCARD_SIZE",
",",
"storage_size",
"=",
"DEFAULT_STORAGE_SIZE",
",",
"headless",
"=",
"False",
")",
":",
"logging",
".",
"info",
"(",
"'Specified emulator named avd_name=%s launched'",
",",
"avd_name",
")",
"emulator",
"=",
"Emulator",
"(",
"avd_name",
",",
"abi",
",",
"enable_kvm",
"=",
"enable_kvm",
",",
"sdcard_size",
"=",
"sdcard_size",
",",
"storage_size",
"=",
"storage_size",
",",
"headless",
"=",
"headless",
")",
"emulator",
".",
"Launch",
"(",
"kill_all_emulators",
"=",
"kill_and_launch",
")",
"emulator",
".",
"ConfirmLaunch",
"(",
"True",
")",
"return",
"emulator"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/utils/emulator.py#L227-L246 | |
NVIDIAGameWorks/kaolin | e5148d05e9c1e2ce92a07881ce3593b1c5c3f166 | kaolin/ops/batch.py | python | packed_to_padded | (packed_tensor, shape_per_tensor, first_idx, padding_value, max_shape=None) | return output | Converts a single packed tensor into a padded tensor.
Args:
packed_tensor (torch.Tensor): a :ref:`packed tensor<packed>`.
shape_per_tensor (torch.LongTensor): the :ref:`shape_per_tensor<packed_shape_per_tensor>`
tensor associated to the padded tensor.
first_idx (torch.LongTensor): :ref:`first_idx<packed_first_idx>` associated to the packed tensor.
padding_value (float): the value that will be used as padding.
max_shape (list, tuple or torch.LongTensor): list of maximum value for each dim
of the output shape (except batch and last axis), if a value is set to None
then it will be the maximum value among the tensors.
Default: All maximum values among the tensors.
Returns:
(torch.Tensor): the :ref:`padded tensor<padded>`. | Converts a single packed tensor into a padded tensor. | [
"Converts",
"a",
"single",
"packed",
"tensor",
"into",
"a",
"padded",
"tensor",
"."
] | def packed_to_padded(packed_tensor, shape_per_tensor, first_idx, padding_value, max_shape=None):
"""Converts a single packed tensor into a padded tensor.
Args:
packed_tensor (torch.Tensor): a :ref:`packed tensor<packed>`.
shape_per_tensor (torch.LongTensor): the :ref:`shape_per_tensor<packed_shape_per_tensor>`
tensor associated to the padded tensor.
first_idx (torch.LongTensor): :ref:`first_idx<packed_first_idx>` associated to the packed tensor.
padding_value (float): the value that will be used as padding.
max_shape (list, tuple or torch.LongTensor): list of maximum value for each dim
of the output shape (except batch and last axis), if a value is set to None
then it will be the maximum value among the tensors.
Default: All maximum values among the tensors.
Returns:
(torch.Tensor): the :ref:`padded tensor<padded>`.
"""
batch_size = shape_per_tensor.shape[0]
last_dim = packed_tensor.shape[1]
max_shape = fill_max_shape(shape_per_tensor, max_shape)
output = torch.full((batch_size, *max_shape, last_dim), fill_value=padding_value,
device=packed_tensor.device, dtype=packed_tensor.dtype)
for i, shape in enumerate(shape_per_tensor):
output[[i] + [slice(elem_dim) for elem_dim in shape]] = \
packed_tensor[first_idx[i]:first_idx[i + 1]].reshape(*shape, last_dim)
return output | [
"def",
"packed_to_padded",
"(",
"packed_tensor",
",",
"shape_per_tensor",
",",
"first_idx",
",",
"padding_value",
",",
"max_shape",
"=",
"None",
")",
":",
"batch_size",
"=",
"shape_per_tensor",
".",
"shape",
"[",
"0",
"]",
"last_dim",
"=",
"packed_tensor",
".",
"shape",
"[",
"1",
"]",
"max_shape",
"=",
"fill_max_shape",
"(",
"shape_per_tensor",
",",
"max_shape",
")",
"output",
"=",
"torch",
".",
"full",
"(",
"(",
"batch_size",
",",
"*",
"max_shape",
",",
"last_dim",
")",
",",
"fill_value",
"=",
"padding_value",
",",
"device",
"=",
"packed_tensor",
".",
"device",
",",
"dtype",
"=",
"packed_tensor",
".",
"dtype",
")",
"for",
"i",
",",
"shape",
"in",
"enumerate",
"(",
"shape_per_tensor",
")",
":",
"output",
"[",
"[",
"i",
"]",
"+",
"[",
"slice",
"(",
"elem_dim",
")",
"for",
"elem_dim",
"in",
"shape",
"]",
"]",
"=",
"packed_tensor",
"[",
"first_idx",
"[",
"i",
"]",
":",
"first_idx",
"[",
"i",
"+",
"1",
"]",
"]",
".",
"reshape",
"(",
"*",
"shape",
",",
"last_dim",
")",
"return",
"output"
] | https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/ops/batch.py#L332-L358 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/AutoDiff.py | python | less | (a, b) | return a < b | Compare blobs elementwise. | Compare blobs elementwise. | [
"Compare",
"blobs",
"elementwise",
"."
] | def less(a, b):
"""Compare blobs elementwise.
"""
if not type(a) is Blob and not type(b) is Blob:
raise ValueError('At least one of `a` and `b` should be neoml.Blob.')
return a < b | [
"def",
"less",
"(",
"a",
",",
"b",
")",
":",
"if",
"not",
"type",
"(",
"a",
")",
"is",
"Blob",
"and",
"not",
"type",
"(",
"b",
")",
"is",
"Blob",
":",
"raise",
"ValueError",
"(",
"'At least one of `a` and `b` should be neoml.Blob.'",
")",
"return",
"a",
"<",
"b"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/AutoDiff.py#L248-L254 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.StyleGetForeground | (*args, **kwargs) | return _stc.StyledTextCtrl_StyleGetForeground(*args, **kwargs) | StyleGetForeground(self, int style) -> Colour
Get the foreground colour of a style. | StyleGetForeground(self, int style) -> Colour | [
"StyleGetForeground",
"(",
"self",
"int",
"style",
")",
"-",
">",
"Colour"
] | def StyleGetForeground(*args, **kwargs):
"""
StyleGetForeground(self, int style) -> Colour
Get the foreground colour of a style.
"""
return _stc.StyledTextCtrl_StyleGetForeground(*args, **kwargs) | [
"def",
"StyleGetForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_StyleGetForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2586-L2592 | |
stitchEm/stitchEm | 0f399501d41ab77933677f2907f41f80ceb704d7 | lib/bindings/samples/metadata/plot_metadata.py | python | write_to_disk | (data_frame, last_written_idx, file_name) | return last_written_idx | Write the data_frame to `file_name`, or append to it if already present.
May not write anything if fewer than NUM_ROWS_BLOCK_TO_WRITE were added
to data_frame since last write.
Returns new last_written_idx. | Write the data_frame to `file_name`, or append to it if already present.
May not write anything if fewer than NUM_ROWS_BLOCK_TO_WRITE were added
to data_frame since last write.
Returns new last_written_idx. | [
"Write",
"the",
"data_frame",
"to",
"file_name",
"or",
"append",
"to",
"it",
"if",
"already",
"present",
".",
"May",
"not",
"write",
"anything",
"if",
"fewer",
"than",
"NUM_ROWS_BLOCK_TO_WRITE",
"were",
"added",
"to",
"data_frame",
"since",
"last",
"write",
".",
"Returns",
"new",
"last_written_idx",
"."
] | def write_to_disk(data_frame, last_written_idx, file_name):
"""
Write the data_frame to `file_name`, or append to it if already present.
May not write anything if fewer than NUM_ROWS_BLOCK_TO_WRITE were added
to data_frame since last write.
Returns new last_written_idx.
"""
# is there any data to write yet?
if len(data_frame.index) == 0:
return -1
if last_written_idx < 0:
data_frame.to_csv(file_name)
return data_frame.index[-1]
elif data_frame.index[-1] - NUM_ROWS_BLOCK_TO_WRITE > last_written_idx:
data_to_append = data_frame[last_written_idx + 1:]
with open(file_name, 'a') as f:
data_to_append.to_csv(f, header=False)
return data_frame.index[-1]
return last_written_idx | [
"def",
"write_to_disk",
"(",
"data_frame",
",",
"last_written_idx",
",",
"file_name",
")",
":",
"# is there any data to write yet?",
"if",
"len",
"(",
"data_frame",
".",
"index",
")",
"==",
"0",
":",
"return",
"-",
"1",
"if",
"last_written_idx",
"<",
"0",
":",
"data_frame",
".",
"to_csv",
"(",
"file_name",
")",
"return",
"data_frame",
".",
"index",
"[",
"-",
"1",
"]",
"elif",
"data_frame",
".",
"index",
"[",
"-",
"1",
"]",
"-",
"NUM_ROWS_BLOCK_TO_WRITE",
">",
"last_written_idx",
":",
"data_to_append",
"=",
"data_frame",
"[",
"last_written_idx",
"+",
"1",
":",
"]",
"with",
"open",
"(",
"file_name",
",",
"'a'",
")",
"as",
"f",
":",
"data_to_append",
".",
"to_csv",
"(",
"f",
",",
"header",
"=",
"False",
")",
"return",
"data_frame",
".",
"index",
"[",
"-",
"1",
"]",
"return",
"last_written_idx"
] | https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/metadata/plot_metadata.py#L221-L242 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/lift_to_graph.py | python | lift_to_graph | (tensors,
graph,
sources=None,
disallowed_placeholders=None,
add_sources=False,
handle_captures=False,
base_graph=None,
op_map=None) | Copies the tensor and all its inputs recursively to the outer graph.
Args:
tensors: The Tensors to lift.
graph: The graph to lift to.
sources: Optional sequence of nodes to start from. If omitted the whole
subgraph which feeds into `init_tensor` is lifted.
disallowed_placeholders: An optional set of ops which may not appear in the
lifted graph. Defaults to all placeholders.
add_sources: A boolean indicating whether placeholders which are not in
sources should be allowed.
handle_captures: A boolean indicating whether to re-capture s in the new
graph or simply create a vanilla placeholder.
base_graph: The graph from which to lift ops. This will be inferred if not
specified.
op_map: A map contains all the existing nodes that have been lifted to the
destination graph, so they won't be lifted and copied again.
Returns:
A mapping from ops in the current default graph to ops in `graph`.
Raises:
UnliftableError: If a placeholder blocks lifting. | Copies the tensor and all its inputs recursively to the outer graph. | [
"Copies",
"the",
"tensor",
"and",
"all",
"its",
"inputs",
"recursively",
"to",
"the",
"outer",
"graph",
"."
] | def lift_to_graph(tensors,
graph,
sources=None,
disallowed_placeholders=None,
add_sources=False,
handle_captures=False,
base_graph=None,
op_map=None):
"""Copies the tensor and all its inputs recursively to the outer graph.
Args:
tensors: The Tensors to lift.
graph: The graph to lift to.
sources: Optional sequence of nodes to start from. If omitted the whole
subgraph which feeds into `init_tensor` is lifted.
disallowed_placeholders: An optional set of ops which may not appear in the
lifted graph. Defaults to all placeholders.
add_sources: A boolean indicating whether placeholders which are not in
sources should be allowed.
handle_captures: A boolean indicating whether to re-capture s in the new
graph or simply create a vanilla placeholder.
base_graph: The graph from which to lift ops. This will be inferred if not
specified.
op_map: A map contains all the existing nodes that have been lifted to the
destination graph, so they won't be lifted and copied again.
Returns:
A mapping from ops in the current default graph to ops in `graph`.
Raises:
UnliftableError: If a placeholder blocks lifting.
"""
variable_init_tensors = []
init_tensors = []
for tensor in tensors:
if isinstance(tensor, resource_variable_ops.ResourceVariable):
variable_init_tensors.append(tensor)
else:
init_tensors.append(tensor)
base_graph = base_graph or init_tensors[0].graph
op_map = op_map or object_identity.ObjectIdentityDictionary()
# Check that the initializer does not depend on any placeholders.
sources = object_identity.ObjectIdentitySet(sources or [])
visited_ops = set(x.op for x in sources)
op_outputs = collections.defaultdict(set)
# First we extract the subgraph between init_tensors and sources.
for init_tensor in init_tensors:
sources.update(op_selector.map_subgraph(
init_tensor=init_tensor,
sources=sources,
disallowed_placeholders=disallowed_placeholders,
visited_ops=visited_ops,
op_outputs=op_outputs,
add_sources=add_sources))
# Try to topologically sort the nodes we've extracted. Now we know how many of
# their outputs are part of this subgraph.
ops_to_copy = []
marked_ops = set([])
ops_to_visit = [_as_operation(t) for t in init_tensors
if not op_outputs[_as_operation(t)]]
unvisited_ops = set(ops_to_visit)
while unvisited_ops:
while ops_to_visit:
op = ops_to_visit.pop()
if op in marked_ops:
continue
marked_ops.add(op)
ops_to_copy.append(op)
for inp in op_selector.graph_inputs(op):
# Don't lift the TPUReplicateMetadata nodes out of the function, because
# it has no registered kernels.
if inp.type == "TPUReplicateMetadata":
continue
unvisited_ops.add(inp)
if (all(x in marked_ops for x in op_outputs[inp]) and
inp not in sources):
ops_to_visit.append(inp)
unvisited_ops.difference_update(marked_ops)
if unvisited_ops:
# `unvisited_ops` should only have elements if the graph has a loop. In
# this case we want to keep copying and there's no topological ordering;
# we'll do ugly post-hoc mutations instead.
ops_to_visit.append(next(iter(unvisited_ops)))
# When lifting from one FuncGraph to another, we will need to capture the
# relevant tensors as well.
captures = []
inverse_captures = object_identity.ObjectIdentityDictionary()
internal_captures = []
if (isinstance(base_graph, func_graph.FuncGraph) and
isinstance(graph, func_graph.FuncGraph)):
captures = base_graph.captures
for external_capture, internal_capture in captures:
inverse_captures[internal_capture] = external_capture
internal_captures = base_graph.internal_captures
# ops_to_copy now holds a reverse topologically sorted list of ops which
# ends in the initializer. We copy those to the outermost graph and
# build the initialization op there.
with graph.as_default():
for i in variable_init_tensors:
op_map[i] = i
source_ops = set()
# Add the sources in the same order as the original graph.
for s in internal_captures:
if s in sources:
sources.remove(s)
source_ops.add(s.op)
_copy_source(
s=s,
graph=graph,
op_map=op_map,
handle_captures=handle_captures,
inverse_captures=inverse_captures,
base_graph=base_graph)
for s in sources:
source_ops.add(s.op)
_copy_source(
s=s,
graph=graph,
op_map=op_map,
handle_captures=handle_captures,
inverse_captures=inverse_captures,
base_graph=base_graph)
input_mutations = []
control_mutations = []
for op in reversed(ops_to_copy):
if op in source_ops or op in op_map:
continue
new_input_mutations, new_control_mutations = _copy_non_source(
op=op, graph=graph, op_map=op_map, base_graph=base_graph)
input_mutations.extend(new_input_mutations)
control_mutations.extend(new_control_mutations)
# Mutate the new graph to insert any loops which existed in the source
# graph due to v1 while_loops.
#
# pylint: disable=protected-access
with graph._mutation_lock():
for mutation in input_mutations:
mutation.copied_op._update_input(
mutation.input_index, op_map[mutation.old_graph_tensor])
for mutation in control_mutations:
# Don't lift the TPUReplicateMetadata nodes out of the function, because
# it has no registered kernels.
if mutation.old_graph_op.type == "TPUReplicateMetadata":
continue
mutation.copied_op._add_control_input(op_map[mutation.old_graph_op])
# pylint: enable=protected-access
return op_map | [
"def",
"lift_to_graph",
"(",
"tensors",
",",
"graph",
",",
"sources",
"=",
"None",
",",
"disallowed_placeholders",
"=",
"None",
",",
"add_sources",
"=",
"False",
",",
"handle_captures",
"=",
"False",
",",
"base_graph",
"=",
"None",
",",
"op_map",
"=",
"None",
")",
":",
"variable_init_tensors",
"=",
"[",
"]",
"init_tensors",
"=",
"[",
"]",
"for",
"tensor",
"in",
"tensors",
":",
"if",
"isinstance",
"(",
"tensor",
",",
"resource_variable_ops",
".",
"ResourceVariable",
")",
":",
"variable_init_tensors",
".",
"append",
"(",
"tensor",
")",
"else",
":",
"init_tensors",
".",
"append",
"(",
"tensor",
")",
"base_graph",
"=",
"base_graph",
"or",
"init_tensors",
"[",
"0",
"]",
".",
"graph",
"op_map",
"=",
"op_map",
"or",
"object_identity",
".",
"ObjectIdentityDictionary",
"(",
")",
"# Check that the initializer does not depend on any placeholders.",
"sources",
"=",
"object_identity",
".",
"ObjectIdentitySet",
"(",
"sources",
"or",
"[",
"]",
")",
"visited_ops",
"=",
"set",
"(",
"x",
".",
"op",
"for",
"x",
"in",
"sources",
")",
"op_outputs",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"# First we extract the subgraph between init_tensors and sources.",
"for",
"init_tensor",
"in",
"init_tensors",
":",
"sources",
".",
"update",
"(",
"op_selector",
".",
"map_subgraph",
"(",
"init_tensor",
"=",
"init_tensor",
",",
"sources",
"=",
"sources",
",",
"disallowed_placeholders",
"=",
"disallowed_placeholders",
",",
"visited_ops",
"=",
"visited_ops",
",",
"op_outputs",
"=",
"op_outputs",
",",
"add_sources",
"=",
"add_sources",
")",
")",
"# Try to topologically sort the nodes we've extracted. Now we know how many of",
"# their outputs are part of this subgraph.",
"ops_to_copy",
"=",
"[",
"]",
"marked_ops",
"=",
"set",
"(",
"[",
"]",
")",
"ops_to_visit",
"=",
"[",
"_as_operation",
"(",
"t",
")",
"for",
"t",
"in",
"init_tensors",
"if",
"not",
"op_outputs",
"[",
"_as_operation",
"(",
"t",
")",
"]",
"]",
"unvisited_ops",
"=",
"set",
"(",
"ops_to_visit",
")",
"while",
"unvisited_ops",
":",
"while",
"ops_to_visit",
":",
"op",
"=",
"ops_to_visit",
".",
"pop",
"(",
")",
"if",
"op",
"in",
"marked_ops",
":",
"continue",
"marked_ops",
".",
"add",
"(",
"op",
")",
"ops_to_copy",
".",
"append",
"(",
"op",
")",
"for",
"inp",
"in",
"op_selector",
".",
"graph_inputs",
"(",
"op",
")",
":",
"# Don't lift the TPUReplicateMetadata nodes out of the function, because",
"# it has no registered kernels.",
"if",
"inp",
".",
"type",
"==",
"\"TPUReplicateMetadata\"",
":",
"continue",
"unvisited_ops",
".",
"add",
"(",
"inp",
")",
"if",
"(",
"all",
"(",
"x",
"in",
"marked_ops",
"for",
"x",
"in",
"op_outputs",
"[",
"inp",
"]",
")",
"and",
"inp",
"not",
"in",
"sources",
")",
":",
"ops_to_visit",
".",
"append",
"(",
"inp",
")",
"unvisited_ops",
".",
"difference_update",
"(",
"marked_ops",
")",
"if",
"unvisited_ops",
":",
"# `unvisited_ops` should only have elements if the graph has a loop. In",
"# this case we want to keep copying and there's no topological ordering;",
"# we'll do ugly post-hoc mutations instead.",
"ops_to_visit",
".",
"append",
"(",
"next",
"(",
"iter",
"(",
"unvisited_ops",
")",
")",
")",
"# When lifting from one FuncGraph to another, we will need to capture the",
"# relevant tensors as well.",
"captures",
"=",
"[",
"]",
"inverse_captures",
"=",
"object_identity",
".",
"ObjectIdentityDictionary",
"(",
")",
"internal_captures",
"=",
"[",
"]",
"if",
"(",
"isinstance",
"(",
"base_graph",
",",
"func_graph",
".",
"FuncGraph",
")",
"and",
"isinstance",
"(",
"graph",
",",
"func_graph",
".",
"FuncGraph",
")",
")",
":",
"captures",
"=",
"base_graph",
".",
"captures",
"for",
"external_capture",
",",
"internal_capture",
"in",
"captures",
":",
"inverse_captures",
"[",
"internal_capture",
"]",
"=",
"external_capture",
"internal_captures",
"=",
"base_graph",
".",
"internal_captures",
"# ops_to_copy now holds a reverse topologically sorted list of ops which",
"# ends in the initializer. We copy those to the outermost graph and",
"# build the initialization op there.",
"with",
"graph",
".",
"as_default",
"(",
")",
":",
"for",
"i",
"in",
"variable_init_tensors",
":",
"op_map",
"[",
"i",
"]",
"=",
"i",
"source_ops",
"=",
"set",
"(",
")",
"# Add the sources in the same order as the original graph.",
"for",
"s",
"in",
"internal_captures",
":",
"if",
"s",
"in",
"sources",
":",
"sources",
".",
"remove",
"(",
"s",
")",
"source_ops",
".",
"add",
"(",
"s",
".",
"op",
")",
"_copy_source",
"(",
"s",
"=",
"s",
",",
"graph",
"=",
"graph",
",",
"op_map",
"=",
"op_map",
",",
"handle_captures",
"=",
"handle_captures",
",",
"inverse_captures",
"=",
"inverse_captures",
",",
"base_graph",
"=",
"base_graph",
")",
"for",
"s",
"in",
"sources",
":",
"source_ops",
".",
"add",
"(",
"s",
".",
"op",
")",
"_copy_source",
"(",
"s",
"=",
"s",
",",
"graph",
"=",
"graph",
",",
"op_map",
"=",
"op_map",
",",
"handle_captures",
"=",
"handle_captures",
",",
"inverse_captures",
"=",
"inverse_captures",
",",
"base_graph",
"=",
"base_graph",
")",
"input_mutations",
"=",
"[",
"]",
"control_mutations",
"=",
"[",
"]",
"for",
"op",
"in",
"reversed",
"(",
"ops_to_copy",
")",
":",
"if",
"op",
"in",
"source_ops",
"or",
"op",
"in",
"op_map",
":",
"continue",
"new_input_mutations",
",",
"new_control_mutations",
"=",
"_copy_non_source",
"(",
"op",
"=",
"op",
",",
"graph",
"=",
"graph",
",",
"op_map",
"=",
"op_map",
",",
"base_graph",
"=",
"base_graph",
")",
"input_mutations",
".",
"extend",
"(",
"new_input_mutations",
")",
"control_mutations",
".",
"extend",
"(",
"new_control_mutations",
")",
"# Mutate the new graph to insert any loops which existed in the source",
"# graph due to v1 while_loops.",
"#",
"# pylint: disable=protected-access",
"with",
"graph",
".",
"_mutation_lock",
"(",
")",
":",
"for",
"mutation",
"in",
"input_mutations",
":",
"mutation",
".",
"copied_op",
".",
"_update_input",
"(",
"mutation",
".",
"input_index",
",",
"op_map",
"[",
"mutation",
".",
"old_graph_tensor",
"]",
")",
"for",
"mutation",
"in",
"control_mutations",
":",
"# Don't lift the TPUReplicateMetadata nodes out of the function, because",
"# it has no registered kernels.",
"if",
"mutation",
".",
"old_graph_op",
".",
"type",
"==",
"\"TPUReplicateMetadata\"",
":",
"continue",
"mutation",
".",
"copied_op",
".",
"_add_control_input",
"(",
"op_map",
"[",
"mutation",
".",
"old_graph_op",
"]",
")",
"# pylint: enable=protected-access",
"return",
"op_map"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/lift_to_graph.py#L203-L357 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/ordered_set.py | python | OrderedSet.__iter__ | (self) | return iter(self.items) | Example:
>>> list(iter(OrderedSet([1, 2, 3])))
[1, 2, 3] | Example:
>>> list(iter(OrderedSet([1, 2, 3])))
[1, 2, 3] | [
"Example",
":",
">>>",
"list",
"(",
"iter",
"(",
"OrderedSet",
"(",
"[",
"1",
"2",
"3",
"]",
")))",
"[",
"1",
"2",
"3",
"]"
] | def __iter__(self):
"""
Example:
>>> list(iter(OrderedSet([1, 2, 3])))
[1, 2, 3]
"""
return iter(self.items) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"items",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/ordered_set.py#L259-L265 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/msvc.py | python | RegistryInfo.vs | (self) | return join(self.sxs, 'VS7') | Microsoft Visual Studio VS7 registry key.
Return
------
str
Registry key | Microsoft Visual Studio VS7 registry key. | [
"Microsoft",
"Visual",
"Studio",
"VS7",
"registry",
"key",
"."
] | def vs(self):
"""
Microsoft Visual Studio VS7 registry key.
Return
------
str
Registry key
"""
return join(self.sxs, 'VS7') | [
"def",
"vs",
"(",
"self",
")",
":",
"return",
"join",
"(",
"self",
".",
"sxs",
",",
"'VS7'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/msvc.py#L538-L547 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/dist.py | python | Distribution._set_command_options | (self, command_obj, option_dict=None) | Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If 'option_dict' is not
supplied, uses the standard option dictionary for this command
(from 'self.command_options'). | Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command'). | [
"Set",
"the",
"options",
"for",
"command_obj",
"from",
"option_dict",
".",
"Basically",
"this",
"means",
"copying",
"elements",
"of",
"a",
"dictionary",
"(",
"option_dict",
")",
"to",
"attributes",
"of",
"an",
"instance",
"(",
"command",
")",
"."
] | def _set_command_options(self, command_obj, option_dict=None):
"""Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If 'option_dict' is not
supplied, uses the standard option dictionary for this command
(from 'self.command_options').
"""
command_name = command_obj.get_command_name()
if option_dict is None:
option_dict = self.get_option_dict(command_name)
if DEBUG:
self.announce(" setting options for '%s' command:" % command_name)
for (option, (source, value)) in option_dict.items():
if DEBUG:
self.announce(" %s = %s (from %s)" % (option, value,
source))
try:
bool_opts = map(translate_longopt, command_obj.boolean_options)
except AttributeError:
bool_opts = []
try:
neg_opt = command_obj.negative_opt
except AttributeError:
neg_opt = {}
try:
is_string = isinstance(value, str)
if option in neg_opt and is_string:
setattr(command_obj, neg_opt[option], not strtobool(value))
elif option in bool_opts and is_string:
setattr(command_obj, option, strtobool(value))
elif hasattr(command_obj, option):
setattr(command_obj, option, value)
else:
raise DistutilsOptionError, \
("error in %s: command '%s' has no such option '%s'"
% (source, command_name, option))
except ValueError, msg:
raise DistutilsOptionError, msg | [
"def",
"_set_command_options",
"(",
"self",
",",
"command_obj",
",",
"option_dict",
"=",
"None",
")",
":",
"command_name",
"=",
"command_obj",
".",
"get_command_name",
"(",
")",
"if",
"option_dict",
"is",
"None",
":",
"option_dict",
"=",
"self",
".",
"get_option_dict",
"(",
"command_name",
")",
"if",
"DEBUG",
":",
"self",
".",
"announce",
"(",
"\" setting options for '%s' command:\"",
"%",
"command_name",
")",
"for",
"(",
"option",
",",
"(",
"source",
",",
"value",
")",
")",
"in",
"option_dict",
".",
"items",
"(",
")",
":",
"if",
"DEBUG",
":",
"self",
".",
"announce",
"(",
"\" %s = %s (from %s)\"",
"%",
"(",
"option",
",",
"value",
",",
"source",
")",
")",
"try",
":",
"bool_opts",
"=",
"map",
"(",
"translate_longopt",
",",
"command_obj",
".",
"boolean_options",
")",
"except",
"AttributeError",
":",
"bool_opts",
"=",
"[",
"]",
"try",
":",
"neg_opt",
"=",
"command_obj",
".",
"negative_opt",
"except",
"AttributeError",
":",
"neg_opt",
"=",
"{",
"}",
"try",
":",
"is_string",
"=",
"isinstance",
"(",
"value",
",",
"str",
")",
"if",
"option",
"in",
"neg_opt",
"and",
"is_string",
":",
"setattr",
"(",
"command_obj",
",",
"neg_opt",
"[",
"option",
"]",
",",
"not",
"strtobool",
"(",
"value",
")",
")",
"elif",
"option",
"in",
"bool_opts",
"and",
"is_string",
":",
"setattr",
"(",
"command_obj",
",",
"option",
",",
"strtobool",
"(",
"value",
")",
")",
"elif",
"hasattr",
"(",
"command_obj",
",",
"option",
")",
":",
"setattr",
"(",
"command_obj",
",",
"option",
",",
"value",
")",
"else",
":",
"raise",
"DistutilsOptionError",
",",
"(",
"\"error in %s: command '%s' has no such option '%s'\"",
"%",
"(",
"source",
",",
"command_name",
",",
"option",
")",
")",
"except",
"ValueError",
",",
"msg",
":",
"raise",
"DistutilsOptionError",
",",
"msg"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/dist.py#L860-L901 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | Context.same_quantum | (self, a, b) | return a.same_quantum(b) | Returns True if the two operands have the same exponent.
The result is never affected by either the sign or the coefficient of
either operand.
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
False
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
True
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
False
>>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
True
>>> ExtendedContext.same_quantum(10000, -1)
True
>>> ExtendedContext.same_quantum(Decimal(10000), -1)
True
>>> ExtendedContext.same_quantum(10000, Decimal(-1))
True | Returns True if the two operands have the same exponent. | [
"Returns",
"True",
"if",
"the",
"two",
"operands",
"have",
"the",
"same",
"exponent",
"."
] | def same_quantum(self, a, b):
"""Returns True if the two operands have the same exponent.
The result is never affected by either the sign or the coefficient of
either operand.
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
False
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
True
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
False
>>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
True
>>> ExtendedContext.same_quantum(10000, -1)
True
>>> ExtendedContext.same_quantum(Decimal(10000), -1)
True
>>> ExtendedContext.same_quantum(10000, Decimal(-1))
True
"""
a = _convert_other(a, raiseit=True)
return a.same_quantum(b) | [
"def",
"same_quantum",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"same_quantum",
"(",
"b",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L5388-L5410 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBStream.GetSize | (self) | return _lldb.SBStream_GetSize(self) | GetSize(self) -> size_t
If this stream is not redirected to a file, it will maintain a local
cache for the stream output whose length can be accessed using this
accessor. | GetSize(self) -> size_t | [
"GetSize",
"(",
"self",
")",
"-",
">",
"size_t"
] | def GetSize(self):
"""
GetSize(self) -> size_t
If this stream is not redirected to a file, it will maintain a local
cache for the stream output whose length can be accessed using this
accessor.
"""
return _lldb.SBStream_GetSize(self) | [
"def",
"GetSize",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBStream_GetSize",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7929-L7937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.