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
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py
python
Descriptor.CopyToProto
(self, proto)
Copies this to a descriptor_pb2.DescriptorProto. Args: proto: An empty descriptor_pb2.DescriptorProto.
Copies this to a descriptor_pb2.DescriptorProto.
[ "Copies", "this", "to", "a", "descriptor_pb2", ".", "DescriptorProto", "." ]
def CopyToProto(self, proto): """Copies this to a descriptor_pb2.DescriptorProto. Args: proto: An empty descriptor_pb2.DescriptorProto. """ # This function is overriden to give a better doc comment. super(Descriptor, self).CopyToProto(proto)
[ "def", "CopyToProto", "(", "self", ",", "proto", ")", ":", "# This function is overriden to give a better doc comment.", "super", "(", "Descriptor", ",", "self", ")", ".", "CopyToProto", "(", "proto", ")" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py#L290-L297
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/util.py
python
_modify_model_input_type_per_subgraph
(model, subgraph_index, signature_index, inference_input_type)
Modify model input type per subgraph.
Modify model input type per subgraph.
[ "Modify", "model", "input", "type", "per", "subgraph", "." ]
def _modify_model_input_type_per_subgraph(model, subgraph_index, signature_index, inference_input_type): """Modify model input type per subgraph.""" subgraph = model.subgraphs[subgraph_index] tensors = subgraph.tensors operators = subgraph.operators # Find all quantize operators quant_opcode_idxs = get_quantize_opcode_idx(model) if operators and not quant_opcode_idxs: for input_idx in subgraph.inputs: input_type = _convert_tflite_enum_type_to_tf_type(tensors[input_idx].type) if input_type == dtypes.float32: raise ValueError("Model input is not dequantized.") # None of the inputs have float32, then they must be int16, int8, or bool return # Validate that the model input is quantized input_quant_ops = [] for op in operators: # Find operators that quantize model input if op.opcodeIndex in quant_opcode_idxs and op.inputs[0] in subgraph.inputs: float_tensor, quant_tensor = tensors[op.inputs[0]], tensors[op.outputs[0]] # If found, validate that the operator's input type is float float_type = _convert_tflite_enum_type_to_tf_type(float_tensor.type) if float_type != dtypes.float32: if float_type == inference_input_type: continue else: raise ValueError( "Initial model input type must be tf.float32. Expected type for " "tensor with name '{}' is tf.float32, instead type is {}".format( float_tensor.name, get_tf_type_name(float_type))) # If found, validate that the operator output is quantized and compatible # with the final model input type quant_type = _convert_tflite_enum_type_to_tf_type(quant_tensor.type) if quant_type not in _MAP_QUANT_TO_IO_TYPES: raise ValueError( "Initial model input is not quantized. Expected type for " "tensor with name '{}' should be in {}, instead type is {}".format( quant_tensor.name, tuple(get_tf_type_name(t) for t in _MAP_QUANT_TO_IO_TYPES.keys()), get_tf_type_name(quant_type))) else: inference_io_types = _MAP_QUANT_TO_IO_TYPES[quant_type] if inference_input_type not in inference_io_types: raise ValueError( "Unsupported `inference_input_type` value. Expected to be in " "{}, instead got {}.".format( tuple(get_tf_type_name(t) for t in inference_io_types), get_tf_type_name(inference_input_type))) input_quant_ops.append(op) if len(subgraph.inputs) != len(input_quant_ops): logging.warning( "For model inputs containing unsupported operations which cannot be " "quantized, the `inference_input_type` attribute will default to the " "original type." ) # Modify model input type if inference_input_type == dtypes.uint8: # Change quant op (float to int8) to quant op (uint8 to int8) for op in input_quant_ops: int8_quantization = tensors[op.outputs[0]].quantization uint8_quantization = schema_fb.QuantizationParametersT() uint8_quantization.scale = [int8_quantization.scale[0]] uint8_quantization.zeroPoint = [int8_quantization.zeroPoint[0] + 128] tensors[op.inputs[0]].quantization = uint8_quantization tensors[op.inputs[0]].type = schema_fb.TensorType.UINT8 elif inference_input_type in _MAP_QUANT_TO_IO_TYPES: # Remove the inputs and the quant operator remove_tensors_idxs = set() for op in input_quant_ops: subgraph.inputs[subgraph.inputs == op.inputs[0]] = op.outputs[0] if signature_index >= 0: signature_def = model.signatureDefs[signature_index] for i in range(len(signature_def.inputs)): if signature_def.inputs[i].tensorIndex == op.inputs[0]: signature_def.inputs[i].tensorIndex = op.outputs[0] remove_tensors_idxs.add(op.inputs[0]) operators.remove(op) # Remove tensors marked for deletion. _remove_tensors_from_model(model, remove_tensors_idxs) else: raise ValueError( "Unsupported `inference_input_type` value {}.".format( get_tf_type_name(inference_input_type)))
[ "def", "_modify_model_input_type_per_subgraph", "(", "model", ",", "subgraph_index", ",", "signature_index", ",", "inference_input_type", ")", ":", "subgraph", "=", "model", ".", "subgraphs", "[", "subgraph_index", "]", "tensors", "=", "subgraph", ".", "tensors", "operators", "=", "subgraph", ".", "operators", "# Find all quantize operators", "quant_opcode_idxs", "=", "get_quantize_opcode_idx", "(", "model", ")", "if", "operators", "and", "not", "quant_opcode_idxs", ":", "for", "input_idx", "in", "subgraph", ".", "inputs", ":", "input_type", "=", "_convert_tflite_enum_type_to_tf_type", "(", "tensors", "[", "input_idx", "]", ".", "type", ")", "if", "input_type", "==", "dtypes", ".", "float32", ":", "raise", "ValueError", "(", "\"Model input is not dequantized.\"", ")", "# None of the inputs have float32, then they must be int16, int8, or bool", "return", "# Validate that the model input is quantized", "input_quant_ops", "=", "[", "]", "for", "op", "in", "operators", ":", "# Find operators that quantize model input", "if", "op", ".", "opcodeIndex", "in", "quant_opcode_idxs", "and", "op", ".", "inputs", "[", "0", "]", "in", "subgraph", ".", "inputs", ":", "float_tensor", ",", "quant_tensor", "=", "tensors", "[", "op", ".", "inputs", "[", "0", "]", "]", ",", "tensors", "[", "op", ".", "outputs", "[", "0", "]", "]", "# If found, validate that the operator's input type is float", "float_type", "=", "_convert_tflite_enum_type_to_tf_type", "(", "float_tensor", ".", "type", ")", "if", "float_type", "!=", "dtypes", ".", "float32", ":", "if", "float_type", "==", "inference_input_type", ":", "continue", "else", ":", "raise", "ValueError", "(", "\"Initial model input type must be tf.float32. Expected type for \"", "\"tensor with name '{}' is tf.float32, instead type is {}\"", ".", "format", "(", "float_tensor", ".", "name", ",", "get_tf_type_name", "(", "float_type", ")", ")", ")", "# If found, validate that the operator output is quantized and compatible", "# with the final model input type", "quant_type", "=", "_convert_tflite_enum_type_to_tf_type", "(", "quant_tensor", ".", "type", ")", "if", "quant_type", "not", "in", "_MAP_QUANT_TO_IO_TYPES", ":", "raise", "ValueError", "(", "\"Initial model input is not quantized. Expected type for \"", "\"tensor with name '{}' should be in {}, instead type is {}\"", ".", "format", "(", "quant_tensor", ".", "name", ",", "tuple", "(", "get_tf_type_name", "(", "t", ")", "for", "t", "in", "_MAP_QUANT_TO_IO_TYPES", ".", "keys", "(", ")", ")", ",", "get_tf_type_name", "(", "quant_type", ")", ")", ")", "else", ":", "inference_io_types", "=", "_MAP_QUANT_TO_IO_TYPES", "[", "quant_type", "]", "if", "inference_input_type", "not", "in", "inference_io_types", ":", "raise", "ValueError", "(", "\"Unsupported `inference_input_type` value. Expected to be in \"", "\"{}, instead got {}.\"", ".", "format", "(", "tuple", "(", "get_tf_type_name", "(", "t", ")", "for", "t", "in", "inference_io_types", ")", ",", "get_tf_type_name", "(", "inference_input_type", ")", ")", ")", "input_quant_ops", ".", "append", "(", "op", ")", "if", "len", "(", "subgraph", ".", "inputs", ")", "!=", "len", "(", "input_quant_ops", ")", ":", "logging", ".", "warning", "(", "\"For model inputs containing unsupported operations which cannot be \"", "\"quantized, the `inference_input_type` attribute will default to the \"", "\"original type.\"", ")", "# Modify model input type", "if", "inference_input_type", "==", "dtypes", ".", "uint8", ":", "# Change quant op (float to int8) to quant op (uint8 to int8)", "for", "op", "in", "input_quant_ops", ":", "int8_quantization", "=", "tensors", "[", "op", ".", "outputs", "[", "0", "]", "]", ".", "quantization", "uint8_quantization", "=", "schema_fb", ".", "QuantizationParametersT", "(", ")", "uint8_quantization", ".", "scale", "=", "[", "int8_quantization", ".", "scale", "[", "0", "]", "]", "uint8_quantization", ".", "zeroPoint", "=", "[", "int8_quantization", ".", "zeroPoint", "[", "0", "]", "+", "128", "]", "tensors", "[", "op", ".", "inputs", "[", "0", "]", "]", ".", "quantization", "=", "uint8_quantization", "tensors", "[", "op", ".", "inputs", "[", "0", "]", "]", ".", "type", "=", "schema_fb", ".", "TensorType", ".", "UINT8", "elif", "inference_input_type", "in", "_MAP_QUANT_TO_IO_TYPES", ":", "# Remove the inputs and the quant operator", "remove_tensors_idxs", "=", "set", "(", ")", "for", "op", "in", "input_quant_ops", ":", "subgraph", ".", "inputs", "[", "subgraph", ".", "inputs", "==", "op", ".", "inputs", "[", "0", "]", "]", "=", "op", ".", "outputs", "[", "0", "]", "if", "signature_index", ">=", "0", ":", "signature_def", "=", "model", ".", "signatureDefs", "[", "signature_index", "]", "for", "i", "in", "range", "(", "len", "(", "signature_def", ".", "inputs", ")", ")", ":", "if", "signature_def", ".", "inputs", "[", "i", "]", ".", "tensorIndex", "==", "op", ".", "inputs", "[", "0", "]", ":", "signature_def", ".", "inputs", "[", "i", "]", ".", "tensorIndex", "=", "op", ".", "outputs", "[", "0", "]", "remove_tensors_idxs", ".", "add", "(", "op", ".", "inputs", "[", "0", "]", ")", "operators", ".", "remove", "(", "op", ")", "# Remove tensors marked for deletion.", "_remove_tensors_from_model", "(", "model", ",", "remove_tensors_idxs", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported `inference_input_type` value {}.\"", ".", "format", "(", "get_tf_type_name", "(", "inference_input_type", ")", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/util.py#L661-L750
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimes.py
python
objects_to_datetime64ns
( data, dayfirst, yearfirst, utc=False, errors="raise", require_iso8601=False, allow_object=False, )
Convert data to array of timestamps. Parameters ---------- data : np.ndarray[object] dayfirst : bool yearfirst : bool utc : bool, default False Whether to convert timezone-aware timestamps to UTC. errors : {'raise', 'ignore', 'coerce'} allow_object : bool Whether to return an object-dtype ndarray instead of raising if the data contains more than one timezone. Returns ------- result : ndarray np.int64 dtype if returned values represent UTC timestamps np.datetime64[ns] if returned values represent wall times object if mixed timezones inferred_tz : tzinfo or None Raises ------ ValueError : if data cannot be converted to datetimes
Convert data to array of timestamps.
[ "Convert", "data", "to", "array", "of", "timestamps", "." ]
def objects_to_datetime64ns( data, dayfirst, yearfirst, utc=False, errors="raise", require_iso8601=False, allow_object=False, ): """ Convert data to array of timestamps. Parameters ---------- data : np.ndarray[object] dayfirst : bool yearfirst : bool utc : bool, default False Whether to convert timezone-aware timestamps to UTC. errors : {'raise', 'ignore', 'coerce'} allow_object : bool Whether to return an object-dtype ndarray instead of raising if the data contains more than one timezone. Returns ------- result : ndarray np.int64 dtype if returned values represent UTC timestamps np.datetime64[ns] if returned values represent wall times object if mixed timezones inferred_tz : tzinfo or None Raises ------ ValueError : if data cannot be converted to datetimes """ assert errors in ["raise", "ignore", "coerce"] # if str-dtype, convert data = np.array(data, copy=False, dtype=np.object_) try: result, tz_parsed = tslib.array_to_datetime( data, errors=errors, utc=utc, dayfirst=dayfirst, yearfirst=yearfirst, require_iso8601=require_iso8601, ) except ValueError as e: try: values, tz_parsed = conversion.datetime_to_datetime64(data) # If tzaware, these values represent unix timestamps, so we # return them as i8 to distinguish from wall times return values.view("i8"), tz_parsed except (ValueError, TypeError): raise e if tz_parsed is not None: # We can take a shortcut since the datetime64 numpy array # is in UTC # Return i8 values to denote unix timestamps return result.view("i8"), tz_parsed elif is_datetime64_dtype(result): # returning M8[ns] denotes wall-times; since tz is None # the distinction is a thin one return result, tz_parsed elif is_object_dtype(result): # GH#23675 when called via `pd.to_datetime`, returning an object-dtype # array is allowed. When called via `pd.DatetimeIndex`, we can # only accept datetime64 dtype, so raise TypeError if object-dtype # is returned, as that indicates the values can be recognized as # datetimes but they have conflicting timezones/awareness if allow_object: return result, tz_parsed raise TypeError(result) else: # pragma: no cover # GH#23675 this TypeError should never be hit, whereas the TypeError # in the object-dtype branch above is reachable. raise TypeError(result)
[ "def", "objects_to_datetime64ns", "(", "data", ",", "dayfirst", ",", "yearfirst", ",", "utc", "=", "False", ",", "errors", "=", "\"raise\"", ",", "require_iso8601", "=", "False", ",", "allow_object", "=", "False", ",", ")", ":", "assert", "errors", "in", "[", "\"raise\"", ",", "\"ignore\"", ",", "\"coerce\"", "]", "# if str-dtype, convert", "data", "=", "np", ".", "array", "(", "data", ",", "copy", "=", "False", ",", "dtype", "=", "np", ".", "object_", ")", "try", ":", "result", ",", "tz_parsed", "=", "tslib", ".", "array_to_datetime", "(", "data", ",", "errors", "=", "errors", ",", "utc", "=", "utc", ",", "dayfirst", "=", "dayfirst", ",", "yearfirst", "=", "yearfirst", ",", "require_iso8601", "=", "require_iso8601", ",", ")", "except", "ValueError", "as", "e", ":", "try", ":", "values", ",", "tz_parsed", "=", "conversion", ".", "datetime_to_datetime64", "(", "data", ")", "# If tzaware, these values represent unix timestamps, so we", "# return them as i8 to distinguish from wall times", "return", "values", ".", "view", "(", "\"i8\"", ")", ",", "tz_parsed", "except", "(", "ValueError", ",", "TypeError", ")", ":", "raise", "e", "if", "tz_parsed", "is", "not", "None", ":", "# We can take a shortcut since the datetime64 numpy array", "# is in UTC", "# Return i8 values to denote unix timestamps", "return", "result", ".", "view", "(", "\"i8\"", ")", ",", "tz_parsed", "elif", "is_datetime64_dtype", "(", "result", ")", ":", "# returning M8[ns] denotes wall-times; since tz is None", "# the distinction is a thin one", "return", "result", ",", "tz_parsed", "elif", "is_object_dtype", "(", "result", ")", ":", "# GH#23675 when called via `pd.to_datetime`, returning an object-dtype", "# array is allowed. When called via `pd.DatetimeIndex`, we can", "# only accept datetime64 dtype, so raise TypeError if object-dtype", "# is returned, as that indicates the values can be recognized as", "# datetimes but they have conflicting timezones/awareness", "if", "allow_object", ":", "return", "result", ",", "tz_parsed", "raise", "TypeError", "(", "result", ")", "else", ":", "# pragma: no cover", "# GH#23675 this TypeError should never be hit, whereas the TypeError", "# in the object-dtype branch above is reachable.", "raise", "TypeError", "(", "result", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimes.py#L1806-L1886
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
platforms/nuttx/NuttX/tools/kconfiglib.py
python
Choice.__str__
(self)
return self.custom_str(standard_sc_expr_str)
Returns a string representation of the choice when it is printed, matching the Kconfig format (though without the contained choice symbols). The returned string does not end in a newline. See Symbol.__str__() as well.
Returns a string representation of the choice when it is printed, matching the Kconfig format (though without the contained choice symbols).
[ "Returns", "a", "string", "representation", "of", "the", "choice", "when", "it", "is", "printed", "matching", "the", "Kconfig", "format", "(", "though", "without", "the", "contained", "choice", "symbols", ")", "." ]
def __str__(self): """ Returns a string representation of the choice when it is printed, matching the Kconfig format (though without the contained choice symbols). The returned string does not end in a newline. See Symbol.__str__() as well. """ return self.custom_str(standard_sc_expr_str)
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "custom_str", "(", "standard_sc_expr_str", ")" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/platforms/nuttx/NuttX/tools/kconfiglib.py#L4933-L4943
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/operator.py
python
contains
(a, b)
return b in a
Same as b in a (note reversed operands).
Same as b in a (note reversed operands).
[ "Same", "as", "b", "in", "a", "(", "note", "reversed", "operands", ")", "." ]
def contains(a, b): "Same as b in a (note reversed operands)." return b in a
[ "def", "contains", "(", "a", ",", "b", ")", ":", "return", "b", "in", "a" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/operator.py#L153-L155
google-coral/edgetpu
5020de9386ff370dcc1f63291a2d0f98eeb98adb
edgetpu/learn/backprop/softmax_regression.py
python
SoftmaxRegression._set_label_map
(self, label_map)
Attaches label_map with the model.
Attaches label_map with the model.
[ "Attaches", "label_map", "with", "the", "model", "." ]
def _set_label_map(self, label_map): """Attaches label_map with the model.""" self.label_map = label_map
[ "def", "_set_label_map", "(", "self", ",", "label_map", ")", ":", "self", ".", "label_map", "=", "label_map" ]
https://github.com/google-coral/edgetpu/blob/5020de9386ff370dcc1f63291a2d0f98eeb98adb/edgetpu/learn/backprop/softmax_regression.py#L220-L222
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBStringList.AppendList
(self, *args)
return _lldb.SBStringList_AppendList(self, *args)
AppendList(self, str strv, int strc) AppendList(self, SBStringList strings)
AppendList(self, str strv, int strc) AppendList(self, SBStringList strings)
[ "AppendList", "(", "self", "str", "strv", "int", "strc", ")", "AppendList", "(", "self", "SBStringList", "strings", ")" ]
def AppendList(self, *args): """ AppendList(self, str strv, int strc) AppendList(self, SBStringList strings) """ return _lldb.SBStringList_AppendList(self, *args)
[ "def", "AppendList", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBStringList_AppendList", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8004-L8009
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
bindings/pydrake/systems/planar_scenegraph_visualizer.py
python
ConnectPlanarSceneGraphVisualizer
(builder, scene_graph, output_port=None, **kwargs)
return visualizer
Creates an instance of PlanarSceneGraphVisualizer, adds it to the diagram, and wires the scene_graph pose bundle output port to the input port of the visualizer. Provides an interface comparable to DrakeVisualizer.AddToBuilder. Args: builder: The diagram builder used to construct the Diagram. scene_graph: The SceneGraph in builder containing the geometry to be visualized. output_port: (optional) If not None, then output_port will be connected to the visualizer input port instead of the scene_graph. get_query_output_port(). This is required, for instance, when the SceneGraph is inside a Diagram, and we must connect the exposed port to the visualizer instead of the original SceneGraph port. Additional kwargs are passed through to the PlanarSceneGraphVisualizer constructor. Returns: The newly created PlanarSceneGraphVisualizer object.
Creates an instance of PlanarSceneGraphVisualizer, adds it to the diagram, and wires the scene_graph pose bundle output port to the input port of the visualizer. Provides an interface comparable to DrakeVisualizer.AddToBuilder.
[ "Creates", "an", "instance", "of", "PlanarSceneGraphVisualizer", "adds", "it", "to", "the", "diagram", "and", "wires", "the", "scene_graph", "pose", "bundle", "output", "port", "to", "the", "input", "port", "of", "the", "visualizer", ".", "Provides", "an", "interface", "comparable", "to", "DrakeVisualizer", ".", "AddToBuilder", "." ]
def ConnectPlanarSceneGraphVisualizer(builder, scene_graph, output_port=None, **kwargs): """Creates an instance of PlanarSceneGraphVisualizer, adds it to the diagram, and wires the scene_graph pose bundle output port to the input port of the visualizer. Provides an interface comparable to DrakeVisualizer.AddToBuilder. Args: builder: The diagram builder used to construct the Diagram. scene_graph: The SceneGraph in builder containing the geometry to be visualized. output_port: (optional) If not None, then output_port will be connected to the visualizer input port instead of the scene_graph. get_query_output_port(). This is required, for instance, when the SceneGraph is inside a Diagram, and we must connect the exposed port to the visualizer instead of the original SceneGraph port. Additional kwargs are passed through to the PlanarSceneGraphVisualizer constructor. Returns: The newly created PlanarSceneGraphVisualizer object. """ visualizer = builder.AddSystem( PlanarSceneGraphVisualizer(scene_graph, **kwargs)) if output_port is None: output_port = scene_graph.get_query_output_port() builder.Connect(output_port, visualizer.get_geometry_query_input_port()) return visualizer
[ "def", "ConnectPlanarSceneGraphVisualizer", "(", "builder", ",", "scene_graph", ",", "output_port", "=", "None", ",", "*", "*", "kwargs", ")", ":", "visualizer", "=", "builder", ".", "AddSystem", "(", "PlanarSceneGraphVisualizer", "(", "scene_graph", ",", "*", "*", "kwargs", ")", ")", "if", "output_port", "is", "None", ":", "output_port", "=", "scene_graph", ".", "get_query_output_port", "(", ")", "builder", ".", "Connect", "(", "output_port", ",", "visualizer", ".", "get_geometry_query_input_port", "(", ")", ")", "return", "visualizer" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/bindings/pydrake/systems/planar_scenegraph_visualizer.py#L407-L440
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
TopLevelWindow.IsActive
(*args, **kwargs)
return _windows_.TopLevelWindow_IsActive(*args, **kwargs)
IsActive(self) -> bool
IsActive(self) -> bool
[ "IsActive", "(", "self", ")", "-", ">", "bool" ]
def IsActive(*args, **kwargs): """IsActive(self) -> bool""" return _windows_.TopLevelWindow_IsActive(*args, **kwargs)
[ "def", "IsActive", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_IsActive", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L473-L475
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/help.py
python
copy_strip
()
Copy idle.html to idlelib/help.html, stripping trailing whitespace. Files with trailing whitespace cannot be pushed to the git cpython repository. For 3.x (on Windows), help.html is generated, after editing idle.rst on the master branch, with sphinx-build -bhtml . build/html python_d.exe -c "from idlelib.help import copy_strip; copy_strip()" Check build/html/library/idle.html, the help.html diff, and the text displayed by Help => IDLE Help. Add a blurb and create a PR. It can be worthwhile to occasionally generate help.html without touching idle.rst. Changes to the master version and to the doc build system may result in changes that should not changed the displayed text, but might break HelpParser. As long as master and maintenance versions of idle.rst remain the same, help.html can be backported. The internal Python version number is not displayed. If maintenance idle.rst diverges from the master version, then instead of backporting help.html from master, repeat the procedure above to generate a maintenance version.
Copy idle.html to idlelib/help.html, stripping trailing whitespace.
[ "Copy", "idle", ".", "html", "to", "idlelib", "/", "help", ".", "html", "stripping", "trailing", "whitespace", "." ]
def copy_strip(): """Copy idle.html to idlelib/help.html, stripping trailing whitespace. Files with trailing whitespace cannot be pushed to the git cpython repository. For 3.x (on Windows), help.html is generated, after editing idle.rst on the master branch, with sphinx-build -bhtml . build/html python_d.exe -c "from idlelib.help import copy_strip; copy_strip()" Check build/html/library/idle.html, the help.html diff, and the text displayed by Help => IDLE Help. Add a blurb and create a PR. It can be worthwhile to occasionally generate help.html without touching idle.rst. Changes to the master version and to the doc build system may result in changes that should not changed the displayed text, but might break HelpParser. As long as master and maintenance versions of idle.rst remain the same, help.html can be backported. The internal Python version number is not displayed. If maintenance idle.rst diverges from the master version, then instead of backporting help.html from master, repeat the procedure above to generate a maintenance version. """ src = join(abspath(dirname(dirname(dirname(__file__)))), 'Doc', 'build', 'html', 'library', 'idle.html') dst = join(abspath(dirname(__file__)), 'help.html') with open(src, 'rb') as inn,\ open(dst, 'wb') as out: for line in inn: out.write(line.rstrip() + b'\n') print(f'{src} copied to {dst}')
[ "def", "copy_strip", "(", ")", ":", "src", "=", "join", "(", "abspath", "(", "dirname", "(", "dirname", "(", "dirname", "(", "__file__", ")", ")", ")", ")", ",", "'Doc'", ",", "'build'", ",", "'html'", ",", "'library'", ",", "'idle.html'", ")", "dst", "=", "join", "(", "abspath", "(", "dirname", "(", "__file__", ")", ")", ",", "'help.html'", ")", "with", "open", "(", "src", ",", "'rb'", ")", "as", "inn", ",", "open", "(", "dst", ",", "'wb'", ")", "as", "out", ":", "for", "line", "in", "inn", ":", "out", ".", "write", "(", "line", ".", "rstrip", "(", ")", "+", "b'\\n'", ")", "print", "(", "f'{src} copied to {dst}'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/help.py#L247-L277
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Sizer.FitInside
(*args, **kwargs)
return _core_.Sizer_FitInside(*args, **kwargs)
FitInside(self, Window window) Tell the sizer to resize the *virtual size* of the *window* to match the sizer's minimal size. This will not alter the on screen size of the window, but may cause the addition/removal/alteration of scrollbars required to view the virtual area in windows which manage it. :see: `wx.ScrolledWindow.SetScrollbars`
FitInside(self, Window window)
[ "FitInside", "(", "self", "Window", "window", ")" ]
def FitInside(*args, **kwargs): """ FitInside(self, Window window) Tell the sizer to resize the *virtual size* of the *window* to match the sizer's minimal size. This will not alter the on screen size of the window, but may cause the addition/removal/alteration of scrollbars required to view the virtual area in windows which manage it. :see: `wx.ScrolledWindow.SetScrollbars` """ return _core_.Sizer_FitInside(*args, **kwargs)
[ "def", "FitInside", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Sizer_FitInside", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14889-L14901
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ftplib.py
python
FTP.dir
(self, *args)
List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)
List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)
[ "List", "a", "directory", "in", "long", "form", ".", "By", "default", "list", "current", "directory", "to", "stdout", ".", "Optional", "last", "argument", "is", "callback", "function", ";", "all", "non", "-", "empty", "arguments", "before", "it", "are", "concatenated", "to", "the", "LIST", "command", ".", "(", "This", "*", "should", "*", "only", "be", "used", "for", "a", "pathname", ".", ")" ]
def dir(self, *args): '''List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)''' cmd = 'LIST' func = None if args[-1:] and type(args[-1]) != type(''): args, func = args[:-1], args[-1] for arg in args: if arg: cmd = cmd + (' ' + arg) self.retrlines(cmd, func)
[ "def", "dir", "(", "self", ",", "*", "args", ")", ":", "cmd", "=", "'LIST'", "func", "=", "None", "if", "args", "[", "-", "1", ":", "]", "and", "type", "(", "args", "[", "-", "1", "]", ")", "!=", "type", "(", "''", ")", ":", "args", ",", "func", "=", "args", "[", ":", "-", "1", "]", ",", "args", "[", "-", "1", "]", "for", "arg", "in", "args", ":", "if", "arg", ":", "cmd", "=", "cmd", "+", "(", "' '", "+", "arg", ")", "self", ".", "retrlines", "(", "cmd", ",", "func", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ftplib.py#L556-L569
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/preprocessing/text.py
python
VocabularyProcessor.restore
(cls, filename)
Restores vocabulary processor from given file. Args: filename: Path to file to load from. Returns: VocabularyProcessor object.
Restores vocabulary processor from given file.
[ "Restores", "vocabulary", "processor", "from", "given", "file", "." ]
def restore(cls, filename): """Restores vocabulary processor from given file. Args: filename: Path to file to load from. Returns: VocabularyProcessor object. """ with gfile.Open(filename, 'rb') as f: return pickle.loads(f.read())
[ "def", "restore", "(", "cls", ",", "filename", ")", ":", "with", "gfile", ".", "Open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "return", "pickle", ".", "loads", "(", "f", ".", "read", "(", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/preprocessing/text.py#L236-L246
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/ttk.py
python
OptionMenu.set_menu
(self, default=None, *values)
Build a new menu of radiobuttons with *values and optionally a default value.
Build a new menu of radiobuttons with *values and optionally a default value.
[ "Build", "a", "new", "menu", "of", "radiobuttons", "with", "*", "values", "and", "optionally", "a", "default", "value", "." ]
def set_menu(self, default=None, *values): """Build a new menu of radiobuttons with *values and optionally a default value.""" menu = self['menu'] menu.delete(0, 'end') for val in values: menu.add_radiobutton(label=val, command=Tkinter._setit(self._variable, val, self._callback), variable=self._variable) if default: self._variable.set(default)
[ "def", "set_menu", "(", "self", ",", "default", "=", "None", ",", "*", "values", ")", ":", "menu", "=", "self", "[", "'menu'", "]", "menu", ".", "delete", "(", "0", ",", "'end'", ")", "for", "val", "in", "values", ":", "menu", ".", "add_radiobutton", "(", "label", "=", "val", ",", "command", "=", "Tkinter", ".", "_setit", "(", "self", ".", "_variable", ",", "val", ",", "self", ".", "_callback", ")", ",", "variable", "=", "self", ".", "_variable", ")", "if", "default", ":", "self", ".", "_variable", ".", "set", "(", "default", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L1610-L1621
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/doc/pattern_tools/svgfig.py
python
pathtoPath
(svg)
return Path(d, **attr)
Converts SVG("path", d="...") into Path(d=[...]).
Converts SVG("path", d="...") into Path(d=[...]).
[ "Converts", "SVG", "(", "path", "d", "=", "...", ")", "into", "Path", "(", "d", "=", "[", "...", "]", ")", "." ]
def pathtoPath(svg): """Converts SVG("path", d="...") into Path(d=[...]).""" if not isinstance(svg, SVG) or svg.t != "path": raise TypeError, "Only SVG <path /> objects can be converted into Paths" attr = dict(svg.attr) d = attr["d"] del attr["d"] for key in attr.keys(): if not isinstance(key, str): value = attr[key] del attr[key] attr[str(key)] = value return Path(d, **attr)
[ "def", "pathtoPath", "(", "svg", ")", ":", "if", "not", "isinstance", "(", "svg", ",", "SVG", ")", "or", "svg", ".", "t", "!=", "\"path\"", ":", "raise", "TypeError", ",", "\"Only SVG <path /> objects can be converted into Paths\"", "attr", "=", "dict", "(", "svg", ".", "attr", ")", "d", "=", "attr", "[", "\"d\"", "]", "del", "attr", "[", "\"d\"", "]", "for", "key", "in", "attr", ".", "keys", "(", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", ":", "value", "=", "attr", "[", "key", "]", "del", "attr", "[", "key", "]", "attr", "[", "str", "(", "key", ")", "]", "=", "value", "return", "Path", "(", "d", ",", "*", "*", "attr", ")" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/doc/pattern_tools/svgfig.py#L1101-L1113
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_collections_abc.py
python
Mapping.values
(self)
return ValuesView(self)
D.values() -> an object providing a view on D's values
D.values() -> an object providing a view on D's values
[ "D", ".", "values", "()", "-", ">", "an", "object", "providing", "a", "view", "on", "D", "s", "values" ]
def values(self): "D.values() -> an object providing a view on D's values" return ValuesView(self)
[ "def", "values", "(", "self", ")", ":", "return", "ValuesView", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_collections_abc.py#L680-L682
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
FontMapper_GetEncoding
(*args, **kwargs)
return _gdi_.FontMapper_GetEncoding(*args, **kwargs)
FontMapper_GetEncoding(size_t n) -> int
FontMapper_GetEncoding(size_t n) -> int
[ "FontMapper_GetEncoding", "(", "size_t", "n", ")", "-", ">", "int" ]
def FontMapper_GetEncoding(*args, **kwargs): """FontMapper_GetEncoding(size_t n) -> int""" return _gdi_.FontMapper_GetEncoding(*args, **kwargs)
[ "def", "FontMapper_GetEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "FontMapper_GetEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2185-L2187
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py
python
PhactoriCSVExportOperation.ExportOperationData
(self, datadescription)
overrides parent class method in order to output .vtm or .vtp\n (vtkMultiBlockData or vtkPolyData) files
overrides parent class method in order to output .vtm or .vtp\n (vtkMultiBlockData or vtkPolyData) files
[ "overrides", "parent", "class", "method", "in", "order", "to", "output", ".", "vtm", "or", ".", "vtp", "\\", "n", "(", "vtkMultiBlockData", "or", "vtkPolyData", ")", "files" ]
def ExportOperationData(self, datadescription): "overrides parent class method in order to output .vtm or .vtp\n (vtkMultiBlockData or vtkPolyData) files" if PhactoriDbg(100): myDebugPrint3("PhactoriCSVExportOperation." \ "ExportOperationData entered\n", 100) self.mFilterToWriteDataFrom.UpdatePipeline() outfilenames = self.CreateCurrentCallbackOutputFilename() if PhactoriDbg(100): myDebugPrint3("outfilenames: " + str(outfilenames) + "\n") if self.mCsvCellWriter == None: self.mCsvCellWriter = CSVWriter(Input=self.mFilterToWriteDataFrom, Precision=self.Precision, FieldAssociation="Cell Data") if self.mCsvPointWriter == None: self.mCsvPointWriter = CSVWriter(Input=self.mFilterToWriteDataFrom, Precision=self.Precision, FieldAssociation="Point Data") if self.mCsvCellWriter != None: self.mCsvCellWriter.FileName = outfilenames[0] UpdatePipelineWithCurrentTimeArgument(self.mCsvCellWriter) if self.mCsvPointWriter != None: self.mCsvPointWriter.FileName = outfilenames[1] UpdatePipelineWithCurrentTimeArgument(self.mCsvPointWriter) if PhactoriDbg(100): myDebugPrint3("PhactoriCSVExportOperation." \ "ExportOperationData returning\n", 100)
[ "def", "ExportOperationData", "(", "self", ",", "datadescription", ")", ":", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "\"PhactoriCSVExportOperation.\"", "\"ExportOperationData entered\\n\"", ",", "100", ")", "self", ".", "mFilterToWriteDataFrom", ".", "UpdatePipeline", "(", ")", "outfilenames", "=", "self", ".", "CreateCurrentCallbackOutputFilename", "(", ")", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "\"outfilenames: \"", "+", "str", "(", "outfilenames", ")", "+", "\"\\n\"", ")", "if", "self", ".", "mCsvCellWriter", "==", "None", ":", "self", ".", "mCsvCellWriter", "=", "CSVWriter", "(", "Input", "=", "self", ".", "mFilterToWriteDataFrom", ",", "Precision", "=", "self", ".", "Precision", ",", "FieldAssociation", "=", "\"Cell Data\"", ")", "if", "self", ".", "mCsvPointWriter", "==", "None", ":", "self", ".", "mCsvPointWriter", "=", "CSVWriter", "(", "Input", "=", "self", ".", "mFilterToWriteDataFrom", ",", "Precision", "=", "self", ".", "Precision", ",", "FieldAssociation", "=", "\"Point Data\"", ")", "if", "self", ".", "mCsvCellWriter", "!=", "None", ":", "self", ".", "mCsvCellWriter", ".", "FileName", "=", "outfilenames", "[", "0", "]", "UpdatePipelineWithCurrentTimeArgument", "(", "self", ".", "mCsvCellWriter", ")", "if", "self", ".", "mCsvPointWriter", "!=", "None", ":", "self", ".", "mCsvPointWriter", ".", "FileName", "=", "outfilenames", "[", "1", "]", "UpdatePipelineWithCurrentTimeArgument", "(", "self", ".", "mCsvPointWriter", ")", "if", "PhactoriDbg", "(", "100", ")", ":", "myDebugPrint3", "(", "\"PhactoriCSVExportOperation.\"", "\"ExportOperationData returning\\n\"", ",", "100", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L8993-L9021
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/lib/type_check.py
python
nan_to_num
(x, copy=True, nan=0.0, posinf=None, neginf=None)
return x[()] if isscalar else x
Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the `nan`, `posinf` and/or `neginf` keywords. If `x` is inexact, NaN is replaced by zero or by the user defined value in `nan` keyword, infinity is replaced by the largest finite floating point values representable by ``x.dtype`` or by the user defined value in `posinf` keyword and -infinity is replaced by the most negative finite floating point values representable by ``x.dtype`` or by the user defined value in `neginf` keyword. For complex dtypes, the above is applied to each of the real and imaginary components of `x` separately. If `x` is not inexact, then no replacements are made. Parameters ---------- x : scalar or array_like Input data. copy : bool, optional Whether to create a copy of `x` (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True. .. versionadded:: 1.13 nan : int, float, optional Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0. .. versionadded:: 1.17 posinf : int, float, optional Value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a very large number. .. versionadded:: 1.17 neginf : int, float, optional Value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number. .. versionadded:: 1.17 Returns ------- out : ndarray `x`, with the non-finite values replaced. If `copy` is False, this may be `x` itself. See Also -------- isinf : Shows which elements are positive or negative infinity. isneginf : Shows which elements are negative infinity. isposinf : Shows which elements are positive infinity. isnan : Shows which elements are Not a Number (NaN). isfinite : Shows which elements are finite (not NaN, not infinity) Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- >>> np.nan_to_num(np.inf) 1.7976931348623157e+308 >>> np.nan_to_num(-np.inf) -1.7976931348623157e+308 >>> np.nan_to_num(np.nan) 0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, 1.2800000e+02]) >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(y) array([ 1.79769313e+308 +0.00000000e+000j, # may vary 0.00000000e+000 +0.00000000e+000j, 0.00000000e+000 +1.79769313e+308j]) >>> np.nan_to_num(y, nan=111111, posinf=222222) array([222222.+111111.j, 111111. +0.j, 111111.+222222.j])
Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the `nan`, `posinf` and/or `neginf` keywords.
[ "Replace", "NaN", "with", "zero", "and", "infinity", "with", "large", "finite", "numbers", "(", "default", "behaviour", ")", "or", "with", "the", "numbers", "defined", "by", "the", "user", "using", "the", "nan", "posinf", "and", "/", "or", "neginf", "keywords", "." ]
def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None): """ Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the `nan`, `posinf` and/or `neginf` keywords. If `x` is inexact, NaN is replaced by zero or by the user defined value in `nan` keyword, infinity is replaced by the largest finite floating point values representable by ``x.dtype`` or by the user defined value in `posinf` keyword and -infinity is replaced by the most negative finite floating point values representable by ``x.dtype`` or by the user defined value in `neginf` keyword. For complex dtypes, the above is applied to each of the real and imaginary components of `x` separately. If `x` is not inexact, then no replacements are made. Parameters ---------- x : scalar or array_like Input data. copy : bool, optional Whether to create a copy of `x` (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True. .. versionadded:: 1.13 nan : int, float, optional Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0. .. versionadded:: 1.17 posinf : int, float, optional Value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a very large number. .. versionadded:: 1.17 neginf : int, float, optional Value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number. .. versionadded:: 1.17 Returns ------- out : ndarray `x`, with the non-finite values replaced. If `copy` is False, this may be `x` itself. See Also -------- isinf : Shows which elements are positive or negative infinity. isneginf : Shows which elements are negative infinity. isposinf : Shows which elements are positive infinity. isnan : Shows which elements are Not a Number (NaN). isfinite : Shows which elements are finite (not NaN, not infinity) Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- >>> np.nan_to_num(np.inf) 1.7976931348623157e+308 >>> np.nan_to_num(-np.inf) -1.7976931348623157e+308 >>> np.nan_to_num(np.nan) 0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, 1.2800000e+02]) >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(y) array([ 1.79769313e+308 +0.00000000e+000j, # may vary 0.00000000e+000 +0.00000000e+000j, 0.00000000e+000 +1.79769313e+308j]) >>> np.nan_to_num(y, nan=111111, posinf=222222) array([222222.+111111.j, 111111. +0.j, 111111.+222222.j]) """ x = _nx.array(x, subok=True, copy=copy) xtype = x.dtype.type isscalar = (x.ndim == 0) if not issubclass(xtype, _nx.inexact): return x[()] if isscalar else x iscomplex = issubclass(xtype, _nx.complexfloating) dest = (x.real, x.imag) if iscomplex else (x,) maxf, minf = _getmaxmin(x.real.dtype) if posinf is not None: maxf = posinf if neginf is not None: minf = neginf for d in dest: idx_nan = isnan(d) idx_posinf = isposinf(d) idx_neginf = isneginf(d) _nx.copyto(d, nan, where=idx_nan) _nx.copyto(d, maxf, where=idx_posinf) _nx.copyto(d, minf, where=idx_neginf) return x[()] if isscalar else x
[ "def", "nan_to_num", "(", "x", ",", "copy", "=", "True", ",", "nan", "=", "0.0", ",", "posinf", "=", "None", ",", "neginf", "=", "None", ")", ":", "x", "=", "_nx", ".", "array", "(", "x", ",", "subok", "=", "True", ",", "copy", "=", "copy", ")", "xtype", "=", "x", ".", "dtype", ".", "type", "isscalar", "=", "(", "x", ".", "ndim", "==", "0", ")", "if", "not", "issubclass", "(", "xtype", ",", "_nx", ".", "inexact", ")", ":", "return", "x", "[", "(", ")", "]", "if", "isscalar", "else", "x", "iscomplex", "=", "issubclass", "(", "xtype", ",", "_nx", ".", "complexfloating", ")", "dest", "=", "(", "x", ".", "real", ",", "x", ".", "imag", ")", "if", "iscomplex", "else", "(", "x", ",", ")", "maxf", ",", "minf", "=", "_getmaxmin", "(", "x", ".", "real", ".", "dtype", ")", "if", "posinf", "is", "not", "None", ":", "maxf", "=", "posinf", "if", "neginf", "is", "not", "None", ":", "minf", "=", "neginf", "for", "d", "in", "dest", ":", "idx_nan", "=", "isnan", "(", "d", ")", "idx_posinf", "=", "isposinf", "(", "d", ")", "idx_neginf", "=", "isneginf", "(", "d", ")", "_nx", ".", "copyto", "(", "d", ",", "nan", ",", "where", "=", "idx_nan", ")", "_nx", ".", "copyto", "(", "d", ",", "maxf", ",", "where", "=", "idx_posinf", ")", "_nx", ".", "copyto", "(", "d", ",", "minf", ",", "where", "=", "idx_neginf", ")", "return", "x", "[", "(", ")", "]", "if", "isscalar", "else", "x" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/type_check.py#L405-L521
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py
python
getsource
(object)
return ''.join(lines)
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An OSError is raised if the source code cannot be retrieved.
Return the text of the source code for an object.
[ "Return", "the", "text", "of", "the", "source", "code", "for", "an", "object", "." ]
def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An OSError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return ''.join(lines)
[ "def", "getsource", "(", "object", ")", ":", "lines", ",", "lnum", "=", "getsourcelines", "(", "object", ")", "return", "''", ".", "join", "(", "lines", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py#L967-L974
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/PythonAnalysis/python/rootplot/utilities.py
python
rootglob
(tdirectory, pathname)
return list(irootglob(tdirectory, pathname))
Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. >>> import rootplot.utilities >>> f = rootplot.utilities.testfile() >>> rootglob(f, '*') ['dir1', 'dir2', 'dir3', 'dir4'] >>> rootglob(f, 'dir1/*') ['dir1/hist1', 'dir1/hist2', 'dir1/hist3', 'dir1/hist4'] >>> rootglob(f, '*/hist1') ['dir1/hist1', 'dir2/hist1', 'dir3/hist1', 'dir4/hist1'] >>> rootglob(f, 'dir1/hist[1-2]') ['dir1/hist1', 'dir1/hist2']
Return a list of paths matching a pathname pattern.
[ "Return", "a", "list", "of", "paths", "matching", "a", "pathname", "pattern", "." ]
def rootglob(tdirectory, pathname): """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. >>> import rootplot.utilities >>> f = rootplot.utilities.testfile() >>> rootglob(f, '*') ['dir1', 'dir2', 'dir3', 'dir4'] >>> rootglob(f, 'dir1/*') ['dir1/hist1', 'dir1/hist2', 'dir1/hist3', 'dir1/hist4'] >>> rootglob(f, '*/hist1') ['dir1/hist1', 'dir2/hist1', 'dir3/hist1', 'dir4/hist1'] >>> rootglob(f, 'dir1/hist[1-2]') ['dir1/hist1', 'dir1/hist2'] """ return list(irootglob(tdirectory, pathname))
[ "def", "rootglob", "(", "tdirectory", ",", "pathname", ")", ":", "return", "list", "(", "irootglob", "(", "tdirectory", ",", "pathname", ")", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/PythonAnalysis/python/rootplot/utilities.py#L559-L575
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/tvm/intrin.py
python
_rule_float_direct
(op)
return None
Intrinsic rule: Directly call pure extern function for floats. This is an example intrinsic generation rule. Parameters ---------- op : Expr The call expression of original intrinsic. Returns ------- ret : Expr The translated intrinsic rule. Return same op if no translation is possible. See Also -------- register_intrin_rule : The registeration function for intrin rule.
Intrinsic rule: Directly call pure extern function for floats.
[ "Intrinsic", "rule", ":", "Directly", "call", "pure", "extern", "function", "for", "floats", "." ]
def _rule_float_direct(op): """Intrinsic rule: Directly call pure extern function for floats. This is an example intrinsic generation rule. Parameters ---------- op : Expr The call expression of original intrinsic. Returns ------- ret : Expr The translated intrinsic rule. Return same op if no translation is possible. See Also -------- register_intrin_rule : The registeration function for intrin rule. """ if str(op.dtype).startswith("float"): return call_pure_extern(op.dtype, op.name, *op.args) return None
[ "def", "_rule_float_direct", "(", "op", ")", ":", "if", "str", "(", "op", ".", "dtype", ")", ".", "startswith", "(", "\"float\"", ")", ":", "return", "call_pure_extern", "(", "op", ".", "dtype", ",", "op", ".", "name", ",", "*", "op", ".", "args", ")", "return", "None" ]
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/intrin.py#L387-L409
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
StatusBar.GetFields
(self)
return [self.GetStatusText(i) for i in range(self.GetFieldsCount())]
Return a list of field values in the status bar.
Return a list of field values in the status bar.
[ "Return", "a", "list", "of", "field", "values", "in", "the", "status", "bar", "." ]
def GetFields(self): """Return a list of field values in the status bar. """ return [self.GetStatusText(i) for i in range(self.GetFieldsCount())]
[ "def", "GetFields", "(", "self", ")", ":", "return", "[", "self", ".", "GetStatusText", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "GetFieldsCount", "(", ")", ")", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L1321-L1323
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozboot/mozboot/osx.py
python
OSXBootstrapper.ensure_package_manager
(self)
return active_name.lower()
Search package mgr in sys.path, if none is found, prompt the user to install one. If only one is found, use that one. If both are found, prompt the user to choose one.
Search package mgr in sys.path, if none is found, prompt the user to install one. If only one is found, use that one. If both are found, prompt the user to choose one.
[ "Search", "package", "mgr", "in", "sys", ".", "path", "if", "none", "is", "found", "prompt", "the", "user", "to", "install", "one", ".", "If", "only", "one", "is", "found", "use", "that", "one", ".", "If", "both", "are", "found", "prompt", "the", "user", "to", "choose", "one", "." ]
def ensure_package_manager(self): ''' Search package mgr in sys.path, if none is found, prompt the user to install one. If only one is found, use that one. If both are found, prompt the user to choose one. ''' installed = [] for name, cmd in PACKAGE_MANAGER.iteritems(): if self.which(cmd) is not None: installed.append(name) active_name, active_cmd = None, None if not installed: print(NO_PACKAGE_MANAGER_WARNING) choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2) active_name = PACKAGE_MANAGER_CHOICES[choice - 1] active_cmd = PACKAGE_MANAGER[active_name] getattr(self, 'install_%s' % active_name.lower())() elif len(installed) == 1: print(PACKAGE_MANAGER_EXISTS % (installed[0], installed[0])) active_name = installed[0] active_cmd = PACKAGE_MANAGER[active_name] else: print(MULTI_PACKAGE_MANAGER_EXISTS) choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2) active_name = PACKAGE_MANAGER_CHOICES[choice - 1] active_cmd = PACKAGE_MANAGER[active_name] # Ensure the active package manager is in $PATH and it comes before # /usr/bin. If it doesn't come before /usr/bin, we'll pick up system # packages before package manager installed packages and the build may # break. p = self.which(active_cmd) if not p: print(PACKAGE_MANAGER_BIN_MISSING % active_cmd) sys.exit(1) p_dir = os.path.dirname(p) for path in os.environ['PATH'].split(os.pathsep): if path == p_dir: break for check in ('/bin', '/usr/bin'): if path == check: print(BAD_PATH_ORDER % (check, p_dir, p_dir, check, p_dir)) sys.exit(1) return active_name.lower()
[ "def", "ensure_package_manager", "(", "self", ")", ":", "installed", "=", "[", "]", "for", "name", ",", "cmd", "in", "PACKAGE_MANAGER", ".", "iteritems", "(", ")", ":", "if", "self", ".", "which", "(", "cmd", ")", "is", "not", "None", ":", "installed", ".", "append", "(", "name", ")", "active_name", ",", "active_cmd", "=", "None", ",", "None", "if", "not", "installed", ":", "print", "(", "NO_PACKAGE_MANAGER_WARNING", ")", "choice", "=", "self", ".", "prompt_int", "(", "prompt", "=", "PACKAGE_MANAGER_CHOICE", ",", "low", "=", "1", ",", "high", "=", "2", ")", "active_name", "=", "PACKAGE_MANAGER_CHOICES", "[", "choice", "-", "1", "]", "active_cmd", "=", "PACKAGE_MANAGER", "[", "active_name", "]", "getattr", "(", "self", ",", "'install_%s'", "%", "active_name", ".", "lower", "(", ")", ")", "(", ")", "elif", "len", "(", "installed", ")", "==", "1", ":", "print", "(", "PACKAGE_MANAGER_EXISTS", "%", "(", "installed", "[", "0", "]", ",", "installed", "[", "0", "]", ")", ")", "active_name", "=", "installed", "[", "0", "]", "active_cmd", "=", "PACKAGE_MANAGER", "[", "active_name", "]", "else", ":", "print", "(", "MULTI_PACKAGE_MANAGER_EXISTS", ")", "choice", "=", "self", ".", "prompt_int", "(", "prompt", "=", "PACKAGE_MANAGER_CHOICE", ",", "low", "=", "1", ",", "high", "=", "2", ")", "active_name", "=", "PACKAGE_MANAGER_CHOICES", "[", "choice", "-", "1", "]", "active_cmd", "=", "PACKAGE_MANAGER", "[", "active_name", "]", "# Ensure the active package manager is in $PATH and it comes before", "# /usr/bin. If it doesn't come before /usr/bin, we'll pick up system", "# packages before package manager installed packages and the build may", "# break.", "p", "=", "self", ".", "which", "(", "active_cmd", ")", "if", "not", "p", ":", "print", "(", "PACKAGE_MANAGER_BIN_MISSING", "%", "active_cmd", ")", "sys", ".", "exit", "(", "1", ")", "p_dir", "=", "os", ".", "path", ".", "dirname", "(", "p", ")", "for", "path", "in", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "if", "path", "==", "p_dir", ":", "break", "for", "check", "in", "(", "'/bin'", ",", "'/usr/bin'", ")", ":", "if", "path", "==", "check", ":", "print", "(", "BAD_PATH_ORDER", "%", "(", "check", ",", "p_dir", ",", "p_dir", ",", "check", ",", "p_dir", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "active_name", ".", "lower", "(", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozboot/mozboot/osx.py#L322-L371
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/rospack.py
python
ManifestManager._load_manifest
(self, name)
return retval
:raises: :exc:`ResourceNotFound`
:raises: :exc:`ResourceNotFound`
[ ":", "raises", ":", ":", "exc", ":", "ResourceNotFound" ]
def _load_manifest(self, name): """ :raises: :exc:`ResourceNotFound` """ retval = self._manifests[name] = parse_manifest_file(self.get_path(name), self._manifest_name, rospack=self) return retval
[ "def", "_load_manifest", "(", "self", ",", "name", ")", ":", "retval", "=", "self", ".", "_manifests", "[", "name", "]", "=", "parse_manifest_file", "(", "self", ".", "get_path", "(", "name", ")", ",", "self", ".", "_manifest_name", ",", "rospack", "=", "self", ")", "return", "retval" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/rospack.py#L204-L209
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
GBSizerItem.SetSpan
(*args, **kwargs)
return _core_.GBSizerItem_SetSpan(*args, **kwargs)
SetSpan(self, GBSpan span) -> bool If the item is already a member of a sizer then first ensure that there is no other item that would intersect with this one with its new spanning size, then set the new spanning. Returns True if the change is successful and after the next Layout() the item will be resized.
SetSpan(self, GBSpan span) -> bool
[ "SetSpan", "(", "self", "GBSpan", "span", ")", "-", ">", "bool" ]
def SetSpan(*args, **kwargs): """ SetSpan(self, GBSpan span) -> bool If the item is already a member of a sizer then first ensure that there is no other item that would intersect with this one with its new spanning size, then set the new spanning. Returns True if the change is successful and after the next Layout() the item will be resized. """ return _core_.GBSizerItem_SetSpan(*args, **kwargs)
[ "def", "SetSpan", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GBSizerItem_SetSpan", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L15766-L15776
Mahlet-Inc/hobbits
071d7a542f1af0a7791bcaab17b08224df9ecd4e
src/hobbits-plugins/analyzers/KaitaiStruct/ksy_py/executable/dex.py
python
Dex.proto_ids
(self)
return self._m_proto_ids if hasattr(self, '_m_proto_ids') else None
method prototype identifiers list. These are identifiers for all prototypes referred to by this file. This list must be sorted in return-type (by type_id index) major order, and then by argument list (lexicographic ordering, individual arguments ordered by type_id index). The list must not contain any duplicate entries.
method prototype identifiers list. These are identifiers for all prototypes referred to by this file. This list must be sorted in return-type (by type_id index) major order, and then by argument list (lexicographic ordering, individual arguments ordered by type_id index). The list must not contain any duplicate entries.
[ "method", "prototype", "identifiers", "list", ".", "These", "are", "identifiers", "for", "all", "prototypes", "referred", "to", "by", "this", "file", ".", "This", "list", "must", "be", "sorted", "in", "return", "-", "type", "(", "by", "type_id", "index", ")", "major", "order", "and", "then", "by", "argument", "list", "(", "lexicographic", "ordering", "individual", "arguments", "ordered", "by", "type_id", "index", ")", ".", "The", "list", "must", "not", "contain", "any", "duplicate", "entries", "." ]
def proto_ids(self): """method prototype identifiers list. These are identifiers for all prototypes referred to by this file. This list must be sorted in return-type (by type_id index) major order, and then by argument list (lexicographic ordering, individual arguments ordered by type_id index). The list must not contain any duplicate entries. """ if hasattr(self, '_m_proto_ids'): return self._m_proto_ids if hasattr(self, '_m_proto_ids') else None _pos = self._io.pos() self._io.seek(self.header.proto_ids_off) self._debug['_m_proto_ids']['start'] = self._io.pos() self._m_proto_ids = [None] * (self.header.proto_ids_size) for i in range(self.header.proto_ids_size): if not 'arr' in self._debug['_m_proto_ids']: self._debug['_m_proto_ids']['arr'] = [] self._debug['_m_proto_ids']['arr'].append({'start': self._io.pos()}) _t__m_proto_ids = Dex.ProtoIdItem(self._io, self, self._root) _t__m_proto_ids._read() self._m_proto_ids[i] = _t__m_proto_ids self._debug['_m_proto_ids']['arr'][i]['end'] = self._io.pos() self._debug['_m_proto_ids']['end'] = self._io.pos() self._io.seek(_pos) return self._m_proto_ids if hasattr(self, '_m_proto_ids') else None
[ "def", "proto_ids", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_m_proto_ids'", ")", ":", "return", "self", ".", "_m_proto_ids", "if", "hasattr", "(", "self", ",", "'_m_proto_ids'", ")", "else", "None", "_pos", "=", "self", ".", "_io", ".", "pos", "(", ")", "self", ".", "_io", ".", "seek", "(", "self", ".", "header", ".", "proto_ids_off", ")", "self", ".", "_debug", "[", "'_m_proto_ids'", "]", "[", "'start'", "]", "=", "self", ".", "_io", ".", "pos", "(", ")", "self", ".", "_m_proto_ids", "=", "[", "None", "]", "*", "(", "self", ".", "header", ".", "proto_ids_size", ")", "for", "i", "in", "range", "(", "self", ".", "header", ".", "proto_ids_size", ")", ":", "if", "not", "'arr'", "in", "self", ".", "_debug", "[", "'_m_proto_ids'", "]", ":", "self", ".", "_debug", "[", "'_m_proto_ids'", "]", "[", "'arr'", "]", "=", "[", "]", "self", ".", "_debug", "[", "'_m_proto_ids'", "]", "[", "'arr'", "]", ".", "append", "(", "{", "'start'", ":", "self", ".", "_io", ".", "pos", "(", ")", "}", ")", "_t__m_proto_ids", "=", "Dex", ".", "ProtoIdItem", "(", "self", ".", "_io", ",", "self", ",", "self", ".", "_root", ")", "_t__m_proto_ids", ".", "_read", "(", ")", "self", ".", "_m_proto_ids", "[", "i", "]", "=", "_t__m_proto_ids", "self", ".", "_debug", "[", "'_m_proto_ids'", "]", "[", "'arr'", "]", "[", "i", "]", "[", "'end'", "]", "=", "self", ".", "_io", ".", "pos", "(", ")", "self", ".", "_debug", "[", "'_m_proto_ids'", "]", "[", "'end'", "]", "=", "self", ".", "_io", ".", "pos", "(", ")", "self", ".", "_io", ".", "seek", "(", "_pos", ")", "return", "self", ".", "_m_proto_ids", "if", "hasattr", "(", "self", ",", "'_m_proto_ids'", ")", "else", "None" ]
https://github.com/Mahlet-Inc/hobbits/blob/071d7a542f1af0a7791bcaab17b08224df9ecd4e/src/hobbits-plugins/analyzers/KaitaiStruct/ksy_py/executable/dex.py#L1025-L1052
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/HeppyCore/python/statistics/counter.py
python
Counter.inc
(self, level, nentries=1)
increment an existing level
increment an existing level
[ "increment", "an", "existing", "level" ]
def inc(self, level, nentries=1): '''increment an existing level ''' if level not in self.dico: raise ValueError('level', level, 'has not been registered') else: self[level][1] += nentries
[ "def", "inc", "(", "self", ",", "level", ",", "nentries", "=", "1", ")", ":", "if", "level", "not", "in", "self", ".", "dico", ":", "raise", "ValueError", "(", "'level'", ",", "level", ",", "'has not been registered'", ")", "else", ":", "self", "[", "level", "]", "[", "1", "]", "+=", "nentries" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/statistics/counter.py#L17-L23
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/waitress/waitress/server.py
python
create_server
(application, map=None, _start=True, # test shim _sock=None, # test shim _dispatcher=None, # test shim **kw # adjustments )
return cls(application, map, _start, _sock, _dispatcher, adj)
if __name__ == '__main__': server = create_server(app) server.run()
if __name__ == '__main__': server = create_server(app) server.run()
[ "if", "__name__", "==", "__main__", ":", "server", "=", "create_server", "(", "app", ")", "server", ".", "run", "()" ]
def create_server(application, map=None, _start=True, # test shim _sock=None, # test shim _dispatcher=None, # test shim **kw # adjustments ): """ if __name__ == '__main__': server = create_server(app) server.run() """ adj = Adjustments(**kw) if adj.unix_socket and hasattr(socket, 'AF_UNIX'): cls = UnixWSGIServer else: cls = TcpWSGIServer return cls(application, map, _start, _sock, _dispatcher, adj)
[ "def", "create_server", "(", "application", ",", "map", "=", "None", ",", "_start", "=", "True", ",", "# test shim", "_sock", "=", "None", ",", "# test shim", "_dispatcher", "=", "None", ",", "# test shim", "*", "*", "kw", "# adjustments", ")", ":", "adj", "=", "Adjustments", "(", "*", "*", "kw", ")", "if", "adj", ".", "unix_socket", "and", "hasattr", "(", "socket", ",", "'AF_UNIX'", ")", ":", "cls", "=", "UnixWSGIServer", "else", ":", "cls", "=", "TcpWSGIServer", "return", "cls", "(", "application", ",", "map", ",", "_start", ",", "_sock", ",", "_dispatcher", ",", "adj", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/waitress/waitress/server.py#L27-L44
SpaceNetChallenge/BuildingDetectors
3def3c44b5847c744cd2f3356182892d92496579
qinhaifang/src/lib/datasets/pascal_voc_det.py
python
PascalVOCDet._load_image_set_index
(self)
return image_index
Load the indexes listed in this dataset's image set file. Examples path is: self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt --------
Load the indexes listed in this dataset's image set file. Examples path is: self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt --------
[ "Load", "the", "indexes", "listed", "in", "this", "dataset", "s", "image", "set", "file", ".", "Examples", "path", "is", ":", "self", ".", "_devkit_path", "+", "/", "VOCdevkit2007", "/", "VOC2007", "/", "ImageSets", "/", "Main", "/", "val", ".", "txt", "--------" ]
def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. Examples path is: self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt -------- """ image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main', self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] return image_index
[ "def", "_load_image_set_index", "(", "self", ")", ":", "image_set_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "'ImageSets'", ",", "'Main'", ",", "self", ".", "_image_set", "+", "'.txt'", ")", "assert", "os", ".", "path", ".", "exists", "(", "image_set_file", ")", ",", "'Path does not exist: {}'", ".", "format", "(", "image_set_file", ")", "with", "open", "(", "image_set_file", ")", "as", "f", ":", "image_index", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "f", ".", "readlines", "(", ")", "]", "return", "image_index" ]
https://github.com/SpaceNetChallenge/BuildingDetectors/blob/3def3c44b5847c744cd2f3356182892d92496579/qinhaifang/src/lib/datasets/pascal_voc_det.py#L94-L107
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/scripts/Python/modify-python-lldb.py
python
NewContent.del_line
(self)
Forget about the previous line, do not commit it.
Forget about the previous line, do not commit it.
[ "Forget", "about", "the", "previous", "line", "do", "not", "commit", "it", "." ]
def del_line(self): """Forget about the previous line, do not commit it.""" self.prev_line = None
[ "def", "del_line", "(", "self", ")", ":", "self", ".", "prev_line", "=", "None" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/scripts/Python/modify-python-lldb.py#L301-L303
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
BufferedPaintDC.__init__
(self, *args, **kwargs)
__init__(self, Window window, Bitmap buffer=NullBitmap, int style=BUFFER_CLIENT_AREA) -> BufferedPaintDC Create a buffered paint DC. As with `wx.BufferedDC`, you may either provide the bitmap to be used for buffering or let this object create one internally (in the latter case, the size of the client part of the window is automatically used).
__init__(self, Window window, Bitmap buffer=NullBitmap, int style=BUFFER_CLIENT_AREA) -> BufferedPaintDC
[ "__init__", "(", "self", "Window", "window", "Bitmap", "buffer", "=", "NullBitmap", "int", "style", "=", "BUFFER_CLIENT_AREA", ")", "-", ">", "BufferedPaintDC" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window window, Bitmap buffer=NullBitmap, int style=BUFFER_CLIENT_AREA) -> BufferedPaintDC Create a buffered paint DC. As with `wx.BufferedDC`, you may either provide the bitmap to be used for buffering or let this object create one internally (in the latter case, the size of the client part of the window is automatically used). """ _gdi_.BufferedPaintDC_swiginit(self,_gdi_.new_BufferedPaintDC(*args, **kwargs)) if len(args) > 1: self.__bmp = args[1]
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "BufferedPaintDC_swiginit", "(", "self", ",", "_gdi_", ".", "new_BufferedPaintDC", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "if", "len", "(", "args", ")", ">", "1", ":", "self", ".", "__bmp", "=", "args", "[", "1", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L5281-L5291
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py
python
_BaseV6._explode_shorthand_ip_string
(self)
return ':'.join(parts)
Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.
Expand a shortened IPv6 address.
[ "Expand", "a", "shortened", "IPv6", "address", "." ]
def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, _BaseNet): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) parts = [] for i in xrange(self._HEXTET_COUNT): parts.append('%04x' % (ip_int & 0xFFFF)) ip_int >>= 16 parts.reverse() if isinstance(self, _BaseNet): return '%s/%d' % (':'.join(parts), self.prefixlen) return ':'.join(parts)
[ "def", "_explode_shorthand_ip_string", "(", "self", ")", ":", "if", "isinstance", "(", "self", ",", "_BaseNet", ")", ":", "ip_str", "=", "str", "(", "self", ".", "ip", ")", "else", ":", "ip_str", "=", "str", "(", "self", ")", "ip_int", "=", "self", ".", "_ip_int_from_string", "(", "ip_str", ")", "parts", "=", "[", "]", "for", "i", "in", "xrange", "(", "self", ".", "_HEXTET_COUNT", ")", ":", "parts", ".", "append", "(", "'%04x'", "%", "(", "ip_int", "&", "0xFFFF", ")", ")", "ip_int", ">>=", "16", "parts", ".", "reverse", "(", ")", "if", "isinstance", "(", "self", ",", "_BaseNet", ")", ":", "return", "'%s/%d'", "%", "(", "':'", ".", "join", "(", "parts", ")", ",", "self", ".", "prefixlen", ")", "return", "':'", ".", "join", "(", "parts", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py#L1572-L1595
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
scripts/cpp_lint.py
python
_NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else case.", "self", ".", "pp_stack", ".", "append", "(", "_PreprocessorInfo", "(", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", ")", ")", "elif", "Match", "(", "r'^\\s*#\\s*(else|elif)\\b'", ",", "line", ")", ":", "# Beginning of #else block", "if", "self", ".", "pp_stack", ":", "if", "not", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# This is the first #else or #elif block. Remember the", "# whole nesting stack up to this point. This is what we", "# keep after the #endif.", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", "=", "True", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "=", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", "# Restore the stack to how it was before the #if", "self", ".", "stack", "=", "copy", ".", "deepcopy", "(", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_if", ")", "else", ":", "# TODO(unknown): unexpected #else, issue warning?", "pass", "elif", "Match", "(", "r'^\\s*#\\s*endif\\b'", ",", "line", ")", ":", "# End of #if or #else blocks.", "if", "self", ".", "pp_stack", ":", "# If we saw an #else, we will need to restore the nesting", "# stack to its former state before the #else, otherwise we", "# will just continue from where we left off.", "if", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# Here we can just use a shallow copy since we are the last", "# reference to it.", "self", ".", "stack", "=", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "# Drop the corresponding #if", "self", ".", "pp_stack", ".", "pop", "(", ")", "else", ":", "# TODO(unknown): unexpected #endif, issue warning?", "pass" ]
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L1952-L2006
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py
python
_RaiseInvalidWireType
(buffer, pos, end)
Skip function for unknown wire types. Raises an exception.
Skip function for unknown wire types. Raises an exception.
[ "Skip", "function", "for", "unknown", "wire", "types", ".", "Raises", "an", "exception", "." ]
def _RaiseInvalidWireType(buffer, pos, end): """Skip function for unknown wire types. Raises an exception.""" raise _DecodeError('Tag had invalid wire type.')
[ "def", "_RaiseInvalidWireType", "(", "buffer", ",", "pos", ",", "end", ")", ":", "raise", "_DecodeError", "(", "'Tag had invalid wire type.'", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py#L603-L606
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/common/tensor.py
python
Tensor.reshape
(self, *shape)
return tensor_operator_registry.get('reshape')()(self, new_shape)
Give a new shape to a tensor without changing its data. Args: shape(Union[int, tuple(int), list(int)]): The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D tensor of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the tensor and remaining dimensions. Returns: Tensor, with new specified shape. Raises: TypeError: If new shape is not integer, list or tuple. ValueError: If new shape is not compatible with the original shape. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> from mindspore import Tensor >>> from mindspore import dtype as mstype >>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32) >>> output = x.reshape((3, 2)) >>> print(output) [[-0.1 0.3] [ 3.6 0.4] [ 0.5 -3.2]]
Give a new shape to a tensor without changing its data.
[ "Give", "a", "new", "shape", "to", "a", "tensor", "without", "changing", "its", "data", "." ]
def reshape(self, *shape): """ Give a new shape to a tensor without changing its data. Args: shape(Union[int, tuple(int), list(int)]): The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D tensor of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the tensor and remaining dimensions. Returns: Tensor, with new specified shape. Raises: TypeError: If new shape is not integer, list or tuple. ValueError: If new shape is not compatible with the original shape. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> from mindspore import Tensor >>> from mindspore import dtype as mstype >>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32) >>> output = x.reshape((3, 2)) >>> print(output) [[-0.1 0.3] [ 3.6 0.4] [ 0.5 -3.2]] """ self._init_check() new_shape = validator.check_reshape_shp(shape) return tensor_operator_registry.get('reshape')()(self, new_shape)
[ "def", "reshape", "(", "self", ",", "*", "shape", ")", ":", "self", ".", "_init_check", "(", ")", "new_shape", "=", "validator", ".", "check_reshape_shp", "(", "shape", ")", "return", "tensor_operator_registry", ".", "get", "(", "'reshape'", ")", "(", ")", "(", "self", ",", "new_shape", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/common/tensor.py#L719-L751
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_transrel.py
python
is_skolem
(sym)
return sym.contains('__')
Symbols with __ in them in the TR are considerd to be implicitly existentially quantified.
Symbols with __ in them in the TR are considerd to be implicitly existentially quantified.
[ "Symbols", "with", "__", "in", "them", "in", "the", "TR", "are", "considerd", "to", "be", "implicitly", "existentially", "quantified", "." ]
def is_skolem(sym): """ Symbols with __ in them in the TR are considerd to be implicitly existentially quantified. """ return sym.contains('__')
[ "def", "is_skolem", "(", "sym", ")", ":", "return", "sym", ".", "contains", "(", "'__'", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_transrel.py#L72-L76
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py
python
Base.Replace
(self, **kw)
Replace existing construction variables in an Environment with new construction variables and/or values.
Replace existing construction variables in an Environment with new construction variables and/or values.
[ "Replace", "existing", "construction", "variables", "in", "an", "Environment", "with", "new", "construction", "variables", "and", "/", "or", "values", "." ]
def Replace(self, **kw): """Replace existing construction variables in an Environment with new construction variables and/or values. """ try: kwbd = kw['BUILDERS'] except KeyError: pass else: kwbd = BuilderDict(kwbd,self) del kw['BUILDERS'] self.__setitem__('BUILDERS', kwbd) kw = copy_non_reserved_keywords(kw) self._update(semi_deepcopy(kw)) self.scanner_map_delete(kw)
[ "def", "Replace", "(", "self", ",", "*", "*", "kw", ")", ":", "try", ":", "kwbd", "=", "kw", "[", "'BUILDERS'", "]", "except", "KeyError", ":", "pass", "else", ":", "kwbd", "=", "BuilderDict", "(", "kwbd", ",", "self", ")", "del", "kw", "[", "'BUILDERS'", "]", "self", ".", "__setitem__", "(", "'BUILDERS'", ",", "kwbd", ")", "kw", "=", "copy_non_reserved_keywords", "(", "kw", ")", "self", ".", "_update", "(", "semi_deepcopy", "(", "kw", ")", ")", "self", ".", "scanner_map_delete", "(", "kw", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py#L1767-L1781
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xpathParserContext.xpathIdFunction
(self, nargs)
Implement the id() XPath function node-set id(object) The id function selects elements by their unique ID (see [5.2.1 Unique IDs]). When the argument to id is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the argument node-set. When the argument to id is of any other type, the argument is converted to a string as if by a call to the string function; the string is split into a whitespace-separated list of tokens (whitespace is any sequence of characters matching the production S); the result is a node-set containing the elements in the same document as the context node that have a unique ID equal to any of the tokens in the list.
Implement the id() XPath function node-set id(object) The id function selects elements by their unique ID (see [5.2.1 Unique IDs]). When the argument to id is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the argument node-set. When the argument to id is of any other type, the argument is converted to a string as if by a call to the string function; the string is split into a whitespace-separated list of tokens (whitespace is any sequence of characters matching the production S); the result is a node-set containing the elements in the same document as the context node that have a unique ID equal to any of the tokens in the list.
[ "Implement", "the", "id", "()", "XPath", "function", "node", "-", "set", "id", "(", "object", ")", "The", "id", "function", "selects", "elements", "by", "their", "unique", "ID", "(", "see", "[", "5", ".", "2", ".", "1", "Unique", "IDs", "]", ")", ".", "When", "the", "argument", "to", "id", "is", "of", "type", "node", "-", "set", "then", "the", "result", "is", "the", "union", "of", "the", "result", "of", "applying", "id", "to", "the", "string", "value", "of", "each", "of", "the", "nodes", "in", "the", "argument", "node", "-", "set", ".", "When", "the", "argument", "to", "id", "is", "of", "any", "other", "type", "the", "argument", "is", "converted", "to", "a", "string", "as", "if", "by", "a", "call", "to", "the", "string", "function", ";", "the", "string", "is", "split", "into", "a", "whitespace", "-", "separated", "list", "of", "tokens", "(", "whitespace", "is", "any", "sequence", "of", "characters", "matching", "the", "production", "S", ")", ";", "the", "result", "is", "a", "node", "-", "set", "containing", "the", "elements", "in", "the", "same", "document", "as", "the", "context", "node", "that", "have", "a", "unique", "ID", "equal", "to", "any", "of", "the", "tokens", "in", "the", "list", "." ]
def xpathIdFunction(self, nargs): """Implement the id() XPath function node-set id(object) The id function selects elements by their unique ID (see [5.2.1 Unique IDs]). When the argument to id is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the argument node-set. When the argument to id is of any other type, the argument is converted to a string as if by a call to the string function; the string is split into a whitespace-separated list of tokens (whitespace is any sequence of characters matching the production S); the result is a node-set containing the elements in the same document as the context node that have a unique ID equal to any of the tokens in the list. """ libxml2mod.xmlXPathIdFunction(self._o, nargs)
[ "def", "xpathIdFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathIdFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6741-L6755
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/revived_types.py
python
VersionedTypeRegistration.__init__
(self, object_factory, version, min_producer_version, min_consumer_version, bad_consumers=None, setter=setattr)
Identify a revived type version. Args: object_factory: A callable which takes a SavedUserObject proto and returns a trackable object. Dependencies are added later via `setter`. version: An integer, the producer version of this wrapper type. When making incompatible changes to a wrapper, add a new `VersionedTypeRegistration` with an incremented `version`. The most recent version will be saved, and all registrations with a matching identifier will be searched for the highest compatible version to use when loading. min_producer_version: The minimum producer version number required to use this `VersionedTypeRegistration` when loading a proto. min_consumer_version: `VersionedTypeRegistration`s with a version number less than `min_consumer_version` will not be used to load a proto saved with this object. `min_consumer_version` should be set to the lowest version number which can successfully load protos saved by this object. If no matching registration is available on load, the object will be revived with a generic trackable type. `min_consumer_version` and `bad_consumers` are a blunt tool, and using them will generally break forward compatibility: previous versions of TensorFlow will revive newly saved objects as opaque trackable objects rather than wrapped objects. When updating wrappers, prefer saving new information but preserving compatibility with previous wrapper versions. They are, however, useful for ensuring that previously-released buggy wrapper versions degrade gracefully rather than throwing exceptions when presented with newly-saved SavedModels. bad_consumers: A list of consumer versions which are incompatible (in addition to any version less than `min_consumer_version`). setter: A callable with the same signature as `setattr` to use when adding dependencies to generated objects.
Identify a revived type version.
[ "Identify", "a", "revived", "type", "version", "." ]
def __init__(self, object_factory, version, min_producer_version, min_consumer_version, bad_consumers=None, setter=setattr): """Identify a revived type version. Args: object_factory: A callable which takes a SavedUserObject proto and returns a trackable object. Dependencies are added later via `setter`. version: An integer, the producer version of this wrapper type. When making incompatible changes to a wrapper, add a new `VersionedTypeRegistration` with an incremented `version`. The most recent version will be saved, and all registrations with a matching identifier will be searched for the highest compatible version to use when loading. min_producer_version: The minimum producer version number required to use this `VersionedTypeRegistration` when loading a proto. min_consumer_version: `VersionedTypeRegistration`s with a version number less than `min_consumer_version` will not be used to load a proto saved with this object. `min_consumer_version` should be set to the lowest version number which can successfully load protos saved by this object. If no matching registration is available on load, the object will be revived with a generic trackable type. `min_consumer_version` and `bad_consumers` are a blunt tool, and using them will generally break forward compatibility: previous versions of TensorFlow will revive newly saved objects as opaque trackable objects rather than wrapped objects. When updating wrappers, prefer saving new information but preserving compatibility with previous wrapper versions. They are, however, useful for ensuring that previously-released buggy wrapper versions degrade gracefully rather than throwing exceptions when presented with newly-saved SavedModels. bad_consumers: A list of consumer versions which are incompatible (in addition to any version less than `min_consumer_version`). setter: A callable with the same signature as `setattr` to use when adding dependencies to generated objects. """ self.setter = setter self.identifier = None # Set after registration self._object_factory = object_factory self.version = version self._min_consumer_version = min_consumer_version self._min_producer_version = min_producer_version if bad_consumers is None: bad_consumers = [] self._bad_consumers = bad_consumers
[ "def", "__init__", "(", "self", ",", "object_factory", ",", "version", ",", "min_producer_version", ",", "min_consumer_version", ",", "bad_consumers", "=", "None", ",", "setter", "=", "setattr", ")", ":", "self", ".", "setter", "=", "setter", "self", ".", "identifier", "=", "None", "# Set after registration", "self", ".", "_object_factory", "=", "object_factory", "self", ".", "version", "=", "version", "self", ".", "_min_consumer_version", "=", "min_consumer_version", "self", ".", "_min_producer_version", "=", "min_producer_version", "if", "bad_consumers", "is", "None", ":", "bad_consumers", "=", "[", "]", "self", ".", "_bad_consumers", "=", "bad_consumers" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/revived_types.py#L28-L71
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/_shard/sharded_optim/api.py
python
ShardedOptimizer.load_state_dict
(self, state_dict: Mapping[str, Any])
r"""Loads the ShardedOptimizer state. Args: state_dict (dict): ShardedOptimizer state. Should be an object returned from a call to :meth:`state_dict`.
r"""Loads the ShardedOptimizer state.
[ "r", "Loads", "the", "ShardedOptimizer", "state", "." ]
def load_state_dict(self, state_dict: Mapping[str, Any]): r"""Loads the ShardedOptimizer state. Args: state_dict (dict): ShardedOptimizer state. Should be an object returned from a call to :meth:`state_dict`. """ # TODO: implement load_state_dict raise NotImplementedError("ShardedOptimizer load_state_dict not implemented yet!")
[ "def", "load_state_dict", "(", "self", ",", "state_dict", ":", "Mapping", "[", "str", ",", "Any", "]", ")", ":", "# TODO: implement load_state_dict", "raise", "NotImplementedError", "(", "\"ShardedOptimizer load_state_dict not implemented yet!\"", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/_shard/sharded_optim/api.py#L84-L92
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Window.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=PanelNameStr) -> Window Construct and show a generic Window.
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=PanelNameStr) -> Window
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "String", "name", "=", "PanelNameStr", ")", "-", ">", "Window" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=PanelNameStr) -> Window Construct and show a generic Window. """ _core_.Window_swiginit(self,_core_.new_Window(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "Window_swiginit", "(", "self", ",", "_core_", ".", "new_Window", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9138-L9146
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
Builder.execute
(self)
Generate target nodes from source node. Must be reimplemented by subclasses.
Generate target nodes from source node.
[ "Generate", "target", "nodes", "from", "source", "node", "." ]
def execute(self): """Generate target nodes from source node. Must be reimplemented by subclasses. """ raise Exception('execute is not implemented for %s' % self)
[ "def", "execute", "(", "self", ")", ":", "raise", "Exception", "(", "'execute is not implemented for %s'", "%", "self", ")" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L2464-L2469
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/setup.py
python
_copy_sources
()
Prepare for a source distribution by assembling a minimal set of source files needed for building
Prepare for a source distribution by assembling a minimal set of source files needed for building
[ "Prepare", "for", "a", "source", "distribution", "by", "assembling", "a", "minimal", "set", "of", "source", "files", "needed", "for", "building" ]
def _copy_sources(): """ Prepare for a source distribution by assembling a minimal set of source files needed for building """ shutil.rmtree(SRC_DIR_LOCAL, ignore_errors=True) os.mkdir(SRC_DIR_LOCAL) shutil.copy(os.path.join(SRC_DIR_REPO, 'LICENSE.txt'), SRC_DIR_LOCAL) shutil.copy(os.path.join(SRC_DIR_REPO, 'z3.pc.cmake.in'), SRC_DIR_LOCAL) shutil.copy(os.path.join(SRC_DIR_REPO, 'CMakeLists.txt'), SRC_DIR_LOCAL) shutil.copytree(os.path.join(SRC_DIR_REPO, 'cmake'), os.path.join(SRC_DIR_LOCAL, 'cmake')) shutil.copytree(os.path.join(SRC_DIR_REPO, 'scripts'), os.path.join(SRC_DIR_LOCAL, 'scripts')) # Copy in src, but avoid recursion def ignore_python_setup_files(src, _): if os.path.normpath(src).endswith('api/python'): return ['core', 'dist', 'MANIFEST', 'MANIFEST.in', 'setup.py', 'z3_solver.egg-info'] return [] shutil.copytree(os.path.join(SRC_DIR_REPO, 'src'), os.path.join(SRC_DIR_LOCAL, 'src'), ignore=ignore_python_setup_files)
[ "def", "_copy_sources", "(", ")", ":", "shutil", ".", "rmtree", "(", "SRC_DIR_LOCAL", ",", "ignore_errors", "=", "True", ")", "os", ".", "mkdir", "(", "SRC_DIR_LOCAL", ")", "shutil", ".", "copy", "(", "os", ".", "path", ".", "join", "(", "SRC_DIR_REPO", ",", "'LICENSE.txt'", ")", ",", "SRC_DIR_LOCAL", ")", "shutil", ".", "copy", "(", "os", ".", "path", ".", "join", "(", "SRC_DIR_REPO", ",", "'z3.pc.cmake.in'", ")", ",", "SRC_DIR_LOCAL", ")", "shutil", ".", "copy", "(", "os", ".", "path", ".", "join", "(", "SRC_DIR_REPO", ",", "'CMakeLists.txt'", ")", ",", "SRC_DIR_LOCAL", ")", "shutil", ".", "copytree", "(", "os", ".", "path", ".", "join", "(", "SRC_DIR_REPO", ",", "'cmake'", ")", ",", "os", ".", "path", ".", "join", "(", "SRC_DIR_LOCAL", ",", "'cmake'", ")", ")", "shutil", ".", "copytree", "(", "os", ".", "path", ".", "join", "(", "SRC_DIR_REPO", ",", "'scripts'", ")", ",", "os", ".", "path", ".", "join", "(", "SRC_DIR_LOCAL", ",", "'scripts'", ")", ")", "# Copy in src, but avoid recursion", "def", "ignore_python_setup_files", "(", "src", ",", "_", ")", ":", "if", "os", ".", "path", ".", "normpath", "(", "src", ")", ".", "endswith", "(", "'api/python'", ")", ":", "return", "[", "'core'", ",", "'dist'", ",", "'MANIFEST'", ",", "'MANIFEST.in'", ",", "'setup.py'", ",", "'z3_solver.egg-info'", "]", "return", "[", "]", "shutil", ".", "copytree", "(", "os", ".", "path", ".", "join", "(", "SRC_DIR_REPO", ",", "'src'", ")", ",", "os", ".", "path", ".", "join", "(", "SRC_DIR_LOCAL", ",", "'src'", ")", ",", "ignore", "=", "ignore_python_setup_files", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/setup.py#L187-L207
AcademySoftwareFoundation/OpenColorIO
73508eb5230374df8d96147a0627c015d359a641
vendor/rv/Python/ociorv.py
python
PyMyStuffMode.get_views
(self)
return available_views
Return [("sRGB", "Film"), ("sRGB", "Log"), ...]
Return [("sRGB", "Film"), ("sRGB", "Log"), ...]
[ "Return", "[", "(", "sRGB", "Film", ")", "(", "sRGB", "Log", ")", "...", "]" ]
def get_views(self): """Return [("sRGB", "Film"), ("sRGB", "Log"), ...] """ available_views = [] cfg = self.get_cfg() for a_display in cfg.getDisplays(): if a_display not in cfg.getActiveDisplays().split(", "): continue for a_view in cfg.getViews(a_display): if a_view not in cfg.getActiveViews(): continue available_views.append( (a_display, a_view)) return available_views
[ "def", "get_views", "(", "self", ")", ":", "available_views", "=", "[", "]", "cfg", "=", "self", ".", "get_cfg", "(", ")", "for", "a_display", "in", "cfg", ".", "getDisplays", "(", ")", ":", "if", "a_display", "not", "in", "cfg", ".", "getActiveDisplays", "(", ")", ".", "split", "(", "\", \"", ")", ":", "continue", "for", "a_view", "in", "cfg", ".", "getViews", "(", "a_display", ")", ":", "if", "a_view", "not", "in", "cfg", ".", "getActiveViews", "(", ")", ":", "continue", "available_views", ".", "append", "(", "(", "a_display", ",", "a_view", ")", ")", "return", "available_views" ]
https://github.com/AcademySoftwareFoundation/OpenColorIO/blob/73508eb5230374df8d96147a0627c015d359a641/vendor/rv/Python/ociorv.py#L229-L245
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBBlock.GetInlinedCallSiteColumn
(self)
return _lldb.SBBlock_GetInlinedCallSiteColumn(self)
GetInlinedCallSiteColumn(SBBlock self) -> uint32_t Get the call site column if this block represents an inlined function; otherwise, return 0.
GetInlinedCallSiteColumn(SBBlock self) -> uint32_t
[ "GetInlinedCallSiteColumn", "(", "SBBlock", "self", ")", "-", ">", "uint32_t" ]
def GetInlinedCallSiteColumn(self): """ GetInlinedCallSiteColumn(SBBlock self) -> uint32_t Get the call site column if this block represents an inlined function; otherwise, return 0. """ return _lldb.SBBlock_GetInlinedCallSiteColumn(self)
[ "def", "GetInlinedCallSiteColumn", "(", "self", ")", ":", "return", "_lldb", ".", "SBBlock_GetInlinedCallSiteColumn", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1286-L1294
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/ltisys.py
python
TransferFunction.den
(self)
return self._den
Denominator of the `TransferFunction` system.
Denominator of the `TransferFunction` system.
[ "Denominator", "of", "the", "TransferFunction", "system", "." ]
def den(self): """Denominator of the `TransferFunction` system.""" return self._den
[ "def", "den", "(", "self", ")", ":", "return", "self", ".", "_den" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L620-L622
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/lib/configureUtil.py
python
checkForBamIndex
(bamFile)
make sure bam file has an index
make sure bam file has an index
[ "make", "sure", "bam", "file", "has", "an", "index" ]
def checkForBamIndex(bamFile): """ make sure bam file has an index """ # check for multi-extension index format PREFIX.bam -> PREFIX.bam.bai: for ext in (".bai", ".csi", ".crai") : indexFile=bamFile + ext if os.path.isfile(indexFile) : return # check for older short index format PREFIX.bam -> PREFIX.bai: for (oldSuffix,newSuffix) in [ (".bam",".bai") ] : if not bamFile.endswith(oldSuffix) : continue indexFile=bamFile[:-len(oldSuffix)] + newSuffix if os.path.isfile(indexFile) : return raise OptParseException("Can't find any expected BAM/CRAM index files for: '%s'" % (bamFile))
[ "def", "checkForBamIndex", "(", "bamFile", ")", ":", "# check for multi-extension index format PREFIX.bam -> PREFIX.bam.bai:", "for", "ext", "in", "(", "\".bai\"", ",", "\".csi\"", ",", "\".crai\"", ")", ":", "indexFile", "=", "bamFile", "+", "ext", "if", "os", ".", "path", ".", "isfile", "(", "indexFile", ")", ":", "return", "# check for older short index format PREFIX.bam -> PREFIX.bai:", "for", "(", "oldSuffix", ",", "newSuffix", ")", "in", "[", "(", "\".bam\"", ",", "\".bai\"", ")", "]", ":", "if", "not", "bamFile", ".", "endswith", "(", "oldSuffix", ")", ":", "continue", "indexFile", "=", "bamFile", "[", ":", "-", "len", "(", "oldSuffix", ")", "]", "+", "newSuffix", "if", "os", ".", "path", ".", "isfile", "(", "indexFile", ")", ":", "return", "raise", "OptParseException", "(", "\"Can't find any expected BAM/CRAM index files for: '%s'\"", "%", "(", "bamFile", ")", ")" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/lib/configureUtil.py#L245-L260
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/bindings/python/clang/cindex.py
python
Cursor.spelling
(self)
return self._spelling
Return the spelling of the entity pointed at by the cursor.
Return the spelling of the entity pointed at by the cursor.
[ "Return", "the", "spelling", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def spelling(self): """Return the spelling of the entity pointed at by the cursor.""" if not hasattr(self, '_spelling'): self._spelling = conf.lib.clang_getCursorSpelling(self) return self._spelling
[ "def", "spelling", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_spelling'", ")", ":", "self", ".", "_spelling", "=", "conf", ".", "lib", ".", "clang_getCursorSpelling", "(", "self", ")", "return", "self", ".", "_spelling" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L1544-L1549
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
build/fbcode_builder/getdeps/subcmd.py
python
SubCmd.run
(self, args)
return 0
perform the command
perform the command
[ "perform", "the", "command" ]
def run(self, args): """perform the command""" return 0
[ "def", "run", "(", "self", ",", "args", ")", ":", "return", "0" ]
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/getdeps/subcmd.py#L11-L13
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pytz/pytz/tzinfo.py
python
StaticTzInfo.normalize
(self, dt, is_dst=False)
return dt.astimezone(self)
Correct the timezone information on the given datetime. This is normally a no-op, as StaticTzInfo timezones never have ambiguous cases to correct: >>> from pytz import timezone >>> gmt = timezone('GMT') >>> isinstance(gmt, StaticTzInfo) True >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt) >>> gmt.normalize(dt) is dt True The supported method of converting between timezones is to use datetime.astimezone(). Currently normalize() also works: >>> la = timezone('America/Los_Angeles') >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3)) >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> gmt.normalize(dt).strftime(fmt) '2011-05-07 08:02:03 GMT (+0000)'
Correct the timezone information on the given datetime.
[ "Correct", "the", "timezone", "information", "on", "the", "given", "datetime", "." ]
def normalize(self, dt, is_dst=False): '''Correct the timezone information on the given datetime. This is normally a no-op, as StaticTzInfo timezones never have ambiguous cases to correct: >>> from pytz import timezone >>> gmt = timezone('GMT') >>> isinstance(gmt, StaticTzInfo) True >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt) >>> gmt.normalize(dt) is dt True The supported method of converting between timezones is to use datetime.astimezone(). Currently normalize() also works: >>> la = timezone('America/Los_Angeles') >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3)) >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> gmt.normalize(dt).strftime(fmt) '2011-05-07 08:02:03 GMT (+0000)' ''' if dt.tzinfo is self: return dt if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.astimezone(self)
[ "def", "normalize", "(", "self", ",", "dt", ",", "is_dst", "=", "False", ")", ":", "if", "dt", ".", "tzinfo", "is", "self", ":", "return", "dt", "if", "dt", ".", "tzinfo", "is", "None", ":", "raise", "ValueError", "(", "'Naive time - no tzinfo set'", ")", "return", "dt", ".", "astimezone", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pytz/pytz/tzinfo.py#L118-L145
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/games/crowd_modelling.py
python
Observer.__init__
(self, params, game)
Initializes an empty observation tensor.
Initializes an empty observation tensor.
[ "Initializes", "an", "empty", "observation", "tensor", "." ]
def __init__(self, params, game): """Initializes an empty observation tensor.""" del params self.size = game.size self.horizon = game.horizon # +1 to allow t == horizon. self.tensor = np.zeros(self.size + self.horizon + 1, np.float32) self.dict = {"x": self.tensor[:self.size], "t": self.tensor[self.size:]}
[ "def", "__init__", "(", "self", ",", "params", ",", "game", ")", ":", "del", "params", "self", ".", "size", "=", "game", ".", "size", "self", ".", "horizon", "=", "game", ".", "horizon", "# +1 to allow t == horizon.", "self", ".", "tensor", "=", "np", ".", "zeros", "(", "self", ".", "size", "+", "self", ".", "horizon", "+", "1", ",", "np", ".", "float32", ")", "self", ".", "dict", "=", "{", "\"x\"", ":", "self", ".", "tensor", "[", ":", "self", ".", "size", "]", ",", "\"t\"", ":", "self", ".", "tensor", "[", "self", ".", "size", ":", "]", "}" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/crowd_modelling.py#L269-L277
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
orttraining/orttraining/python/training/ortmodule/ortmodule.py
python
ORTModule.named_modules
(self, *args, **kwargs)
Override :meth:`~torch.nn.Module.named_modules`
Override :meth:`~torch.nn.Module.named_modules`
[ "Override", ":", "meth", ":", "~torch", ".", "nn", ".", "Module", ".", "named_modules" ]
def named_modules(self, *args, **kwargs): """Override :meth:`~torch.nn.Module.named_modules`""" yield from self._torch_module.named_modules(*args, **kwargs)
[ "def", "named_modules", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "yield", "from", "self", ".", "_torch_module", ".", "named_modules", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/ortmodule/ortmodule.py#L270-L273
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py
python
EC2Connection.reset_image_attribute
(self, image_id, attribute='launchPermission', dry_run=False)
return self.get_status('ResetImageAttribute', params, verb='POST')
Resets an attribute of an AMI to its default value. :type image_id: string :param image_id: ID of the AMI for which an attribute will be described :type attribute: string :param attribute: The attribute to reset :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: Whether the operation succeeded or not
Resets an attribute of an AMI to its default value.
[ "Resets", "an", "attribute", "of", "an", "AMI", "to", "its", "default", "value", "." ]
def reset_image_attribute(self, image_id, attribute='launchPermission', dry_run=False): """ Resets an attribute of an AMI to its default value. :type image_id: string :param image_id: ID of the AMI for which an attribute will be described :type attribute: string :param attribute: The attribute to reset :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: Whether the operation succeeded or not """ params = {'ImageId': image_id, 'Attribute': attribute} if dry_run: params['DryRun'] = 'true' return self.get_status('ResetImageAttribute', params, verb='POST')
[ "def", "reset_image_attribute", "(", "self", ",", "image_id", ",", "attribute", "=", "'launchPermission'", ",", "dry_run", "=", "False", ")", ":", "params", "=", "{", "'ImageId'", ":", "image_id", ",", "'Attribute'", ":", "attribute", "}", "if", "dry_run", ":", "params", "[", "'DryRun'", "]", "=", "'true'", "return", "self", ".", "get_status", "(", "'ResetImageAttribute'", ",", "params", ",", "verb", "=", "'POST'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py#L521-L542
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/_osx_support.py
python
_supports_universal_builds
()
return bool(osx_version >= (10, 4)) if osx_version else False
Returns True if universal builds are supported on this system
Returns True if universal builds are supported on this system
[ "Returns", "True", "if", "universal", "builds", "are", "supported", "on", "this", "system" ]
def _supports_universal_builds(): """Returns True if universal builds are supported on this system""" # As an approximation, we assume that if we are running on 10.4 or above, # then we are running with an Xcode environment that supports universal # builds, in particular -isysroot and -arch arguments to the compiler. This # is in support of allowing 10.4 universal builds to run on 10.3.x systems. osx_version = _get_system_version() if osx_version: try: osx_version = tuple(int(i) for i in osx_version.split('.')) except ValueError: osx_version = '' return bool(osx_version >= (10, 4)) if osx_version else False
[ "def", "_supports_universal_builds", "(", ")", ":", "# As an approximation, we assume that if we are running on 10.4 or above,", "# then we are running with an Xcode environment that supports universal", "# builds, in particular -isysroot and -arch arguments to the compiler. This", "# is in support of allowing 10.4 universal builds to run on 10.3.x systems.", "osx_version", "=", "_get_system_version", "(", ")", "if", "osx_version", ":", "try", ":", "osx_version", "=", "tuple", "(", "int", "(", "i", ")", "for", "i", "in", "osx_version", ".", "split", "(", "'.'", ")", ")", "except", "ValueError", ":", "osx_version", "=", "''", "return", "bool", "(", "osx_version", ">=", "(", "10", ",", "4", ")", ")", "if", "osx_version", "else", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/_osx_support.py#L128-L141
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
CursorKind.is_expression
(self)
return conf.lib.clang_isExpression(self)
Test if this is an expression kind.
Test if this is an expression kind.
[ "Test", "if", "this", "is", "an", "expression", "kind", "." ]
def is_expression(self): """Test if this is an expression kind.""" return conf.lib.clang_isExpression(self)
[ "def", "is_expression", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isExpression", "(", "self", ")" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L527-L529
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
IndigoObject.setDataSGroupXY
(self, x, y, options="")
return self.dispatcher._checkResult( Indigo._lib.indigoSetDataSGroupXY( self.id, x, y, options.encode(ENCODE_ENCODING) ) )
SGroup method sets coordinates Args: x (float): X coordinate y (float): Y coordinate options (str): options. Optional, defaults to "". Returns: int: 1 if there are no errors
SGroup method sets coordinates
[ "SGroup", "method", "sets", "coordinates" ]
def setDataSGroupXY(self, x, y, options=""): """SGroup method sets coordinates Args: x (float): X coordinate y (float): Y coordinate options (str): options. Optional, defaults to "". Returns: int: 1 if there are no errors """ self.dispatcher._setSessionId() if options is None: options = "" return self.dispatcher._checkResult( Indigo._lib.indigoSetDataSGroupXY( self.id, x, y, options.encode(ENCODE_ENCODING) ) )
[ "def", "setDataSGroupXY", "(", "self", ",", "x", ",", "y", ",", "options", "=", "\"\"", ")", ":", "self", ".", "dispatcher", ".", "_setSessionId", "(", ")", "if", "options", "is", "None", ":", "options", "=", "\"\"", "return", "self", ".", "dispatcher", ".", "_checkResult", "(", "Indigo", ".", "_lib", ".", "indigoSetDataSGroupXY", "(", "self", ".", "id", ",", "x", ",", "y", ",", "options", ".", "encode", "(", "ENCODE_ENCODING", ")", ")", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L1622-L1640
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_orthoarray.py
python
OrthoArray.click
(self, event_cb=None)
Execute as a callback when the pointer clicks on the 3D view. It should act as if the Enter key was pressed, or the OK button was pressed in the task panel.
Execute as a callback when the pointer clicks on the 3D view.
[ "Execute", "as", "a", "callback", "when", "the", "pointer", "clicks", "on", "the", "3D", "view", "." ]
def click(self, event_cb=None): """Execute as a callback when the pointer clicks on the 3D view. It should act as if the Enter key was pressed, or the OK button was pressed in the task panel. """ if event_cb: event = event_cb.getEvent() if (event.getState() != coin.SoMouseButtonEvent.DOWN or event.getButton() != coin.SoMouseButtonEvent.BUTTON1): return if self.ui and self.point: # The accept function of the interface # should call the completed function # of the calling class (this one). self.ui.accept()
[ "def", "click", "(", "self", ",", "event_cb", "=", "None", ")", ":", "if", "event_cb", ":", "event", "=", "event_cb", ".", "getEvent", "(", ")", "if", "(", "event", ".", "getState", "(", ")", "!=", "coin", ".", "SoMouseButtonEvent", ".", "DOWN", "or", "event", ".", "getButton", "(", ")", "!=", "coin", ".", "SoMouseButtonEvent", ".", "BUTTON1", ")", ":", "return", "if", "self", ".", "ui", "and", "self", ".", "point", ":", "# The accept function of the interface", "# should call the completed function", "# of the calling class (this one).", "self", ".", "ui", ".", "accept", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_orthoarray.py#L93-L108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/__init__.py
python
compatible_platforms
(provided, required)
return False
Can code for the `provided` platform run on the `required` platform? Returns true if either platform is ``None``, or the platforms are equal. XXX Needs compatibility checks for Linux and other unixy OSes.
Can code for the `provided` platform run on the `required` platform?
[ "Can", "code", "for", "the", "provided", "platform", "run", "on", "the", "required", "platform?" ]
def compatible_platforms(provided, required): """Can code for the `provided` platform run on the `required` platform? Returns true if either platform is ``None``, or the platforms are equal. XXX Needs compatibility checks for Linux and other unixy OSes. """ if provided is None or required is None or provided == required: # easy case return True # Mac OS X special cases reqMac = macosVersionString.match(required) if reqMac: provMac = macosVersionString.match(provided) # is this a Mac package? if not provMac: # this is backwards compatibility for packages built before # setuptools 0.6. All packages built after this point will # use the new macosx designation. provDarwin = darwinVersionString.match(provided) if provDarwin: dversion = int(provDarwin.group(1)) macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2)) if dversion == 7 and macosversion >= "10.3" or \ dversion == 8 and macosversion >= "10.4": return True # egg isn't macosx or legacy darwin return False # are they the same major version and machine type? if provMac.group(1) != reqMac.group(1) or \ provMac.group(3) != reqMac.group(3): return False # is the required OS major update >= the provided one? if int(provMac.group(2)) > int(reqMac.group(2)): return False return True # XXX Linux and other platforms' special cases should go here return False
[ "def", "compatible_platforms", "(", "provided", ",", "required", ")", ":", "if", "provided", "is", "None", "or", "required", "is", "None", "or", "provided", "==", "required", ":", "# easy case", "return", "True", "# Mac OS X special cases", "reqMac", "=", "macosVersionString", ".", "match", "(", "required", ")", "if", "reqMac", ":", "provMac", "=", "macosVersionString", ".", "match", "(", "provided", ")", "# is this a Mac package?", "if", "not", "provMac", ":", "# this is backwards compatibility for packages built before", "# setuptools 0.6. All packages built after this point will", "# use the new macosx designation.", "provDarwin", "=", "darwinVersionString", ".", "match", "(", "provided", ")", "if", "provDarwin", ":", "dversion", "=", "int", "(", "provDarwin", ".", "group", "(", "1", ")", ")", "macosversion", "=", "\"%s.%s\"", "%", "(", "reqMac", ".", "group", "(", "1", ")", ",", "reqMac", ".", "group", "(", "2", ")", ")", "if", "dversion", "==", "7", "and", "macosversion", ">=", "\"10.3\"", "or", "dversion", "==", "8", "and", "macosversion", ">=", "\"10.4\"", ":", "return", "True", "# egg isn't macosx or legacy darwin", "return", "False", "# are they the same major version and machine type?", "if", "provMac", ".", "group", "(", "1", ")", "!=", "reqMac", ".", "group", "(", "1", ")", "or", "provMac", ".", "group", "(", "3", ")", "!=", "reqMac", ".", "group", "(", "3", ")", ":", "return", "False", "# is the required OS major update >= the provided one?", "if", "int", "(", "provMac", ".", "group", "(", "2", ")", ")", ">", "int", "(", "reqMac", ".", "group", "(", "2", ")", ")", ":", "return", "False", "return", "True", "# XXX Linux and other platforms' special cases should go here", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/__init__.py#L418-L461
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/configobj/configobj.py
python
ConfigObj._parse
(self, infile)
Actually parse the config file.
Actually parse the config file.
[ "Actually", "parse", "the", "config", "file", "." ]
def _parse(self, infile): """Actually parse the config file.""" temp_list_values = self.list_values if self.unrepr: self.list_values = False comment_list = [] done_start = False this_section = self maxline = len(infile) - 1 cur_index = -1 reset_comment = False while cur_index < maxline: if reset_comment: comment_list = [] cur_index += 1 line = infile[cur_index] sline = line.strip() # do we have anything on the line ? if not sline or sline.startswith('#'): reset_comment = False comment_list.append(line) continue if not done_start: # preserve initial comment self.initial_comment = comment_list comment_list = [] done_start = True reset_comment = True # first we check if it's a section marker mat = self._sectionmarker.match(line) if mat is not None: # is a section line (indent, sect_open, sect_name, sect_close, comment) = mat.groups() if indent and (self.indent_type is None): self.indent_type = indent cur_depth = sect_open.count('[') if cur_depth != sect_close.count(']'): self._handle_error("Cannot compute the section depth at line %s.", NestingError, infile, cur_index) continue if cur_depth < this_section.depth: # the new section is dropping back to a previous level try: parent = self._match_depth(this_section, cur_depth).parent except SyntaxError: self._handle_error("Cannot compute nesting level at line %s.", NestingError, infile, cur_index) continue elif cur_depth == this_section.depth: # the new section is a sibling of the current section parent = this_section.parent elif cur_depth == this_section.depth + 1: # the new section is a child the current section parent = this_section else: self._handle_error("Section too nested at line %s.", NestingError, infile, cur_index) sect_name = self._unquote(sect_name) if sect_name in parent: self._handle_error('Duplicate section name at line %s.', DuplicateError, infile, cur_index) continue # create the new section this_section = Section( parent, cur_depth, self, name=sect_name) parent[sect_name] = this_section parent.inline_comments[sect_name] = comment parent.comments[sect_name] = comment_list continue # # it's not a section marker, # so it should be a valid ``key = value`` line mat = self._keyword.match(line) if mat is None: # it neither matched as a keyword # or a section marker self._handle_error( 'Invalid line at line "%s".', ParseError, infile, cur_index) else: # is a keyword value # value will include any inline comment (indent, key, value) = mat.groups() if indent and (self.indent_type is None): self.indent_type = indent # check for a multiline value if value[:3] in ['"""', "'''"]: try: value, comment, cur_index = self._multiline( value, infile, cur_index, maxline) except SyntaxError: self._handle_error( 'Parse error in value at line %s.', ParseError, infile, cur_index) continue else: if self.unrepr: comment = '' try: value = unrepr(value) except Exception, e: if type(e) == UnknownType: msg = 'Unknown name or type in value at line %s.' else: msg = 'Parse error in value at line %s.' self._handle_error(msg, UnreprError, infile, cur_index) continue else: if self.unrepr: comment = '' try: value = unrepr(value) except Exception, e: if isinstance(e, UnknownType): msg = 'Unknown name or type in value at line %s.' else: msg = 'Parse error in value at line %s.' self._handle_error(msg, UnreprError, infile, cur_index) continue else: # extract comment and lists try: (value, comment) = self._handle_value(value) except SyntaxError: self._handle_error( 'Parse error in value at line %s.', ParseError, infile, cur_index) continue # key = self._unquote(key) if key in this_section: self._handle_error( 'Duplicate keyword name at line %s.', DuplicateError, infile, cur_index) continue # add the key. # we set unrepr because if we have got this far we will never # be creating a new section this_section.__setitem__(key, value, unrepr=True) this_section.inline_comments[key] = comment this_section.comments[key] = comment_list continue # if self.indent_type is None: # no indentation used, set the type accordingly self.indent_type = '' # preserve the final comment if not self and not self.initial_comment: self.initial_comment = comment_list elif not reset_comment: self.final_comment = comment_list self.list_values = temp_list_values
[ "def", "_parse", "(", "self", ",", "infile", ")", ":", "temp_list_values", "=", "self", ".", "list_values", "if", "self", ".", "unrepr", ":", "self", ".", "list_values", "=", "False", "comment_list", "=", "[", "]", "done_start", "=", "False", "this_section", "=", "self", "maxline", "=", "len", "(", "infile", ")", "-", "1", "cur_index", "=", "-", "1", "reset_comment", "=", "False", "while", "cur_index", "<", "maxline", ":", "if", "reset_comment", ":", "comment_list", "=", "[", "]", "cur_index", "+=", "1", "line", "=", "infile", "[", "cur_index", "]", "sline", "=", "line", ".", "strip", "(", ")", "# do we have anything on the line ?", "if", "not", "sline", "or", "sline", ".", "startswith", "(", "'#'", ")", ":", "reset_comment", "=", "False", "comment_list", ".", "append", "(", "line", ")", "continue", "if", "not", "done_start", ":", "# preserve initial comment", "self", ".", "initial_comment", "=", "comment_list", "comment_list", "=", "[", "]", "done_start", "=", "True", "reset_comment", "=", "True", "# first we check if it's a section marker", "mat", "=", "self", ".", "_sectionmarker", ".", "match", "(", "line", ")", "if", "mat", "is", "not", "None", ":", "# is a section line", "(", "indent", ",", "sect_open", ",", "sect_name", ",", "sect_close", ",", "comment", ")", "=", "mat", ".", "groups", "(", ")", "if", "indent", "and", "(", "self", ".", "indent_type", "is", "None", ")", ":", "self", ".", "indent_type", "=", "indent", "cur_depth", "=", "sect_open", ".", "count", "(", "'['", ")", "if", "cur_depth", "!=", "sect_close", ".", "count", "(", "']'", ")", ":", "self", ".", "_handle_error", "(", "\"Cannot compute the section depth at line %s.\"", ",", "NestingError", ",", "infile", ",", "cur_index", ")", "continue", "if", "cur_depth", "<", "this_section", ".", "depth", ":", "# the new section is dropping back to a previous level", "try", ":", "parent", "=", "self", ".", "_match_depth", "(", "this_section", ",", "cur_depth", ")", ".", "parent", "except", "SyntaxError", ":", "self", ".", "_handle_error", "(", "\"Cannot compute nesting level at line %s.\"", ",", "NestingError", ",", "infile", ",", "cur_index", ")", "continue", "elif", "cur_depth", "==", "this_section", ".", "depth", ":", "# the new section is a sibling of the current section", "parent", "=", "this_section", ".", "parent", "elif", "cur_depth", "==", "this_section", ".", "depth", "+", "1", ":", "# the new section is a child the current section", "parent", "=", "this_section", "else", ":", "self", ".", "_handle_error", "(", "\"Section too nested at line %s.\"", ",", "NestingError", ",", "infile", ",", "cur_index", ")", "sect_name", "=", "self", ".", "_unquote", "(", "sect_name", ")", "if", "sect_name", "in", "parent", ":", "self", ".", "_handle_error", "(", "'Duplicate section name at line %s.'", ",", "DuplicateError", ",", "infile", ",", "cur_index", ")", "continue", "# create the new section", "this_section", "=", "Section", "(", "parent", ",", "cur_depth", ",", "self", ",", "name", "=", "sect_name", ")", "parent", "[", "sect_name", "]", "=", "this_section", "parent", ".", "inline_comments", "[", "sect_name", "]", "=", "comment", "parent", ".", "comments", "[", "sect_name", "]", "=", "comment_list", "continue", "#", "# it's not a section marker,", "# so it should be a valid ``key = value`` line", "mat", "=", "self", ".", "_keyword", ".", "match", "(", "line", ")", "if", "mat", "is", "None", ":", "# it neither matched as a keyword", "# or a section marker", "self", ".", "_handle_error", "(", "'Invalid line at line \"%s\".'", ",", "ParseError", ",", "infile", ",", "cur_index", ")", "else", ":", "# is a keyword value", "# value will include any inline comment", "(", "indent", ",", "key", ",", "value", ")", "=", "mat", ".", "groups", "(", ")", "if", "indent", "and", "(", "self", ".", "indent_type", "is", "None", ")", ":", "self", ".", "indent_type", "=", "indent", "# check for a multiline value", "if", "value", "[", ":", "3", "]", "in", "[", "'\"\"\"'", ",", "\"'''\"", "]", ":", "try", ":", "value", ",", "comment", ",", "cur_index", "=", "self", ".", "_multiline", "(", "value", ",", "infile", ",", "cur_index", ",", "maxline", ")", "except", "SyntaxError", ":", "self", ".", "_handle_error", "(", "'Parse error in value at line %s.'", ",", "ParseError", ",", "infile", ",", "cur_index", ")", "continue", "else", ":", "if", "self", ".", "unrepr", ":", "comment", "=", "''", "try", ":", "value", "=", "unrepr", "(", "value", ")", "except", "Exception", ",", "e", ":", "if", "type", "(", "e", ")", "==", "UnknownType", ":", "msg", "=", "'Unknown name or type in value at line %s.'", "else", ":", "msg", "=", "'Parse error in value at line %s.'", "self", ".", "_handle_error", "(", "msg", ",", "UnreprError", ",", "infile", ",", "cur_index", ")", "continue", "else", ":", "if", "self", ".", "unrepr", ":", "comment", "=", "''", "try", ":", "value", "=", "unrepr", "(", "value", ")", "except", "Exception", ",", "e", ":", "if", "isinstance", "(", "e", ",", "UnknownType", ")", ":", "msg", "=", "'Unknown name or type in value at line %s.'", "else", ":", "msg", "=", "'Parse error in value at line %s.'", "self", ".", "_handle_error", "(", "msg", ",", "UnreprError", ",", "infile", ",", "cur_index", ")", "continue", "else", ":", "# extract comment and lists", "try", ":", "(", "value", ",", "comment", ")", "=", "self", ".", "_handle_value", "(", "value", ")", "except", "SyntaxError", ":", "self", ".", "_handle_error", "(", "'Parse error in value at line %s.'", ",", "ParseError", ",", "infile", ",", "cur_index", ")", "continue", "#", "key", "=", "self", ".", "_unquote", "(", "key", ")", "if", "key", "in", "this_section", ":", "self", ".", "_handle_error", "(", "'Duplicate keyword name at line %s.'", ",", "DuplicateError", ",", "infile", ",", "cur_index", ")", "continue", "# add the key.", "# we set unrepr because if we have got this far we will never", "# be creating a new section", "this_section", ".", "__setitem__", "(", "key", ",", "value", ",", "unrepr", "=", "True", ")", "this_section", ".", "inline_comments", "[", "key", "]", "=", "comment", "this_section", ".", "comments", "[", "key", "]", "=", "comment_list", "continue", "#", "if", "self", ".", "indent_type", "is", "None", ":", "# no indentation used, set the type accordingly", "self", ".", "indent_type", "=", "''", "# preserve the final comment", "if", "not", "self", "and", "not", "self", ".", "initial_comment", ":", "self", ".", "initial_comment", "=", "comment_list", "elif", "not", "reset_comment", ":", "self", ".", "final_comment", "=", "comment_list", "self", ".", "list_values", "=", "temp_list_values" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/configobj/configobj.py#L1533-L1698
junhyukoh/caffe-lstm
598d45456fa2a1b127a644f4aa38daa8fb9fc722
python/caffe/io.py
python
datum_to_array
(datum)
Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label.
Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label.
[ "Converts", "a", "datum", "to", "an", "array", ".", "Note", "that", "the", "label", "is", "not", "returned", "as", "one", "can", "easily", "get", "it", "by", "calling", "datum", ".", "label", "." ]
def datum_to_array(datum): """Converts a datum to an array. Note that the label is not returned, as one can easily get it by calling datum.label. """ if len(datum.data): return np.fromstring(datum.data, dtype=np.uint8).reshape( datum.channels, datum.height, datum.width) else: return np.array(datum.float_data).astype(float).reshape( datum.channels, datum.height, datum.width)
[ "def", "datum_to_array", "(", "datum", ")", ":", "if", "len", "(", "datum", ".", "data", ")", ":", "return", "np", ".", "fromstring", "(", "datum", ".", "data", ",", "dtype", "=", "np", ".", "uint8", ")", ".", "reshape", "(", "datum", ".", "channels", ",", "datum", ".", "height", ",", "datum", ".", "width", ")", "else", ":", "return", "np", ".", "array", "(", "datum", ".", "float_data", ")", ".", "astype", "(", "float", ")", ".", "reshape", "(", "datum", ".", "channels", ",", "datum", ".", "height", ",", "datum", ".", "width", ")" ]
https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/python/caffe/io.py#L80-L89
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
InputStream.flush
(*args, **kwargs)
return _core_.InputStream_flush(*args, **kwargs)
flush(self)
flush(self)
[ "flush", "(", "self", ")" ]
def flush(*args, **kwargs): """flush(self)""" return _core_.InputStream_flush(*args, **kwargs)
[ "def", "flush", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "InputStream_flush", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2162-L2164
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py
python
PtyProcess.sendeof
(self)
return self._writeb(_EOF), _EOF
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line.
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line.
[ "This", "sends", "an", "EOF", "to", "the", "child", ".", "This", "sends", "a", "character", "which", "causes", "the", "pending", "parent", "output", "buffer", "to", "be", "sent", "to", "the", "waiting", "child", "program", "without", "waiting", "for", "end", "-", "of", "-", "line", ".", "If", "it", "is", "the", "first", "character", "of", "the", "line", "the", "read", "()", "in", "the", "user", "program", "returns", "0", "which", "signifies", "end", "-", "of", "-", "file", ".", "This", "means", "to", "work", "as", "expected", "a", "sendeof", "()", "has", "to", "be", "called", "at", "the", "beginning", "of", "a", "line", ".", "This", "method", "does", "not", "send", "a", "newline", ".", "It", "is", "the", "responsibility", "of", "the", "caller", "to", "ensure", "the", "eof", "is", "sent", "at", "the", "beginning", "of", "a", "line", "." ]
def sendeof(self): '''This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. This means to work as expected a sendeof() has to be called at the beginning of a line. This method does not send a newline. It is the responsibility of the caller to ensure the eof is sent at the beginning of a line. ''' return self._writeb(_EOF), _EOF
[ "def", "sendeof", "(", "self", ")", ":", "return", "self", ".", "_writeb", "(", "_EOF", ")", ",", "_EOF" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L592-L602
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/generator/cmake.py
python
WriteRules
(target_name, rules, extra_sources, extra_deps, path_to_gyp, output)
Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined.
Write CMake for the 'rules' in the target.
[ "Write", "CMake", "for", "the", "rules", "in", "the", "target", "." ]
def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for rule in rules: rule_name = StringToCMakeTargetName(target_name + '__' + rule['rule_name']) inputs = rule.get('inputs', []) inputs_name = rule_name + '__input' SetVariableList(output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs]) outputs = rule['outputs'] var_outputs = [] for count, rule_source in enumerate(rule.get('rule_sources', [])): action_name = rule_name + '_' + str(count) rule_source_dirname, rule_source_basename = os.path.split(rule_source) rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename) SetVariable(output, 'RULE_INPUT_PATH', rule_source) SetVariable(output, 'RULE_INPUT_DIRNAME', rule_source_dirname) SetVariable(output, 'RULE_INPUT_NAME', rule_source_basename) SetVariable(output, 'RULE_INPUT_ROOT', rule_source_root) SetVariable(output, 'RULE_INPUT_EXT', rule_source_ext) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) # Create variables for the output, as 'local' variable will be unset. these_outputs = [] for output_index, out in enumerate(outputs): output_name = action_name + '_' + str(output_index) SetVariable(output, output_name, NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source)) if int(rule.get('process_outputs_as_sources', False)): extra_sources.append(('${' + output_name + '}', out)) these_outputs.append('${' + output_name + '}') var_outputs.append('${' + output_name + '}') # add_custom_command output.write('add_custom_command(OUTPUT\n') for out in these_outputs: output.write(' ') output.write(out) output.write('\n') for directory in dirs: output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ') output.write(directory) output.write('\n') output.write(' COMMAND ') output.write(gyp.common.EncodePOSIXShellList(rule['action'])) output.write('\n') output.write(' DEPENDS ') WriteVariable(output, inputs_name) output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') # CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives. # The cwd is the current build directory. output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/') output.write(path_to_gyp) output.write('\n') output.write(' COMMENT ') if 'message' in rule: output.write(rule['message']) else: output.write(action_name) output.write('\n') output.write(' VERBATIM\n') output.write(')\n') UnsetVariable(output, 'RULE_INPUT_PATH') UnsetVariable(output, 'RULE_INPUT_DIRNAME') UnsetVariable(output, 'RULE_INPUT_NAME') UnsetVariable(output, 'RULE_INPUT_ROOT') UnsetVariable(output, 'RULE_INPUT_EXT') # add_custom_target output.write('add_custom_target(') output.write(rule_name) output.write(' DEPENDS\n') for out in var_outputs: output.write(' ') output.write(out) output.write('\n') output.write('SOURCES ') WriteVariable(output, inputs_name) output.write('\n') for rule_source in rule.get('rule_sources', []): output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') output.write(')\n') extra_deps.append(rule_name)
[ "def", "WriteRules", "(", "target_name", ",", "rules", ",", "extra_sources", ",", "extra_deps", ",", "path_to_gyp", ",", "output", ")", ":", "for", "rule", "in", "rules", ":", "rule_name", "=", "StringToCMakeTargetName", "(", "target_name", "+", "'__'", "+", "rule", "[", "'rule_name'", "]", ")", "inputs", "=", "rule", ".", "get", "(", "'inputs'", ",", "[", "]", ")", "inputs_name", "=", "rule_name", "+", "'__input'", "SetVariableList", "(", "output", ",", "inputs_name", ",", "[", "NormjoinPathForceCMakeSource", "(", "path_to_gyp", ",", "dep", ")", "for", "dep", "in", "inputs", "]", ")", "outputs", "=", "rule", "[", "'outputs'", "]", "var_outputs", "=", "[", "]", "for", "count", ",", "rule_source", "in", "enumerate", "(", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ")", ":", "action_name", "=", "rule_name", "+", "'_'", "+", "str", "(", "count", ")", "rule_source_dirname", ",", "rule_source_basename", "=", "os", ".", "path", ".", "split", "(", "rule_source", ")", "rule_source_root", ",", "rule_source_ext", "=", "os", ".", "path", ".", "splitext", "(", "rule_source_basename", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_PATH'", ",", "rule_source", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_DIRNAME'", ",", "rule_source_dirname", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_NAME'", ",", "rule_source_basename", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_ROOT'", ",", "rule_source_root", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_EXT'", ",", "rule_source_ext", ")", "# Build up a list of outputs.", "# Collect the output dirs we'll need.", "dirs", "=", "set", "(", "dir", "for", "dir", "in", "(", "os", ".", "path", ".", "dirname", "(", "o", ")", "for", "o", "in", "outputs", ")", "if", "dir", ")", "# Create variables for the output, as 'local' variable will be unset.", "these_outputs", "=", "[", "]", "for", "output_index", ",", "out", "in", "enumerate", "(", "outputs", ")", ":", "output_name", "=", "action_name", "+", "'_'", "+", "str", "(", "output_index", ")", "SetVariable", "(", "output", ",", "output_name", ",", "NormjoinRulePathForceCMakeSource", "(", "path_to_gyp", ",", "out", ",", "rule_source", ")", ")", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", ".", "append", "(", "(", "'${'", "+", "output_name", "+", "'}'", ",", "out", ")", ")", "these_outputs", ".", "append", "(", "'${'", "+", "output_name", "+", "'}'", ")", "var_outputs", ".", "append", "(", "'${'", "+", "output_name", "+", "'}'", ")", "# add_custom_command", "output", ".", "write", "(", "'add_custom_command(OUTPUT\\n'", ")", "for", "out", "in", "these_outputs", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "out", ")", "output", ".", "write", "(", "'\\n'", ")", "for", "directory", "in", "dirs", ":", "output", ".", "write", "(", "' COMMAND ${CMAKE_COMMAND} -E make_directory '", ")", "output", ".", "write", "(", "directory", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' COMMAND '", ")", "output", ".", "write", "(", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "rule", "[", "'action'", "]", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' DEPENDS '", ")", "WriteVariable", "(", "output", ",", "inputs_name", ")", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "NormjoinPath", "(", "path_to_gyp", ",", "rule_source", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "# CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives.", "# The cwd is the current build directory.", "output", ".", "write", "(", "' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/'", ")", "output", ".", "write", "(", "path_to_gyp", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' COMMENT '", ")", "if", "'message'", "in", "rule", ":", "output", ".", "write", "(", "rule", "[", "'message'", "]", ")", "else", ":", "output", ".", "write", "(", "action_name", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' VERBATIM\\n'", ")", "output", ".", "write", "(", "')\\n'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_PATH'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_DIRNAME'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_NAME'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_ROOT'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_EXT'", ")", "# add_custom_target", "output", ".", "write", "(", "'add_custom_target('", ")", "output", ".", "write", "(", "rule_name", ")", "output", ".", "write", "(", "' DEPENDS\\n'", ")", "for", "out", "in", "var_outputs", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "out", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "'SOURCES '", ")", "WriteVariable", "(", "output", ",", "inputs_name", ")", "output", ".", "write", "(", "'\\n'", ")", "for", "rule_source", "in", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "NormjoinPath", "(", "path_to_gyp", ",", "rule_source", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "')\\n'", ")", "extra_deps", ".", "append", "(", "rule_name", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/cmake.py#L335-L446
AstarLight/Lets_OCR
b2af7120a34d785434c96e820b6eb1aa69269d20
recognizer/crnn/lib/convert.py
python
StrConverter.encode
(self, text)
return (torch.IntTensor(text), torch.IntTensor(length))
Support batch or single str. Args: text (str or list of str): texts to convert. Returns: torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts. torch.IntTensor [n]: length of each text.
Support batch or single str.
[ "Support", "batch", "or", "single", "str", "." ]
def encode(self, text): """Support batch or single str. Args: text (str or list of str): texts to convert. Returns: torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts. torch.IntTensor [n]: length of each text. """ if isinstance(text, str): text = [self.dict[char] for char in text] length = [len(text)] elif isinstance(text, collections.Iterable): length = [len(s) for s in text] text = ''.join(text) text, _ = self.encode(text) return (torch.IntTensor(text), torch.IntTensor(length))
[ "def", "encode", "(", "self", ",", "text", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "[", "self", ".", "dict", "[", "char", "]", "for", "char", "in", "text", "]", "length", "=", "[", "len", "(", "text", ")", "]", "elif", "isinstance", "(", "text", ",", "collections", ".", "Iterable", ")", ":", "length", "=", "[", "len", "(", "s", ")", "for", "s", "in", "text", "]", "text", "=", "''", ".", "join", "(", "text", ")", "text", ",", "_", "=", "self", ".", "encode", "(", "text", ")", "return", "(", "torch", ".", "IntTensor", "(", "text", ")", ",", "torch", ".", "IntTensor", "(", "length", ")", ")" ]
https://github.com/AstarLight/Lets_OCR/blob/b2af7120a34d785434c96e820b6eb1aa69269d20/recognizer/crnn/lib/convert.py#L101-L118
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/multi.py
python
MultiIndex.insert
(self, loc: int, item)
return MultiIndex( levels=new_levels, codes=new_codes, names=self.names, verify_integrity=False )
Make new MultiIndex inserting new item at location Parameters ---------- loc : int item : tuple Must be same length as number of levels in the MultiIndex Returns ------- new_index : Index
Make new MultiIndex inserting new item at location
[ "Make", "new", "MultiIndex", "inserting", "new", "item", "at", "location" ]
def insert(self, loc: int, item) -> MultiIndex: """ Make new MultiIndex inserting new item at location Parameters ---------- loc : int item : tuple Must be same length as number of levels in the MultiIndex Returns ------- new_index : Index """ item = self._validate_fill_value(item) new_levels = [] new_codes = [] for k, level, level_codes in zip(item, self.levels, self.codes): if k not in level: # have to insert into level # must insert at end otherwise you have to recompute all the # other codes lev_loc = len(level) level = level.insert(lev_loc, k) else: lev_loc = level.get_loc(k) new_levels.append(level) new_codes.append(np.insert(ensure_int64(level_codes), loc, lev_loc)) return MultiIndex( levels=new_levels, codes=new_codes, names=self.names, verify_integrity=False )
[ "def", "insert", "(", "self", ",", "loc", ":", "int", ",", "item", ")", "->", "MultiIndex", ":", "item", "=", "self", ".", "_validate_fill_value", "(", "item", ")", "new_levels", "=", "[", "]", "new_codes", "=", "[", "]", "for", "k", ",", "level", ",", "level_codes", "in", "zip", "(", "item", ",", "self", ".", "levels", ",", "self", ".", "codes", ")", ":", "if", "k", "not", "in", "level", ":", "# have to insert into level", "# must insert at end otherwise you have to recompute all the", "# other codes", "lev_loc", "=", "len", "(", "level", ")", "level", "=", "level", ".", "insert", "(", "lev_loc", ",", "k", ")", "else", ":", "lev_loc", "=", "level", ".", "get_loc", "(", "k", ")", "new_levels", ".", "append", "(", "level", ")", "new_codes", ".", "append", "(", "np", ".", "insert", "(", "ensure_int64", "(", "level_codes", ")", ",", "loc", ",", "lev_loc", ")", ")", "return", "MultiIndex", "(", "levels", "=", "new_levels", ",", "codes", "=", "new_codes", ",", "names", "=", "self", ".", "names", ",", "verify_integrity", "=", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L3670-L3703
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py
python
variables_initializer
(var_list, name="init")
return control_flow_ops.no_op(name=name)
Returns an Op that initializes a list of variables. After you launch the graph in a session, you can run the returned Op to initialize all the variables in `var_list`. This Op runs all the initializers of the variables in `var_list` in parallel. Calling `initialize_variables()` is equivalent to passing the list of initializers to `Group()`. If `var_list` is empty, however, the function still returns an Op that can be run. That Op just has no effect. Args: var_list: List of `Variable` objects to initialize. name: Optional name for the returned operation. Returns: An Op that run the initializers of all the specified variables.
Returns an Op that initializes a list of variables.
[ "Returns", "an", "Op", "that", "initializes", "a", "list", "of", "variables", "." ]
def variables_initializer(var_list, name="init"): """Returns an Op that initializes a list of variables. After you launch the graph in a session, you can run the returned Op to initialize all the variables in `var_list`. This Op runs all the initializers of the variables in `var_list` in parallel. Calling `initialize_variables()` is equivalent to passing the list of initializers to `Group()`. If `var_list` is empty, however, the function still returns an Op that can be run. That Op just has no effect. Args: var_list: List of `Variable` objects to initialize. name: Optional name for the returned operation. Returns: An Op that run the initializers of all the specified variables. """ if var_list and not context.executing_eagerly(): return control_flow_ops.group(*[v.initializer for v in var_list], name=name) return control_flow_ops.no_op(name=name)
[ "def", "variables_initializer", "(", "var_list", ",", "name", "=", "\"init\"", ")", ":", "if", "var_list", "and", "not", "context", ".", "executing_eagerly", "(", ")", ":", "return", "control_flow_ops", ".", "group", "(", "*", "[", "v", ".", "initializer", "for", "v", "in", "var_list", "]", ",", "name", "=", "name", ")", "return", "control_flow_ops", ".", "no_op", "(", "name", "=", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py#L3196-L3218
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/third_party/Python/module/pexpect-2.4/FSM.py
python
FSM.process_list
(self, input_symbols)
This takes a list and sends each element to process(). The list may be a string or any iterable object.
This takes a list and sends each element to process(). The list may be a string or any iterable object.
[ "This", "takes", "a", "list", "and", "sends", "each", "element", "to", "process", "()", ".", "The", "list", "may", "be", "a", "string", "or", "any", "iterable", "object", "." ]
def process_list(self, input_symbols): """This takes a list and sends each element to process(). The list may be a string or any iterable object. """ for s in input_symbols: self.process(s)
[ "def", "process_list", "(", "self", ",", "input_symbols", ")", ":", "for", "s", "in", "input_symbols", ":", "self", ".", "process", "(", "s", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/FSM.py#L232-L237
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/tabart.py
python
AuiSimpleTabArt.SetSelectedFont
(self, font)
Sets the selected tab font for drawing tab labels. :param Font `font`: the new font to use to draw tab labels in their selected state.
Sets the selected tab font for drawing tab labels.
[ "Sets", "the", "selected", "tab", "font", "for", "drawing", "tab", "labels", "." ]
def SetSelectedFont(self, font): """ Sets the selected tab font for drawing tab labels. :param Font `font`: the new font to use to draw tab labels in their selected state. """ self._selected_font = font
[ "def", "SetSelectedFont", "(", "self", ",", "font", ")", ":", "self", ".", "_selected_font", "=", "font" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/tabart.py#L1569-L1576
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
docs/custom_inheritance_diagram/btd/sphinx/inheritance_diagram.py
python
texinfo_visit_inheritance_diagram
( self: TexinfoTranslator, node: inheritance_diagram )
Output the graph for Texinfo. This will insert a PNG.
Output the graph for Texinfo. This will insert a PNG.
[ "Output", "the", "graph", "for", "Texinfo", ".", "This", "will", "insert", "a", "PNG", "." ]
def texinfo_visit_inheritance_diagram( self: TexinfoTranslator, node: inheritance_diagram ) -> None: """ Output the graph for Texinfo. This will insert a PNG. """ graph = node["graph"] graph_hash = get_graph_hash(node) name = "inheritance%s" % graph_hash dotcode = graph.generate_dot( name, env=self.builder.env, graph_attrs={"size": '"6.0,6.0"'} ) render_dot_texinfo(self, node, dotcode, {}, "inheritance") raise nodes.SkipNode
[ "def", "texinfo_visit_inheritance_diagram", "(", "self", ":", "TexinfoTranslator", ",", "node", ":", "inheritance_diagram", ")", "->", "None", ":", "graph", "=", "node", "[", "\"graph\"", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "\"inheritance%s\"", "%", "graph_hash", "dotcode", "=", "graph", ".", "generate_dot", "(", "name", ",", "env", "=", "self", ".", "builder", ".", "env", ",", "graph_attrs", "=", "{", "\"size\"", ":", "'\"6.0,6.0\"'", "}", ")", "render_dot_texinfo", "(", "self", ",", "node", ",", "dotcode", ",", "{", "}", ",", "\"inheritance\"", ")", "raise", "nodes", ".", "SkipNode" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/docs/custom_inheritance_diagram/btd/sphinx/inheritance_diagram.py#L515-L530
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/ExodusViewer/plugins/BlockPlugin.py
python
BlockPlugin.onUpdateWindow
(self, window, reader, result)
Update the block list, if needed.
Update the block list, if needed.
[ "Update", "the", "block", "list", "if", "needed", "." ]
def onUpdateWindow(self, window, reader, result): """ Update the block list, if needed. """ blocks = self._blocksChanged(reader, self.BlockSelector, chigger.exodus.ExodusReader.BLOCK) sideset = self._blocksChanged(reader, self.SidesetSelector, chigger.exodus.ExodusReader.SIDESET) nodeset = self._blocksChanged(reader, self.NodesetSelector, chigger.exodus.ExodusReader.NODESET) if any([blocks, sideset, nodeset]): self.onSetupResult(result)
[ "def", "onUpdateWindow", "(", "self", ",", "window", ",", "reader", ",", "result", ")", ":", "blocks", "=", "self", ".", "_blocksChanged", "(", "reader", ",", "self", ".", "BlockSelector", ",", "chigger", ".", "exodus", ".", "ExodusReader", ".", "BLOCK", ")", "sideset", "=", "self", ".", "_blocksChanged", "(", "reader", ",", "self", ".", "SidesetSelector", ",", "chigger", ".", "exodus", ".", "ExodusReader", ".", "SIDESET", ")", "nodeset", "=", "self", ".", "_blocksChanged", "(", "reader", ",", "self", ".", "NodesetSelector", ",", "chigger", ".", "exodus", ".", "ExodusReader", ".", "NODESET", ")", "if", "any", "(", "[", "blocks", ",", "sideset", ",", "nodeset", "]", ")", ":", "self", ".", "onSetupResult", "(", "result", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/BlockPlugin.py#L91-L99
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozpack/mozjar.py
python
Deflater._flush
(self)
Flush the underlying zlib compression object.
Flush the underlying zlib compression object.
[ "Flush", "the", "underlying", "zlib", "compression", "object", "." ]
def _flush(self): ''' Flush the underlying zlib compression object. ''' if self.compress and self._deflater: self._deflated.write(self._deflater.flush()) self._deflater = None
[ "def", "_flush", "(", "self", ")", ":", "if", "self", ".", "compress", "and", "self", ".", "_deflater", ":", "self", ".", "_deflated", ".", "write", "(", "self", ".", "_deflater", ".", "flush", "(", ")", ")", "self", ".", "_deflater", "=", "None" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/mozjar.py#L685-L691
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Tools/gdc.py
python
common_flags_gdc
(conf)
Sets the flags required by *gdc*
Sets the flags required by *gdc*
[ "Sets", "the", "flags", "required", "by", "*", "gdc", "*" ]
def common_flags_gdc(conf): """ Sets the flags required by *gdc* """ v = conf.env v.DFLAGS = [] v.D_SRC_F = ['-c'] v.D_TGT_F = '-o%s' v.D_LINKER = v.D v.DLNK_SRC_F = '' v.DLNK_TGT_F = '-o%s' v.DINC_ST = '-I%s' v.DSHLIB_MARKER = v.DSTLIB_MARKER = '' v.DSTLIB_ST = v.DSHLIB_ST = '-l%s' v.DSTLIBPATH_ST = v.DLIBPATH_ST = '-L%s' v.LINKFLAGS_dshlib = ['-shared'] v.DHEADER_ext = '.di' v.DFLAGS_d_with_header = '-fintfc' v.D_HDR_F = '-fintfc-file=%s'
[ "def", "common_flags_gdc", "(", "conf", ")", ":", "v", "=", "conf", ".", "env", "v", ".", "DFLAGS", "=", "[", "]", "v", ".", "D_SRC_F", "=", "[", "'-c'", "]", "v", ".", "D_TGT_F", "=", "'-o%s'", "v", ".", "D_LINKER", "=", "v", ".", "D", "v", ".", "DLNK_SRC_F", "=", "''", "v", ".", "DLNK_TGT_F", "=", "'-o%s'", "v", ".", "DINC_ST", "=", "'-I%s'", "v", ".", "DSHLIB_MARKER", "=", "v", ".", "DSTLIB_MARKER", "=", "''", "v", ".", "DSTLIB_ST", "=", "v", ".", "DSHLIB_ST", "=", "'-l%s'", "v", ".", "DSTLIBPATH_ST", "=", "v", ".", "DLIBPATH_ST", "=", "'-L%s'", "v", ".", "LINKFLAGS_dshlib", "=", "[", "'-shared'", "]", "v", ".", "DHEADER_ext", "=", "'.di'", "v", ".", "DFLAGS_d_with_header", "=", "'-fintfc'", "v", ".", "D_HDR_F", "=", "'-fintfc-file=%s'" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/gdc.py#L20-L44
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/ndimage/measurements.py
python
find_objects
(input, max_label=0)
return _nd_image.find_objects(input, max_label)
Find objects in a labeled array. Parameters ---------- input : ndarray of ints Array containing objects defined by different labels. Labels with value 0 are ignored. max_label : int, optional Maximum label to be searched for in `input`. If max_label is not given, the positions of all objects are returned. Returns ------- object_slices : list of tuples A list of tuples, with each tuple containing N slices (with N the dimension of the input array). Slices correspond to the minimal parallelepiped that contains the object. If a number is missing, None is returned instead of a slice. See Also -------- label, center_of_mass Notes ----- This function is very useful for isolating a volume of interest inside a 3-D array, that cannot be "seen through". Examples -------- >>> from scipy import ndimage >>> a = np.zeros((6,6), dtype=int) >>> a[2:4, 2:4] = 1 >>> a[4, 4] = 1 >>> a[:2, :3] = 2 >>> a[0, 5] = 3 >>> a array([[2, 2, 2, 0, 0, 3], [2, 2, 2, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) >>> ndimage.find_objects(a) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None)), (slice(0, 1, None), slice(5, 6, None))] >>> ndimage.find_objects(a, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))] >>> ndimage.find_objects(a == 1, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), None] >>> loc = ndimage.find_objects(a)[0] >>> a[loc] array([[1, 1, 0], [1, 1, 0], [0, 0, 1]])
Find objects in a labeled array.
[ "Find", "objects", "in", "a", "labeled", "array", "." ]
def find_objects(input, max_label=0): """ Find objects in a labeled array. Parameters ---------- input : ndarray of ints Array containing objects defined by different labels. Labels with value 0 are ignored. max_label : int, optional Maximum label to be searched for in `input`. If max_label is not given, the positions of all objects are returned. Returns ------- object_slices : list of tuples A list of tuples, with each tuple containing N slices (with N the dimension of the input array). Slices correspond to the minimal parallelepiped that contains the object. If a number is missing, None is returned instead of a slice. See Also -------- label, center_of_mass Notes ----- This function is very useful for isolating a volume of interest inside a 3-D array, that cannot be "seen through". Examples -------- >>> from scipy import ndimage >>> a = np.zeros((6,6), dtype=int) >>> a[2:4, 2:4] = 1 >>> a[4, 4] = 1 >>> a[:2, :3] = 2 >>> a[0, 5] = 3 >>> a array([[2, 2, 2, 0, 0, 3], [2, 2, 2, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) >>> ndimage.find_objects(a) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None)), (slice(0, 1, None), slice(5, 6, None))] >>> ndimage.find_objects(a, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))] >>> ndimage.find_objects(a == 1, max_label=2) [(slice(2, 5, None), slice(2, 5, None)), None] >>> loc = ndimage.find_objects(a)[0] >>> a[loc] array([[1, 1, 0], [1, 1, 0], [0, 0, 1]]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') if max_label < 1: max_label = input.max() return _nd_image.find_objects(input, max_label)
[ "def", "find_objects", "(", "input", ",", "max_label", "=", "0", ")", ":", "input", "=", "numpy", ".", "asarray", "(", "input", ")", "if", "numpy", ".", "iscomplexobj", "(", "input", ")", ":", "raise", "TypeError", "(", "'Complex type not supported'", ")", "if", "max_label", "<", "1", ":", "max_label", "=", "input", ".", "max", "(", ")", "return", "_nd_image", ".", "find_objects", "(", "input", ",", "max_label", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/measurements.py#L206-L272
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/youtube/youtube_api.py
python
Videos.setTreeViewIcon
(self, dir_icon=None)
return self.tree_dir_icon
Check if there is a specific generic tree view icon. If not default to the channel icon. return self.tree_dir_icon
Check if there is a specific generic tree view icon. If not default to the channel icon. return self.tree_dir_icon
[ "Check", "if", "there", "is", "a", "specific", "generic", "tree", "view", "icon", ".", "If", "not", "default", "to", "the", "channel", "icon", ".", "return", "self", ".", "tree_dir_icon" ]
def setTreeViewIcon(self, dir_icon=None): '''Check if there is a specific generic tree view icon. If not default to the channel icon. return self.tree_dir_icon ''' self.tree_dir_icon = self.channel_icon if not dir_icon: if self.tree_key not in self.feed_icons: return self.tree_dir_icon dir_icon = self.feed_icons[self.tree_key] if not dir_icon: return self.tree_dir_icon self.tree_dir_icon = '%%SHAREDIR%%/mythnetvision/icons/%s.png' % (dir_icon, ) return self.tree_dir_icon
[ "def", "setTreeViewIcon", "(", "self", ",", "dir_icon", "=", "None", ")", ":", "self", ".", "tree_dir_icon", "=", "self", ".", "channel_icon", "if", "not", "dir_icon", ":", "if", "self", ".", "tree_key", "not", "in", "self", ".", "feed_icons", ":", "return", "self", ".", "tree_dir_icon", "dir_icon", "=", "self", ".", "feed_icons", "[", "self", ".", "tree_key", "]", "if", "not", "dir_icon", ":", "return", "self", ".", "tree_dir_icon", "self", ".", "tree_dir_icon", "=", "'%%SHAREDIR%%/mythnetvision/icons/%s.png'", "%", "(", "dir_icon", ",", ")", "return", "self", ".", "tree_dir_icon" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/youtube/youtube_api.py#L350-L362
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/parallel/algo_parameter_config.py
python
get_algo_parameters
(attr_key)
return get_func()
Get the algorithm parameter config attributes. Note: The attribute name is required. This interface works ONLY in AUTO_PARALLEL mode. Args: attr_key (str): The key of the attribute. The keys include: "fully_use_devices", "elementwise_op_strategy_follow", "enable_algo_approxi", "algo_approxi_epsilon", "tensor_slice_align_enable","tensor_slice_align_size". Returns: Return attribute value according to the key. Raises: ValueError: If context keyword is not recognized.
Get the algorithm parameter config attributes.
[ "Get", "the", "algorithm", "parameter", "config", "attributes", "." ]
def get_algo_parameters(attr_key): """ Get the algorithm parameter config attributes. Note: The attribute name is required. This interface works ONLY in AUTO_PARALLEL mode. Args: attr_key (str): The key of the attribute. The keys include: "fully_use_devices", "elementwise_op_strategy_follow", "enable_algo_approxi", "algo_approxi_epsilon", "tensor_slice_align_enable","tensor_slice_align_size". Returns: Return attribute value according to the key. Raises: ValueError: If context keyword is not recognized. """ if attr_key not in get_algo_parameters_config_func_map: raise ValueError("Get context keyword %s is not recognized!" % attr_key) get_func = get_algo_parameters_config_func_map[attr_key] return get_func()
[ "def", "get_algo_parameters", "(", "attr_key", ")", ":", "if", "attr_key", "not", "in", "get_algo_parameters_config_func_map", ":", "raise", "ValueError", "(", "\"Get context keyword %s is not recognized!\"", "%", "attr_key", ")", "get_func", "=", "get_algo_parameters_config_func_map", "[", "attr_key", "]", "return", "get_func", "(", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/parallel/algo_parameter_config.py#L264-L285
google/tink
59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14
python/tink/core/_registry.py
python
Registry.public_key_data
(cls, private_key_data: tink_pb2.KeyData)
return key_mgr.public_key_data(private_key_data)
Generates a new key for the specified key_template.
Generates a new key for the specified key_template.
[ "Generates", "a", "new", "key", "for", "the", "specified", "key_template", "." ]
def public_key_data(cls, private_key_data: tink_pb2.KeyData) -> tink_pb2.KeyData: """Generates a new key for the specified key_template.""" if (private_key_data.key_material_type != tink_pb2.KeyData.ASYMMETRIC_PRIVATE): raise _tink_error.TinkError('The keyset contains a non-private key') key_mgr = cls.key_manager(private_key_data.type_url) if not isinstance(key_mgr, _key_manager.PrivateKeyManager): raise _tink_error.TinkError( 'manager for key type {} is not a PrivateKeyManager' .format(private_key_data.type_url)) return key_mgr.public_key_data(private_key_data)
[ "def", "public_key_data", "(", "cls", ",", "private_key_data", ":", "tink_pb2", ".", "KeyData", ")", "->", "tink_pb2", ".", "KeyData", ":", "if", "(", "private_key_data", ".", "key_material_type", "!=", "tink_pb2", ".", "KeyData", ".", "ASYMMETRIC_PRIVATE", ")", ":", "raise", "_tink_error", ".", "TinkError", "(", "'The keyset contains a non-private key'", ")", "key_mgr", "=", "cls", ".", "key_manager", "(", "private_key_data", ".", "type_url", ")", "if", "not", "isinstance", "(", "key_mgr", ",", "_key_manager", ".", "PrivateKeyManager", ")", ":", "raise", "_tink_error", ".", "TinkError", "(", "'manager for key type {} is not a PrivateKeyManager'", ".", "format", "(", "private_key_data", ".", "type_url", ")", ")", "return", "key_mgr", ".", "public_key_data", "(", "private_key_data", ")" ]
https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/core/_registry.py#L147-L158
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/cmdoptions.py
python
_handle_no_cache_dir
(option, opt, value, parser)
Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option.
Process a value provided for the --no-cache-dir option.
[ "Process", "a", "value", "provided", "for", "the", "--", "no", "-", "cache", "-", "dir", "option", "." ]
def _handle_no_cache_dir(option, opt, value, parser): # type: (Option, str, str, OptionParser) -> None """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc)) # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
[ "def", "_handle_no_cache_dir", "(", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "# type: (Option, str, str, OptionParser) -> None", "# The value argument will be None if --no-cache-dir is passed via the", "# command-line, since the option doesn't accept arguments. However,", "# the value can be non-None if the option is triggered e.g. by an", "# environment variable, like PIP_NO_CACHE_DIR=true.", "if", "value", "is", "not", "None", ":", "# Then parse the string value to get argument error-checking.", "try", ":", "strtobool", "(", "value", ")", "except", "ValueError", "as", "exc", ":", "raise_option_error", "(", "parser", ",", "option", "=", "option", ",", "msg", "=", "str", "(", "exc", ")", ")", "# Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()", "# converted to 0 (like \"false\" or \"no\") caused cache_dir to be disabled", "# rather than enabled (logic would say the latter). Thus, we disable", "# the cache directory not just on values that parse to True, but (for", "# backwards compatibility reasons) also on values that parse to False.", "# In other words, always set it to False if the option is provided in", "# some (valid) form.", "parser", ".", "values", ".", "cache_dir", "=", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/cmdoptions.py#L650-L675
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/contrib/crosstalk/__init__.py
python
Crosstalk.set_workdir
(self, dir)
Set up a working directory for save/load numpy values(.npy) or python data (.pkl) Args: dir (`str`): Working directory
Set up a working directory for save/load numpy values(.npy) or python data (.pkl) Args: dir (`str`): Working directory
[ "Set", "up", "a", "working", "directory", "for", "save", "/", "load", "numpy", "values", "(", ".", "npy", ")", "or", "python", "data", "(", ".", "pkl", ")", "Args", ":", "dir", "(", "str", ")", ":", "Working", "directory" ]
def set_workdir(self, dir): ''' Set up a working directory for save/load numpy values(.npy) or python data (.pkl) Args: dir (`str`): Working directory ''' self.work_dir = dir if not os.path.exists(dir): os.makedirs(dir)
[ "def", "set_workdir", "(", "self", ",", "dir", ")", ":", "self", ".", "work_dir", "=", "dir", "if", "not", "os", ".", "path", ".", "exists", "(", "dir", ")", ":", "os", ".", "makedirs", "(", "dir", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/crosstalk/__init__.py#L140-L149
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/experimental/ops/unique.py
python
unique
()
return _apply_fn
Creates a `Dataset` from another `Dataset`, discarding duplicates. Use this transformation to produce a dataset that contains one instance of each unique element in the input. For example: ```python dataset = tf.data.Dataset.from_tensor_slices([1, 37, 2, 37, 2, 1]) # Using `unique()` will drop the duplicate elements. dataset = dataset.apply(tf.data.experimental.unique()) # ==> { 1, 37, 2 } ``` Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`.
Creates a `Dataset` from another `Dataset`, discarding duplicates.
[ "Creates", "a", "Dataset", "from", "another", "Dataset", "discarding", "duplicates", "." ]
def unique(): """Creates a `Dataset` from another `Dataset`, discarding duplicates. Use this transformation to produce a dataset that contains one instance of each unique element in the input. For example: ```python dataset = tf.data.Dataset.from_tensor_slices([1, 37, 2, 37, 2, 1]) # Using `unique()` will drop the duplicate elements. dataset = dataset.apply(tf.data.experimental.unique()) # ==> { 1, 37, 2 } ``` Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`. """ def _apply_fn(dataset): return _UniqueDataset(dataset) return _apply_fn
[ "def", "unique", "(", ")", ":", "def", "_apply_fn", "(", "dataset", ")", ":", "return", "_UniqueDataset", "(", "dataset", ")", "return", "_apply_fn" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/experimental/ops/unique.py#L27-L48
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/forwarders/android_forwarder.py
python
AndroidRndisConfigurator._GetHostAddresses
(self, iface)
return addresses, iface_address
Returns the IP addresses on host's interfaces, breaking out |iface|.
Returns the IP addresses on host's interfaces, breaking out |iface|.
[ "Returns", "the", "IP", "addresses", "on", "host", "s", "interfaces", "breaking", "out", "|iface|", "." ]
def _GetHostAddresses(self, iface): """Returns the IP addresses on host's interfaces, breaking out |iface|.""" interface_list = self._EnumerateHostInterfaces() addresses = [] iface_address = None found_iface = False for line in interface_list: if not line.startswith(' '): found_iface = iface in line match = re.search('(?<=inet )\S+', line) if match: address = match.group(0) if found_iface: assert not iface_address, ( 'Found %s twice when parsing host interfaces.' % iface) iface_address = address else: addresses.append(address) return addresses, iface_address
[ "def", "_GetHostAddresses", "(", "self", ",", "iface", ")", ":", "interface_list", "=", "self", ".", "_EnumerateHostInterfaces", "(", ")", "addresses", "=", "[", "]", "iface_address", "=", "None", "found_iface", "=", "False", "for", "line", "in", "interface_list", ":", "if", "not", "line", ".", "startswith", "(", "' '", ")", ":", "found_iface", "=", "iface", "in", "line", "match", "=", "re", ".", "search", "(", "'(?<=inet )\\S+'", ",", "line", ")", "if", "match", ":", "address", "=", "match", ".", "group", "(", "0", ")", "if", "found_iface", ":", "assert", "not", "iface_address", ",", "(", "'Found %s twice when parsing host interfaces.'", "%", "iface", ")", "iface_address", "=", "address", "else", ":", "addresses", ".", "append", "(", "address", ")", "return", "addresses", ",", "iface_address" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/forwarders/android_forwarder.py#L284-L302
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/assign_scalar_input_to_entities_process.py
python
AssignScalarInputToEntitiesProcess.ExecuteFinalizeSolutionStep
(self)
This method is executed in order to finalize the current step Keyword arguments: self -- It signifies an instance of a class.
This method is executed in order to finalize the current step
[ "This", "method", "is", "executed", "in", "order", "to", "finalize", "the", "current", "step" ]
def ExecuteFinalizeSolutionStep(self): """ This method is executed in order to finalize the current step Keyword arguments: self -- It signifies an instance of a class. """ self.step_is_active = False
[ "def", "ExecuteFinalizeSolutionStep", "(", "self", ")", ":", "self", ".", "step_is_active", "=", "False" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/assign_scalar_input_to_entities_process.py#L104-L110
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/pyratemp.py
python
LoaderString.load
(self, string)
return u
Return template-string as unicode.
Return template-string as unicode.
[ "Return", "template", "-", "string", "as", "unicode", "." ]
def load(self, string): """Return template-string as unicode. """ if isinstance(string, unicode): u = string else: u = unicode(string, self.encoding) return u
[ "def", "load", "(", "self", ",", "string", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "u", "=", "string", "else", ":", "u", "=", "unicode", "(", "string", ",", "self", ".", "encoding", ")", "return", "u" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/pyratemp.py#L349-L356
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/rulerctrl.py
python
RulerCtrl.GetIndicator
(self, mousePos)
Returns the indicator located at the mouse position `mousePos` (if any). :param `mousePos`: the mouse position, an instance of :class:`Point`.
Returns the indicator located at the mouse position `mousePos` (if any).
[ "Returns", "the", "indicator", "located", "at", "the", "mouse", "position", "mousePos", "(", "if", "any", ")", "." ]
def GetIndicator(self, mousePos): """ Returns the indicator located at the mouse position `mousePos` (if any). :param `mousePos`: the mouse position, an instance of :class:`Point`. """ for indicator in self._indicators: if indicator.GetRect().Contains(mousePos): self._currentIndicator = indicator break
[ "def", "GetIndicator", "(", "self", ",", "mousePos", ")", ":", "for", "indicator", "in", "self", ".", "_indicators", ":", "if", "indicator", ".", "GetRect", "(", ")", ".", "Contains", "(", "mousePos", ")", ":", "self", ".", "_currentIndicator", "=", "indicator", "break" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/rulerctrl.py#L780-L790
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py
python
Block.get_block_values
(self, dtype=None)
return self.get_values(dtype=dtype)
This is used in the JSON C code
This is used in the JSON C code
[ "This", "is", "used", "in", "the", "JSON", "C", "code" ]
def get_block_values(self, dtype=None): """ This is used in the JSON C code """ return self.get_values(dtype=dtype)
[ "def", "get_block_values", "(", "self", ",", "dtype", "=", "None", ")", ":", "return", "self", ".", "get_values", "(", "dtype", "=", "dtype", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L234-L238
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Image.width
(self)
return getint( self.tk.call('image', 'width', self.name))
Return the width of the image.
Return the width of the image.
[ "Return", "the", "width", "of", "the", "image", "." ]
def width(self): """Return the width of the image.""" return getint( self.tk.call('image', 'width', self.name))
[ "def", "width", "(", "self", ")", ":", "return", "getint", "(", "self", ".", "tk", ".", "call", "(", "'image'", ",", "'width'", ",", "self", ".", "name", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L3294-L3297
continental/ecal
204dab80a24fe01abca62541133b311bf0c09608
lang/python/core/ecal/proto/helper.py
python
get_type_from_descriptor
(typename, descriptor)
return google.protobuf.message_factory.MessageFactory(desc_pool).GetPrototype(desc)
Returns a file descriptor set which contains all dependencies of a protobuf type that can be used for reflection purposes in eCAL. :param typename: name of the type of the protobuf message :param descriptor: descriptor as stored in a measurement
Returns a file descriptor set which contains all dependencies of a protobuf type that can be used for reflection purposes in eCAL.
[ "Returns", "a", "file", "descriptor", "set", "which", "contains", "all", "dependencies", "of", "a", "protobuf", "type", "that", "can", "be", "used", "for", "reflection", "purposes", "in", "eCAL", "." ]
def get_type_from_descriptor(typename, descriptor): """ Returns a file descriptor set which contains all dependencies of a protobuf type that can be used for reflection purposes in eCAL. :param typename: name of the type of the protobuf message :param descriptor: descriptor as stored in a measurement """ file_desc_set = google.protobuf.descriptor_pb2.FileDescriptorSet() file_desc_set.ParseFromString(descriptor) desc_pool = google.protobuf.descriptor_pool.DescriptorPool() for file_desc_proto in file_desc_set.file: desc_pool.Add(file_desc_proto) desc = desc_pool.FindMessageTypeByName(typename) return google.protobuf.message_factory.MessageFactory(desc_pool).GetPrototype(desc)
[ "def", "get_type_from_descriptor", "(", "typename", ",", "descriptor", ")", ":", "file_desc_set", "=", "google", ".", "protobuf", ".", "descriptor_pb2", ".", "FileDescriptorSet", "(", ")", "file_desc_set", ".", "ParseFromString", "(", "descriptor", ")", "desc_pool", "=", "google", ".", "protobuf", ".", "descriptor_pool", ".", "DescriptorPool", "(", ")", "for", "file_desc_proto", "in", "file_desc_set", ".", "file", ":", "desc_pool", ".", "Add", "(", "file_desc_proto", ")", "desc", "=", "desc_pool", ".", "FindMessageTypeByName", "(", "typename", ")", "return", "google", ".", "protobuf", ".", "message_factory", ".", "MessageFactory", "(", "desc_pool", ")", ".", "GetPrototype", "(", "desc", ")" ]
https://github.com/continental/ecal/blob/204dab80a24fe01abca62541133b311bf0c09608/lang/python/core/ecal/proto/helper.py#L53-L67
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/statetracker.py
python
StateTracker.Reset
(self)
Resets the state tracker to prepare for processing a new page.
Resets the state tracker to prepare for processing a new page.
[ "Resets", "the", "state", "tracker", "to", "prepare", "for", "processing", "a", "new", "page", "." ]
def Reset(self): """Resets the state tracker to prepare for processing a new page.""" self._block_depth = 0 self._is_block_close = False self._paren_depth = 0 self._functions = [] self._functions_by_name = {} self._last_comment = None self._doc_comment = None self._cumulative_params = None self._block_types = [] self._last_non_space_token = None self._last_line = None self._first_token = None self._documented_identifiers = set()
[ "def", "Reset", "(", "self", ")", ":", "self", ".", "_block_depth", "=", "0", "self", ".", "_is_block_close", "=", "False", "self", ".", "_paren_depth", "=", "0", "self", ".", "_functions", "=", "[", "]", "self", ".", "_functions_by_name", "=", "{", "}", "self", ".", "_last_comment", "=", "None", "self", ".", "_doc_comment", "=", "None", "self", ".", "_cumulative_params", "=", "None", "self", ".", "_block_types", "=", "[", "]", "self", ".", "_last_non_space_token", "=", "None", "self", ".", "_last_line", "=", "None", "self", ".", "_first_token", "=", "None", "self", ".", "_documented_identifiers", "=", "set", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/statetracker.py#L575-L589
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/types/fulltype.py
python
FullType.memberAccess
(self)
return self.memberAccess_
Return the operator used to access members of variables of the specified type.
Return the operator used to access members of variables of the specified type.
[ "Return", "the", "operator", "used", "to", "access", "members", "of", "variables", "of", "the", "specified", "type", "." ]
def memberAccess(self): """Return the operator used to access members of variables of the specified type.""" return self.memberAccess_
[ "def", "memberAccess", "(", "self", ")", ":", "return", "self", ".", "memberAccess_" ]
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/types/fulltype.py#L60-L63
google/certificate-transparency
2588562fd306a447958471b6f06c1069619c1641
python/utilities/log_list/cpp_generator.py
python
generate_cpp_header
(json_log_list, output_file)
Generate a header file of known logs to be included by Chromium.
Generate a header file of known logs to be included by Chromium.
[ "Generate", "a", "header", "file", "of", "known", "logs", "to", "be", "included", "by", "Chromium", "." ]
def generate_cpp_header(json_log_list, output_file): """Generate a header file of known logs to be included by Chromium.""" include_guard = (output_file.upper().replace('.', '_').replace('/', '_') + '_') f = open(output_file, "w") _write_cpp_header(f, include_guard) logs = json_log_list["logs"] list_code = [] google_operator_id = _find_google_operator_id(json_log_list) google_log_ids = [] for log in logs: log_key = base64.decodestring(log["key"]) split_hex_key = split_and_hexify_binary_data(log_key) s = " {" s += "\n ".join(split_hex_key) s += ',\n %d' % (len(log_key)) s += ',\n "%s"' % (log["description"]) s += ',\n "https://%s/"}' % (log["url"]) list_code.append(s) # operated_by is a list, in practice we have not witnessed # a log co-operated by more than one operator. Ensure we take this # case into consideration if it ever happens. assert(len(log["operated_by"]) == 1) operator_id = log["operated_by"][0] if operator_id == google_operator_id: google_log_ids.append(hashlib.sha256(log_key).digest()) _write_log_info_struct_definition(f) f.write("const CTLogInfo kCTLogList[] = {\n") f.write(",\n" . join(list_code)) f.write("};\n") write_log_ids_array(f, google_log_ids, 'kGoogleLogIDs') _write_cpp_footer(f, include_guard)
[ "def", "generate_cpp_header", "(", "json_log_list", ",", "output_file", ")", ":", "include_guard", "=", "(", "output_file", ".", "upper", "(", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", ".", "replace", "(", "'/'", ",", "'_'", ")", "+", "'_'", ")", "f", "=", "open", "(", "output_file", ",", "\"w\"", ")", "_write_cpp_header", "(", "f", ",", "include_guard", ")", "logs", "=", "json_log_list", "[", "\"logs\"", "]", "list_code", "=", "[", "]", "google_operator_id", "=", "_find_google_operator_id", "(", "json_log_list", ")", "google_log_ids", "=", "[", "]", "for", "log", "in", "logs", ":", "log_key", "=", "base64", ".", "decodestring", "(", "log", "[", "\"key\"", "]", ")", "split_hex_key", "=", "split_and_hexify_binary_data", "(", "log_key", ")", "s", "=", "\" {\"", "s", "+=", "\"\\n \"", ".", "join", "(", "split_hex_key", ")", "s", "+=", "',\\n %d'", "%", "(", "len", "(", "log_key", ")", ")", "s", "+=", "',\\n \"%s\"'", "%", "(", "log", "[", "\"description\"", "]", ")", "s", "+=", "',\\n \"https://%s/\"}'", "%", "(", "log", "[", "\"url\"", "]", ")", "list_code", ".", "append", "(", "s", ")", "# operated_by is a list, in practice we have not witnessed", "# a log co-operated by more than one operator. Ensure we take this", "# case into consideration if it ever happens.", "assert", "(", "len", "(", "log", "[", "\"operated_by\"", "]", ")", "==", "1", ")", "operator_id", "=", "log", "[", "\"operated_by\"", "]", "[", "0", "]", "if", "operator_id", "==", "google_operator_id", ":", "google_log_ids", ".", "append", "(", "hashlib", ".", "sha256", "(", "log_key", ")", ".", "digest", "(", ")", ")", "_write_log_info_struct_definition", "(", "f", ")", "f", ".", "write", "(", "\"const CTLogInfo kCTLogList[] = {\\n\"", ")", "f", ".", "write", "(", "\",\\n\"", ".", "join", "(", "list_code", ")", ")", "f", ".", "write", "(", "\"};\\n\"", ")", "write_log_ids_array", "(", "f", ",", "google_log_ids", ",", "'kGoogleLogIDs'", ")", "_write_cpp_footer", "(", "f", ",", "include_guard", ")" ]
https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/utilities/log_list/cpp_generator.py#L68-L103
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
SimRobotSensor.getEnabled
(self)
return _robotsim.SimRobotSensor_getEnabled(self)
r""" getEnabled(SimRobotSensor self) -> bool Return whether the sensor is enabled during simulation (helper for getSetting)
r""" getEnabled(SimRobotSensor self) -> bool
[ "r", "getEnabled", "(", "SimRobotSensor", "self", ")", "-", ">", "bool" ]
def getEnabled(self) -> "bool": r""" getEnabled(SimRobotSensor self) -> bool Return whether the sensor is enabled during simulation (helper for getSetting) """ return _robotsim.SimRobotSensor_getEnabled(self)
[ "def", "getEnabled", "(", "self", ")", "->", "\"bool\"", ":", "return", "_robotsim", ".", "SimRobotSensor_getEnabled", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L7221-L7229
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/turtle.py
python
TurtleScreenBase._onkeyrelease
(self, fun, key)
Bind fun to key-release event of key. Canvas must have focus. See method listen
Bind fun to key-release event of key. Canvas must have focus. See method listen
[ "Bind", "fun", "to", "key", "-", "release", "event", "of", "key", ".", "Canvas", "must", "have", "focus", ".", "See", "method", "listen" ]
def _onkeyrelease(self, fun, key): """Bind fun to key-release event of key. Canvas must have focus. See method listen """ if fun is None: self.cv.unbind("<KeyRelease-%s>" % key, None) else: def eventfun(event): fun() self.cv.bind("<KeyRelease-%s>" % key, eventfun)
[ "def", "_onkeyrelease", "(", "self", ",", "fun", ",", "key", ")", ":", "if", "fun", "is", "None", ":", "self", ".", "cv", ".", "unbind", "(", "\"<KeyRelease-%s>\"", "%", "key", ",", "None", ")", "else", ":", "def", "eventfun", "(", "event", ")", ":", "fun", "(", ")", "self", ".", "cv", ".", "bind", "(", "\"<KeyRelease-%s>\"", "%", "key", ",", "eventfun", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L677-L686
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/device.py
python
set_prealloc_config
( alignment: int = 1, min_req: int = 32 * 1024 * 1024, max_overhead: int = 0, growth_factor=2.0, device_type=DeviceType.CUDA, )
r"""Specifies how to pre-allocate from raw device allocator. Args: alignment: specifies the alignment in bytes. min_req: min request size in bytes. max_overhead: max overhead above required size in bytes. growth_factor: request size / cur allocated` device_type: the device type alignment: int: min_req: int: max_overhead: int:
r"""Specifies how to pre-allocate from raw device allocator.
[ "r", "Specifies", "how", "to", "pre", "-", "allocate", "from", "raw", "device", "allocator", "." ]
def set_prealloc_config( alignment: int = 1, min_req: int = 32 * 1024 * 1024, max_overhead: int = 0, growth_factor=2.0, device_type=DeviceType.CUDA, ): r"""Specifies how to pre-allocate from raw device allocator. Args: alignment: specifies the alignment in bytes. min_req: min request size in bytes. max_overhead: max overhead above required size in bytes. growth_factor: request size / cur allocated` device_type: the device type alignment: int: min_req: int: max_overhead: int: """ assert alignment > 0 assert min_req > 0 assert max_overhead >= 0 assert growth_factor >= 1 _set_prealloc_config(alignment, min_req, max_overhead, growth_factor, device_type)
[ "def", "set_prealloc_config", "(", "alignment", ":", "int", "=", "1", ",", "min_req", ":", "int", "=", "32", "*", "1024", "*", "1024", ",", "max_overhead", ":", "int", "=", "0", ",", "growth_factor", "=", "2.0", ",", "device_type", "=", "DeviceType", ".", "CUDA", ",", ")", ":", "assert", "alignment", ">", "0", "assert", "min_req", ">", "0", "assert", "max_overhead", ">=", "0", "assert", "growth_factor", ">=", "1", "_set_prealloc_config", "(", "alignment", ",", "min_req", ",", "max_overhead", ",", "growth_factor", ",", "device_type", ")" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/device.py#L225-L248
yushroom/FishEngine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
Script/reflect/clang/cindex.py
python
Diagnostic.category_number
(self)
return conf.lib.clang_getDiagnosticCategory(self)
The category number for this diagnostic or 0 if unavailable.
The category number for this diagnostic or 0 if unavailable.
[ "The", "category", "number", "for", "this", "diagnostic", "or", "0", "if", "unavailable", "." ]
def category_number(self): """The category number for this diagnostic or 0 if unavailable.""" return conf.lib.clang_getDiagnosticCategory(self)
[ "def", "category_number", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getDiagnosticCategory", "(", "self", ")" ]
https://github.com/yushroom/FishEngine/blob/a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9/Script/reflect/clang/cindex.py#L388-L390
randomascii/blogstuff
07074af1c2df6e61d30bb4fb7704e4166d0dc9ed
ChromiumBuildAnalysis/analyze_chrome.py
python
Target.__init__
(self, start, end)
Creates a target object by passing in the start/end times in seconds as a float.
Creates a target object by passing in the start/end times in seconds as a float.
[ "Creates", "a", "target", "object", "by", "passing", "in", "the", "start", "/", "end", "times", "in", "seconds", "as", "a", "float", "." ]
def __init__(self, start, end): """Creates a target object by passing in the start/end times in seconds as a float.""" self.start = start self.end = end # A list of targets, appended to by the owner of this object. self.targets = []
[ "def", "__init__", "(", "self", ",", "start", ",", "end", ")", ":", "self", ".", "start", "=", "start", "self", ".", "end", "=", "end", "# A list of targets, appended to by the owner of this object.", "self", ".", "targets", "=", "[", "]" ]
https://github.com/randomascii/blogstuff/blob/07074af1c2df6e61d30bb4fb7704e4166d0dc9ed/ChromiumBuildAnalysis/analyze_chrome.py#L29-L35
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.GetSizeMM
(*args, **kwargs)
return _gdi_.DC_GetSizeMM(*args, **kwargs)
GetSizeMM(self) -> Size Get the DC size in milimeters.
GetSizeMM(self) -> Size
[ "GetSizeMM", "(", "self", ")", "-", ">", "Size" ]
def GetSizeMM(*args, **kwargs): """ GetSizeMM(self) -> Size Get the DC size in milimeters. """ return _gdi_.DC_GetSizeMM(*args, **kwargs)
[ "def", "GetSizeMM", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetSizeMM", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L4199-L4205
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Point.__ne__
(*args, **kwargs)
return _core_.Point___ne__(*args, **kwargs)
__ne__(self, PyObject other) -> bool Test for inequality of wx.Point objects.
__ne__(self, PyObject other) -> bool
[ "__ne__", "(", "self", "PyObject", "other", ")", "-", ">", "bool" ]
def __ne__(*args, **kwargs): """ __ne__(self, PyObject other) -> bool Test for inequality of wx.Point objects. """ return _core_.Point___ne__(*args, **kwargs)
[ "def", "__ne__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Point___ne__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1195-L1201
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/rsa/rsa/_version200.py
python
find_p_q
(nbits)
return (p, q)
Returns a tuple of two different primes of nbits bits
Returns a tuple of two different primes of nbits bits
[ "Returns", "a", "tuple", "of", "two", "different", "primes", "of", "nbits", "bits" ]
def find_p_q(nbits): """Returns a tuple of two different primes of nbits bits""" pbits = nbits + (nbits/16) #Make sure that p and q aren't too close qbits = nbits - (nbits/16) #or the factoring programs can factor n p = getprime(pbits) while True: q = getprime(qbits) #Make sure p and q are different. if not q == p: break return (p, q)
[ "def", "find_p_q", "(", "nbits", ")", ":", "pbits", "=", "nbits", "+", "(", "nbits", "/", "16", ")", "#Make sure that p and q aren't too close", "qbits", "=", "nbits", "-", "(", "nbits", "/", "16", ")", "#or the factoring programs can factor n", "p", "=", "getprime", "(", "pbits", ")", "while", "True", ":", "q", "=", "getprime", "(", "qbits", ")", "#Make sure p and q are different.", "if", "not", "q", "==", "p", ":", "break", "return", "(", "p", ",", "q", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/rsa/rsa/_version200.py#L311-L320
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html2.py
python
WebView.CanUndo
(*args, **kwargs)
return _html2.WebView_CanUndo(*args, **kwargs)
CanUndo(self) -> bool
CanUndo(self) -> bool
[ "CanUndo", "(", "self", ")", "-", ">", "bool" ]
def CanUndo(*args, **kwargs): """CanUndo(self) -> bool""" return _html2.WebView_CanUndo(*args, **kwargs)
[ "def", "CanUndo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html2", ".", "WebView_CanUndo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html2.py#L294-L296
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/range-sum-query-mutable.py
python
NumArray2.__init__
(self, nums, query_fn=lambda x, y: x+y, update_fn=lambda x, y: y, default_val=0)
initialize your data structure here. :type nums: List[int]
initialize your data structure here. :type nums: List[int]
[ "initialize", "your", "data", "structure", "here", ".", ":", "type", "nums", ":", "List", "[", "int", "]" ]
def __init__(self, nums, query_fn=lambda x, y: x+y, update_fn=lambda x, y: y, default_val=0): """ initialize your data structure here. :type nums: List[int] """ N = len(nums) self.__original_length = N self.__tree_length = 2**(N.bit_length() + (N&(N-1) != 0))-1 self.__query_fn = query_fn self.__update_fn = update_fn self.__default_val = default_val self.__tree = [default_val for _ in range(self.__tree_length)] self.__lazy = [None for _ in range(self.__tree_length)] self.__constructTree(nums, 0, self.__original_length-1, 0)
[ "def", "__init__", "(", "self", ",", "nums", ",", "query_fn", "=", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "update_fn", "=", "lambda", "x", ",", "y", ":", "y", ",", "default_val", "=", "0", ")", ":", "N", "=", "len", "(", "nums", ")", "self", ".", "__original_length", "=", "N", "self", ".", "__tree_length", "=", "2", "**", "(", "N", ".", "bit_length", "(", ")", "+", "(", "N", "&", "(", "N", "-", "1", ")", "!=", "0", ")", ")", "-", "1", "self", ".", "__query_fn", "=", "query_fn", "self", ".", "__update_fn", "=", "update_fn", "self", ".", "__default_val", "=", "default_val", "self", ".", "__tree", "=", "[", "default_val", "for", "_", "in", "range", "(", "self", ".", "__tree_length", ")", "]", "self", ".", "__lazy", "=", "[", "None", "for", "_", "in", "range", "(", "self", ".", "__tree_length", ")", "]", "self", ".", "__constructTree", "(", "nums", ",", "0", ",", "self", ".", "__original_length", "-", "1", ",", "0", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/range-sum-query-mutable.py#L63-L79