nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
PyApp.ResumeProcessingOfPendingEvents
(*args, **kwargs)
return _core_.PyApp_ResumeProcessingOfPendingEvents(*args, **kwargs)
ResumeProcessingOfPendingEvents(self) Resume (after having been suspended) the processing of pending events.
ResumeProcessingOfPendingEvents(self)
[ "ResumeProcessingOfPendingEvents", "(", "self", ")" ]
def ResumeProcessingOfPendingEvents(*args, **kwargs): """ ResumeProcessingOfPendingEvents(self) Resume (after having been suspended) the processing of pending events. """ return _core_.PyApp_ResumeProcessingOfPendingEvents(*args, **kwargs)
[ "def", "ResumeProcessingOfPendingEvents", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_ResumeProcessingOfPendingEvents", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L7850-L7856
tzlaine/text
b576f19c2643ac1b08080844fa6044df6939c5c7
benchmark-v1.2.0/tools/gbench/util.py
python
remove_benchmark_flags
(prefix, benchmark_flags)
return [f for f in benchmark_flags if not f.startswith(prefix)]
Return a new list containing the specified benchmark_flags except those with the specified prefix.
Return a new list containing the specified benchmark_flags except those with the specified prefix.
[ "Return", "a", "new", "list", "containing", "the", "specified", "benchmark_flags", "except", "those", "with", "the", "specified", "prefix", "." ]
def remove_benchmark_flags(prefix, benchmark_flags): """ Return a new list containing the specified benchmark_flags except those with the specified prefix. """ assert prefix.startswith('--') and prefix.endswith('=') return [f for f in benchmark_flags if not f.startswith(prefix)]
[ "def", "remove_benchmark_flags", "(", "prefix", ",", "benchmark_flags", ")", ":", "assert", "prefix", ".", "startswith", "(", "'--'", ")", "and", "prefix", ".", "endswith", "(", "'='", ")", "return", "[", "f", "for", "f", "in", "benchmark_flags", "if", "not", "f", ".", "startswith", "(", "prefix", ")", "]" ]
https://github.com/tzlaine/text/blob/b576f19c2643ac1b08080844fa6044df6939c5c7/benchmark-v1.2.0/tools/gbench/util.py#L100-L106
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/sponge_ops.py
python
DihedralForce.__init__
(self, dihedral_numbers)
Initialize DihedralForce.
Initialize DihedralForce.
[ "Initialize", "DihedralForce", "." ]
def __init__(self, dihedral_numbers): """Initialize DihedralForce.""" validator.check_value_type('dihedral_numbers', dihedral_numbers, int, self.name) self.dihedral_numbers = dihedral_numbers self.init_prim_io_names(inputs=['uint_crd_f', 'scaler_f', 'atom_a', 'atom_b', 'atom_c', 'atom_d', 'ipn', 'pk', 'gamc', 'gams', 'pn'], outputs=['frc_f']) self.add_prim_attr('dihedral_numbers', self.dihedral_numbers)
[ "def", "__init__", "(", "self", ",", "dihedral_numbers", ")", ":", "validator", ".", "check_value_type", "(", "'dihedral_numbers'", ",", "dihedral_numbers", ",", "int", ",", "self", ".", "name", ")", "self", ".", "dihedral_numbers", "=", "dihedral_numbers", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'uint_crd_f'", ",", "'scaler_f'", ",", "'atom_a'", ",", "'atom_b'", ",", "'atom_c'", ",", "'atom_d'", ",", "'ipn'", ",", "'pk'", ",", "'gamc'", ",", "'gams'", ",", "'pn'", "]", ",", "outputs", "=", "[", "'frc_f'", "]", ")", "self", ".", "add_prim_attr", "(", "'dihedral_numbers'", ",", "self", ".", "dihedral_numbers", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/sponge_ops.py#L504-L511
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
Clipboard.SetData
(*args, **kwargs)
return _misc_.Clipboard_SetData(*args, **kwargs)
SetData(self, DataObject data) -> bool Set the clipboard data, this is the same as `Clear` followed by `AddData`. :see: `wx.DataObject`
SetData(self, DataObject data) -> bool
[ "SetData", "(", "self", "DataObject", "data", ")", "-", ">", "bool" ]
def SetData(*args, **kwargs): """ SetData(self, DataObject data) -> bool Set the clipboard data, this is the same as `Clear` followed by `AddData`. :see: `wx.DataObject` """ return _misc_.Clipboard_SetData(*args, **kwargs)
[ "def", "SetData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Clipboard_SetData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5832-L5841
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py
python
MutableHashTable.lookup
(self, keys, name=None)
return values
Looks up `keys` in a table, outputs the corresponding values. The `default_value` is used for keys not present in the table. Args: keys: Keys to look up. Can be a tensor of any shape. Must match the table's key_dtype. name: A name for the operation (optional). Returns: A tensor containing the values in the same shape as `keys` using the table's value type. Raises: TypeError: when `keys` do not match the table data types.
Looks up `keys` in a table, outputs the corresponding values.
[ "Looks", "up", "keys", "in", "a", "table", "outputs", "the", "corresponding", "values", "." ]
def lookup(self, keys, name=None): """Looks up `keys` in a table, outputs the corresponding values. The `default_value` is used for keys not present in the table. Args: keys: Keys to look up. Can be a tensor of any shape. Must match the table's key_dtype. name: A name for the operation (optional). Returns: A tensor containing the values in the same shape as `keys` using the table's value type. Raises: TypeError: when `keys` do not match the table data types. """ if keys.dtype != self._key_dtype: raise TypeError("Signature mismatch. Keys must be dtype %s, got %s." % (self._key_dtype, keys.dtype)) with ops.op_scope([self._table_ref, keys], name, "%s_lookup_table_find" % self._name) as name: # pylint: disable=protected-access values = gen_data_flow_ops._lookup_table_find(self._table_ref, keys, self._default_value, name=name) # pylint: enable=protected-access values.set_shape(keys.get_shape().concatenate(self._value_shape)) return values
[ "def", "lookup", "(", "self", ",", "keys", ",", "name", "=", "None", ")", ":", "if", "keys", ".", "dtype", "!=", "self", ".", "_key_dtype", ":", "raise", "TypeError", "(", "\"Signature mismatch. Keys must be dtype %s, got %s.\"", "%", "(", "self", ".", "_key_dtype", ",", "keys", ".", "dtype", ")", ")", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "_table_ref", ",", "keys", "]", ",", "name", ",", "\"%s_lookup_table_find\"", "%", "self", ".", "_name", ")", "as", "name", ":", "# pylint: disable=protected-access", "values", "=", "gen_data_flow_ops", ".", "_lookup_table_find", "(", "self", ".", "_table_ref", ",", "keys", ",", "self", ".", "_default_value", ",", "name", "=", "name", ")", "# pylint: enable=protected-access", "values", ".", "set_shape", "(", "keys", ".", "get_shape", "(", ")", ".", "concatenate", "(", "self", ".", "_value_shape", ")", ")", "return", "values" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py#L768-L799
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py
python
TelnetSubnegotiation.isReady
(self)
return self.state == ACTIVE
\ check if answer from server has been received. when server rejects the change, raise a ValueError.
\ check if answer from server has been received. when server rejects the change, raise a ValueError.
[ "\\", "check", "if", "answer", "from", "server", "has", "been", "received", ".", "when", "server", "rejects", "the", "change", "raise", "a", "ValueError", "." ]
def isReady(self): """\ check if answer from server has been received. when server rejects the change, raise a ValueError. """ if self.state == REALLY_INACTIVE: raise ValueError("remote rejected value for option %r" % (self.name)) return self.state == ACTIVE
[ "def", "isReady", "(", "self", ")", ":", "if", "self", ".", "state", "==", "REALLY_INACTIVE", ":", "raise", "ValueError", "(", "\"remote rejected value for option %r\"", "%", "(", "self", ".", "name", ")", ")", "return", "self", ".", "state", "==", "ACTIVE" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py#L323-L330
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
EraseEvent.GetDC
(*args, **kwargs)
return _core_.EraseEvent_GetDC(*args, **kwargs)
GetDC(self) -> DC Returns the device context the event handler should draw upon. If ``None`` is returned then create a temporary `wx.ClientDC` and use that instead.
GetDC(self) -> DC
[ "GetDC", "(", "self", ")", "-", ">", "DC" ]
def GetDC(*args, **kwargs): """ GetDC(self) -> DC Returns the device context the event handler should draw upon. If ``None`` is returned then create a temporary `wx.ClientDC` and use that instead. """ return _core_.EraseEvent_GetDC(*args, **kwargs)
[ "def", "GetDC", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "EraseEvent_GetDC", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L6273-L6281
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextParagraphLayoutBox.HasCharacterAttributes
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_HasCharacterAttributes(*args, **kwargs)
HasCharacterAttributes(self, RichTextRange range, RichTextAttr style) -> bool
HasCharacterAttributes(self, RichTextRange range, RichTextAttr style) -> bool
[ "HasCharacterAttributes", "(", "self", "RichTextRange", "range", "RichTextAttr", "style", ")", "-", ">", "bool" ]
def HasCharacterAttributes(*args, **kwargs): """HasCharacterAttributes(self, RichTextRange range, RichTextAttr style) -> bool""" return _richtext.RichTextParagraphLayoutBox_HasCharacterAttributes(*args, **kwargs)
[ "def", "HasCharacterAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_HasCharacterAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1802-L1804
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBMemoryRegionInfo.__ne__
(self, *args)
return _lldb.SBMemoryRegionInfo___ne__(self, *args)
__ne__(self, SBMemoryRegionInfo rhs) -> bool
__ne__(self, SBMemoryRegionInfo rhs) -> bool
[ "__ne__", "(", "self", "SBMemoryRegionInfo", "rhs", ")", "-", ">", "bool" ]
def __ne__(self, *args): """__ne__(self, SBMemoryRegionInfo rhs) -> bool""" return _lldb.SBMemoryRegionInfo___ne__(self, *args)
[ "def", "__ne__", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBMemoryRegionInfo___ne__", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5858-L5860
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/descriptor.py
python
MakeDescriptor
(desc_proto, package='', build_file_if_cpp=True, syntax=None)
return Descriptor(desc_proto.name, desc_name, None, None, fields, list(nested_types.values()), list(enum_types.values()), [], options=desc_proto.options)
Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently only be resolved if the message is defined in the same scope as the field. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: Optional package name for the new message Descriptor (string). build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to False on recursion, so no duplicates are created. syntax: The syntax/semantics that should be used. Set to "proto3" to get proto3 field presence semantics. Returns: A Descriptor for protobuf messages.
Make a protobuf Descriptor given a DescriptorProto protobuf.
[ "Make", "a", "protobuf", "Descriptor", "given", "a", "DescriptorProto", "protobuf", "." ]
def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True, syntax=None): """Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently only be resolved if the message is defined in the same scope as the field. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: Optional package name for the new message Descriptor (string). build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to False on recursion, so no duplicates are created. syntax: The syntax/semantics that should be used. Set to "proto3" to get proto3 field presence semantics. Returns: A Descriptor for protobuf messages. """ if api_implementation.Type() == 'cpp' and build_file_if_cpp: # The C++ implementation requires all descriptors to be backed by the same # definition in the C++ descriptor pool. To do this, we build a # FileDescriptorProto with the same definition as this descriptor and build # it into the pool. from google.protobuf import descriptor_pb2 file_descriptor_proto = descriptor_pb2.FileDescriptorProto() file_descriptor_proto.message_type.add().MergeFrom(desc_proto) # Generate a random name for this proto file to prevent conflicts with any # imported ones. We need to specify a file name so the descriptor pool # accepts our FileDescriptorProto, but it is not important what that file # name is actually set to. proto_name = str(uuid.uuid4()) if package: file_descriptor_proto.name = os.path.join(package.replace('.', '/'), proto_name + '.proto') file_descriptor_proto.package = package else: file_descriptor_proto.name = proto_name + '.proto' _message.default_pool.Add(file_descriptor_proto) result = _message.default_pool.FindFileByName(file_descriptor_proto.name) if _USE_C_DESCRIPTORS: return result.message_types_by_name[desc_proto.name] full_message_name = [desc_proto.name] if package: full_message_name.insert(0, package) # Create Descriptors for enum types enum_types = {} for enum_proto in desc_proto.enum_type: full_name = '.'.join(full_message_name + [enum_proto.name]) enum_desc = EnumDescriptor( enum_proto.name, full_name, None, [ EnumValueDescriptor(enum_val.name, ii, enum_val.number) for ii, enum_val in enumerate(enum_proto.value)]) enum_types[full_name] = enum_desc # Create Descriptors for nested types nested_types = {} for nested_proto in desc_proto.nested_type: full_name = '.'.join(full_message_name + [nested_proto.name]) # Nested types are just those defined inside of the message, not all types # used by fields in the message, so no loops are possible here. nested_desc = MakeDescriptor(nested_proto, package='.'.join(full_message_name), build_file_if_cpp=False, syntax=syntax) nested_types[full_name] = nested_desc fields = [] for field_proto in desc_proto.field: full_name = '.'.join(full_message_name + [field_proto.name]) enum_desc = None nested_desc = None if field_proto.HasField('type_name'): type_name = field_proto.type_name full_type_name = '.'.join(full_message_name + [type_name[type_name.rfind('.')+1:]]) if full_type_name in nested_types: nested_desc = nested_types[full_type_name] elif full_type_name in enum_types: enum_desc = enum_types[full_type_name] # Else type_name references a non-local type, which isn't implemented field = FieldDescriptor( field_proto.name, full_name, field_proto.number - 1, field_proto.number, field_proto.type, FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), field_proto.label, None, nested_desc, enum_desc, None, False, None, options=field_proto.options, has_default_value=False) fields.append(field) desc_name = '.'.join(full_message_name) return Descriptor(desc_proto.name, desc_name, None, None, fields, list(nested_types.values()), list(enum_types.values()), [], options=desc_proto.options)
[ "def", "MakeDescriptor", "(", "desc_proto", ",", "package", "=", "''", ",", "build_file_if_cpp", "=", "True", ",", "syntax", "=", "None", ")", ":", "if", "api_implementation", ".", "Type", "(", ")", "==", "'cpp'", "and", "build_file_if_cpp", ":", "# The C++ implementation requires all descriptors to be backed by the same", "# definition in the C++ descriptor pool. To do this, we build a", "# FileDescriptorProto with the same definition as this descriptor and build", "# it into the pool.", "from", "google", ".", "protobuf", "import", "descriptor_pb2", "file_descriptor_proto", "=", "descriptor_pb2", ".", "FileDescriptorProto", "(", ")", "file_descriptor_proto", ".", "message_type", ".", "add", "(", ")", ".", "MergeFrom", "(", "desc_proto", ")", "# Generate a random name for this proto file to prevent conflicts with any", "# imported ones. We need to specify a file name so the descriptor pool", "# accepts our FileDescriptorProto, but it is not important what that file", "# name is actually set to.", "proto_name", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "package", ":", "file_descriptor_proto", ".", "name", "=", "os", ".", "path", ".", "join", "(", "package", ".", "replace", "(", "'.'", ",", "'/'", ")", ",", "proto_name", "+", "'.proto'", ")", "file_descriptor_proto", ".", "package", "=", "package", "else", ":", "file_descriptor_proto", ".", "name", "=", "proto_name", "+", "'.proto'", "_message", ".", "default_pool", ".", "Add", "(", "file_descriptor_proto", ")", "result", "=", "_message", ".", "default_pool", ".", "FindFileByName", "(", "file_descriptor_proto", ".", "name", ")", "if", "_USE_C_DESCRIPTORS", ":", "return", "result", ".", "message_types_by_name", "[", "desc_proto", ".", "name", "]", "full_message_name", "=", "[", "desc_proto", ".", "name", "]", "if", "package", ":", "full_message_name", ".", "insert", "(", "0", ",", "package", ")", "# Create Descriptors for enum types", "enum_types", "=", "{", "}", "for", "enum_proto", "in", "desc_proto", ".", "enum_type", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "enum_proto", ".", "name", "]", ")", "enum_desc", "=", "EnumDescriptor", "(", "enum_proto", ".", "name", ",", "full_name", ",", "None", ",", "[", "EnumValueDescriptor", "(", "enum_val", ".", "name", ",", "ii", ",", "enum_val", ".", "number", ")", "for", "ii", ",", "enum_val", "in", "enumerate", "(", "enum_proto", ".", "value", ")", "]", ")", "enum_types", "[", "full_name", "]", "=", "enum_desc", "# Create Descriptors for nested types", "nested_types", "=", "{", "}", "for", "nested_proto", "in", "desc_proto", ".", "nested_type", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "nested_proto", ".", "name", "]", ")", "# Nested types are just those defined inside of the message, not all types", "# used by fields in the message, so no loops are possible here.", "nested_desc", "=", "MakeDescriptor", "(", "nested_proto", ",", "package", "=", "'.'", ".", "join", "(", "full_message_name", ")", ",", "build_file_if_cpp", "=", "False", ",", "syntax", "=", "syntax", ")", "nested_types", "[", "full_name", "]", "=", "nested_desc", "fields", "=", "[", "]", "for", "field_proto", "in", "desc_proto", ".", "field", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "field_proto", ".", "name", "]", ")", "enum_desc", "=", "None", "nested_desc", "=", "None", "if", "field_proto", ".", "HasField", "(", "'type_name'", ")", ":", "type_name", "=", "field_proto", ".", "type_name", "full_type_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "type_name", "[", "type_name", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "]", ")", "if", "full_type_name", "in", "nested_types", ":", "nested_desc", "=", "nested_types", "[", "full_type_name", "]", "elif", "full_type_name", "in", "enum_types", ":", "enum_desc", "=", "enum_types", "[", "full_type_name", "]", "# Else type_name references a non-local type, which isn't implemented", "field", "=", "FieldDescriptor", "(", "field_proto", ".", "name", ",", "full_name", ",", "field_proto", ".", "number", "-", "1", ",", "field_proto", ".", "number", ",", "field_proto", ".", "type", ",", "FieldDescriptor", ".", "ProtoTypeToCppProtoType", "(", "field_proto", ".", "type", ")", ",", "field_proto", ".", "label", ",", "None", ",", "nested_desc", ",", "enum_desc", ",", "None", ",", "False", ",", "None", ",", "options", "=", "field_proto", ".", "options", ",", "has_default_value", "=", "False", ")", "fields", ".", "append", "(", "field", ")", "desc_name", "=", "'.'", ".", "join", "(", "full_message_name", ")", "return", "Descriptor", "(", "desc_proto", ".", "name", ",", "desc_name", ",", "None", ",", "None", ",", "fields", ",", "list", "(", "nested_types", ".", "values", "(", ")", ")", ",", "list", "(", "enum_types", ".", "values", "(", ")", ")", ",", "[", "]", ",", "options", "=", "desc_proto", ".", "options", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/descriptor.py#L897-L993
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/_parameterized.py
python
named_parameters
(*testcases)
return _ParameterDecorator(_FIRST_ARG, testcases)
A decorator for creating parameterized tests. See the module docstring for a usage example. The first element of each parameter tuple should be a string and will be appended to the name of the test method. Args: *testcases: Parameters for the decorated method, either a single iterable, or a list of tuples. Returns: A test generator to be handled by TestGeneratorMetaclass.
A decorator for creating parameterized tests.
[ "A", "decorator", "for", "creating", "parameterized", "tests", "." ]
def named_parameters(*testcases): # pylint: disable=invalid-name """A decorator for creating parameterized tests. See the module docstring for a usage example. The first element of each parameter tuple should be a string and will be appended to the name of the test method. Args: *testcases: Parameters for the decorated method, either a single iterable, or a list of tuples. Returns: A test generator to be handled by TestGeneratorMetaclass. """ return _ParameterDecorator(_FIRST_ARG, testcases)
[ "def", "named_parameters", "(", "*", "testcases", ")", ":", "# pylint: disable=invalid-name", "return", "_ParameterDecorator", "(", "_FIRST_ARG", ",", "testcases", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/_parameterized.py#L330-L344
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tix.py
python
CheckList.open
(self, entrypath)
Open the entry given by entryPath if its mode is open.
Open the entry given by entryPath if its mode is open.
[ "Open", "the", "entry", "given", "by", "entryPath", "if", "its", "mode", "is", "open", "." ]
def open(self, entrypath): '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath)
[ "def", "open", "(", "self", ",", "entrypath", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'open'", ",", "entrypath", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tix.py#L1580-L1582
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/prefilter.py
python
PrefilterManager.init_transformers
(self)
Create the default transformers.
Create the default transformers.
[ "Create", "the", "default", "transformers", "." ]
def init_transformers(self): """Create the default transformers.""" self._transformers = [] for transformer_cls in _default_transformers: transformer_cls( shell=self.shell, prefilter_manager=self, parent=self )
[ "def", "init_transformers", "(", "self", ")", ":", "self", ".", "_transformers", "=", "[", "]", "for", "transformer_cls", "in", "_default_transformers", ":", "transformer_cls", "(", "shell", "=", "self", ".", "shell", ",", "prefilter_manager", "=", "self", ",", "parent", "=", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/prefilter.py#L131-L137
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBSection.GetFileAddress
(self)
return _lldb.SBSection_GetFileAddress(self)
GetFileAddress(self) -> addr_t
GetFileAddress(self) -> addr_t
[ "GetFileAddress", "(", "self", ")", "-", ">", "addr_t" ]
def GetFileAddress(self): """GetFileAddress(self) -> addr_t""" return _lldb.SBSection_GetFileAddress(self)
[ "def", "GetFileAddress", "(", "self", ")", ":", "return", "_lldb", ".", "SBSection_GetFileAddress", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7704-L7706
jsupancic/deep_hand_pose
22cbeae1a8410ff5d37c060c7315719d0a5d608f
scripts/cpp_lint.py
python
FindPreviousMatchingAngleBracket
(clean_lines, linenum, init_prefix)
return False
Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists.
Find the corresponding < that started a template.
[ "Find", "the", "corresponding", "<", "that", "started", "a", "template", "." ]
def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): """Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists. """ line = init_prefix nesting_stack = ['>'] while True: # Find the previous operator match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) if match: # Found an operator, update nesting stack operator = match.group(2) line = match.group(1) if nesting_stack[-1] == '>': # Expecting opening angle bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator == '<': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma before a bracket, this is most likely a # template argument. The opening angle bracket is probably # there if we look for it, so just return early here. return True else: # Got some other operator. return False else: # Expecting opening parenthesis or opening bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator in ('(', '['): nesting_stack.pop() else: # Scan the previous line linenum -= 1 if linenum < 0: break line = clean_lines.elided[linenum] # Exhausted all earlier lines and still no matching angle bracket. return False
[ "def", "FindPreviousMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_prefix", ")", ":", "line", "=", "init_prefix", "nesting_stack", "=", "[", "'>'", "]", "while", "True", ":", "# Find the previous operator", "match", "=", "Search", "(", "r'^(.*)([<>(),;\\[\\]])[^<>(),;\\[\\]]*$'", ",", "line", ")", "if", "match", ":", "# Found an operator, update nesting stack", "operator", "=", "match", ".", "group", "(", "2", ")", "line", "=", "match", ".", "group", "(", "1", ")", "if", "nesting_stack", "[", "-", "1", "]", "==", "'>'", ":", "# Expecting opening angle bracket", "if", "operator", "in", "(", "'>'", ",", "')'", ",", "']'", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "==", "'<'", ":", "nesting_stack", ".", "pop", "(", ")", "if", "not", "nesting_stack", ":", "# Found matching angle bracket", "return", "True", "elif", "operator", "==", "','", ":", "# Got a comma before a bracket, this is most likely a", "# template argument. The opening angle bracket is probably", "# there if we look for it, so just return early here.", "return", "True", "else", ":", "# Got some other operator.", "return", "False", "else", ":", "# Expecting opening parenthesis or opening bracket", "if", "operator", "in", "(", "'>'", ",", "')'", ",", "']'", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "in", "(", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "pop", "(", ")", "else", ":", "# Scan the previous line", "linenum", "-=", "1", "if", "linenum", "<", "0", ":", "break", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Exhausted all earlier lines and still no matching angle bracket.", "return", "False" ]
https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L2586-L2640
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "." ]
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] startchar = line[pos] if startchar not in '({[<': return (line, clean_lines.NumLines(), -1) if startchar == '(': endchar = ')' if startchar == '[': endchar = ']' if startchar == '{': endchar = '}' if startchar == '<': endchar = '>' # Check first line (end_pos, num_open) = FindEndOfExpressionInLine( line, pos, 0, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, num_open) = FindEndOfExpressionInLine( line, 0, num_open, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Did not find endchar before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "startchar", "=", "line", "[", "pos", "]", "if", "startchar", "not", "in", "'({[<'", ":", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")", "if", "startchar", "==", "'('", ":", "endchar", "=", "')'", "if", "startchar", "==", "'['", ":", "endchar", "=", "']'", "if", "startchar", "==", "'{'", ":", "endchar", "=", "'}'", "if", "startchar", "==", "'<'", ":", "endchar", "=", "'>'", "# Check first line", "(", "end_pos", ",", "num_open", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Continue scanning forward", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "linenum", "+=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "end_pos", ",", "num_open", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "0", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Did not find endchar before end of file, give up", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L1254-L1297
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pythonapi.py
python
PythonAPI.long_from_unsigned_int
(self, ival)
Same as long_from_signed_int, but for unsigned values.
Same as long_from_signed_int, but for unsigned values.
[ "Same", "as", "long_from_signed_int", "but", "for", "unsigned", "values", "." ]
def long_from_unsigned_int(self, ival): """ Same as long_from_signed_int, but for unsigned values. """ bits = ival.type.width if bits <= self.ulong.width: return self.long_from_ulong(self.builder.zext(ival, self.ulong)) elif bits <= self.ulonglong.width: return self.long_from_ulonglong(self.builder.zext(ival, self.ulonglong)) else: raise OverflowError("integer too big (%d bits)" % (bits))
[ "def", "long_from_unsigned_int", "(", "self", ",", "ival", ")", ":", "bits", "=", "ival", ".", "type", ".", "width", "if", "bits", "<=", "self", ".", "ulong", ".", "width", ":", "return", "self", ".", "long_from_ulong", "(", "self", ".", "builder", ".", "zext", "(", "ival", ",", "self", ".", "ulong", ")", ")", "elif", "bits", "<=", "self", ".", "ulonglong", ".", "width", ":", "return", "self", ".", "long_from_ulonglong", "(", "self", ".", "builder", ".", "zext", "(", "ival", ",", "self", ".", "ulonglong", ")", ")", "else", ":", "raise", "OverflowError", "(", "\"integer too big (%d bits)\"", "%", "(", "bits", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pythonapi.py#L559-L569
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
KeyEvent.GetRawKeyCode
(*args, **kwargs)
return _core_.KeyEvent_GetRawKeyCode(*args, **kwargs)
GetRawKeyCode(self) -> unsigned int Returns the raw key code for this event. This is a platform-dependent scan code which should only be used in advanced applications. Currently the raw key codes are not supported by all ports.
GetRawKeyCode(self) -> unsigned int
[ "GetRawKeyCode", "(", "self", ")", "-", ">", "unsigned", "int" ]
def GetRawKeyCode(*args, **kwargs): """ GetRawKeyCode(self) -> unsigned int Returns the raw key code for this event. This is a platform-dependent scan code which should only be used in advanced applications. Currently the raw key codes are not supported by all ports. """ return _core_.KeyEvent_GetRawKeyCode(*args, **kwargs)
[ "def", "GetRawKeyCode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "KeyEvent_GetRawKeyCode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L6040-L6049
netease-youdao/hex
d7b8773dae8dde63f3807cef1d48c017077db727
tools/make_hex_module.py
python
transfer_files
(cef_dir, script_dir, transfer_cfg, output_dir, quiet)
Transfer files based on the specified configuration.
Transfer files based on the specified configuration.
[ "Transfer", "files", "based", "on", "the", "specified", "configuration", "." ]
def transfer_files(cef_dir, script_dir, transfer_cfg, output_dir, quiet): """ Transfer files based on the specified configuration. """ if not path_exists(transfer_cfg): return configs = eval_file(transfer_cfg) for cfg in configs: dst = os.path.join(output_dir, cfg['target']) # perform a copy if source is specified if not cfg['source'] is None: src = os.path.join(cef_dir, cfg['source']) dst_path = os.path.dirname(dst) make_dir(dst_path, quiet) copy_file(src, dst, quiet) # place a readme file in the destination directory readme = os.path.join(dst_path, 'README-TRANSFER.txt') if not path_exists(readme): copy_file(os.path.join(script_dir, 'distrib/README-TRANSFER.txt'), readme) open(readme, 'ab').write(cfg['source']+"\n") # perform any required post-processing if 'post-process' in cfg: post = cfg['post-process'] if post == 'normalize_headers': new_path = '' if cfg.has_key('new_header_path'): new_path = cfg['new_header_path'] normalize_headers(dst, new_path)
[ "def", "transfer_files", "(", "cef_dir", ",", "script_dir", ",", "transfer_cfg", ",", "output_dir", ",", "quiet", ")", ":", "if", "not", "path_exists", "(", "transfer_cfg", ")", ":", "return", "configs", "=", "eval_file", "(", "transfer_cfg", ")", "for", "cfg", "in", "configs", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "cfg", "[", "'target'", "]", ")", "# perform a copy if source is specified", "if", "not", "cfg", "[", "'source'", "]", "is", "None", ":", "src", "=", "os", ".", "path", ".", "join", "(", "cef_dir", ",", "cfg", "[", "'source'", "]", ")", "dst_path", "=", "os", ".", "path", ".", "dirname", "(", "dst", ")", "make_dir", "(", "dst_path", ",", "quiet", ")", "copy_file", "(", "src", ",", "dst", ",", "quiet", ")", "# place a readme file in the destination directory", "readme", "=", "os", ".", "path", ".", "join", "(", "dst_path", ",", "'README-TRANSFER.txt'", ")", "if", "not", "path_exists", "(", "readme", ")", ":", "copy_file", "(", "os", ".", "path", ".", "join", "(", "script_dir", ",", "'distrib/README-TRANSFER.txt'", ")", ",", "readme", ")", "open", "(", "readme", ",", "'ab'", ")", ".", "write", "(", "cfg", "[", "'source'", "]", "+", "\"\\n\"", ")", "# perform any required post-processing", "if", "'post-process'", "in", "cfg", ":", "post", "=", "cfg", "[", "'post-process'", "]", "if", "post", "==", "'normalize_headers'", ":", "new_path", "=", "''", "if", "cfg", ".", "has_key", "(", "'new_header_path'", ")", ":", "new_path", "=", "cfg", "[", "'new_header_path'", "]", "normalize_headers", "(", "dst", ",", "new_path", ")" ]
https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/make_hex_module.py#L147-L176
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/multi_process_runner.py
python
get_barrier
()
return _barrier
Returns a `multiprocessing.Barrier` for `multi_process_runner.run`. `tf.__internal__.distribute.multi_process_runner.get_barrier()` returns a `multiprocessing.Barrier` object which can be used within `fn` of `tf.__internal__.distribute.multi_process_runner` to wait with `barrier.wait()` call until all other tasks have also reached the `barrier.wait()` call, before they can proceed individually. Note that all tasks (subprocesses) have to reach `barrier.wait()` call to proceed. Currently it is not supported to block on only a subset of tasks in the cluster. Example: ```python def fn(): some_work_to_be_done_by_all_tasks() tf.__internal__.distribute.multi_process_runner.get_barrier().wait() # The barrier guarantees that at this point, all tasks have finished # `some_work_to_be_done_by_all_tasks()` some_other_work_to_be_done_by_all_tasks() result = tf.__internal__.distribute.multi_process_runner.run( fn=fn, cluster_spec=( tf.__internal__ .distribute.multi_process_runner.create_cluster_spec( num_workers=2))) ``` Returns: A `multiprocessing.Barrier` for `multi_process_runner.run`.
Returns a `multiprocessing.Barrier` for `multi_process_runner.run`.
[ "Returns", "a", "multiprocessing", ".", "Barrier", "for", "multi_process_runner", ".", "run", "." ]
def get_barrier(): """Returns a `multiprocessing.Barrier` for `multi_process_runner.run`. `tf.__internal__.distribute.multi_process_runner.get_barrier()` returns a `multiprocessing.Barrier` object which can be used within `fn` of `tf.__internal__.distribute.multi_process_runner` to wait with `barrier.wait()` call until all other tasks have also reached the `barrier.wait()` call, before they can proceed individually. Note that all tasks (subprocesses) have to reach `barrier.wait()` call to proceed. Currently it is not supported to block on only a subset of tasks in the cluster. Example: ```python def fn(): some_work_to_be_done_by_all_tasks() tf.__internal__.distribute.multi_process_runner.get_barrier().wait() # The barrier guarantees that at this point, all tasks have finished # `some_work_to_be_done_by_all_tasks()` some_other_work_to_be_done_by_all_tasks() result = tf.__internal__.distribute.multi_process_runner.run( fn=fn, cluster_spec=( tf.__internal__ .distribute.multi_process_runner.create_cluster_spec( num_workers=2))) ``` Returns: A `multiprocessing.Barrier` for `multi_process_runner.run`. """ if _barrier is None: raise ValueError( 'barrier is not defined. It is likely because you are calling ' 'get_barrier() in the main process. get_barrier() can only be called ' 'in the subprocesses.' ) return _barrier
[ "def", "get_barrier", "(", ")", ":", "if", "_barrier", "is", "None", ":", "raise", "ValueError", "(", "'barrier is not defined. It is likely because you are calling '", "'get_barrier() in the main process. get_barrier() can only be called '", "'in the subprocesses.'", ")", "return", "_barrier" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/multi_process_runner.py#L1338-L1381
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathEngraveBase.py
python
ObjectOp.opSetDefaultValues
(self, obj, job)
opSetDefaultValues(obj) ... set depths for engraving
opSetDefaultValues(obj) ... set depths for engraving
[ "opSetDefaultValues", "(", "obj", ")", "...", "set", "depths", "for", "engraving" ]
def opSetDefaultValues(self, obj, job): """opSetDefaultValues(obj) ... set depths for engraving""" if PathOp.FeatureDepths & self.opFeatures(obj): if job and len(job.Model.Group) > 0: bb = job.Proxy.modelBoundBox(job) obj.OpStartDepth = bb.ZMax obj.OpFinalDepth = bb.ZMax - max(obj.StepDown.Value, 0.1) else: obj.OpFinalDepth = -0.1
[ "def", "opSetDefaultValues", "(", "self", ",", "obj", ",", "job", ")", ":", "if", "PathOp", ".", "FeatureDepths", "&", "self", ".", "opFeatures", "(", "obj", ")", ":", "if", "job", "and", "len", "(", "job", ".", "Model", ".", "Group", ")", ">", "0", ":", "bb", "=", "job", ".", "Proxy", ".", "modelBoundBox", "(", "job", ")", "obj", ".", "OpStartDepth", "=", "bb", ".", "ZMax", "obj", ".", "OpFinalDepth", "=", "bb", ".", "ZMax", "-", "max", "(", "obj", ".", "StepDown", ".", "Value", ",", "0.1", ")", "else", ":", "obj", ".", "OpFinalDepth", "=", "-", "0.1" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathEngraveBase.py#L156-L164
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py
python
ChainMap.popitem
(self)
Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.
Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.
[ "Remove", "and", "return", "an", "item", "pair", "from", "maps", "[", "0", "]", ".", "Raise", "KeyError", "is", "maps", "[", "0", "]", "is", "empty", "." ]
def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except KeyError: raise KeyError('No keys found in the first mapping.')
[ "def", "popitem", "(", "self", ")", ":", "try", ":", "return", "self", ".", "maps", "[", "0", "]", ".", "popitem", "(", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'No keys found in the first mapping.'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/collections/__init__.py#L974-L979
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/javascripttokenizer.py
python
JavaScriptTokenizer.BuildMatchers
(cls)
return { # Matchers for basic text mode. JavaScriptModes.TEXT_MODE: [ # Check a big group - strings, starting comments, and regexes - all # of which could be intertwined. 'string with /regex/', # /regex with 'string'/, /* comment with /regex/ and string */ (and # so on) Matcher(cls.START_DOC_COMMENT, Type.START_DOC_COMMENT, JavaScriptModes.DOC_COMMENT_MODE), Matcher(cls.START_BLOCK_COMMENT, Type.START_BLOCK_COMMENT, JavaScriptModes.BLOCK_COMMENT_MODE), Matcher(cls.END_OF_LINE_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT), Matcher(cls.START_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT, JavaScriptModes.LINE_COMMENT_MODE), Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_START, JavaScriptModes.SINGLE_QUOTE_STRING_MODE), Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_START, JavaScriptModes.DOUBLE_QUOTE_STRING_MODE), Matcher(cls.REGEX, Type.REGEX), # Next we check for start blocks appearing outside any of the items # above. Matcher(cls.START_BLOCK, Type.START_BLOCK), Matcher(cls.END_BLOCK, Type.END_BLOCK), # Then we search for function declarations. Matcher(cls.FUNCTION_DECLARATION, Type.FUNCTION_DECLARATION, JavaScriptModes.FUNCTION_MODE), # Next, we convert non-function related parens to tokens. Matcher(cls.OPENING_PAREN, Type.START_PAREN), Matcher(cls.CLOSING_PAREN, Type.END_PAREN), # Next, we convert brackets to tokens. Matcher(cls.OPENING_BRACKET, Type.START_BRACKET), Matcher(cls.CLOSING_BRACKET, Type.END_BRACKET), # Find numbers. This has to happen before operators because # scientific notation numbers can have + and - in them. Matcher(cls.NUMBER, Type.NUMBER), # Find operators and simple assignments Matcher(cls.SIMPLE_LVALUE, Type.SIMPLE_LVALUE), Matcher(cls.OPERATOR, Type.OPERATOR), # Find key words and whitespace. Matcher(keyword, Type.KEYWORD), Matcher(cls.WHITESPACE, Type.WHITESPACE), # Find identifiers. Matcher(cls.IDENTIFIER, Type.IDENTIFIER), # Finally, we convert semicolons to tokens. Matcher(cls.SEMICOLON, Type.SEMICOLON)], # Matchers for single quote strings. JavaScriptModes.SINGLE_QUOTE_STRING_MODE: [ Matcher(cls.SINGLE_QUOTE_TEXT, Type.STRING_TEXT), Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_END, JavaScriptModes.TEXT_MODE)], # Matchers for double quote strings. JavaScriptModes.DOUBLE_QUOTE_STRING_MODE: [ Matcher(cls.DOUBLE_QUOTE_TEXT, Type.STRING_TEXT), Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_END, JavaScriptModes.TEXT_MODE)], # Matchers for block comments. JavaScriptModes.BLOCK_COMMENT_MODE: [ # First we check for exiting a block comment. Matcher(cls.END_BLOCK_COMMENT, Type.END_BLOCK_COMMENT, JavaScriptModes.TEXT_MODE), # Match non-comment-ending text.. Matcher(cls.BLOCK_COMMENT_TEXT, Type.COMMENT)], # Matchers for doc comments. JavaScriptModes.DOC_COMMENT_MODE: cls.COMMON_DOC_MATCHERS + [ Matcher(cls.DOC_COMMENT_TEXT, Type.COMMENT)], JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: cls.COMMON_DOC_MATCHERS + [ Matcher(cls.WHITESPACE, Type.COMMENT), Matcher(cls.DOC_COMMENT_NO_SPACES_TEXT, Type.COMMENT)], # Matchers for single line comments. JavaScriptModes.LINE_COMMENT_MODE: [ # We greedy match until the end of the line in line comment mode. Matcher(cls.ANYTHING, Type.COMMENT, JavaScriptModes.TEXT_MODE)], # Matchers for code after the function keyword. JavaScriptModes.FUNCTION_MODE: [ # Must match open paren before anything else and move into parameter # mode, otherwise everything inside the parameter list is parsed # incorrectly. Matcher(cls.OPENING_PAREN, Type.START_PARAMETERS, JavaScriptModes.PARAMETER_MODE), Matcher(cls.WHITESPACE, Type.WHITESPACE), Matcher(cls.IDENTIFIER, Type.FUNCTION_NAME)], # Matchers for function parameters JavaScriptModes.PARAMETER_MODE: [ # When in function parameter mode, a closing paren is treated # specially. Everything else is treated as lines of parameters. Matcher(cls.CLOSING_PAREN_WITH_SPACE, Type.END_PARAMETERS, JavaScriptModes.TEXT_MODE), Matcher(cls.PARAMETERS, Type.PARAMETERS, JavaScriptModes.PARAMETER_MODE)]}
Builds the token matcher group. The token matcher groups work as follows: it is a list of Matcher objects. The matchers will be tried in this order, and the first to match will be returned. Hence the order is important because the matchers that come first overrule the matchers that come later. Returns: The completed token matcher group.
Builds the token matcher group.
[ "Builds", "the", "token", "matcher", "group", "." ]
def BuildMatchers(cls): """Builds the token matcher group. The token matcher groups work as follows: it is a list of Matcher objects. The matchers will be tried in this order, and the first to match will be returned. Hence the order is important because the matchers that come first overrule the matchers that come later. Returns: The completed token matcher group. """ # Match a keyword string followed by a non-identifier character in order to # not match something like doSomething as do + Something. keyword = re.compile('(%s)((?=[^%s])|$)' % ( '|'.join(cls.KEYWORD_LIST), cls.IDENTIFIER_CHAR)) return { # Matchers for basic text mode. JavaScriptModes.TEXT_MODE: [ # Check a big group - strings, starting comments, and regexes - all # of which could be intertwined. 'string with /regex/', # /regex with 'string'/, /* comment with /regex/ and string */ (and # so on) Matcher(cls.START_DOC_COMMENT, Type.START_DOC_COMMENT, JavaScriptModes.DOC_COMMENT_MODE), Matcher(cls.START_BLOCK_COMMENT, Type.START_BLOCK_COMMENT, JavaScriptModes.BLOCK_COMMENT_MODE), Matcher(cls.END_OF_LINE_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT), Matcher(cls.START_SINGLE_LINE_COMMENT, Type.START_SINGLE_LINE_COMMENT, JavaScriptModes.LINE_COMMENT_MODE), Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_START, JavaScriptModes.SINGLE_QUOTE_STRING_MODE), Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_START, JavaScriptModes.DOUBLE_QUOTE_STRING_MODE), Matcher(cls.REGEX, Type.REGEX), # Next we check for start blocks appearing outside any of the items # above. Matcher(cls.START_BLOCK, Type.START_BLOCK), Matcher(cls.END_BLOCK, Type.END_BLOCK), # Then we search for function declarations. Matcher(cls.FUNCTION_DECLARATION, Type.FUNCTION_DECLARATION, JavaScriptModes.FUNCTION_MODE), # Next, we convert non-function related parens to tokens. Matcher(cls.OPENING_PAREN, Type.START_PAREN), Matcher(cls.CLOSING_PAREN, Type.END_PAREN), # Next, we convert brackets to tokens. Matcher(cls.OPENING_BRACKET, Type.START_BRACKET), Matcher(cls.CLOSING_BRACKET, Type.END_BRACKET), # Find numbers. This has to happen before operators because # scientific notation numbers can have + and - in them. Matcher(cls.NUMBER, Type.NUMBER), # Find operators and simple assignments Matcher(cls.SIMPLE_LVALUE, Type.SIMPLE_LVALUE), Matcher(cls.OPERATOR, Type.OPERATOR), # Find key words and whitespace. Matcher(keyword, Type.KEYWORD), Matcher(cls.WHITESPACE, Type.WHITESPACE), # Find identifiers. Matcher(cls.IDENTIFIER, Type.IDENTIFIER), # Finally, we convert semicolons to tokens. Matcher(cls.SEMICOLON, Type.SEMICOLON)], # Matchers for single quote strings. JavaScriptModes.SINGLE_QUOTE_STRING_MODE: [ Matcher(cls.SINGLE_QUOTE_TEXT, Type.STRING_TEXT), Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_END, JavaScriptModes.TEXT_MODE)], # Matchers for double quote strings. JavaScriptModes.DOUBLE_QUOTE_STRING_MODE: [ Matcher(cls.DOUBLE_QUOTE_TEXT, Type.STRING_TEXT), Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_END, JavaScriptModes.TEXT_MODE)], # Matchers for block comments. JavaScriptModes.BLOCK_COMMENT_MODE: [ # First we check for exiting a block comment. Matcher(cls.END_BLOCK_COMMENT, Type.END_BLOCK_COMMENT, JavaScriptModes.TEXT_MODE), # Match non-comment-ending text.. Matcher(cls.BLOCK_COMMENT_TEXT, Type.COMMENT)], # Matchers for doc comments. JavaScriptModes.DOC_COMMENT_MODE: cls.COMMON_DOC_MATCHERS + [ Matcher(cls.DOC_COMMENT_TEXT, Type.COMMENT)], JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: cls.COMMON_DOC_MATCHERS + [ Matcher(cls.WHITESPACE, Type.COMMENT), Matcher(cls.DOC_COMMENT_NO_SPACES_TEXT, Type.COMMENT)], # Matchers for single line comments. JavaScriptModes.LINE_COMMENT_MODE: [ # We greedy match until the end of the line in line comment mode. Matcher(cls.ANYTHING, Type.COMMENT, JavaScriptModes.TEXT_MODE)], # Matchers for code after the function keyword. JavaScriptModes.FUNCTION_MODE: [ # Must match open paren before anything else and move into parameter # mode, otherwise everything inside the parameter list is parsed # incorrectly. Matcher(cls.OPENING_PAREN, Type.START_PARAMETERS, JavaScriptModes.PARAMETER_MODE), Matcher(cls.WHITESPACE, Type.WHITESPACE), Matcher(cls.IDENTIFIER, Type.FUNCTION_NAME)], # Matchers for function parameters JavaScriptModes.PARAMETER_MODE: [ # When in function parameter mode, a closing paren is treated # specially. Everything else is treated as lines of parameters. Matcher(cls.CLOSING_PAREN_WITH_SPACE, Type.END_PARAMETERS, JavaScriptModes.TEXT_MODE), Matcher(cls.PARAMETERS, Type.PARAMETERS, JavaScriptModes.PARAMETER_MODE)]}
[ "def", "BuildMatchers", "(", "cls", ")", ":", "# Match a keyword string followed by a non-identifier character in order to", "# not match something like doSomething as do + Something.", "keyword", "=", "re", ".", "compile", "(", "'(%s)((?=[^%s])|$)'", "%", "(", "'|'", ".", "join", "(", "cls", ".", "KEYWORD_LIST", ")", ",", "cls", ".", "IDENTIFIER_CHAR", ")", ")", "return", "{", "# Matchers for basic text mode.", "JavaScriptModes", ".", "TEXT_MODE", ":", "[", "# Check a big group - strings, starting comments, and regexes - all", "# of which could be intertwined. 'string with /regex/',", "# /regex with 'string'/, /* comment with /regex/ and string */ (and", "# so on)", "Matcher", "(", "cls", ".", "START_DOC_COMMENT", ",", "Type", ".", "START_DOC_COMMENT", ",", "JavaScriptModes", ".", "DOC_COMMENT_MODE", ")", ",", "Matcher", "(", "cls", ".", "START_BLOCK_COMMENT", ",", "Type", ".", "START_BLOCK_COMMENT", ",", "JavaScriptModes", ".", "BLOCK_COMMENT_MODE", ")", ",", "Matcher", "(", "cls", ".", "END_OF_LINE_SINGLE_LINE_COMMENT", ",", "Type", ".", "START_SINGLE_LINE_COMMENT", ")", ",", "Matcher", "(", "cls", ".", "START_SINGLE_LINE_COMMENT", ",", "Type", ".", "START_SINGLE_LINE_COMMENT", ",", "JavaScriptModes", ".", "LINE_COMMENT_MODE", ")", ",", "Matcher", "(", "cls", ".", "SINGLE_QUOTE", ",", "Type", ".", "SINGLE_QUOTE_STRING_START", ",", "JavaScriptModes", ".", "SINGLE_QUOTE_STRING_MODE", ")", ",", "Matcher", "(", "cls", ".", "DOUBLE_QUOTE", ",", "Type", ".", "DOUBLE_QUOTE_STRING_START", ",", "JavaScriptModes", ".", "DOUBLE_QUOTE_STRING_MODE", ")", ",", "Matcher", "(", "cls", ".", "REGEX", ",", "Type", ".", "REGEX", ")", ",", "# Next we check for start blocks appearing outside any of the items", "# above.", "Matcher", "(", "cls", ".", "START_BLOCK", ",", "Type", ".", "START_BLOCK", ")", ",", "Matcher", "(", "cls", ".", "END_BLOCK", ",", "Type", ".", "END_BLOCK", ")", ",", "# Then we search for function declarations.", "Matcher", "(", "cls", ".", "FUNCTION_DECLARATION", ",", "Type", ".", "FUNCTION_DECLARATION", ",", "JavaScriptModes", ".", "FUNCTION_MODE", ")", ",", "# Next, we convert non-function related parens to tokens.", "Matcher", "(", "cls", ".", "OPENING_PAREN", ",", "Type", ".", "START_PAREN", ")", ",", "Matcher", "(", "cls", ".", "CLOSING_PAREN", ",", "Type", ".", "END_PAREN", ")", ",", "# Next, we convert brackets to tokens.", "Matcher", "(", "cls", ".", "OPENING_BRACKET", ",", "Type", ".", "START_BRACKET", ")", ",", "Matcher", "(", "cls", ".", "CLOSING_BRACKET", ",", "Type", ".", "END_BRACKET", ")", ",", "# Find numbers. This has to happen before operators because", "# scientific notation numbers can have + and - in them.", "Matcher", "(", "cls", ".", "NUMBER", ",", "Type", ".", "NUMBER", ")", ",", "# Find operators and simple assignments", "Matcher", "(", "cls", ".", "SIMPLE_LVALUE", ",", "Type", ".", "SIMPLE_LVALUE", ")", ",", "Matcher", "(", "cls", ".", "OPERATOR", ",", "Type", ".", "OPERATOR", ")", ",", "# Find key words and whitespace.", "Matcher", "(", "keyword", ",", "Type", ".", "KEYWORD", ")", ",", "Matcher", "(", "cls", ".", "WHITESPACE", ",", "Type", ".", "WHITESPACE", ")", ",", "# Find identifiers.", "Matcher", "(", "cls", ".", "IDENTIFIER", ",", "Type", ".", "IDENTIFIER", ")", ",", "# Finally, we convert semicolons to tokens.", "Matcher", "(", "cls", ".", "SEMICOLON", ",", "Type", ".", "SEMICOLON", ")", "]", ",", "# Matchers for single quote strings.", "JavaScriptModes", ".", "SINGLE_QUOTE_STRING_MODE", ":", "[", "Matcher", "(", "cls", ".", "SINGLE_QUOTE_TEXT", ",", "Type", ".", "STRING_TEXT", ")", ",", "Matcher", "(", "cls", ".", "SINGLE_QUOTE", ",", "Type", ".", "SINGLE_QUOTE_STRING_END", ",", "JavaScriptModes", ".", "TEXT_MODE", ")", "]", ",", "# Matchers for double quote strings.", "JavaScriptModes", ".", "DOUBLE_QUOTE_STRING_MODE", ":", "[", "Matcher", "(", "cls", ".", "DOUBLE_QUOTE_TEXT", ",", "Type", ".", "STRING_TEXT", ")", ",", "Matcher", "(", "cls", ".", "DOUBLE_QUOTE", ",", "Type", ".", "DOUBLE_QUOTE_STRING_END", ",", "JavaScriptModes", ".", "TEXT_MODE", ")", "]", ",", "# Matchers for block comments.", "JavaScriptModes", ".", "BLOCK_COMMENT_MODE", ":", "[", "# First we check for exiting a block comment.", "Matcher", "(", "cls", ".", "END_BLOCK_COMMENT", ",", "Type", ".", "END_BLOCK_COMMENT", ",", "JavaScriptModes", ".", "TEXT_MODE", ")", ",", "# Match non-comment-ending text..", "Matcher", "(", "cls", ".", "BLOCK_COMMENT_TEXT", ",", "Type", ".", "COMMENT", ")", "]", ",", "# Matchers for doc comments.", "JavaScriptModes", ".", "DOC_COMMENT_MODE", ":", "cls", ".", "COMMON_DOC_MATCHERS", "+", "[", "Matcher", "(", "cls", ".", "DOC_COMMENT_TEXT", ",", "Type", ".", "COMMENT", ")", "]", ",", "JavaScriptModes", ".", "DOC_COMMENT_LEX_SPACES_MODE", ":", "cls", ".", "COMMON_DOC_MATCHERS", "+", "[", "Matcher", "(", "cls", ".", "WHITESPACE", ",", "Type", ".", "COMMENT", ")", ",", "Matcher", "(", "cls", ".", "DOC_COMMENT_NO_SPACES_TEXT", ",", "Type", ".", "COMMENT", ")", "]", ",", "# Matchers for single line comments.", "JavaScriptModes", ".", "LINE_COMMENT_MODE", ":", "[", "# We greedy match until the end of the line in line comment mode.", "Matcher", "(", "cls", ".", "ANYTHING", ",", "Type", ".", "COMMENT", ",", "JavaScriptModes", ".", "TEXT_MODE", ")", "]", ",", "# Matchers for code after the function keyword.", "JavaScriptModes", ".", "FUNCTION_MODE", ":", "[", "# Must match open paren before anything else and move into parameter", "# mode, otherwise everything inside the parameter list is parsed", "# incorrectly.", "Matcher", "(", "cls", ".", "OPENING_PAREN", ",", "Type", ".", "START_PARAMETERS", ",", "JavaScriptModes", ".", "PARAMETER_MODE", ")", ",", "Matcher", "(", "cls", ".", "WHITESPACE", ",", "Type", ".", "WHITESPACE", ")", ",", "Matcher", "(", "cls", ".", "IDENTIFIER", ",", "Type", ".", "FUNCTION_NAME", ")", "]", ",", "# Matchers for function parameters", "JavaScriptModes", ".", "PARAMETER_MODE", ":", "[", "# When in function parameter mode, a closing paren is treated", "# specially. Everything else is treated as lines of parameters.", "Matcher", "(", "cls", ".", "CLOSING_PAREN_WITH_SPACE", ",", "Type", ".", "END_PARAMETERS", ",", "JavaScriptModes", ".", "TEXT_MODE", ")", ",", "Matcher", "(", "cls", ".", "PARAMETERS", ",", "Type", ".", "PARAMETERS", ",", "JavaScriptModes", ".", "PARAMETER_MODE", ")", "]", "}" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/javascripttokenizer.py#L309-L433
wy1iu/LargeMargin_Softmax_Loss
c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec
python/caffe/coord_map.py
python
compose
(base_map, next_map)
return ax, a1 * a2, a1 * b2 + b1
Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1.
Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1.
[ "Compose", "a", "base", "coord", "map", "with", "scale", "a1", "shift", "b1", "with", "a", "further", "coord", "map", "with", "scale", "a2", "shift", "b2", ".", "The", "scales", "multiply", "and", "the", "further", "shift", "b2", "is", "scaled", "by", "base", "coord", "scale", "a1", "." ]
def compose(base_map, next_map): """ Compose a base coord map with scale a1, shift b1 with a further coord map with scale a2, shift b2. The scales multiply and the further shift, b2, is scaled by base coord scale a1. """ ax1, a1, b1 = base_map ax2, a2, b2 = next_map if ax1 is None: ax = ax2 elif ax2 is None or ax1 == ax2: ax = ax1 else: raise AxisMismatchException return ax, a1 * a2, a1 * b2 + b1
[ "def", "compose", "(", "base_map", ",", "next_map", ")", ":", "ax1", ",", "a1", ",", "b1", "=", "base_map", "ax2", ",", "a2", ",", "b2", "=", "next_map", "if", "ax1", "is", "None", ":", "ax", "=", "ax2", "elif", "ax2", "is", "None", "or", "ax1", "==", "ax2", ":", "ax", "=", "ax1", "else", ":", "raise", "AxisMismatchException", "return", "ax", ",", "a1", "*", "a2", ",", "a1", "*", "b2", "+", "b1" ]
https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/python/caffe/coord_map.py#L89-L103
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/graph_analytics/_model_base.py
python
GraphAnalyticsModel._result_fields
(self)
return {"graph": "SGraph. See m['graph']"}
Return results information Fields should NOT be wrapped by _precomputed_field
Return results information Fields should NOT be wrapped by _precomputed_field
[ "Return", "results", "information", "Fields", "should", "NOT", "be", "wrapped", "by", "_precomputed_field" ]
def _result_fields(self): """ Return results information Fields should NOT be wrapped by _precomputed_field """ return {"graph": "SGraph. See m['graph']"}
[ "def", "_result_fields", "(", "self", ")", ":", "return", "{", "\"graph\"", ":", "\"SGraph. See m['graph']\"", "}" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/graph_analytics/_model_base.py#L179-L184
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextObject.Dump
(*args, **kwargs)
return _richtext.RichTextObject_Dump(*args, **kwargs)
Dump(self) -> String
Dump(self) -> String
[ "Dump", "(", "self", ")", "-", ">", "String" ]
def Dump(*args, **kwargs): """Dump(self) -> String""" return _richtext.RichTextObject_Dump(*args, **kwargs)
[ "def", "Dump", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_Dump", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L1250-L1252
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/osr.py
python
SpatialReference.GetAuthorityCode
(self, *args)
return _osr.SpatialReference_GetAuthorityCode(self, *args)
r"""GetAuthorityCode(SpatialReference self, char const * target_key) -> char const *
r"""GetAuthorityCode(SpatialReference self, char const * target_key) -> char const *
[ "r", "GetAuthorityCode", "(", "SpatialReference", "self", "char", "const", "*", "target_key", ")", "-", ">", "char", "const", "*" ]
def GetAuthorityCode(self, *args): r"""GetAuthorityCode(SpatialReference self, char const * target_key) -> char const *""" return _osr.SpatialReference_GetAuthorityCode(self, *args)
[ "def", "GetAuthorityCode", "(", "self", ",", "*", "args", ")", ":", "return", "_osr", ".", "SpatialReference_GetAuthorityCode", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L442-L444
widelands/widelands
e9f047d46a23d81312237d52eabf7d74e8de52d6
utils/find_unused_includes.py
python
find_includes
(file_to_check)
return files
Returns a set of includes.
Returns a set of includes.
[ "Returns", "a", "set", "of", "includes", "." ]
def find_includes(file_to_check): """Returns a set of includes.""" files = set() with open(file_to_check, 'r', encoding='utf-8') as f: for line in f.readlines(): line = line.strip() # Skip comments if line.startswith('*') or line.startswith('/'): continue match = HEADER_REGEX.match(line) if match and len(match.groups()) == 1: include_file = match.groups()[0] if os.path.isfile(include_file): files.add(include_file) return files
[ "def", "find_includes", "(", "file_to_check", ")", ":", "files", "=", "set", "(", ")", "with", "open", "(", "file_to_check", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "# Skip comments", "if", "line", ".", "startswith", "(", "'*'", ")", "or", "line", ".", "startswith", "(", "'/'", ")", ":", "continue", "match", "=", "HEADER_REGEX", ".", "match", "(", "line", ")", "if", "match", "and", "len", "(", "match", ".", "groups", "(", ")", ")", "==", "1", ":", "include_file", "=", "match", ".", "groups", "(", ")", "[", "0", "]", "if", "os", ".", "path", ".", "isfile", "(", "include_file", ")", ":", "files", ".", "add", "(", "include_file", ")", "return", "files" ]
https://github.com/widelands/widelands/blob/e9f047d46a23d81312237d52eabf7d74e8de52d6/utils/find_unused_includes.py#L108-L124
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/contacts/client.py
python
ContactsClient.get_feed_uri
(self, kind='contacts', contact_list=None, projection='full', scheme="http")
return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
Builds a feed URI. Args: kind: The type of feed to return, typically 'groups' or 'contacts'. Default value: 'contacts'. contact_list: The contact list to return a feed for. Default value: self.contact_list. projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given kind, contact list, and projection. Example: '/m8/feeds/contacts/default/full'.
Builds a feed URI.
[ "Builds", "a", "feed", "URI", "." ]
def get_feed_uri(self, kind='contacts', contact_list=None, projection='full', scheme="http"): """Builds a feed URI. Args: kind: The type of feed to return, typically 'groups' or 'contacts'. Default value: 'contacts'. contact_list: The contact list to return a feed for. Default value: self.contact_list. projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given kind, contact list, and projection. Example: '/m8/feeds/contacts/default/full'. """ contact_list = contact_list or self.contact_list if kind == 'profiles': contact_list = 'domain/%s' % contact_list prefix = scheme and '%s://%s' % (scheme, self.server) or '' return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
[ "def", "get_feed_uri", "(", "self", ",", "kind", "=", "'contacts'", ",", "contact_list", "=", "None", ",", "projection", "=", "'full'", ",", "scheme", "=", "\"http\"", ")", ":", "contact_list", "=", "contact_list", "or", "self", ".", "contact_list", "if", "kind", "==", "'profiles'", ":", "contact_list", "=", "'domain/%s'", "%", "contact_list", "prefix", "=", "scheme", "and", "'%s://%s'", "%", "(", "scheme", ",", "self", ".", "server", ")", "or", "''", "return", "'%s/m8/feeds/%s/%s/%s'", "%", "(", "prefix", ",", "kind", ",", "contact_list", ",", "projection", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/contacts/client.py#L38-L60
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/data/experimental/ops/io.py
python
save
(dataset, path, compression=None, shard_func=None, checkpoint_args=None)
Saves the content of the given dataset. Example usage: >>> import tempfile >>> path = os.path.join(tempfile.gettempdir(), "saved_data") >>> # Save a dataset >>> dataset = tf.data.Dataset.range(2) >>> tf.data.experimental.save(dataset, path) >>> new_dataset = tf.data.experimental.load(path) >>> for elem in new_dataset: ... print(elem) tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) The saved dataset is saved in multiple file "shards". By default, the dataset output is divided to shards in a round-robin fashion but custom sharding can be specified via the `shard_func` function. For example, you can save the dataset to using a single shard as follows: ```python dataset = make_dataset() def custom_shard_func(element): return 0 dataset = tf.data.experimental.save( path="/path/to/data", ..., shard_func=custom_shard_func) ``` To enable checkpointing, pass in `checkpoint_args` to the `save` method as follows: ```python dataset = tf.data.Dataset.range(100) save_dir = "..." checkpoint_prefix = "..." step_counter = tf.Variable(0, trainable=False) checkpoint_args = { "checkpoint_interval": 50, "step_counter": step_counter, "directory": checkpoint_prefix, "max_to_keep": 20, } dataset.save(dataset, save_dir, checkpoint_args=checkpoint_args) ``` NOTE: The directory layout and file format used for saving the dataset is considered an implementation detail and may change. For this reason, datasets saved through `tf.data.experimental.save` should only be consumed through `tf.data.experimental.load`, which is guaranteed to be backwards compatible. Args: dataset: The dataset to save. path: Required. A directory to use for saving the dataset. compression: Optional. The algorithm to use to compress data when writing it. Supported options are `GZIP` and `NONE`. Defaults to `NONE`. shard_func: Optional. A function to control the mapping of dataset elements to file shards. The function is expected to map elements of the input dataset to int64 shard IDs. If present, the function will be traced and executed as graph computation. checkpoint_args: Optional args for checkpointing which will be passed into the `tf.train.CheckpointManager`. If `checkpoint_args` are not specified, then checkpointing will not be performed. The `save()` implementation creates a `tf.train.Checkpoint` object internally, so users should not set the `checkpoint` argument in `checkpoint_args`. Raises: ValueError if `checkpoint` is passed into `checkpoint_args`.
Saves the content of the given dataset.
[ "Saves", "the", "content", "of", "the", "given", "dataset", "." ]
def save(dataset, path, compression=None, shard_func=None, checkpoint_args=None): """Saves the content of the given dataset. Example usage: >>> import tempfile >>> path = os.path.join(tempfile.gettempdir(), "saved_data") >>> # Save a dataset >>> dataset = tf.data.Dataset.range(2) >>> tf.data.experimental.save(dataset, path) >>> new_dataset = tf.data.experimental.load(path) >>> for elem in new_dataset: ... print(elem) tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) The saved dataset is saved in multiple file "shards". By default, the dataset output is divided to shards in a round-robin fashion but custom sharding can be specified via the `shard_func` function. For example, you can save the dataset to using a single shard as follows: ```python dataset = make_dataset() def custom_shard_func(element): return 0 dataset = tf.data.experimental.save( path="/path/to/data", ..., shard_func=custom_shard_func) ``` To enable checkpointing, pass in `checkpoint_args` to the `save` method as follows: ```python dataset = tf.data.Dataset.range(100) save_dir = "..." checkpoint_prefix = "..." step_counter = tf.Variable(0, trainable=False) checkpoint_args = { "checkpoint_interval": 50, "step_counter": step_counter, "directory": checkpoint_prefix, "max_to_keep": 20, } dataset.save(dataset, save_dir, checkpoint_args=checkpoint_args) ``` NOTE: The directory layout and file format used for saving the dataset is considered an implementation detail and may change. For this reason, datasets saved through `tf.data.experimental.save` should only be consumed through `tf.data.experimental.load`, which is guaranteed to be backwards compatible. Args: dataset: The dataset to save. path: Required. A directory to use for saving the dataset. compression: Optional. The algorithm to use to compress data when writing it. Supported options are `GZIP` and `NONE`. Defaults to `NONE`. shard_func: Optional. A function to control the mapping of dataset elements to file shards. The function is expected to map elements of the input dataset to int64 shard IDs. If present, the function will be traced and executed as graph computation. checkpoint_args: Optional args for checkpointing which will be passed into the `tf.train.CheckpointManager`. If `checkpoint_args` are not specified, then checkpointing will not be performed. The `save()` implementation creates a `tf.train.Checkpoint` object internally, so users should not set the `checkpoint` argument in `checkpoint_args`. Raises: ValueError if `checkpoint` is passed into `checkpoint_args`. """ if (context.executing_eagerly() and checkpoint_args and compat.forward_compatible(2021, 6, 29)): save_dataset = _SaveDataset(dataset, path, shard_func, compression) save_iterator = iter(save_dataset) if "checkpoint" in checkpoint_args: raise ValueError( "'Invalid `checkpoint_args`. `checkpoint_args` are not allowed " "to include 'checkpoint'." ) checkpoint = tracking.util.Checkpoint(iterator=save_iterator) checkpoint_args["checkpoint"] = checkpoint manager = checkpoint_management.CheckpointManager(**checkpoint_args) checkpoint.restore(manager.latest_checkpoint) for _ in enumerate(save_iterator): if "step_counter" in checkpoint_args: checkpoint_args["step_counter"].assign_add(delta=1) manager.save(check_interval=True) else: dataset, shard_func, use_shard_func, path = _set_save_dataset_attributes( dataset, shard_func, path) gen_experimental_dataset_ops.save_dataset( dataset._variant_tensor, # pylint: disable=protected-access path=path, shard_func_other_args=shard_func.captured_inputs, compression=compression, shard_func=shard_func, use_shard_func=use_shard_func)
[ "def", "save", "(", "dataset", ",", "path", ",", "compression", "=", "None", ",", "shard_func", "=", "None", ",", "checkpoint_args", "=", "None", ")", ":", "if", "(", "context", ".", "executing_eagerly", "(", ")", "and", "checkpoint_args", "and", "compat", ".", "forward_compatible", "(", "2021", ",", "6", ",", "29", ")", ")", ":", "save_dataset", "=", "_SaveDataset", "(", "dataset", ",", "path", ",", "shard_func", ",", "compression", ")", "save_iterator", "=", "iter", "(", "save_dataset", ")", "if", "\"checkpoint\"", "in", "checkpoint_args", ":", "raise", "ValueError", "(", "\"'Invalid `checkpoint_args`. `checkpoint_args` are not allowed \"", "\"to include 'checkpoint'.\"", ")", "checkpoint", "=", "tracking", ".", "util", ".", "Checkpoint", "(", "iterator", "=", "save_iterator", ")", "checkpoint_args", "[", "\"checkpoint\"", "]", "=", "checkpoint", "manager", "=", "checkpoint_management", ".", "CheckpointManager", "(", "*", "*", "checkpoint_args", ")", "checkpoint", ".", "restore", "(", "manager", ".", "latest_checkpoint", ")", "for", "_", "in", "enumerate", "(", "save_iterator", ")", ":", "if", "\"step_counter\"", "in", "checkpoint_args", ":", "checkpoint_args", "[", "\"step_counter\"", "]", ".", "assign_add", "(", "delta", "=", "1", ")", "manager", ".", "save", "(", "check_interval", "=", "True", ")", "else", ":", "dataset", ",", "shard_func", ",", "use_shard_func", ",", "path", "=", "_set_save_dataset_attributes", "(", "dataset", ",", "shard_func", ",", "path", ")", "gen_experimental_dataset_ops", ".", "save_dataset", "(", "dataset", ".", "_variant_tensor", ",", "# pylint: disable=protected-access", "path", "=", "path", ",", "shard_func_other_args", "=", "shard_func", ".", "captured_inputs", ",", "compression", "=", "compression", ",", "shard_func", "=", "shard_func", ",", "use_shard_func", "=", "use_shard_func", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/experimental/ops/io.py#L44-L144
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_trackers.py
python
ghostTracker.remove
(self)
Remove the ghost when switching to and from subelement mode.
Remove the ghost when switching to and from subelement mode.
[ "Remove", "the", "ghost", "when", "switching", "to", "and", "from", "subelement", "mode", "." ]
def remove(self): """Remove the ghost when switching to and from subelement mode.""" if self.switch: self.finalize()
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "switch", ":", "self", ".", "finalize", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trackers.py#L699-L702
strukturag/libheif
0082fea96ee70a20c8906a0373bedec0c01777bc
scripts/cpplint.py
python
_ShouldPrintError
(category, confidence, linenum)
return True
If confidence >= verbose, category passes filter and is not suppressed.
If confidence >= verbose, category passes filter and is not suppressed.
[ "If", "confidence", ">", "=", "verbose", "category", "passes", "filter", "and", "is", "not", "suppressed", "." ]
def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True
[ "def", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "# There are three ways we might decide not to print an error message:", "# a \"NOLINT(category)\" comment appears in the source,", "# the verbosity level isn't high enough, or the filters filter it out.", "if", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "False", "if", "confidence", "<", "_cpplint_state", ".", "verbose_level", ":", "return", "False", "is_filtered", "=", "False", "for", "one_filter", "in", "_Filters", "(", ")", ":", "if", "one_filter", ".", "startswith", "(", "'-'", ")", ":", "if", "category", ".", "startswith", "(", "one_filter", "[", "1", ":", "]", ")", ":", "is_filtered", "=", "True", "elif", "one_filter", ".", "startswith", "(", "'+'", ")", ":", "if", "category", ".", "startswith", "(", "one_filter", "[", "1", ":", "]", ")", ":", "is_filtered", "=", "False", "else", ":", "assert", "False", "# should have been checked for in SetFilter.", "if", "is_filtered", ":", "return", "False", "return", "True" ]
https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L1141-L1166
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/compat/__init__.py
python
add_metaclass
(metaclass)
return wrapper
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
[ "Class", "decorator", "for", "creating", "a", "class", "with", "a", "metaclass", "." ]
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) for slots_var in orig_vars.get('__slots__', ()): orig_vars.pop(slots_var) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "orig_vars", ".", "pop", "(", "'__dict__'", ",", "None", ")", "orig_vars", ".", "pop", "(", "'__weakref__'", ",", "None", ")", "for", "slots_var", "in", "orig_vars", ".", "get", "(", "'__slots__'", ",", "(", ")", ")", ":", "orig_vars", ".", "pop", "(", "slots_var", ")", "return", "metaclass", "(", "cls", ".", "__name__", ",", "cls", ".", "__bases__", ",", "orig_vars", ")", "return", "wrapper" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/compat/__init__.py#L403-L412
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/mpcd/update.py
python
sort.set_period
(self, period)
Change the sorting period. Args: period (int): New period to set. Examples:: sorter.set_period(100) sorter.set_period(1) While the simulation is running, the action of each updater is executed every *period* time steps. Changing the period does not change the phase set when the analyzer was first created.
Change the sorting period.
[ "Change", "the", "sorting", "period", "." ]
def set_period(self, period): """ Change the sorting period. Args: period (int): New period to set. Examples:: sorter.set_period(100) sorter.set_period(1) While the simulation is running, the action of each updater is executed every *period* time steps. Changing the period does not change the phase set when the analyzer was first created. """ self.period = period self._cpp.setPeriod(hoomd.context.current.system.getCurrentTimeStep(), self.period)
[ "def", "set_period", "(", "self", ",", "period", ")", ":", "self", ".", "period", "=", "period", "self", ".", "_cpp", ".", "setPeriod", "(", "hoomd", ".", "context", ".", "current", ".", "system", ".", "getCurrentTimeStep", "(", ")", ",", "self", ".", "period", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/mpcd/update.py#L75-L94
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
StandardDialogLayoutAdapter_DoReparentControls
(*args, **kwargs)
return _windows_.StandardDialogLayoutAdapter_DoReparentControls(*args, **kwargs)
StandardDialogLayoutAdapter_DoReparentControls(Window parent, Window reparentTo, Sizer buttonSizer=None)
StandardDialogLayoutAdapter_DoReparentControls(Window parent, Window reparentTo, Sizer buttonSizer=None)
[ "StandardDialogLayoutAdapter_DoReparentControls", "(", "Window", "parent", "Window", "reparentTo", "Sizer", "buttonSizer", "=", "None", ")" ]
def StandardDialogLayoutAdapter_DoReparentControls(*args, **kwargs): """StandardDialogLayoutAdapter_DoReparentControls(Window parent, Window reparentTo, Sizer buttonSizer=None)""" return _windows_.StandardDialogLayoutAdapter_DoReparentControls(*args, **kwargs)
[ "def", "StandardDialogLayoutAdapter_DoReparentControls", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "StandardDialogLayoutAdapter_DoReparentControls", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1034-L1036
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/shapenet_single.py
python
shapenet_single.image_path_from_index
(self, index)
return image_path
Construct an image path from the image's "index" identifier.
Construct an image path from the image's "index" identifier.
[ "Construct", "an", "image", "path", "from", "the", "image", "s", "index", "identifier", "." ]
def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ image_path = os.path.join(self._data_path, index + '_rgba' + self._image_ext) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path
[ "def", "image_path_from_index", "(", "self", ",", "index", ")", ":", "image_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "index", "+", "'_rgba'", "+", "self", ".", "_image_ext", ")", "assert", "os", ".", "path", ".", "exists", "(", "image_path", ")", ",", "'Path does not exist: {}'", ".", "format", "(", "image_path", ")", "return", "image_path" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_single.py#L40-L48
alibaba/AliSQLBackup
26573de135d115b100dbbfb9698274463ade5c8d
libevent/event_rpcgen.py
python
Struct.PrintTags
(self, file)
Prints the tag definitions for a structure.
Prints the tag definitions for a structure.
[ "Prints", "the", "tag", "definitions", "for", "a", "structure", "." ]
def PrintTags(self, file): """Prints the tag definitions for a structure.""" print >>file, '/* Tag definition for %s */' % self._name print >>file, 'enum %s_ {' % self._name.lower() for entry in self._entries: print >>file, ' %s=%d,' % (self.EntryTagName(entry), entry.Tag()) print >>file, ' %s_MAX_TAGS' % (self._name.upper()) print >>file, '};\n'
[ "def", "PrintTags", "(", "self", ",", "file", ")", ":", "print", ">>", "file", ",", "'/* Tag definition for %s */'", "%", "self", ".", "_name", "print", ">>", "file", ",", "'enum %s_ {'", "%", "self", ".", "_name", ".", "lower", "(", ")", "for", "entry", "in", "self", ".", "_entries", ":", "print", ">>", "file", ",", "' %s=%d,'", "%", "(", "self", ".", "EntryTagName", "(", "entry", ")", ",", "entry", ".", "Tag", "(", ")", ")", "print", ">>", "file", ",", "' %s_MAX_TAGS'", "%", "(", "self", ".", "_name", ".", "upper", "(", ")", ")", "print", ">>", "file", ",", "'};\\n'" ]
https://github.com/alibaba/AliSQLBackup/blob/26573de135d115b100dbbfb9698274463ade5c8d/libevent/event_rpcgen.py#L57-L65
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/gan/python/train.py
python
gan_train_ops
( model, loss, generator_optimizer, discriminator_optimizer, check_for_unused_update_ops=True, # Optional args to pass directly to the `create_train_op`. **kwargs)
return namedtuples.GANTrainOps(gen_train_op, disc_train_op, global_step_inc)
Returns GAN train ops. The highest-level call in TFGAN. It is composed of functions that can also be called, should a user require more control over some part of the GAN training process. Args: model: A GANModel. loss: A GANLoss. generator_optimizer: The optimizer for generator updates. discriminator_optimizer: The optimizer for the discriminator updates. check_for_unused_update_ops: If `True`, throws an exception if there are update ops outside of the generator or discriminator scopes. **kwargs: Keyword args to pass directly to `training.create_train_op` for both the generator and discriminator train op. Returns: A GANTrainOps tuple of (generator_train_op, discriminator_train_op) that can be used to train a generator/discriminator pair.
Returns GAN train ops.
[ "Returns", "GAN", "train", "ops", "." ]
def gan_train_ops( model, loss, generator_optimizer, discriminator_optimizer, check_for_unused_update_ops=True, # Optional args to pass directly to the `create_train_op`. **kwargs): """Returns GAN train ops. The highest-level call in TFGAN. It is composed of functions that can also be called, should a user require more control over some part of the GAN training process. Args: model: A GANModel. loss: A GANLoss. generator_optimizer: The optimizer for generator updates. discriminator_optimizer: The optimizer for the discriminator updates. check_for_unused_update_ops: If `True`, throws an exception if there are update ops outside of the generator or discriminator scopes. **kwargs: Keyword args to pass directly to `training.create_train_op` for both the generator and discriminator train op. Returns: A GANTrainOps tuple of (generator_train_op, discriminator_train_op) that can be used to train a generator/discriminator pair. """ # Create global step increment op. global_step = training_util.get_or_create_global_step() global_step_inc = global_step.assign_add(1) # Get generator and discriminator update ops. We split them so that update # ops aren't accidentally run multiple times. For now, throw an error if # there are update ops that aren't associated with either the generator or # the discriminator. Might modify the `kwargs` dictionary. gen_update_ops, dis_update_ops = _get_update_ops( kwargs, model.generator_scope.name, model.discriminator_scope.name, check_for_unused_update_ops) generator_global_step = None if isinstance(generator_optimizer, sync_replicas_optimizer.SyncReplicasOptimizer): # TODO(joelshor): Figure out a way to get this work without including the # dummy global step in the checkpoint. # WARNING: Making this variable a local variable causes sync replicas to # hang forever. generator_global_step = variable_scope.get_variable( 'dummy_global_step_generator', shape=[], dtype=global_step.dtype.base_dtype, initializer=init_ops.zeros_initializer(), trainable=False, collections=[ops.GraphKeys.GLOBAL_VARIABLES]) gen_update_ops += [generator_global_step.assign(global_step)] with ops.name_scope('generator_train'): gen_train_op = training.create_train_op( total_loss=loss.generator_loss, optimizer=generator_optimizer, variables_to_train=model.generator_variables, global_step=generator_global_step, update_ops=gen_update_ops, **kwargs) discriminator_global_step = None if isinstance(discriminator_optimizer, sync_replicas_optimizer.SyncReplicasOptimizer): # See comment above `generator_global_step`. discriminator_global_step = variable_scope.get_variable( 'dummy_global_step_discriminator', shape=[], dtype=global_step.dtype.base_dtype, initializer=init_ops.zeros_initializer(), trainable=False, collections=[ops.GraphKeys.GLOBAL_VARIABLES]) dis_update_ops += [discriminator_global_step.assign(global_step)] with ops.name_scope('discriminator_train'): disc_train_op = training.create_train_op( total_loss=loss.discriminator_loss, optimizer=discriminator_optimizer, variables_to_train=model.discriminator_variables, global_step=discriminator_global_step, update_ops=dis_update_ops, **kwargs) return namedtuples.GANTrainOps(gen_train_op, disc_train_op, global_step_inc)
[ "def", "gan_train_ops", "(", "model", ",", "loss", ",", "generator_optimizer", ",", "discriminator_optimizer", ",", "check_for_unused_update_ops", "=", "True", ",", "# Optional args to pass directly to the `create_train_op`.", "*", "*", "kwargs", ")", ":", "# Create global step increment op.", "global_step", "=", "training_util", ".", "get_or_create_global_step", "(", ")", "global_step_inc", "=", "global_step", ".", "assign_add", "(", "1", ")", "# Get generator and discriminator update ops. We split them so that update", "# ops aren't accidentally run multiple times. For now, throw an error if", "# there are update ops that aren't associated with either the generator or", "# the discriminator. Might modify the `kwargs` dictionary.", "gen_update_ops", ",", "dis_update_ops", "=", "_get_update_ops", "(", "kwargs", ",", "model", ".", "generator_scope", ".", "name", ",", "model", ".", "discriminator_scope", ".", "name", ",", "check_for_unused_update_ops", ")", "generator_global_step", "=", "None", "if", "isinstance", "(", "generator_optimizer", ",", "sync_replicas_optimizer", ".", "SyncReplicasOptimizer", ")", ":", "# TODO(joelshor): Figure out a way to get this work without including the", "# dummy global step in the checkpoint.", "# WARNING: Making this variable a local variable causes sync replicas to", "# hang forever.", "generator_global_step", "=", "variable_scope", ".", "get_variable", "(", "'dummy_global_step_generator'", ",", "shape", "=", "[", "]", ",", "dtype", "=", "global_step", ".", "dtype", ".", "base_dtype", ",", "initializer", "=", "init_ops", ".", "zeros_initializer", "(", ")", ",", "trainable", "=", "False", ",", "collections", "=", "[", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", "]", ")", "gen_update_ops", "+=", "[", "generator_global_step", ".", "assign", "(", "global_step", ")", "]", "with", "ops", ".", "name_scope", "(", "'generator_train'", ")", ":", "gen_train_op", "=", "training", ".", "create_train_op", "(", "total_loss", "=", "loss", ".", "generator_loss", ",", "optimizer", "=", "generator_optimizer", ",", "variables_to_train", "=", "model", ".", "generator_variables", ",", "global_step", "=", "generator_global_step", ",", "update_ops", "=", "gen_update_ops", ",", "*", "*", "kwargs", ")", "discriminator_global_step", "=", "None", "if", "isinstance", "(", "discriminator_optimizer", ",", "sync_replicas_optimizer", ".", "SyncReplicasOptimizer", ")", ":", "# See comment above `generator_global_step`.", "discriminator_global_step", "=", "variable_scope", ".", "get_variable", "(", "'dummy_global_step_discriminator'", ",", "shape", "=", "[", "]", ",", "dtype", "=", "global_step", ".", "dtype", ".", "base_dtype", ",", "initializer", "=", "init_ops", ".", "zeros_initializer", "(", ")", ",", "trainable", "=", "False", ",", "collections", "=", "[", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", "]", ")", "dis_update_ops", "+=", "[", "discriminator_global_step", ".", "assign", "(", "global_step", ")", "]", "with", "ops", ".", "name_scope", "(", "'discriminator_train'", ")", ":", "disc_train_op", "=", "training", ".", "create_train_op", "(", "total_loss", "=", "loss", ".", "discriminator_loss", ",", "optimizer", "=", "discriminator_optimizer", ",", "variables_to_train", "=", "model", ".", "discriminator_variables", ",", "global_step", "=", "discriminator_global_step", ",", "update_ops", "=", "dis_update_ops", ",", "*", "*", "kwargs", ")", "return", "namedtuples", ".", "GANTrainOps", "(", "gen_train_op", ",", "disc_train_op", ",", "global_step_inc", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/gan/python/train.py#L476-L562
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/ros_carla_bridge/carla_ego_vehicle/src/carla_ego_vehicle/carla_ego_vehicle.py
python
CarlaEgoVehicle.setup_sensors
(self, sensors)
return actors
Create the sensors defined by the user and attach them to the ego-vehicle :param sensors: list of sensors :return:
Create the sensors defined by the user and attach them to the ego-vehicle :param sensors: list of sensors :return:
[ "Create", "the", "sensors", "defined", "by", "the", "user", "and", "attach", "them", "to", "the", "ego", "-", "vehicle", ":", "param", "sensors", ":", "list", "of", "sensors", ":", "return", ":" ]
def setup_sensors(self, sensors): """ Create the sensors defined by the user and attach them to the ego-vehicle :param sensors: list of sensors :return: """ actors = [] bp_library = self.world.get_blueprint_library() for sensor_spec in sensors: try: bp = bp_library.find(str(sensor_spec['type'])) bp.set_attribute('role_name', str(sensor_spec['id'])) if sensor_spec['type'].startswith('sensor.camera'): bp.set_attribute('image_size_x', str(sensor_spec['width'])) bp.set_attribute('image_size_y', str(sensor_spec['height'])) bp.set_attribute('fov', str(sensor_spec['fov'])) try: bp.set_attribute('sensor_tick', str(sensor_spec['sensor_tick'])) except KeyError: pass sensor_location = carla.Location(x=sensor_spec['x'], y=sensor_spec['y'], z=sensor_spec['z']) sensor_rotation = carla.Rotation(pitch=sensor_spec['pitch'], roll=sensor_spec['roll'], yaw=sensor_spec['yaw']) elif sensor_spec['type'].startswith('sensor.lidar'): bp.set_attribute('range', str(sensor_spec['range'])) bp.set_attribute('rotation_frequency', str(sensor_spec['rotation_frequency'])) bp.set_attribute('channels', str(sensor_spec['channels'])) bp.set_attribute('upper_fov', str(sensor_spec['upper_fov'])) bp.set_attribute('lower_fov', str(sensor_spec['lower_fov'])) bp.set_attribute('points_per_second', str(sensor_spec['points_per_second'])) try: bp.set_attribute('sensor_tick', str(sensor_spec['sensor_tick'])) except KeyError: pass sensor_location = carla.Location(x=sensor_spec['x'], y=sensor_spec['y'], z=sensor_spec['z']) sensor_rotation = carla.Rotation(pitch=sensor_spec['pitch'], roll=sensor_spec['roll'], yaw=sensor_spec['yaw']) elif sensor_spec['type'].startswith('sensor.other.gnss'): sensor_location = carla.Location(x=sensor_spec['x'], y=sensor_spec['y'], z=sensor_spec['z']) sensor_rotation = carla.Rotation() except KeyError as e: rospy.logfatal( "Sensor will not be spawned, because sensor spec is invalid: '{}'".format(e)) continue # create sensor sensor_transform = carla.Transform(sensor_location, sensor_rotation) sensor = self.world.spawn_actor(bp, sensor_transform, attach_to=self.player) actors.append(sensor) return actors
[ "def", "setup_sensors", "(", "self", ",", "sensors", ")", ":", "actors", "=", "[", "]", "bp_library", "=", "self", ".", "world", ".", "get_blueprint_library", "(", ")", "for", "sensor_spec", "in", "sensors", ":", "try", ":", "bp", "=", "bp_library", ".", "find", "(", "str", "(", "sensor_spec", "[", "'type'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'role_name'", ",", "str", "(", "sensor_spec", "[", "'id'", "]", ")", ")", "if", "sensor_spec", "[", "'type'", "]", ".", "startswith", "(", "'sensor.camera'", ")", ":", "bp", ".", "set_attribute", "(", "'image_size_x'", ",", "str", "(", "sensor_spec", "[", "'width'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'image_size_y'", ",", "str", "(", "sensor_spec", "[", "'height'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'fov'", ",", "str", "(", "sensor_spec", "[", "'fov'", "]", ")", ")", "try", ":", "bp", ".", "set_attribute", "(", "'sensor_tick'", ",", "str", "(", "sensor_spec", "[", "'sensor_tick'", "]", ")", ")", "except", "KeyError", ":", "pass", "sensor_location", "=", "carla", ".", "Location", "(", "x", "=", "sensor_spec", "[", "'x'", "]", ",", "y", "=", "sensor_spec", "[", "'y'", "]", ",", "z", "=", "sensor_spec", "[", "'z'", "]", ")", "sensor_rotation", "=", "carla", ".", "Rotation", "(", "pitch", "=", "sensor_spec", "[", "'pitch'", "]", ",", "roll", "=", "sensor_spec", "[", "'roll'", "]", ",", "yaw", "=", "sensor_spec", "[", "'yaw'", "]", ")", "elif", "sensor_spec", "[", "'type'", "]", ".", "startswith", "(", "'sensor.lidar'", ")", ":", "bp", ".", "set_attribute", "(", "'range'", ",", "str", "(", "sensor_spec", "[", "'range'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'rotation_frequency'", ",", "str", "(", "sensor_spec", "[", "'rotation_frequency'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'channels'", ",", "str", "(", "sensor_spec", "[", "'channels'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'upper_fov'", ",", "str", "(", "sensor_spec", "[", "'upper_fov'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'lower_fov'", ",", "str", "(", "sensor_spec", "[", "'lower_fov'", "]", ")", ")", "bp", ".", "set_attribute", "(", "'points_per_second'", ",", "str", "(", "sensor_spec", "[", "'points_per_second'", "]", ")", ")", "try", ":", "bp", ".", "set_attribute", "(", "'sensor_tick'", ",", "str", "(", "sensor_spec", "[", "'sensor_tick'", "]", ")", ")", "except", "KeyError", ":", "pass", "sensor_location", "=", "carla", ".", "Location", "(", "x", "=", "sensor_spec", "[", "'x'", "]", ",", "y", "=", "sensor_spec", "[", "'y'", "]", ",", "z", "=", "sensor_spec", "[", "'z'", "]", ")", "sensor_rotation", "=", "carla", ".", "Rotation", "(", "pitch", "=", "sensor_spec", "[", "'pitch'", "]", ",", "roll", "=", "sensor_spec", "[", "'roll'", "]", ",", "yaw", "=", "sensor_spec", "[", "'yaw'", "]", ")", "elif", "sensor_spec", "[", "'type'", "]", ".", "startswith", "(", "'sensor.other.gnss'", ")", ":", "sensor_location", "=", "carla", ".", "Location", "(", "x", "=", "sensor_spec", "[", "'x'", "]", ",", "y", "=", "sensor_spec", "[", "'y'", "]", ",", "z", "=", "sensor_spec", "[", "'z'", "]", ")", "sensor_rotation", "=", "carla", ".", "Rotation", "(", ")", "except", "KeyError", "as", "e", ":", "rospy", ".", "logfatal", "(", "\"Sensor will not be spawned, because sensor spec is invalid: '{}'\"", ".", "format", "(", "e", ")", ")", "continue", "# create sensor", "sensor_transform", "=", "carla", ".", "Transform", "(", "sensor_location", ",", "sensor_rotation", ")", "sensor", "=", "self", ".", "world", ".", "spawn_actor", "(", "bp", ",", "sensor_transform", ",", "attach_to", "=", "self", ".", "player", ")", "actors", ".", "append", "(", "sensor", ")", "return", "actors" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ego_vehicle/src/carla_ego_vehicle/carla_ego_vehicle.py#L165-L220
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftgeoutils/faces.py
python
removeSplitter
(shape)
return None
Return a face from removing the splitter in a list of faces. This is an alternative, shared edge-based version of Part.removeSplitter. Returns a face, or `None` if the operation failed.
Return a face from removing the splitter in a list of faces.
[ "Return", "a", "face", "from", "removing", "the", "splitter", "in", "a", "list", "of", "faces", "." ]
def removeSplitter(shape): """Return a face from removing the splitter in a list of faces. This is an alternative, shared edge-based version of Part.removeSplitter. Returns a face, or `None` if the operation failed. """ lookup = dict() for f in shape.Faces: for e in f.Edges: h = e.hashCode() if h in lookup: lookup[h].append(e) else: lookup[h] = [e] edges = [e[0] for e in lookup.values() if len(e) == 1] try: face = Part.Face(Part.Wire(edges)) except Part.OCCError: # operation failed return None else: if face.isValid(): return face return None
[ "def", "removeSplitter", "(", "shape", ")", ":", "lookup", "=", "dict", "(", ")", "for", "f", "in", "shape", ".", "Faces", ":", "for", "e", "in", "f", ".", "Edges", ":", "h", "=", "e", ".", "hashCode", "(", ")", "if", "h", "in", "lookup", ":", "lookup", "[", "h", "]", ".", "append", "(", "e", ")", "else", ":", "lookup", "[", "h", "]", "=", "[", "e", "]", "edges", "=", "[", "e", "[", "0", "]", "for", "e", "in", "lookup", ".", "values", "(", ")", "if", "len", "(", "e", ")", "==", "1", "]", "try", ":", "face", "=", "Part", ".", "Face", "(", "Part", ".", "Wire", "(", "edges", ")", ")", "except", "Part", ".", "OCCError", ":", "# operation failed", "return", "None", "else", ":", "if", "face", ".", "isValid", "(", ")", ":", "return", "face", "return", "None" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftgeoutils/faces.py#L248-L274
tkn-tub/ns3-gym
19bfe0a583e641142609939a090a09dfc63a095f
src/visualizer/visualizer/ipython_view.py
python
IterableIPShell.__init__
(self,argv=None,user_ns=None,user_global_ns=None, cin=None, cout=None,cerr=None, input_func=None)
! Initializer @param self: this object @param argv: Command line options for IPython @param user_ns: User namespace. @param user_global_ns: User global namespace. @param cin: Console standard input. @param cout: Console standard output. @param cerr: Console standard error. @param input_func: Replacement for builtin raw_input() @return none
! Initializer
[ "!", "Initializer" ]
def __init__(self,argv=None,user_ns=None,user_global_ns=None, cin=None, cout=None,cerr=None, input_func=None): """! Initializer @param self: this object @param argv: Command line options for IPython @param user_ns: User namespace. @param user_global_ns: User global namespace. @param cin: Console standard input. @param cout: Console standard output. @param cerr: Console standard error. @param input_func: Replacement for builtin raw_input() @return none """ io = IPython.utils.io if input_func: if parse_version(IPython.release.version) >= parse_version("1.2.1"): IPython.terminal.interactiveshell.raw_input_original = input_func else: IPython.frontend.terminal.interactiveshell.raw_input_original = input_func if cin: io.stdin = io.IOStream(cin) if cout: io.stdout = io.IOStream(cout) if cerr: io.stderr = io.IOStream(cerr) # This is to get rid of the blockage that occurs during # IPython.Shell.InteractiveShell.user_setup() io.raw_input = lambda x: None os.environ['TERM'] = 'dumb' excepthook = sys.excepthook from IPython.config.loader import Config cfg = Config() cfg.InteractiveShell.colors = "Linux" # InteractiveShell's __init__ overwrites io.stdout,io.stderr with # sys.stdout, sys.stderr, this makes sure they are right # old_stdout, old_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = io.stdout.stream, io.stderr.stream # InteractiveShell inherits from SingletonConfigurable, so use instance() # if parse_version(IPython.release.version) >= parse_version("1.2.1"): self.IP = IPython.terminal.embed.InteractiveShellEmbed.instance(\ config=cfg, user_ns=user_ns) else: self.IP = IPython.frontend.terminal.embed.InteractiveShellEmbed.instance(\ config=cfg, user_ns=user_ns) sys.stdout, sys.stderr = old_stdout, old_stderr self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd), header='IPython system call: ') # local_ns=user_ns) #global_ns=user_global_ns) #verbose=self.IP.rc.system_verbose) self.IP.raw_input = input_func sys.excepthook = excepthook self.iter_more = 0 self.history_level = 0 self.complete_sep = re.compile('[\s\{\}\[\]\(\)]') self.updateNamespace({'exit':lambda:None}) self.updateNamespace({'quit':lambda:None}) self.IP.readline_startup_hook(self.IP.pre_readline) # Workaround for updating namespace with sys.modules # self.__update_namespace()
[ "def", "__init__", "(", "self", ",", "argv", "=", "None", ",", "user_ns", "=", "None", ",", "user_global_ns", "=", "None", ",", "cin", "=", "None", ",", "cout", "=", "None", ",", "cerr", "=", "None", ",", "input_func", "=", "None", ")", ":", "io", "=", "IPython", ".", "utils", ".", "io", "if", "input_func", ":", "if", "parse_version", "(", "IPython", ".", "release", ".", "version", ")", ">=", "parse_version", "(", "\"1.2.1\"", ")", ":", "IPython", ".", "terminal", ".", "interactiveshell", ".", "raw_input_original", "=", "input_func", "else", ":", "IPython", ".", "frontend", ".", "terminal", ".", "interactiveshell", ".", "raw_input_original", "=", "input_func", "if", "cin", ":", "io", ".", "stdin", "=", "io", ".", "IOStream", "(", "cin", ")", "if", "cout", ":", "io", ".", "stdout", "=", "io", ".", "IOStream", "(", "cout", ")", "if", "cerr", ":", "io", ".", "stderr", "=", "io", ".", "IOStream", "(", "cerr", ")", "# This is to get rid of the blockage that occurs during ", "# IPython.Shell.InteractiveShell.user_setup()", "io", ".", "raw_input", "=", "lambda", "x", ":", "None", "os", ".", "environ", "[", "'TERM'", "]", "=", "'dumb'", "excepthook", "=", "sys", ".", "excepthook", "from", "IPython", ".", "config", ".", "loader", "import", "Config", "cfg", "=", "Config", "(", ")", "cfg", ".", "InteractiveShell", ".", "colors", "=", "\"Linux\"", "# InteractiveShell's __init__ overwrites io.stdout,io.stderr with", "# sys.stdout, sys.stderr, this makes sure they are right", "#", "old_stdout", ",", "old_stderr", "=", "sys", ".", "stdout", ",", "sys", ".", "stderr", "sys", ".", "stdout", ",", "sys", ".", "stderr", "=", "io", ".", "stdout", ".", "stream", ",", "io", ".", "stderr", ".", "stream", "# InteractiveShell inherits from SingletonConfigurable, so use instance()", "#", "if", "parse_version", "(", "IPython", ".", "release", ".", "version", ")", ">=", "parse_version", "(", "\"1.2.1\"", ")", ":", "self", ".", "IP", "=", "IPython", ".", "terminal", ".", "embed", ".", "InteractiveShellEmbed", ".", "instance", "(", "config", "=", "cfg", ",", "user_ns", "=", "user_ns", ")", "else", ":", "self", ".", "IP", "=", "IPython", ".", "frontend", ".", "terminal", ".", "embed", ".", "InteractiveShellEmbed", ".", "instance", "(", "config", "=", "cfg", ",", "user_ns", "=", "user_ns", ")", "sys", ".", "stdout", ",", "sys", ".", "stderr", "=", "old_stdout", ",", "old_stderr", "self", ".", "IP", ".", "system", "=", "lambda", "cmd", ":", "self", ".", "shell", "(", "self", ".", "IP", ".", "var_expand", "(", "cmd", ")", ",", "header", "=", "'IPython system call: '", ")", "# local_ns=user_ns)", "#global_ns=user_global_ns)", "#verbose=self.IP.rc.system_verbose)", "self", ".", "IP", ".", "raw_input", "=", "input_func", "sys", ".", "excepthook", "=", "excepthook", "self", ".", "iter_more", "=", "0", "self", ".", "history_level", "=", "0", "self", ".", "complete_sep", "=", "re", ".", "compile", "(", "'[\\s\\{\\}\\[\\]\\(\\)]'", ")", "self", ".", "updateNamespace", "(", "{", "'exit'", ":", "lambda", ":", "None", "}", ")", "self", ".", "updateNamespace", "(", "{", "'quit'", ":", "lambda", ":", "None", "}", ")", "self", ".", "IP", ".", "readline_startup_hook", "(", "self", ".", "IP", ".", "pre_readline", ")", "# Workaround for updating namespace with sys.modules", "#", "self", ".", "__update_namespace", "(", ")" ]
https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/visualizer/visualizer/ipython_view.py#L74-L146
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiManager.DrawHintRect
(self, pane_window, pt, offset)
Calculates the hint rectangle by calling :meth:`CalculateHintRect`. If there is a rectangle, it shows it by calling :meth:`ShowHint`, otherwise it hides any hint rectangle currently shown. :param Window `pane_window`: it is the window pointer of the pane being dragged; :param Point `pt`: is the mouse position, in client coordinates; :param Point `offset`: describes the offset that the mouse is from the upper-left corner of the item being dragged.
Calculates the hint rectangle by calling :meth:`CalculateHintRect`. If there is a rectangle, it shows it by calling :meth:`ShowHint`, otherwise it hides any hint rectangle currently shown.
[ "Calculates", "the", "hint", "rectangle", "by", "calling", ":", "meth", ":", "CalculateHintRect", ".", "If", "there", "is", "a", "rectangle", "it", "shows", "it", "by", "calling", ":", "meth", ":", "ShowHint", "otherwise", "it", "hides", "any", "hint", "rectangle", "currently", "shown", "." ]
def DrawHintRect(self, pane_window, pt, offset): """ Calculates the hint rectangle by calling :meth:`CalculateHintRect`. If there is a rectangle, it shows it by calling :meth:`ShowHint`, otherwise it hides any hint rectangle currently shown. :param Window `pane_window`: it is the window pointer of the pane being dragged; :param Point `pt`: is the mouse position, in client coordinates; :param Point `offset`: describes the offset that the mouse is from the upper-left corner of the item being dragged. """ rect = self.CalculateHintRect(pane_window, pt, offset) if rect.IsEmpty(): self.HideHint() self._hint_rect = wx.Rect() else: self.ShowHint(rect) self._hint_rect = wx.Rect(*rect)
[ "def", "DrawHintRect", "(", "self", ",", "pane_window", ",", "pt", ",", "offset", ")", ":", "rect", "=", "self", ".", "CalculateHintRect", "(", "pane_window", ",", "pt", ",", "offset", ")", "if", "rect", ".", "IsEmpty", "(", ")", ":", "self", ".", "HideHint", "(", ")", "self", ".", "_hint_rect", "=", "wx", ".", "Rect", "(", ")", "else", ":", "self", ".", "ShowHint", "(", "rect", ")", "self", ".", "_hint_rect", "=", "wx", ".", "Rect", "(", "*", "rect", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L8316-L8335
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/ert/ves.py
python
VESManager.invert
(self, data=None, err=None, ab2=None, mn2=None, **kwargs)
return super(VESManager, self).invert(data=data, err=err, **kwargs)
Invert measured data. Parameters ---------- Keyword Arguments ---------------- **kwargs Additional kwargs inherited from %(MethodManager1d.invert) and %(Inversion.run) Returns ------- model : pg.Vector inversion result
Invert measured data.
[ "Invert", "measured", "data", "." ]
def invert(self, data=None, err=None, ab2=None, mn2=None, **kwargs): """Invert measured data. Parameters ---------- Keyword Arguments ---------------- **kwargs Additional kwargs inherited from %(MethodManager1d.invert) and %(Inversion.run) Returns ------- model : pg.Vector inversion result """ if ab2 is not None and mn2 is not None: self.fop.setDataSpace(ab2=ab2, mn2=mn2) if data is not None: if self.complex: nData = len(data)//2 self.dataTrans = pg.trans.TransCumulative() self.dataTrans.add(self.rhoaTrans, nData) self.dataTrans.add(self.phiaTrans, nData) else: self.dataTrans = pg.trans.TransLog() self.inv.dataTrans = self.dataTrans if 'layerLimits' not in kwargs: kwargs['layerLimits'] = [min(self.fop.mn2)/5, max(self.fop.ab2)/2] if 'paraLimits' in kwargs and self.complex: pL = kwargs['paraLimits'][1] kwargs['paraLimits'][1] = [pL[0]/1000, pL[1]/1000] return super(VESManager, self).invert(data=data, err=err, **kwargs)
[ "def", "invert", "(", "self", ",", "data", "=", "None", ",", "err", "=", "None", ",", "ab2", "=", "None", ",", "mn2", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ab2", "is", "not", "None", "and", "mn2", "is", "not", "None", ":", "self", ".", "fop", ".", "setDataSpace", "(", "ab2", "=", "ab2", ",", "mn2", "=", "mn2", ")", "if", "data", "is", "not", "None", ":", "if", "self", ".", "complex", ":", "nData", "=", "len", "(", "data", ")", "//", "2", "self", ".", "dataTrans", "=", "pg", ".", "trans", ".", "TransCumulative", "(", ")", "self", ".", "dataTrans", ".", "add", "(", "self", ".", "rhoaTrans", ",", "nData", ")", "self", ".", "dataTrans", ".", "add", "(", "self", ".", "phiaTrans", ",", "nData", ")", "else", ":", "self", ".", "dataTrans", "=", "pg", ".", "trans", ".", "TransLog", "(", ")", "self", ".", "inv", ".", "dataTrans", "=", "self", ".", "dataTrans", "if", "'layerLimits'", "not", "in", "kwargs", ":", "kwargs", "[", "'layerLimits'", "]", "=", "[", "min", "(", "self", ".", "fop", ".", "mn2", ")", "/", "5", ",", "max", "(", "self", ".", "fop", ".", "ab2", ")", "/", "2", "]", "if", "'paraLimits'", "in", "kwargs", "and", "self", ".", "complex", ":", "pL", "=", "kwargs", "[", "'paraLimits'", "]", "[", "1", "]", "kwargs", "[", "'paraLimits'", "]", "[", "1", "]", "=", "[", "pL", "[", "0", "]", "/", "1000", ",", "pL", "[", "1", "]", "/", "1000", "]", "return", "super", "(", "VESManager", ",", "self", ")", ".", "invert", "(", "data", "=", "data", ",", "err", "=", "err", ",", "*", "*", "kwargs", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ves.py#L459-L498
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/stub.py
python
Stubber.activate
(self)
Activates the stubber on the client
Activates the stubber on the client
[ "Activates", "the", "stubber", "on", "the", "client" ]
def activate(self): """ Activates the stubber on the client """ self.client.meta.events.register_first( 'before-parameter-build.*.*', self._assert_expected_params, unique_id=self._expected_params_event_id) self.client.meta.events.register( 'before-call.*.*', self._get_response_handler, unique_id=self._event_id)
[ "def", "activate", "(", "self", ")", ":", "self", ".", "client", ".", "meta", ".", "events", ".", "register_first", "(", "'before-parameter-build.*.*'", ",", "self", ".", "_assert_expected_params", ",", "unique_id", "=", "self", ".", "_expected_params_event_id", ")", "self", ".", "client", ".", "meta", ".", "events", ".", "register", "(", "'before-call.*.*'", ",", "self", ".", "_get_response_handler", ",", "unique_id", "=", "self", ".", "_event_id", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/stub.py#L178-L189
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Palette.GetRGB
(*args, **kwargs)
return _gdi_.Palette_GetRGB(*args, **kwargs)
GetRGB(self, int pixel) -> (success, R,G,B)
GetRGB(self, int pixel) -> (success, R,G,B)
[ "GetRGB", "(", "self", "int", "pixel", ")", "-", ">", "(", "success", "R", "G", "B", ")" ]
def GetRGB(*args, **kwargs): """GetRGB(self, int pixel) -> (success, R,G,B)""" return _gdi_.Palette_GetRGB(*args, **kwargs)
[ "def", "GetRGB", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Palette_GetRGB", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L345-L347
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/google_appengine_cloudstorage/cloudstorage/errors.py
python
check_status
(status, expected, path, headers=None, resp_headers=None, extras=None)
Check HTTP response status is expected. Args: status: HTTP response status. int. expected: a list of expected statuses. A list of ints. path: filename or a path prefix. headers: HTTP request headers. resp_headers: HTTP response headers. extras: extra info to be logged verbatim if error occurs. Raises: AuthorizationError: if authorization failed. NotFoundError: if an object that's expected to exist doesn't. TimeoutError: if HTTP request timed out. ServerError: if server experienced some errors. FatalError: if any other unexpected errors occurred.
Check HTTP response status is expected.
[ "Check", "HTTP", "response", "status", "is", "expected", "." ]
def check_status(status, expected, path, headers=None, resp_headers=None, extras=None): """Check HTTP response status is expected. Args: status: HTTP response status. int. expected: a list of expected statuses. A list of ints. path: filename or a path prefix. headers: HTTP request headers. resp_headers: HTTP response headers. extras: extra info to be logged verbatim if error occurs. Raises: AuthorizationError: if authorization failed. NotFoundError: if an object that's expected to exist doesn't. TimeoutError: if HTTP request timed out. ServerError: if server experienced some errors. FatalError: if any other unexpected errors occurred. """ if status in expected: return msg = ('Expect status %r from Google Storage. But got status %d.\n' 'Path: %r.\n' 'Request headers: %r.\n' 'Response headers: %r.\n' 'Extra info: %r.\n' % (expected, status, path, headers, resp_headers, extras)) if status == httplib.UNAUTHORIZED: raise AuthorizationError(msg) elif status == httplib.FORBIDDEN: raise ForbiddenError(msg) elif status == httplib.NOT_FOUND: raise NotFoundError(msg) elif status == httplib.REQUEST_TIMEOUT: raise TimeoutError(msg) elif status == httplib.REQUESTED_RANGE_NOT_SATISFIABLE: raise InvalidRange(msg) elif (status == httplib.OK and 308 in expected and httplib.OK not in expected): raise FileClosedError(msg) elif status >= 500: raise ServerError(msg) else: raise FatalError(msg)
[ "def", "check_status", "(", "status", ",", "expected", ",", "path", ",", "headers", "=", "None", ",", "resp_headers", "=", "None", ",", "extras", "=", "None", ")", ":", "if", "status", "in", "expected", ":", "return", "msg", "=", "(", "'Expect status %r from Google Storage. But got status %d.\\n'", "'Path: %r.\\n'", "'Request headers: %r.\\n'", "'Response headers: %r.\\n'", "'Extra info: %r.\\n'", "%", "(", "expected", ",", "status", ",", "path", ",", "headers", ",", "resp_headers", ",", "extras", ")", ")", "if", "status", "==", "httplib", ".", "UNAUTHORIZED", ":", "raise", "AuthorizationError", "(", "msg", ")", "elif", "status", "==", "httplib", ".", "FORBIDDEN", ":", "raise", "ForbiddenError", "(", "msg", ")", "elif", "status", "==", "httplib", ".", "NOT_FOUND", ":", "raise", "NotFoundError", "(", "msg", ")", "elif", "status", "==", "httplib", ".", "REQUEST_TIMEOUT", ":", "raise", "TimeoutError", "(", "msg", ")", "elif", "status", "==", "httplib", ".", "REQUESTED_RANGE_NOT_SATISFIABLE", ":", "raise", "InvalidRange", "(", "msg", ")", "elif", "(", "status", "==", "httplib", ".", "OK", "and", "308", "in", "expected", "and", "httplib", ".", "OK", "not", "in", "expected", ")", ":", "raise", "FileClosedError", "(", "msg", ")", "elif", "status", ">=", "500", ":", "raise", "ServerError", "(", "msg", ")", "else", ":", "raise", "FatalError", "(", "msg", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/errors.py#L95-L140
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/command/install_lib.py
python
install_lib._gen_exclusion_paths
()
Generate file paths to be excluded for namespace packages (bytecode cache files).
Generate file paths to be excluded for namespace packages (bytecode cache files).
[ "Generate", "file", "paths", "to", "be", "excluded", "for", "namespace", "packages", "(", "bytecode", "cache", "files", ")", "." ]
def _gen_exclusion_paths(): """ Generate file paths to be excluded for namespace packages (bytecode cache files). """ # always exclude the package module itself yield '__init__.py' yield '__init__.pyc' yield '__init__.pyo' if not hasattr(sys, 'implementation'): return base = os.path.join('__pycache__', '__init__.' + sys.implementation.cache_tag) yield base + '.pyc' yield base + '.pyo' yield base + '.opt-1.pyc' yield base + '.opt-2.pyc'
[ "def", "_gen_exclusion_paths", "(", ")", ":", "# always exclude the package module itself", "yield", "'__init__.py'", "yield", "'__init__.pyc'", "yield", "'__init__.pyo'", "if", "not", "hasattr", "(", "sys", ",", "'implementation'", ")", ":", "return", "base", "=", "os", ".", "path", ".", "join", "(", "'__pycache__'", ",", "'__init__.'", "+", "sys", ".", "implementation", ".", "cache_tag", ")", "yield", "base", "+", "'.pyc'", "yield", "base", "+", "'.pyo'", "yield", "base", "+", "'.opt-1.pyc'", "yield", "base", "+", "'.opt-2.pyc'" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/install_lib.py#L66-L84
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
GraphicsPath.AddArc
(*args)
return _gdi_.GraphicsPath_AddArc(*args)
AddArc(self, Double x, Double y, Double r, Double startAngle, Double endAngle, bool clockwise=True) AddArc(self, Point2D c, Double r, Double startAngle, Double endAngle, bool clockwise=True) Adds an arc of a circle centering at (x,y) with radius (r) from startAngle to endAngle
AddArc(self, Double x, Double y, Double r, Double startAngle, Double endAngle, bool clockwise=True) AddArc(self, Point2D c, Double r, Double startAngle, Double endAngle, bool clockwise=True)
[ "AddArc", "(", "self", "Double", "x", "Double", "y", "Double", "r", "Double", "startAngle", "Double", "endAngle", "bool", "clockwise", "=", "True", ")", "AddArc", "(", "self", "Point2D", "c", "Double", "r", "Double", "startAngle", "Double", "endAngle", "bool", "clockwise", "=", "True", ")" ]
def AddArc(*args): """ AddArc(self, Double x, Double y, Double r, Double startAngle, Double endAngle, bool clockwise=True) AddArc(self, Point2D c, Double r, Double startAngle, Double endAngle, bool clockwise=True) Adds an arc of a circle centering at (x,y) with radius (r) from startAngle to endAngle """ return _gdi_.GraphicsPath_AddArc(*args)
[ "def", "AddArc", "(", "*", "args", ")", ":", "return", "_gdi_", ".", "GraphicsPath_AddArc", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5771-L5781
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ) or } or ] or >, finds the position that opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "if", "endchar", "==", "')'", ":", "startchar", "=", "'('", "if", "endchar", "==", "']'", ":", "startchar", "=", "'['", "if", "endchar", "==", "'}'", ":", "startchar", "=", "'{'", "if", "endchar", "==", "'>'", ":", "startchar", "=", "'<'", "# Check last line", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Continue scanning backward", "while", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Did not find startchar before beginning of file, give up", "return", "(", "line", ",", "0", ",", "-", "1", ")" ]
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L1327-L1369
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/tensorflow/ops/nn_ops.py
python
conv2d_transpose
(value, filter, output_shape, strides, padding='SAME', data_format='NHWC', name=None)
Compute 2D deconvolution according to the given 4D ``input`` and ``filter``. For **NHWC** format, filter should be as ``[filter_height, filter_width, out_channels, in_channels]``. For **NCHW** format, filter should be as ``[in_channels, out_channels, filter_height, filter_width]``. ``output_shape`` will be ignored if padding algorithm is **VALID**. Parameters ---------- input : Tensor The input tensor. filter : Tensor The filter tensor. output_shape : list of int The deterministic output shape for **SAME** padding. strides : list of int The strides with length 4. padding : str The padding algorithm. ``VALID`` or ``SAME``. data_format : str The data format. ``NHWC`` or ``NCHW``. name : str The optional name for this operator. Returns ------- Tensor The output tensor.
Compute 2D deconvolution according to the given 4D ``input`` and ``filter``.
[ "Compute", "2D", "deconvolution", "according", "to", "the", "given", "4D", "input", "and", "filter", "." ]
def conv2d_transpose(value, filter, output_shape, strides, padding='SAME', data_format='NHWC', name=None): """Compute 2D deconvolution according to the given 4D ``input`` and ``filter``. For **NHWC** format, filter should be as ``[filter_height, filter_width, out_channels, in_channels]``. For **NCHW** format, filter should be as ``[in_channels, out_channels, filter_height, filter_width]``. ``output_shape`` will be ignored if padding algorithm is **VALID**. Parameters ---------- input : Tensor The input tensor. filter : Tensor The filter tensor. output_shape : list of int The deterministic output shape for **SAME** padding. strides : list of int The strides with length 4. padding : str The padding algorithm. ``VALID`` or ``SAME``. data_format : str The data format. ``NHWC`` or ``NCHW``. name : str The optional name for this operator. Returns ------- Tensor The output tensor. """ if filter.shape is None: raise ValueError('filter must have a valid shape.') else: if len(filter.shape) != 4: raise ValueError('filter must be a 4D Tensor.') if len(strides) != 4: raise ValueError('strides must be a list with length 4.') if not isinstance(output_shape, list): raise TypeError('output_shape should be a list.') if len(output_shape) != 4: raise ValueError('output_shape should be a list with length 4.') if data_format == 'NHWC': output = ops.Conv2dTranspose([value, filter], num_output=filter.shape[2], kernel_size=filter.shape[0:2], stride=strides[1:3], padding=padding, data_format=data_format, output_shape=output_shape) return output elif data_format == 'NCHW': output = ops.Conv2dTranspose([value, filter], num_output=filter.shape[1], kernel_size=filter.shape[2:4], stride=strides[2:4], padding=padding, data_format=data_format, output_shape=output_shape) return output else: raise ValueError('Unknown data format: {}'.format(data_format))
[ "def", "conv2d_transpose", "(", "value", ",", "filter", ",", "output_shape", ",", "strides", ",", "padding", "=", "'SAME'", ",", "data_format", "=", "'NHWC'", ",", "name", "=", "None", ")", ":", "if", "filter", ".", "shape", "is", "None", ":", "raise", "ValueError", "(", "'filter must have a valid shape.'", ")", "else", ":", "if", "len", "(", "filter", ".", "shape", ")", "!=", "4", ":", "raise", "ValueError", "(", "'filter must be a 4D Tensor.'", ")", "if", "len", "(", "strides", ")", "!=", "4", ":", "raise", "ValueError", "(", "'strides must be a list with length 4.'", ")", "if", "not", "isinstance", "(", "output_shape", ",", "list", ")", ":", "raise", "TypeError", "(", "'output_shape should be a list.'", ")", "if", "len", "(", "output_shape", ")", "!=", "4", ":", "raise", "ValueError", "(", "'output_shape should be a list with length 4.'", ")", "if", "data_format", "==", "'NHWC'", ":", "output", "=", "ops", ".", "Conv2dTranspose", "(", "[", "value", ",", "filter", "]", ",", "num_output", "=", "filter", ".", "shape", "[", "2", "]", ",", "kernel_size", "=", "filter", ".", "shape", "[", "0", ":", "2", "]", ",", "stride", "=", "strides", "[", "1", ":", "3", "]", ",", "padding", "=", "padding", ",", "data_format", "=", "data_format", ",", "output_shape", "=", "output_shape", ")", "return", "output", "elif", "data_format", "==", "'NCHW'", ":", "output", "=", "ops", ".", "Conv2dTranspose", "(", "[", "value", ",", "filter", "]", ",", "num_output", "=", "filter", ".", "shape", "[", "1", "]", ",", "kernel_size", "=", "filter", ".", "shape", "[", "2", ":", "4", "]", ",", "stride", "=", "strides", "[", "2", ":", "4", "]", ",", "padding", "=", "padding", ",", "data_format", "=", "data_format", ",", "output_shape", "=", "output_shape", ")", "return", "output", "else", ":", "raise", "ValueError", "(", "'Unknown data format: {}'", ".", "format", "(", "data_format", ")", ")" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/tensorflow/ops/nn_ops.py#L143-L207
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
SymbolFunction.detect
(self, pos)
return pos.current() in SymbolFunction.commandmap
Find the symbol
Find the symbol
[ "Find", "the", "symbol" ]
def detect(self, pos): "Find the symbol" return pos.current() in SymbolFunction.commandmap
[ "def", "detect", "(", "self", ",", "pos", ")", ":", "return", "pos", ".", "current", "(", ")", "in", "SymbolFunction", ".", "commandmap" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4239-L4241
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
PyAuiTabArt.GetFlags
(*args, **kwargs)
return _aui.PyAuiTabArt_GetFlags(*args, **kwargs)
GetFlags(self) -> int
GetFlags(self) -> int
[ "GetFlags", "(", "self", ")", "-", ">", "int" ]
def GetFlags(*args, **kwargs): """GetFlags(self) -> int""" return _aui.PyAuiTabArt_GetFlags(*args, **kwargs)
[ "def", "GetFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "PyAuiTabArt_GetFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L2447-L2449
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/dataview.py
python
DataViewTreeStoreNode.GetIcon
(*args, **kwargs)
return _dataview.DataViewTreeStoreNode_GetIcon(*args, **kwargs)
GetIcon(self) -> Icon
GetIcon(self) -> Icon
[ "GetIcon", "(", "self", ")", "-", ">", "Icon" ]
def GetIcon(*args, **kwargs): """GetIcon(self) -> Icon""" return _dataview.DataViewTreeStoreNode_GetIcon(*args, **kwargs)
[ "def", "GetIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewTreeStoreNode_GetIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L2240-L2242
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Tux/PersistentToolbars.py
python
addBottom
(name, toolbars)
addBottom("name", ["toolbars"]) Description: Look at addTop for more information.
addBottom("name", ["toolbars"])
[ "addBottom", "(", "name", "[", "toolbars", "]", ")" ]
def addBottom(name, toolbars): """addBottom("name", ["toolbars"]) Description: Look at addTop for more information.""" p = App.ParamGet("User parameter:Tux/PersistentToolbars/System") p.GetGroup(name).SetBool("Saved", 1) p.GetGroup(name).SetString("Bottom", ",".join(toolbars))
[ "def", "addBottom", "(", "name", ",", "toolbars", ")", ":", "p", "=", "App", ".", "ParamGet", "(", "\"User parameter:Tux/PersistentToolbars/System\"", ")", "p", ".", "GetGroup", "(", "name", ")", ".", "SetBool", "(", "\"Saved\"", ",", "1", ")", "p", ".", "GetGroup", "(", "name", ")", ".", "SetString", "(", "\"Bottom\"", ",", "\",\"", ".", "join", "(", "toolbars", ")", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Tux/PersistentToolbars.py#L74-L82
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/offline_debug/dbg_services.py
python
DbgServices.add_watchpoint
(self, watchpoint_id, watch_condition, check_node_list, parameter_list)
return self.dbg_instance.AddWatchpoint(watchpoint_id, watch_condition, check_node_list, parameter_list_inst)
Adding watchpoint to Debug Service instance. Args: watchpoint_id (int): Watchpoint id watch_condition (int): A representation of the condition to be checked. check_node_list (dict): Dictionary of node names (str or '*' to check all nodes) as key, mapping to rank_id (list of ints or '*' to check all devices), root_graph_id (list of ints or '*' to check all graphs) and is_output (bool). parameter_list (list): List of parameters in watchpoint. Parameters should be instances of Parameter class. Each parameter describes the value to be checked in watchpoint. Returns: Debug Service instance with added watchpoint. Examples: >>> from mindspore.ccsrc.debug.debugger.offline_debug import dbg_services >>> d = dbg_services.DbgServices(dump_file_path="dump_file_path") >>> d_init = d.initialize(is_sync_mode=True) >>> d_wp = d_init.add_watchpoint(watchpoint_id=1, ... watch_condition=6, ... check_node_list={"conv2.bias" : {"rank_id": [0], ... root_graph_id: [0], "is_output": True}}, ... parameter_list=[dbg_services.Parameter(name="param", ... disabled=False, ... value=0.0, ... hit=False, ... actual_value=0.0)])
Adding watchpoint to Debug Service instance.
[ "Adding", "watchpoint", "to", "Debug", "Service", "instance", "." ]
def add_watchpoint(self, watchpoint_id, watch_condition, check_node_list, parameter_list): """ Adding watchpoint to Debug Service instance. Args: watchpoint_id (int): Watchpoint id watch_condition (int): A representation of the condition to be checked. check_node_list (dict): Dictionary of node names (str or '*' to check all nodes) as key, mapping to rank_id (list of ints or '*' to check all devices), root_graph_id (list of ints or '*' to check all graphs) and is_output (bool). parameter_list (list): List of parameters in watchpoint. Parameters should be instances of Parameter class. Each parameter describes the value to be checked in watchpoint. Returns: Debug Service instance with added watchpoint. Examples: >>> from mindspore.ccsrc.debug.debugger.offline_debug import dbg_services >>> d = dbg_services.DbgServices(dump_file_path="dump_file_path") >>> d_init = d.initialize(is_sync_mode=True) >>> d_wp = d_init.add_watchpoint(watchpoint_id=1, ... watch_condition=6, ... check_node_list={"conv2.bias" : {"rank_id": [0], ... root_graph_id: [0], "is_output": True}}, ... parameter_list=[dbg_services.Parameter(name="param", ... disabled=False, ... value=0.0, ... hit=False, ... actual_value=0.0)]) """ logger.info("in Python AddWatchpoint") for node_name, node_info in check_node_list.items(): for info_name, info_param in node_info.items(): check_node_list = self.transform_check_node_list(info_name, info_param, node_name, check_node_list) parameter_list_inst = [] for elem in parameter_list: parameter_list_inst.append(elem.instance) return self.dbg_instance.AddWatchpoint(watchpoint_id, watch_condition, check_node_list, parameter_list_inst)
[ "def", "add_watchpoint", "(", "self", ",", "watchpoint_id", ",", "watch_condition", ",", "check_node_list", ",", "parameter_list", ")", ":", "logger", ".", "info", "(", "\"in Python AddWatchpoint\"", ")", "for", "node_name", ",", "node_info", "in", "check_node_list", ".", "items", "(", ")", ":", "for", "info_name", ",", "info_param", "in", "node_info", ".", "items", "(", ")", ":", "check_node_list", "=", "self", ".", "transform_check_node_list", "(", "info_name", ",", "info_param", ",", "node_name", ",", "check_node_list", ")", "parameter_list_inst", "=", "[", "]", "for", "elem", "in", "parameter_list", ":", "parameter_list_inst", ".", "append", "(", "elem", ".", "instance", ")", "return", "self", ".", "dbg_instance", ".", "AddWatchpoint", "(", "watchpoint_id", ",", "watch_condition", ",", "check_node_list", ",", "parameter_list_inst", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/offline_debug/dbg_services.py#L129-L166
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/wheel.py
python
check_compatibility
(version, name)
Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given
Raises errors or warns if called with an incompatible Wheel-Version.
[ "Raises", "errors", "or", "warns", "if", "called", "with", "an", "incompatible", "Wheel", "-", "Version", "." ]
def check_compatibility(version, name): """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), )
[ "def", "check_compatibility", "(", "version", ",", "name", ")", ":", "if", "not", "version", ":", "raise", "UnsupportedWheel", "(", "\"%s is in an unsupported or invalid wheel\"", "%", "name", ")", "if", "version", "[", "0", "]", ">", "VERSION_COMPATIBLE", "[", "0", "]", ":", "raise", "UnsupportedWheel", "(", "\"%s's Wheel-Version (%s) is not compatible with this version \"", "\"of pip\"", "%", "(", "name", ",", "'.'", ".", "join", "(", "map", "(", "str", ",", "version", ")", ")", ")", ")", "elif", "version", ">", "VERSION_COMPATIBLE", ":", "logger", ".", "warning", "(", "'Installing from a newer Wheel-Version (%s)'", ",", "'.'", ".", "join", "(", "map", "(", "str", ",", "version", ")", ")", ",", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/wheel.py#L560-L586
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_vim.py
python
EditraCommander.IsAtLineStart
(self)
return self._GetCol() == 0
Is the cursor currently at the start of a line @return: bool
Is the cursor currently at the start of a line @return: bool
[ "Is", "the", "cursor", "currently", "at", "the", "start", "of", "a", "line", "@return", ":", "bool" ]
def IsAtLineStart(self): """Is the cursor currently at the start of a line @return: bool """ return self._GetCol() == 0
[ "def", "IsAtLineStart", "(", "self", ")", ":", "return", "self", ".", "_GetCol", "(", ")", "==", "0" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_vim.py#L132-L137
rbgirshick/caffe-fast-rcnn
28a579eaf0668850705598b3075b8969f22226d9
scripts/cpp_lint.py
python
ParseNolintSuppressions
(filename, raw_line, linenum, error)
Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler.
Updates the global list of error-suppressions.
[ "Updates", "the", "global", "list", "of", "error", "-", "suppressions", "." ]
def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*). matched = _RE_SUPPRESSION.search(raw_line) if matched: if matched.group(1) == '_NEXT_LINE': linenum += 1 category = matched.group(2) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(linenum) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(linenum) else: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category)
[ "def", "ParseNolintSuppressions", "(", "filename", ",", "raw_line", ",", "linenum", ",", "error", ")", ":", "# FIXME(adonovan): \"NOLINT(\" is misparsed as NOLINT(*).", "matched", "=", "_RE_SUPPRESSION", ".", "search", "(", "raw_line", ")", "if", "matched", ":", "if", "matched", ".", "group", "(", "1", ")", "==", "'_NEXT_LINE'", ":", "linenum", "+=", "1", "category", "=", "matched", ".", "group", "(", "2", ")", "if", "category", "in", "(", "None", ",", "'(*)'", ")", ":", "# => \"suppress all\"", "_error_suppressions", ".", "setdefault", "(", "None", ",", "set", "(", ")", ")", ".", "add", "(", "linenum", ")", "else", ":", "if", "category", ".", "startswith", "(", "'('", ")", "and", "category", ".", "endswith", "(", "')'", ")", ":", "category", "=", "category", "[", "1", ":", "-", "1", "]", "if", "category", "in", "_ERROR_CATEGORIES", ":", "_error_suppressions", ".", "setdefault", "(", "category", ",", "set", "(", ")", ")", ".", "add", "(", "linenum", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/nolint'", ",", "5", ",", "'Unknown NOLINT error category: %s'", "%", "category", ")" ]
https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L464-L492
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/rnn_grad.py
python
_block_lstm_grad
(op, *grads)
return (None, x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, b_grad)
Gradient for the BlockLSTM op.
Gradient for the BlockLSTM op.
[ "Gradient", "for", "the", "BlockLSTM", "op", "." ]
def _block_lstm_grad(op, *grads): """Gradient for the BlockLSTM op.""" seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b = op.inputs i, cs, f, o, ci, co, h = op.outputs _, cs_grad, _, _, _, _, h_grad = grads (x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, b_grad) = gen_rnn_ops.block_lstm_grad( seq_len_max=seq_len_max, x=x, cs_prev=cs_prev, h_prev=h_prev, w=w, wci=wci, wcf=wcf, wco=wco, b=b, i=i, cs=cs, f=f, o=o, ci=ci, co=co, h=h, cs_grad=cs_grad, h_grad=h_grad, use_peephole=op.get_attr("use_peephole")) return (None, x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, b_grad)
[ "def", "_block_lstm_grad", "(", "op", ",", "*", "grads", ")", ":", "seq_len_max", ",", "x", ",", "cs_prev", ",", "h_prev", ",", "w", ",", "wci", ",", "wcf", ",", "wco", ",", "b", "=", "op", ".", "inputs", "i", ",", "cs", ",", "f", ",", "o", ",", "ci", ",", "co", ",", "h", "=", "op", ".", "outputs", "_", ",", "cs_grad", ",", "_", ",", "_", ",", "_", ",", "_", ",", "h_grad", "=", "grads", "(", "x_grad", ",", "cs_prev_grad", ",", "h_prev_grad", ",", "w_grad", ",", "wci_grad", ",", "wcf_grad", ",", "wco_grad", ",", "b_grad", ")", "=", "gen_rnn_ops", ".", "block_lstm_grad", "(", "seq_len_max", "=", "seq_len_max", ",", "x", "=", "x", ",", "cs_prev", "=", "cs_prev", ",", "h_prev", "=", "h_prev", ",", "w", "=", "w", ",", "wci", "=", "wci", ",", "wcf", "=", "wcf", ",", "wco", "=", "wco", ",", "b", "=", "b", ",", "i", "=", "i", ",", "cs", "=", "cs", ",", "f", "=", "f", ",", "o", "=", "o", ",", "ci", "=", "ci", ",", "co", "=", "co", ",", "h", "=", "h", ",", "cs_grad", "=", "cs_grad", ",", "h_grad", "=", "h_grad", ",", "use_peephole", "=", "op", ".", "get_attr", "(", "\"use_peephole\"", ")", ")", "return", "(", "None", ",", "x_grad", ",", "cs_prev_grad", ",", "h_prev_grad", ",", "w_grad", ",", "wci_grad", ",", "wcf_grad", ",", "wco_grad", ",", "b_grad", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/rnn_grad.py#L24-L51
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
DCFontChanger.__init__
(self, *args, **kwargs)
__init__(self, DC dc, Font font) -> DCFontChanger wx.wxDCFontChanger sets the DC's font when it is constructed, and then restores the old font whrn it goes out of scope.
__init__(self, DC dc, Font font) -> DCFontChanger
[ "__init__", "(", "self", "DC", "dc", "Font", "font", ")", "-", ">", "DCFontChanger" ]
def __init__(self, *args, **kwargs): """ __init__(self, DC dc, Font font) -> DCFontChanger wx.wxDCFontChanger sets the DC's font when it is constructed, and then restores the old font whrn it goes out of scope. """ _gdi_.DCFontChanger_swiginit(self,_gdi_.new_DCFontChanger(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "DCFontChanger_swiginit", "(", "self", ",", "_gdi_", ".", "new_DCFontChanger", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L5061-L5068
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/cli/req_command.py
python
SessionCommandMixin._get_index_urls
(cls, options)
return index_urls or None
Return a list of index urls from user-provided options.
Return a list of index urls from user-provided options.
[ "Return", "a", "list", "of", "index", "urls", "from", "user", "-", "provided", "options", "." ]
def _get_index_urls(cls, options): # type: (Values) -> Optional[List[str]] """Return a list of index urls from user-provided options.""" index_urls = [] if not getattr(options, "no_index", False): url = getattr(options, "index_url", None) if url: index_urls.append(url) urls = getattr(options, "extra_index_urls", None) if urls: index_urls.extend(urls) # Return None rather than an empty list return index_urls or None
[ "def", "_get_index_urls", "(", "cls", ",", "options", ")", ":", "# type: (Values) -> Optional[List[str]]", "index_urls", "=", "[", "]", "if", "not", "getattr", "(", "options", ",", "\"no_index\"", ",", "False", ")", ":", "url", "=", "getattr", "(", "options", ",", "\"index_url\"", ",", "None", ")", "if", "url", ":", "index_urls", ".", "append", "(", "url", ")", "urls", "=", "getattr", "(", "options", ",", "\"extra_index_urls\"", ",", "None", ")", "if", "urls", ":", "index_urls", ".", "extend", "(", "urls", ")", "# Return None rather than an empty list", "return", "index_urls", "or", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/cli/req_command.py#L115-L139
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/numbers.py
python
Complex.__pow__
(self, exponent)
self**exponent; should promote to float or complex when necessary.
self**exponent; should promote to float or complex when necessary.
[ "self", "**", "exponent", ";", "should", "promote", "to", "float", "or", "complex", "when", "necessary", "." ]
def __pow__(self, exponent): """self**exponent; should promote to float or complex when necessary.""" raise NotImplementedError
[ "def", "__pow__", "(", "self", ",", "exponent", ")", ":", "raise", "NotImplementedError" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/numbers.py#L137-L139
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2.py
python
RequestHandler.error
(self, code)
Clears the response and sets the given HTTP status code. This doesn't stop code execution; for this, use :meth:`abort`. :param code: HTTP status error code (e.g., 501).
Clears the response and sets the given HTTP status code.
[ "Clears", "the", "response", "and", "sets", "the", "given", "HTTP", "status", "code", "." ]
def error(self, code): """Clears the response and sets the given HTTP status code. This doesn't stop code execution; for this, use :meth:`abort`. :param code: HTTP status error code (e.g., 501). """ self.response.status = code self.response.clear()
[ "def", "error", "(", "self", ",", "code", ")", ":", "self", ".", "response", ".", "status", "=", "code", "self", ".", "response", ".", "clear", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2.py#L574-L583
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMT_SIGNATURE.sigAlg
(self)
return signature.GetUnionSelector() if signature else TPM_ALG_ID.NULL
Selector of the algorithm used to construct the signature
Selector of the algorithm used to construct the signature
[ "Selector", "of", "the", "algorithm", "used", "to", "construct", "the", "signature" ]
def sigAlg(self): # TPM_ALG_ID """ Selector of the algorithm used to construct the signature """ return signature.GetUnionSelector() if signature else TPM_ALG_ID.NULL
[ "def", "sigAlg", "(", "self", ")", ":", "# TPM_ALG_ID", "return", "signature", ".", "GetUnionSelector", "(", ")", "if", "signature", "else", "TPM_ALG_ID", ".", "NULL" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L7782-L7784
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py
python
HighPage.save_as_new_theme
(self)
Prompt for new theme name and create the theme. Methods: get_new_theme_name create_new
Prompt for new theme name and create the theme.
[ "Prompt", "for", "new", "theme", "name", "and", "create", "the", "theme", "." ]
def save_as_new_theme(self): """Prompt for new theme name and create the theme. Methods: get_new_theme_name create_new """ new_theme_name = self.get_new_theme_name('New Theme Name:') if new_theme_name: self.create_new(new_theme_name)
[ "def", "save_as_new_theme", "(", "self", ")", ":", "new_theme_name", "=", "self", ".", "get_new_theme_name", "(", "'New Theme Name:'", ")", "if", "new_theme_name", ":", "self", ".", "create_new", "(", "new_theme_name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L1137-L1146
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/package_index.py
python
unique_everseen
(iterable, key=None)
List unique elements, preserving order. Remember all elements ever seen.
List unique elements, preserving order. Remember all elements ever seen.
[ "List", "unique", "elements", "preserving", "order", ".", "Remember", "all", "elements", "ever", "seen", "." ]
def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in six.moves.filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element
[ "def", "unique_everseen", "(", "iterable", ",", "key", "=", "None", ")", ":", "# unique_everseen('AAAABBBCCDAABBB') --> A B C D", "# unique_everseen('ABBCcAD', str.lower) --> A B C D", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "if", "key", "is", "None", ":", "for", "element", "in", "six", ".", "moves", ".", "filterfalse", "(", "seen", ".", "__contains__", ",", "iterable", ")", ":", "seen_add", "(", "element", ")", "yield", "element", "else", ":", "for", "element", "in", "iterable", ":", "k", "=", "key", "(", "element", ")", "if", "k", "not", "in", "seen", ":", "seen_add", "(", "k", ")", "yield", "element" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/package_index.py#L188-L203
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/tools/android/build_incremental_dexmanifest.py
python
DexmanifestBuilder.Checksum
(self, filename)
return h.hexdigest()
Compute the SHA-256 checksum of a file.
Compute the SHA-256 checksum of a file.
[ "Compute", "the", "SHA", "-", "256", "checksum", "of", "a", "file", "." ]
def Checksum(self, filename): """Compute the SHA-256 checksum of a file.""" h = hashlib.sha256() with file(filename, "r") as f: while True: data = f.read(65536) if not data: break h.update(data) return h.hexdigest()
[ "def", "Checksum", "(", "self", ",", "filename", ")", ":", "h", "=", "hashlib", ".", "sha256", "(", ")", "with", "file", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", "(", "65536", ")", "if", "not", "data", ":", "break", "h", ".", "update", "(", "data", ")", "return", "h", ".", "hexdigest", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/tools/android/build_incremental_dexmanifest.py#L58-L69
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/cpplint.py
python
_GetTextInside
(text, start_pattern)
return text[start_position:position - 1]
Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found.
Retrieves all the text between matching open and close parentheses.
[ "Retrieves", "all", "the", "text", "between", "matching", "open", "and", "close", "parentheses", "." ]
def _GetTextInside(text, start_pattern): """Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1]
[ "def", "_GetTextInside", "(", "text", ",", "start_pattern", ")", ":", "# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably", "# rewritten to use _GetTextInside (and use inferior regexp matching today).", "# Give opening punctuations to get the matching close-punctuations.", "matching_punctuation", "=", "{", "'('", ":", "')'", ",", "'{'", ":", "'}'", ",", "'['", ":", "']'", "}", "closing_punctuation", "=", "set", "(", "matching_punctuation", ".", "itervalues", "(", ")", ")", "# Find the position to start extracting text.", "match", "=", "re", ".", "search", "(", "start_pattern", ",", "text", ",", "re", ".", "M", ")", "if", "not", "match", ":", "# start_pattern not found in text.", "return", "None", "start_position", "=", "match", ".", "end", "(", "0", ")", "assert", "start_position", ">", "0", ",", "(", "'start_pattern must ends with an opening punctuation.'", ")", "assert", "text", "[", "start_position", "-", "1", "]", "in", "matching_punctuation", ",", "(", "'start_pattern must ends with an opening punctuation.'", ")", "# Stack of closing punctuations we expect to have in text after position.", "punctuation_stack", "=", "[", "matching_punctuation", "[", "text", "[", "start_position", "-", "1", "]", "]", "]", "position", "=", "start_position", "while", "punctuation_stack", "and", "position", "<", "len", "(", "text", ")", ":", "if", "text", "[", "position", "]", "==", "punctuation_stack", "[", "-", "1", "]", ":", "punctuation_stack", ".", "pop", "(", ")", "elif", "text", "[", "position", "]", "in", "closing_punctuation", ":", "# A closing punctuation without matching opening punctuations.", "return", "None", "elif", "text", "[", "position", "]", "in", "matching_punctuation", ":", "punctuation_stack", ".", "append", "(", "matching_punctuation", "[", "text", "[", "position", "]", "]", ")", "position", "+=", "1", "if", "punctuation_stack", ":", "# Opening punctuations left without matching close-punctuations.", "return", "None", "# punctuations match.", "return", "text", "[", "start_position", ":", "position", "-", "1", "]" ]
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L2469-L2522
s9xie/DSN
065e49898d239f5c96be558616b2556eabc50351
python/caffe/drawnet.py
python
draw_net_to_file
(caffe_net, filename)
Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs.
Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs.
[ "Draws", "a", "caffe", "net", "and", "saves", "it", "to", "file", "using", "the", "format", "given", "as", "the", "file", "extension", ".", "Use", ".", "raw", "to", "output", "raw", "text", "that", "you", "can", "manually", "feed", "to", "graphviz", "to", "draw", "graphs", "." ]
def draw_net_to_file(caffe_net, filename): """Draws a caffe net, and saves it to file using the format given as the file extension. Use '.raw' to output raw text that you can manually feed to graphviz to draw graphs. """ ext = filename[filename.rfind('.')+1:] with open(filename, 'w') as fid: fid.write(draw_net(caffe_net, ext))
[ "def", "draw_net_to_file", "(", "caffe_net", ",", "filename", ")", ":", "ext", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fid", ":", "fid", ".", "write", "(", "draw_net", "(", "caffe_net", ",", "ext", ")", ")" ]
https://github.com/s9xie/DSN/blob/065e49898d239f5c96be558616b2556eabc50351/python/caffe/drawnet.py#L60-L67
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Window.Show
(*args, **kwargs)
return _core_.Window_Show(*args, **kwargs)
Show(self, bool show=True) -> bool Shows or hides the window. You may need to call Raise for a top level window if you want to bring it to top, although this is not needed if Show is called immediately after the frame creation. Returns True if the window has been shown or hidden or False if nothing was done because it already was in the requested state.
Show(self, bool show=True) -> bool
[ "Show", "(", "self", "bool", "show", "=", "True", ")", "-", ">", "bool" ]
def Show(*args, **kwargs): """ Show(self, bool show=True) -> bool Shows or hides the window. You may need to call Raise for a top level window if you want to bring it to top, although this is not needed if Show is called immediately after the frame creation. Returns True if the window has been shown or hidden or False if nothing was done because it already was in the requested state. """ return _core_.Window_Show(*args, **kwargs)
[ "def", "Show", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_Show", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L9912-L9922
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pgen2/parse.py
python
Parser.shift
(self, type, value, newstate, context)
Shift a token. (Internal)
Shift a token. (Internal)
[ "Shift", "a", "token", ".", "(", "Internal", ")" ]
def shift(self, type, value, newstate, context): """Shift a token. (Internal)""" dfa, state, node = self.stack[-1] newnode = (type, value, context, None) newnode = self.convert(self.grammar, newnode) if newnode is not None: node[-1].append(newnode) self.stack[-1] = (dfa, newstate, node)
[ "def", "shift", "(", "self", ",", "type", ",", "value", ",", "newstate", ",", "context", ")", ":", "dfa", ",", "state", ",", "node", "=", "self", ".", "stack", "[", "-", "1", "]", "newnode", "=", "(", "type", ",", "value", ",", "context", ",", "None", ")", "newnode", "=", "self", ".", "convert", "(", "self", ".", "grammar", ",", "newnode", ")", "if", "newnode", "is", "not", "None", ":", "node", "[", "-", "1", "]", ".", "append", "(", "newnode", ")", "self", ".", "stack", "[", "-", "1", "]", "=", "(", "dfa", ",", "newstate", ",", "node", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pgen2/parse.py#L175-L182
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/cython/Cython/Compiler/ExprNodes.py
python
make_dedup_key
(outer_type, item_nodes)
return outer_type, tuple(item_keys)
Recursively generate a deduplication key from a sequence of values. Includes Cython node types to work around the fact that (1, 2.0) == (1.0, 2), for example. @param outer_type: The type of the outer container. @param item_nodes: A sequence of constant nodes that will be traversed recursively. @return: A tuple that can be used as a dict key for deduplication.
Recursively generate a deduplication key from a sequence of values. Includes Cython node types to work around the fact that (1, 2.0) == (1.0, 2), for example.
[ "Recursively", "generate", "a", "deduplication", "key", "from", "a", "sequence", "of", "values", ".", "Includes", "Cython", "node", "types", "to", "work", "around", "the", "fact", "that", "(", "1", "2", ".", "0", ")", "==", "(", "1", ".", "0", "2", ")", "for", "example", "." ]
def make_dedup_key(outer_type, item_nodes): """ Recursively generate a deduplication key from a sequence of values. Includes Cython node types to work around the fact that (1, 2.0) == (1.0, 2), for example. @param outer_type: The type of the outer container. @param item_nodes: A sequence of constant nodes that will be traversed recursively. @return: A tuple that can be used as a dict key for deduplication. """ item_keys = [ (py_object_type, None, type(None)) if node is None # For sequences and their "mult_factor", see TupleNode. else make_dedup_key(node.type, [node.mult_factor if node.is_literal else None] + node.args) if node.is_sequence_constructor else make_dedup_key(node.type, (node.start, node.stop, node.step)) if node.is_slice # For constants, look at the Python value type if we don't know the concrete Cython type. else (node.type, node.constant_result, type(node.constant_result) if node.type is py_object_type else None) if node.has_constant_result() else None # something we cannot handle => short-circuit below for node in item_nodes ] if None in item_keys: return None return outer_type, tuple(item_keys)
[ "def", "make_dedup_key", "(", "outer_type", ",", "item_nodes", ")", ":", "item_keys", "=", "[", "(", "py_object_type", ",", "None", ",", "type", "(", "None", ")", ")", "if", "node", "is", "None", "# For sequences and their \"mult_factor\", see TupleNode.", "else", "make_dedup_key", "(", "node", ".", "type", ",", "[", "node", ".", "mult_factor", "if", "node", ".", "is_literal", "else", "None", "]", "+", "node", ".", "args", ")", "if", "node", ".", "is_sequence_constructor", "else", "make_dedup_key", "(", "node", ".", "type", ",", "(", "node", ".", "start", ",", "node", ".", "stop", ",", "node", ".", "step", ")", ")", "if", "node", ".", "is_slice", "# For constants, look at the Python value type if we don't know the concrete Cython type.", "else", "(", "node", ".", "type", ",", "node", ".", "constant_result", ",", "type", "(", "node", ".", "constant_result", ")", "if", "node", ".", "type", "is", "py_object_type", "else", "None", ")", "if", "node", ".", "has_constant_result", "(", ")", "else", "None", "# something we cannot handle => short-circuit below", "for", "node", "in", "item_nodes", "]", "if", "None", "in", "item_keys", ":", "return", "None", "return", "outer_type", ",", "tuple", "(", "item_keys", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/ExprNodes.py#L191-L213
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/utils.py
python
copy_and_modify
(src_file, dst_file, pattern_and_replace_tuples)
Read a source file, apply replacements, and save to a target file :param src_file: The source file to read and do the replacements :param dst_file: The target file :param pattern_and_replace_tuples: Pattern+Replacement tuples
Read a source file, apply replacements, and save to a target file
[ "Read", "a", "source", "file", "apply", "replacements", "and", "save", "to", "a", "target", "file" ]
def copy_and_modify(src_file, dst_file, pattern_and_replace_tuples): """ Read a source file, apply replacements, and save to a target file :param src_file: The source file to read and do the replacements :param dst_file: The target file :param pattern_and_replace_tuples: Pattern+Replacement tuples """ if not os.path.exists(src_file): raise ValueError('Source file ({}) does not exist.'.format(src_file)) with open(src_file,'r') as src_file_file: src_file_content = src_file_file.read() for pattern_str, replacement_str in pattern_and_replace_tuples: src_file_content = re.sub(pattern_str, replacement_str, src_file_content) with open(dst_file,'w') as dst_file: dst_file.write(src_file_content)
[ "def", "copy_and_modify", "(", "src_file", ",", "dst_file", ",", "pattern_and_replace_tuples", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "src_file", ")", ":", "raise", "ValueError", "(", "'Source file ({}) does not exist.'", ".", "format", "(", "src_file", ")", ")", "with", "open", "(", "src_file", ",", "'r'", ")", "as", "src_file_file", ":", "src_file_content", "=", "src_file_file", ".", "read", "(", ")", "for", "pattern_str", ",", "replacement_str", "in", "pattern_and_replace_tuples", ":", "src_file_content", "=", "re", ".", "sub", "(", "pattern_str", ",", "replacement_str", ",", "src_file_content", ")", "with", "open", "(", "dst_file", ",", "'w'", ")", "as", "dst_file", ":", "dst_file", ".", "write", "(", "src_file_content", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/utils.py#L114-L132
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/cubecolourdialog.py
python
ColourPanel.OnPaint
(self, event)
Handles the ``wx.EVT_PAINT`` for :class:`ColourPanel`. :param `event`: a :class:`PaintEvent` event to be processed.
Handles the ``wx.EVT_PAINT`` for :class:`ColourPanel`.
[ "Handles", "the", "wx", ".", "EVT_PAINT", "for", ":", "class", ":", "ColourPanel", "." ]
def OnPaint(self, event): """ Handles the ``wx.EVT_PAINT`` for :class:`ColourPanel`. :param `event`: a :class:`PaintEvent` event to be processed. """ pdc = wx.PaintDC(self) dc = wx.GCDC(pdc) mem_dc = wx.MemoryDC() rect = self.GetClientRect() bmp = wx.EmptyBitmap(rect.width, rect.height) mem_dc.SelectObject(bmp) backBrush = wx.Brush(self.GetParent().GetBackgroundColour()) mem_dc.SetBackground(backBrush) mem_dc.Clear() mem_dc.SetBrush(wx.WHITE_BRUSH) mem_dc.DrawRectangleRect(rect) DrawCheckerBoard(mem_dc, rect, checkColour, box=10) gcdc = wx.GCDC(mem_dc) colour_gcdc = wx.Colour(self._colour.r, self._colour.g, self._colour.b, self._colour._alpha) gcdc.SetBrush(wx.Brush(colour_gcdc)) gcdc.SetPen(wx.Pen(colour_gcdc)) gcdc.DrawRectangleRect(rect) mem_dc.SelectObject(wx.NullBitmap) dc.DrawBitmap(bmp, 0, 0)
[ "def", "OnPaint", "(", "self", ",", "event", ")", ":", "pdc", "=", "wx", ".", "PaintDC", "(", "self", ")", "dc", "=", "wx", ".", "GCDC", "(", "pdc", ")", "mem_dc", "=", "wx", ".", "MemoryDC", "(", ")", "rect", "=", "self", ".", "GetClientRect", "(", ")", "bmp", "=", "wx", ".", "EmptyBitmap", "(", "rect", ".", "width", ",", "rect", ".", "height", ")", "mem_dc", ".", "SelectObject", "(", "bmp", ")", "backBrush", "=", "wx", ".", "Brush", "(", "self", ".", "GetParent", "(", ")", ".", "GetBackgroundColour", "(", ")", ")", "mem_dc", ".", "SetBackground", "(", "backBrush", ")", "mem_dc", ".", "Clear", "(", ")", "mem_dc", ".", "SetBrush", "(", "wx", ".", "WHITE_BRUSH", ")", "mem_dc", ".", "DrawRectangleRect", "(", "rect", ")", "DrawCheckerBoard", "(", "mem_dc", ",", "rect", ",", "checkColour", ",", "box", "=", "10", ")", "gcdc", "=", "wx", ".", "GCDC", "(", "mem_dc", ")", "colour_gcdc", "=", "wx", ".", "Colour", "(", "self", ".", "_colour", ".", "r", ",", "self", ".", "_colour", ".", "g", ",", "self", ".", "_colour", ".", "b", ",", "self", ".", "_colour", ".", "_alpha", ")", "gcdc", ".", "SetBrush", "(", "wx", ".", "Brush", "(", "colour_gcdc", ")", ")", "gcdc", ".", "SetPen", "(", "wx", ".", "Pen", "(", "colour_gcdc", ")", ")", "gcdc", ".", "DrawRectangleRect", "(", "rect", ")", "mem_dc", ".", "SelectObject", "(", "wx", ".", "NullBitmap", ")", "dc", ".", "DrawBitmap", "(", "bmp", ",", "0", ",", "0", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L2531-L2562
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Tk.__init__
(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None)
Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.
Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.
[ "Return", "a", "new", "Toplevel", "widget", "on", "screen", "SCREENNAME", ".", "A", "new", "Tcl", "interpreter", "will", "be", "created", ".", "BASENAME", "will", "be", "used", "for", "the", "identification", "of", "the", "profile", "file", "(", "see", "readprofile", ")", ".", "It", "is", "constructed", "from", "sys", ".", "argv", "[", "0", "]", "without", "extensions", "if", "None", "is", "given", ".", "CLASSNAME", "is", "the", "name", "of", "the", "widget", "class", "." ]
def __init__(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None): """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.""" self.master = None self.children = {} self._tkloaded = 0 # to avoid recursions in the getattr code in case of failure, we # ensure that self.tk is always _something_. self.tk = None if baseName is None: import sys, os baseName = os.path.basename(sys.argv[0]) baseName, ext = os.path.splitext(baseName) if ext not in ('.py', '.pyc', '.pyo'): baseName = baseName + ext interactive = 0 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) if useTk: self._loadtk() if not sys.flags.ignore_environment: # Issue #16248: Honor the -E flag to avoid code injection. self.readprofile(baseName, className)
[ "def", "__init__", "(", "self", ",", "screenName", "=", "None", ",", "baseName", "=", "None", ",", "className", "=", "'Tk'", ",", "useTk", "=", "1", ",", "sync", "=", "0", ",", "use", "=", "None", ")", ":", "self", ".", "master", "=", "None", "self", ".", "children", "=", "{", "}", "self", ".", "_tkloaded", "=", "0", "# to avoid recursions in the getattr code in case of failure, we", "# ensure that self.tk is always _something_.", "self", ".", "tk", "=", "None", "if", "baseName", "is", "None", ":", "import", "sys", ",", "os", "baseName", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "baseName", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "baseName", ")", "if", "ext", "not", "in", "(", "'.py'", ",", "'.pyc'", ",", "'.pyo'", ")", ":", "baseName", "=", "baseName", "+", "ext", "interactive", "=", "0", "self", ".", "tk", "=", "_tkinter", ".", "create", "(", "screenName", ",", "baseName", ",", "className", ",", "interactive", ",", "wantobjects", ",", "useTk", ",", "sync", ",", "use", ")", "if", "useTk", ":", "self", ".", "_loadtk", "(", ")", "if", "not", "sys", ".", "flags", ".", "ignore_environment", ":", "# Issue #16248: Honor the -E flag to avoid code injection.", "self", ".", "readprofile", "(", "baseName", ",", "className", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1725-L1750
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/generators.py
python
PyGeneratorLower.init_generator_state
(self, lower)
NULL-initialize all generator state variables, to avoid spurious decref's on cleanup.
NULL-initialize all generator state variables, to avoid spurious decref's on cleanup.
[ "NULL", "-", "initialize", "all", "generator", "state", "variables", "to", "avoid", "spurious", "decref", "s", "on", "cleanup", "." ]
def init_generator_state(self, lower): """ NULL-initialize all generator state variables, to avoid spurious decref's on cleanup. """ lower.builder.store(Constant.null(self.gen_state_ptr.type.pointee), self.gen_state_ptr)
[ "def", "init_generator_state", "(", "self", ",", "lower", ")", ":", "lower", ".", "builder", ".", "store", "(", "Constant", ".", "null", "(", "self", ".", "gen_state_ptr", ".", "type", ".", "pointee", ")", ",", "self", ".", "gen_state_ptr", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/generators.py#L261-L267
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
sandbox/mintime/RRT_Smooth.py
python
RRT
(robot,goal_config)
return rave_traj
Find a RRT trajectory using OpenRAVE's bi-rrt Linear smoothing by dichotomy to reduce the number of via-points Return a rave trajectory robot -- the robot goal_config -- goal configuration
Find a RRT trajectory using OpenRAVE's bi-rrt Linear smoothing by dichotomy to reduce the number of via-points Return a rave trajectory robot -- the robot goal_config -- goal configuration
[ "Find", "a", "RRT", "trajectory", "using", "OpenRAVE", "s", "bi", "-", "rrt", "Linear", "smoothing", "by", "dichotomy", "to", "reduce", "the", "number", "of", "via", "-", "points", "Return", "a", "rave", "trajectory", "robot", "--", "the", "robot", "goal_config", "--", "goal", "configuration" ]
def RRT(robot,goal_config): """Find a RRT trajectory using OpenRAVE's bi-rrt Linear smoothing by dichotomy to reduce the number of via-points Return a rave trajectory robot -- the robot goal_config -- goal configuration """ params = Planner.PlannerParameters() params.SetRobotActiveJoints(robot) params.SetGoalConfig(goal_config) params.SetExtraParameters('<_postprocessing planner="shortcut_linear"><_nmaxiterations>40</_nmaxiterations></_postprocessing>') env=robot.GetEnv() planner=RaveCreatePlanner(env,'birrt') planner.InitPlan(robot, params) traj = RaveCreateTrajectory(env,'') planner.PlanPath(traj) traj_rrt=[] for i in range(traj.GetNumWaypoints()): traj_rrt.append(traj.GetWaypoint(i)) # Linear smoothing by dichotomy via_points=linear_smooth_dichotomy(robot,traj_rrt,0.001) dt_vect=array([1]*len(via_points)) dt_vect[0]=0 rave_traj=RaveCreateTrajectory(env,'') spec = robot.GetActiveConfigurationSpecification('linear') spec.AddDeltaTimeGroup() rave_traj.Init(spec) rave_traj.Insert(0,c_[via_points,dt_vect].flatten()) return rave_traj
[ "def", "RRT", "(", "robot", ",", "goal_config", ")", ":", "params", "=", "Planner", ".", "PlannerParameters", "(", ")", "params", ".", "SetRobotActiveJoints", "(", "robot", ")", "params", ".", "SetGoalConfig", "(", "goal_config", ")", "params", ".", "SetExtraParameters", "(", "'<_postprocessing planner=\"shortcut_linear\"><_nmaxiterations>40</_nmaxiterations></_postprocessing>'", ")", "env", "=", "robot", ".", "GetEnv", "(", ")", "planner", "=", "RaveCreatePlanner", "(", "env", ",", "'birrt'", ")", "planner", ".", "InitPlan", "(", "robot", ",", "params", ")", "traj", "=", "RaveCreateTrajectory", "(", "env", ",", "''", ")", "planner", ".", "PlanPath", "(", "traj", ")", "traj_rrt", "=", "[", "]", "for", "i", "in", "range", "(", "traj", ".", "GetNumWaypoints", "(", ")", ")", ":", "traj_rrt", ".", "append", "(", "traj", ".", "GetWaypoint", "(", "i", ")", ")", "# Linear smoothing by dichotomy", "via_points", "=", "linear_smooth_dichotomy", "(", "robot", ",", "traj_rrt", ",", "0.001", ")", "dt_vect", "=", "array", "(", "[", "1", "]", "*", "len", "(", "via_points", ")", ")", "dt_vect", "[", "0", "]", "=", "0", "rave_traj", "=", "RaveCreateTrajectory", "(", "env", ",", "''", ")", "spec", "=", "robot", ".", "GetActiveConfigurationSpecification", "(", "'linear'", ")", "spec", ".", "AddDeltaTimeGroup", "(", ")", "rave_traj", ".", "Init", "(", "spec", ")", "rave_traj", ".", "Insert", "(", "0", ",", "c_", "[", "via_points", ",", "dt_vect", "]", ".", "flatten", "(", ")", ")", "return", "rave_traj" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/sandbox/mintime/RRT_Smooth.py#L81-L117
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/examples/wxTerminal.py
python
TerminalFrame.StartThread
(self)
Start the receiver thread
Start the receiver thread
[ "Start", "the", "receiver", "thread" ]
def StartThread(self): """Start the receiver thread""" self.thread = threading.Thread(target=self.ComPortThread) self.thread.setDaemon(1) self.alive.set() self.thread.start() self.serial.rts = True self.serial.dtr = True self.frame_terminal_menubar.Check(ID_RTS, self.serial.rts) self.frame_terminal_menubar.Check(ID_DTR, self.serial.dtr)
[ "def", "StartThread", "(", "self", ")", ":", "self", ".", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "ComPortThread", ")", "self", ".", "thread", ".", "setDaemon", "(", "1", ")", "self", ".", "alive", ".", "set", "(", ")", "self", ".", "thread", ".", "start", "(", ")", "self", ".", "serial", ".", "rts", "=", "True", "self", ".", "serial", ".", "dtr", "=", "True", "self", ".", "frame_terminal_menubar", ".", "Check", "(", "ID_RTS", ",", "self", ".", "serial", ".", "rts", ")", "self", ".", "frame_terminal_menubar", ".", "Check", "(", "ID_DTR", ",", "self", ".", "serial", ".", "dtr", ")" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/examples/wxTerminal.py#L177-L186
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/learn/python/learn/dataframe/estimator_utils.py
python
to_feature_columns_and_input_fn
(dataframe, base_input_keys_with_defaults, feature_keys, target_keys=None, **kwargs)
return feature_columns, input_fn
Build a list of FeatureColumns and an input_fn for use with Estimator. Args: dataframe: the underlying dataframe base_input_keys_with_defaults: a dict from the names of columns to be considered base features to their default values. These columns will be fed via input_fn. feature_keys: the names of columns from which to generate FeatureColumns. These may include base features and/or derived features. target_keys: the names of columns to be used as targets. None is acceptable for unsupervised learning. **kwargs: Additional keyword arguments, unused here. Returns: A tuple of two elements: * A list of `FeatureColumn`s to be used when constructing an Estimator * An input_fn, i.e. a function that returns a pair of dicts (features, targets), each mapping string names to Tensors. the feature dict provides mappings for all the base columns required by the FeatureColumns. Raises: ValueError: when the feature and target key sets are non-disjoint, or the base_input and target sets are non-disjoint.
Build a list of FeatureColumns and an input_fn for use with Estimator.
[ "Build", "a", "list", "of", "FeatureColumns", "and", "an", "input_fn", "for", "use", "with", "Estimator", "." ]
def to_feature_columns_and_input_fn(dataframe, base_input_keys_with_defaults, feature_keys, target_keys=None, **kwargs): """Build a list of FeatureColumns and an input_fn for use with Estimator. Args: dataframe: the underlying dataframe base_input_keys_with_defaults: a dict from the names of columns to be considered base features to their default values. These columns will be fed via input_fn. feature_keys: the names of columns from which to generate FeatureColumns. These may include base features and/or derived features. target_keys: the names of columns to be used as targets. None is acceptable for unsupervised learning. **kwargs: Additional keyword arguments, unused here. Returns: A tuple of two elements: * A list of `FeatureColumn`s to be used when constructing an Estimator * An input_fn, i.e. a function that returns a pair of dicts (features, targets), each mapping string names to Tensors. the feature dict provides mappings for all the base columns required by the FeatureColumns. Raises: ValueError: when the feature and target key sets are non-disjoint, or the base_input and target sets are non-disjoint. """ if feature_keys is None or not feature_keys: raise ValueError("feature_keys must be specified.") if target_keys is None: target_keys = [] base_input_keys = base_input_keys_with_defaults.keys() in_two = (set(feature_keys) & set(target_keys)) or (set(base_input_keys) & set(target_keys)) if in_two: raise ValueError("Columns cannot be used for both features and targets: %s" % ", ".join(in_two)) # Obtain the feature series in the alternate universe new_feature_series_dict, feature_specs = _build_alternate_universe( dataframe, base_input_keys_with_defaults, feature_keys) # TODO(soergel): Allow non-real, non-dense DataFrameColumns for key in new_feature_series_dict.keys(): spec = feature_specs[key] if not ( isinstance(spec, parsing_ops.FixedLenFeature) and (spec.dtype.is_integer or spec.dtype.is_floating)): raise ValueError("For now, only real dense columns can be passed from " "DataFrame to Estimator. %s is %s of %s" % ( (key, type(spec).__name__, spec.dtype))) # Make FeatureColumns from these feature_columns = [feature_column.DataFrameColumn(name, s) for name, s in new_feature_series_dict.items()] # Make a new DataFrame with only the Series needed for input_fn. # This is important to avoid starting queue feeders that won't be used. limited_dataframe = dataframe.select_columns( list(base_input_keys) + list(target_keys)) # Build an input_fn suitable for use with Estimator. def input_fn(): """An input_fn() for feeding the given set of DataFrameColumns.""" # It's important to build all the tensors together in one DataFrame. # If we did df.select() for both key sets and then build those, the two # resulting DataFrames would be shuffled independently. tensors = limited_dataframe.build(**kwargs) base_input_features = {key: tensors[key] for key in base_input_keys} targets = {key: tensors[key] for key in target_keys} # TODO(soergel): Remove this special case when b/30367437 is fixed. if len(targets) == 1: targets = list(targets.values())[0] return base_input_features, targets return feature_columns, input_fn
[ "def", "to_feature_columns_and_input_fn", "(", "dataframe", ",", "base_input_keys_with_defaults", ",", "feature_keys", ",", "target_keys", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "feature_keys", "is", "None", "or", "not", "feature_keys", ":", "raise", "ValueError", "(", "\"feature_keys must be specified.\"", ")", "if", "target_keys", "is", "None", ":", "target_keys", "=", "[", "]", "base_input_keys", "=", "base_input_keys_with_defaults", ".", "keys", "(", ")", "in_two", "=", "(", "set", "(", "feature_keys", ")", "&", "set", "(", "target_keys", ")", ")", "or", "(", "set", "(", "base_input_keys", ")", "&", "set", "(", "target_keys", ")", ")", "if", "in_two", ":", "raise", "ValueError", "(", "\"Columns cannot be used for both features and targets: %s\"", "%", "\", \"", ".", "join", "(", "in_two", ")", ")", "# Obtain the feature series in the alternate universe", "new_feature_series_dict", ",", "feature_specs", "=", "_build_alternate_universe", "(", "dataframe", ",", "base_input_keys_with_defaults", ",", "feature_keys", ")", "# TODO(soergel): Allow non-real, non-dense DataFrameColumns", "for", "key", "in", "new_feature_series_dict", ".", "keys", "(", ")", ":", "spec", "=", "feature_specs", "[", "key", "]", "if", "not", "(", "isinstance", "(", "spec", ",", "parsing_ops", ".", "FixedLenFeature", ")", "and", "(", "spec", ".", "dtype", ".", "is_integer", "or", "spec", ".", "dtype", ".", "is_floating", ")", ")", ":", "raise", "ValueError", "(", "\"For now, only real dense columns can be passed from \"", "\"DataFrame to Estimator. %s is %s of %s\"", "%", "(", "(", "key", ",", "type", "(", "spec", ")", ".", "__name__", ",", "spec", ".", "dtype", ")", ")", ")", "# Make FeatureColumns from these", "feature_columns", "=", "[", "feature_column", ".", "DataFrameColumn", "(", "name", ",", "s", ")", "for", "name", ",", "s", "in", "new_feature_series_dict", ".", "items", "(", ")", "]", "# Make a new DataFrame with only the Series needed for input_fn.", "# This is important to avoid starting queue feeders that won't be used.", "limited_dataframe", "=", "dataframe", ".", "select_columns", "(", "list", "(", "base_input_keys", ")", "+", "list", "(", "target_keys", ")", ")", "# Build an input_fn suitable for use with Estimator.", "def", "input_fn", "(", ")", ":", "\"\"\"An input_fn() for feeding the given set of DataFrameColumns.\"\"\"", "# It's important to build all the tensors together in one DataFrame.", "# If we did df.select() for both key sets and then build those, the two", "# resulting DataFrames would be shuffled independently.", "tensors", "=", "limited_dataframe", ".", "build", "(", "*", "*", "kwargs", ")", "base_input_features", "=", "{", "key", ":", "tensors", "[", "key", "]", "for", "key", "in", "base_input_keys", "}", "targets", "=", "{", "key", ":", "tensors", "[", "key", "]", "for", "key", "in", "target_keys", "}", "# TODO(soergel): Remove this special case when b/30367437 is fixed.", "if", "len", "(", "targets", ")", "==", "1", ":", "targets", "=", "list", "(", "targets", ".", "values", "(", ")", ")", "[", "0", "]", "return", "base_input_features", ",", "targets", "return", "feature_columns", ",", "input_fn" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/dataframe/estimator_utils.py#L91-L175
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
binary_search_tree/compare_two_bst.py
python
main
()
operational function
operational function
[ "operational", "function" ]
def main(): """ operational function """ root1 = Node(5) root1.left = Node(3) root1.right = Node(8) root1.left.left = Node(2) root1.left.right = Node(4) root2 = Node(5) root2.left = Node(3) root2.right = Node(8) root2.left.left = Node(2) print(is_identical(root1, root2)) root2.left.right = Node(4) print(is_identical(root1, root2))
[ "def", "main", "(", ")", ":", "root1", "=", "Node", "(", "5", ")", "root1", ".", "left", "=", "Node", "(", "3", ")", "root1", ".", "right", "=", "Node", "(", "8", ")", "root1", ".", "left", ".", "left", "=", "Node", "(", "2", ")", "root1", ".", "left", ".", "right", "=", "Node", "(", "4", ")", "root2", "=", "Node", "(", "5", ")", "root2", ".", "left", "=", "Node", "(", "3", ")", "root2", ".", "right", "=", "Node", "(", "8", ")", "root2", ".", "left", ".", "left", "=", "Node", "(", "2", ")", "print", "(", "is_identical", "(", "root1", ",", "root2", ")", ")", "root2", ".", "left", ".", "right", "=", "Node", "(", "4", ")", "print", "(", "is_identical", "(", "root1", ",", "root2", ")", ")" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/binary_search_tree/compare_two_bst.py#L30-L46
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
CommandBit.parseliteral
(self, pos)
return bracket.literal
Parse a literal bracket.
Parse a literal bracket.
[ "Parse", "a", "literal", "bracket", "." ]
def parseliteral(self, pos): "Parse a literal bracket." self.factory.clearskipped(pos) if not self.factory.detecttype(Bracket, pos): if not pos.isvalue(): Trace.error('No literal parameter found at: ' + pos.identifier()) return None return pos.globvalue() bracket = Bracket().setfactory(self.factory) self.add(bracket.parseliteral(pos)) return bracket.literal
[ "def", "parseliteral", "(", "self", ",", "pos", ")", ":", "self", ".", "factory", ".", "clearskipped", "(", "pos", ")", "if", "not", "self", ".", "factory", ".", "detecttype", "(", "Bracket", ",", "pos", ")", ":", "if", "not", "pos", ".", "isvalue", "(", ")", ":", "Trace", ".", "error", "(", "'No literal parameter found at: '", "+", "pos", ".", "identifier", "(", ")", ")", "return", "None", "return", "pos", ".", "globvalue", "(", ")", "bracket", "=", "Bracket", "(", ")", ".", "setfactory", "(", "self", ".", "factory", ")", "self", ".", "add", "(", "bracket", ".", "parseliteral", "(", "pos", ")", ")", "return", "bracket", ".", "literal" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4156-L4166
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/IntegrateSingePtSubWindow.py
python
IntegrateSinglePtIntensityWindow.change_scan_number
(self, increment)
return
change the scan number in the :param increment: :return:
change the scan number in the :param increment: :return:
[ "change", "the", "scan", "number", "in", "the", ":", "param", "increment", ":", ":", "return", ":" ]
def change_scan_number(self, increment): """ change the scan number in the :param increment: :return: """ # FIXME - 20180809 - This behaviors weird... Need debugging output - TODO # get the list of scan number from the table, in future, a real-time updated list shall be used. run_number_list = list() for irow in range(self.ui.tableView_summary.rowCount()): run_number_list.append(self.ui.tableView_summary.get_scan_number(irow)) curr_scan = int(self.ui.lineEdit_Scan.text()) try: curr_scan_index = run_number_list.index(curr_scan) except IndexError: curr_scan_index = 0 next_scan_index = curr_scan_index + increment next_scan_index = (next_scan_index + len(run_number_list)) % len(run_number_list) # set self.ui.lineEdit_Scan.setText('{}'.format(run_number_list[next_scan_index])) return
[ "def", "change_scan_number", "(", "self", ",", "increment", ")", ":", "# FIXME - 20180809 - This behaviors weird... Need debugging output - TODO", "# get the list of scan number from the table, in future, a real-time updated list shall be used.", "run_number_list", "=", "list", "(", ")", "for", "irow", "in", "range", "(", "self", ".", "ui", ".", "tableView_summary", ".", "rowCount", "(", ")", ")", ":", "run_number_list", ".", "append", "(", "self", ".", "ui", ".", "tableView_summary", ".", "get_scan_number", "(", "irow", ")", ")", "curr_scan", "=", "int", "(", "self", ".", "ui", ".", "lineEdit_Scan", ".", "text", "(", ")", ")", "try", ":", "curr_scan_index", "=", "run_number_list", ".", "index", "(", "curr_scan", ")", "except", "IndexError", ":", "curr_scan_index", "=", "0", "next_scan_index", "=", "curr_scan_index", "+", "increment", "next_scan_index", "=", "(", "next_scan_index", "+", "len", "(", "run_number_list", ")", ")", "%", "len", "(", "run_number_list", ")", "# set", "self", ".", "ui", ".", "lineEdit_Scan", ".", "setText", "(", "'{}'", ".", "format", "(", "run_number_list", "[", "next_scan_index", "]", ")", ")", "return" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/IntegrateSingePtSubWindow.py#L549-L572
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
StatusBar.GetFieldsCount
(*args, **kwargs)
return _windows_.StatusBar_GetFieldsCount(*args, **kwargs)
GetFieldsCount(self) -> int
GetFieldsCount(self) -> int
[ "GetFieldsCount", "(", "self", ")", "-", ">", "int" ]
def GetFieldsCount(*args, **kwargs): """GetFieldsCount(self) -> int""" return _windows_.StatusBar_GetFieldsCount(*args, **kwargs)
[ "def", "GetFieldsCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "StatusBar_GetFieldsCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1243-L1245
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/ops/einsum.py
python
Einsum.adjust_equation_with_NCHW_layout
(node_name: str, equation: str, input_ranks: list, output_rank: int, input_correct_layout_mask: list, output_correct_layout_mask: bool)
return permuted_equation, is_inputs_adjusted, is_output_adjusted
In order to satisfy NCHW layout, subscripts for tensors with rank greater than three must be adjusted by moving labels of the last dimension to the second position in the subscript. There is an exception for such tensors when the label is ellipsis and it covers multiple tail dimensions. The method returns equation with adjusted subscripts to NCHW layout along with a boolean mask to indicate which subscripts are adjusted. :param node_name: Einsum node name for which equation is adjusted :param equation: Equation to be adjusted :param input_ranks: a list of input ranks :param output_rank: output rank :return: adjusted equation, boolean mask for inputs, and boolean flag if output subscript is adjusted
In order to satisfy NCHW layout, subscripts for tensors with rank greater than three must be adjusted by moving labels of the last dimension to the second position in the subscript. There is an exception for such tensors when the label is ellipsis and it covers multiple tail dimensions. The method returns equation with adjusted subscripts to NCHW layout along with a boolean mask to indicate which subscripts are adjusted.
[ "In", "order", "to", "satisfy", "NCHW", "layout", "subscripts", "for", "tensors", "with", "rank", "greater", "than", "three", "must", "be", "adjusted", "by", "moving", "labels", "of", "the", "last", "dimension", "to", "the", "second", "position", "in", "the", "subscript", ".", "There", "is", "an", "exception", "for", "such", "tensors", "when", "the", "label", "is", "ellipsis", "and", "it", "covers", "multiple", "tail", "dimensions", ".", "The", "method", "returns", "equation", "with", "adjusted", "subscripts", "to", "NCHW", "layout", "along", "with", "a", "boolean", "mask", "to", "indicate", "which", "subscripts", "are", "adjusted", "." ]
def adjust_equation_with_NCHW_layout(node_name: str, equation: str, input_ranks: list, output_rank: int, input_correct_layout_mask: list, output_correct_layout_mask: bool) -> ( str, list, bool): """ In order to satisfy NCHW layout, subscripts for tensors with rank greater than three must be adjusted by moving labels of the last dimension to the second position in the subscript. There is an exception for such tensors when the label is ellipsis and it covers multiple tail dimensions. The method returns equation with adjusted subscripts to NCHW layout along with a boolean mask to indicate which subscripts are adjusted. :param node_name: Einsum node name for which equation is adjusted :param equation: Equation to be adjusted :param input_ranks: a list of input ranks :param output_rank: output rank :return: adjusted equation, boolean mask for inputs, and boolean flag if output subscript is adjusted """ is_inputs_adjusted = [] input_subscripts, output_subscript = Einsum.parse_equation(node_name, equation) num_inputs = len(input_ranks) assert len(input_subscripts) == num_inputs, "The number of inputs must match a number " \ "of input subscripts" assert len(input_correct_layout_mask) == num_inputs, "The number of inputs must match a number " \ "elements in input_correct_layout_mask list" # permute labels in input subscripts and mark inputs for which inference in NCHW layout is acceptable # in case ellipsis covering multiple dimensions in the end, the permutation is impossible # so the corresponding input must be in the original format (NHWC) permuted_input_subscripts = [] for input_ind in range(num_inputs): input_subscript = input_subscripts[input_ind] input_rank = input_ranks[input_ind] labels = Einsum.extract_subscript_labels(node_name, input_subscript) num_broadcasted_dims = input_rank - len(labels) + 1 if input_correct_layout_mask[input_ind]: is_inputs_adjusted.append(True) elif input_rank > 3 and (labels[-1] != "..." or labels[-1] == "..." and num_broadcasted_dims == 1): is_inputs_adjusted.append(True) labels.insert(1, labels[-1]) del labels[-1] else: is_inputs_adjusted.append(False) permuted_input_subscript = ''.join(labels) permuted_input_subscripts.append(permuted_input_subscript) # perform the same procedure for the output subscript as for the inputs subscripts labels = Einsum.extract_subscript_labels(node_name, output_subscript) num_broadcasted_dims = output_rank - len(labels) + 1 if output_correct_layout_mask: is_output_adjusted = True elif output_rank > 3 and (labels[-1] != "..." or labels[-1] == "..." and num_broadcasted_dims == 1): is_output_adjusted = True labels.insert(1, labels[-1]) del labels[-1] else: is_output_adjusted = False permuted_output_subscript = ''.join(labels) # concatenate the left and right hands of the resulted equation left_hand = ','.join(permuted_input_subscripts) right_hand = permuted_output_subscript permuted_equation = left_hand + "->" + right_hand return permuted_equation, is_inputs_adjusted, is_output_adjusted
[ "def", "adjust_equation_with_NCHW_layout", "(", "node_name", ":", "str", ",", "equation", ":", "str", ",", "input_ranks", ":", "list", ",", "output_rank", ":", "int", ",", "input_correct_layout_mask", ":", "list", ",", "output_correct_layout_mask", ":", "bool", ")", "->", "(", "str", ",", "list", ",", "bool", ")", ":", "is_inputs_adjusted", "=", "[", "]", "input_subscripts", ",", "output_subscript", "=", "Einsum", ".", "parse_equation", "(", "node_name", ",", "equation", ")", "num_inputs", "=", "len", "(", "input_ranks", ")", "assert", "len", "(", "input_subscripts", ")", "==", "num_inputs", ",", "\"The number of inputs must match a number \"", "\"of input subscripts\"", "assert", "len", "(", "input_correct_layout_mask", ")", "==", "num_inputs", ",", "\"The number of inputs must match a number \"", "\"elements in input_correct_layout_mask list\"", "# permute labels in input subscripts and mark inputs for which inference in NCHW layout is acceptable", "# in case ellipsis covering multiple dimensions in the end, the permutation is impossible", "# so the corresponding input must be in the original format (NHWC)", "permuted_input_subscripts", "=", "[", "]", "for", "input_ind", "in", "range", "(", "num_inputs", ")", ":", "input_subscript", "=", "input_subscripts", "[", "input_ind", "]", "input_rank", "=", "input_ranks", "[", "input_ind", "]", "labels", "=", "Einsum", ".", "extract_subscript_labels", "(", "node_name", ",", "input_subscript", ")", "num_broadcasted_dims", "=", "input_rank", "-", "len", "(", "labels", ")", "+", "1", "if", "input_correct_layout_mask", "[", "input_ind", "]", ":", "is_inputs_adjusted", ".", "append", "(", "True", ")", "elif", "input_rank", ">", "3", "and", "(", "labels", "[", "-", "1", "]", "!=", "\"...\"", "or", "labels", "[", "-", "1", "]", "==", "\"...\"", "and", "num_broadcasted_dims", "==", "1", ")", ":", "is_inputs_adjusted", ".", "append", "(", "True", ")", "labels", ".", "insert", "(", "1", ",", "labels", "[", "-", "1", "]", ")", "del", "labels", "[", "-", "1", "]", "else", ":", "is_inputs_adjusted", ".", "append", "(", "False", ")", "permuted_input_subscript", "=", "''", ".", "join", "(", "labels", ")", "permuted_input_subscripts", ".", "append", "(", "permuted_input_subscript", ")", "# perform the same procedure for the output subscript as for the inputs subscripts", "labels", "=", "Einsum", ".", "extract_subscript_labels", "(", "node_name", ",", "output_subscript", ")", "num_broadcasted_dims", "=", "output_rank", "-", "len", "(", "labels", ")", "+", "1", "if", "output_correct_layout_mask", ":", "is_output_adjusted", "=", "True", "elif", "output_rank", ">", "3", "and", "(", "labels", "[", "-", "1", "]", "!=", "\"...\"", "or", "labels", "[", "-", "1", "]", "==", "\"...\"", "and", "num_broadcasted_dims", "==", "1", ")", ":", "is_output_adjusted", "=", "True", "labels", ".", "insert", "(", "1", ",", "labels", "[", "-", "1", "]", ")", "del", "labels", "[", "-", "1", "]", "else", ":", "is_output_adjusted", "=", "False", "permuted_output_subscript", "=", "''", ".", "join", "(", "labels", ")", "# concatenate the left and right hands of the resulted equation", "left_hand", "=", "','", ".", "join", "(", "permuted_input_subscripts", ")", "right_hand", "=", "permuted_output_subscript", "permuted_equation", "=", "left_hand", "+", "\"->\"", "+", "right_hand", "return", "permuted_equation", ",", "is_inputs_adjusted", ",", "is_output_adjusted" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/ops/einsum.py#L140-L200
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
PointCloud.setProperty
(self, *args)
return _robotsim.PointCloud_setProperty(self, *args)
setProperty(PointCloud self, int index, int pindex, double value) setProperty(PointCloud self, int index, std::string const & pname, double value) Sets the property named pname of point index to the given value.
setProperty(PointCloud self, int index, int pindex, double value) setProperty(PointCloud self, int index, std::string const & pname, double value)
[ "setProperty", "(", "PointCloud", "self", "int", "index", "int", "pindex", "double", "value", ")", "setProperty", "(", "PointCloud", "self", "int", "index", "std", "::", "string", "const", "&", "pname", "double", "value", ")" ]
def setProperty(self, *args): """ setProperty(PointCloud self, int index, int pindex, double value) setProperty(PointCloud self, int index, std::string const & pname, double value) Sets the property named pname of point index to the given value. """ return _robotsim.PointCloud_setProperty(self, *args)
[ "def", "setProperty", "(", "self", ",", "*", "args", ")", ":", "return", "_robotsim", ".", "PointCloud_setProperty", "(", "self", ",", "*", "args", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L1146-L1156
NVIDIA/MDL-SDK
aa9642b2546ad7b6236b5627385d882c2ed83c5d
src/mdl/jit/llvm/dist/utils/lit/lit/ProgressBar.py
python
TerminalController.__init__
(self, term_stream=sys.stdout)
Create a `TerminalController` and initialize its attributes with appropriate values for the current terminal. `term_stream` is the stream that will be used for terminal output; if this stream is not a tty, then the terminal is assumed to be a dumb terminal (i.e., have no capabilities).
Create a `TerminalController` and initialize its attributes with appropriate values for the current terminal. `term_stream` is the stream that will be used for terminal output; if this stream is not a tty, then the terminal is assumed to be a dumb terminal (i.e., have no capabilities).
[ "Create", "a", "TerminalController", "and", "initialize", "its", "attributes", "with", "appropriate", "values", "for", "the", "current", "terminal", ".", "term_stream", "is", "the", "stream", "that", "will", "be", "used", "for", "terminal", "output", ";", "if", "this", "stream", "is", "not", "a", "tty", "then", "the", "terminal", "is", "assumed", "to", "be", "a", "dumb", "terminal", "(", "i", ".", "e", ".", "have", "no", "capabilities", ")", "." ]
def __init__(self, term_stream=sys.stdout): """ Create a `TerminalController` and initialize its attributes with appropriate values for the current terminal. `term_stream` is the stream that will be used for terminal output; if this stream is not a tty, then the terminal is assumed to be a dumb terminal (i.e., have no capabilities). """ # Curses isn't available on all platforms try: import curses except: return # If the stream isn't a tty, then assume it has no capabilities. if not term_stream.isatty(): return # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return # Look up numeric capabilities. self.COLS = curses.tigetnum('cols') self.LINES = curses.tigetnum('lines') self.XN = curses.tigetflag('xenl') # Look up string capabilities. for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, self._tigetstr(cap_name) or '') # Colors set_fg = self._tigetstr('setf') if set_fg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, self._tparm(set_fg, i)) set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, self._tparm(set_fg_ansi, i)) set_bg = self._tigetstr('setb') if set_bg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, 'BG_'+color, self._tparm(set_bg, i)) set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, 'BG_'+color, self._tparm(set_bg_ansi, i))
[ "def", "__init__", "(", "self", ",", "term_stream", "=", "sys", ".", "stdout", ")", ":", "# Curses isn't available on all platforms", "try", ":", "import", "curses", "except", ":", "return", "# If the stream isn't a tty, then assume it has no capabilities.", "if", "not", "term_stream", ".", "isatty", "(", ")", ":", "return", "# Check the terminal type. If we fail, then assume that the", "# terminal has no capabilities.", "try", ":", "curses", ".", "setupterm", "(", ")", "except", ":", "return", "# Look up numeric capabilities.", "self", ".", "COLS", "=", "curses", ".", "tigetnum", "(", "'cols'", ")", "self", ".", "LINES", "=", "curses", ".", "tigetnum", "(", "'lines'", ")", "self", ".", "XN", "=", "curses", ".", "tigetflag", "(", "'xenl'", ")", "# Look up string capabilities.", "for", "capability", "in", "self", ".", "_STRING_CAPABILITIES", ":", "(", "attrib", ",", "cap_name", ")", "=", "capability", ".", "split", "(", "'='", ")", "setattr", "(", "self", ",", "attrib", ",", "self", ".", "_tigetstr", "(", "cap_name", ")", "or", "''", ")", "# Colors", "set_fg", "=", "self", ".", "_tigetstr", "(", "'setf'", ")", "if", "set_fg", ":", "for", "i", ",", "color", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_COLORS", ")", ")", ",", "self", ".", "_COLORS", ")", ":", "setattr", "(", "self", ",", "color", ",", "self", ".", "_tparm", "(", "set_fg", ",", "i", ")", ")", "set_fg_ansi", "=", "self", ".", "_tigetstr", "(", "'setaf'", ")", "if", "set_fg_ansi", ":", "for", "i", ",", "color", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_ANSICOLORS", ")", ")", ",", "self", ".", "_ANSICOLORS", ")", ":", "setattr", "(", "self", ",", "color", ",", "self", ".", "_tparm", "(", "set_fg_ansi", ",", "i", ")", ")", "set_bg", "=", "self", ".", "_tigetstr", "(", "'setb'", ")", "if", "set_bg", ":", "for", "i", ",", "color", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_COLORS", ")", ")", ",", "self", ".", "_COLORS", ")", ":", "setattr", "(", "self", ",", "'BG_'", "+", "color", ",", "self", ".", "_tparm", "(", "set_bg", ",", "i", ")", ")", "set_bg_ansi", "=", "self", ".", "_tigetstr", "(", "'setab'", ")", "if", "set_bg_ansi", ":", "for", "i", ",", "color", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_ANSICOLORS", ")", ")", ",", "self", ".", "_ANSICOLORS", ")", ":", "setattr", "(", "self", ",", "'BG_'", "+", "color", ",", "self", ".", "_tparm", "(", "set_bg_ansi", ",", "i", ")", ")" ]
https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/utils/lit/lit/ProgressBar.py#L89-L135
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py
python
SpawnBase.compile_pattern_list
(self, patterns)
return compiled_pattern_list
This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(cpl, timeout) ...
This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern).
[ "This", "compiles", "a", "pattern", "-", "string", "or", "a", "list", "of", "pattern", "-", "strings", ".", "Patterns", "must", "be", "a", "StringType", "EOF", "TIMEOUT", "SRE_Pattern", "or", "a", "list", "of", "those", ".", "Patterns", "may", "also", "be", "None", "which", "results", "in", "an", "empty", "list", "(", "you", "might", "do", "this", "if", "waiting", "for", "an", "EOF", "or", "TIMEOUT", "condition", "without", "expecting", "any", "pattern", ")", "." ]
def compile_pattern_list(self, patterns): '''This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TIMEOUT condition without expecting any pattern). This is used by expect() when calling expect_list(). Thus expect() is nothing more than:: cpl = self.compile_pattern_list(pl) return self.expect_list(cpl, timeout) If you are using expect() within a loop it may be more efficient to compile the patterns first and then call expect_list(). This avoid calls in a loop to compile_pattern_list():: cpl = self.compile_pattern_list(my_pattern) while some_condition: ... i = self.expect_list(cpl, timeout) ... ''' if patterns is None: return [] if not isinstance(patterns, list): patterns = [patterns] # Allow dot to match \n compile_flags = re.DOTALL if self.ignorecase: compile_flags = compile_flags | re.IGNORECASE compiled_pattern_list = [] for idx, p in enumerate(patterns): if isinstance(p, self.allowed_string_types): p = self._coerce_expect_string(p) compiled_pattern_list.append(re.compile(p, compile_flags)) elif p is EOF: compiled_pattern_list.append(EOF) elif p is TIMEOUT: compiled_pattern_list.append(TIMEOUT) elif isinstance(p, type(re.compile(''))): compiled_pattern_list.append(p) else: self._pattern_type_err(p) return compiled_pattern_list
[ "def", "compile_pattern_list", "(", "self", ",", "patterns", ")", ":", "if", "patterns", "is", "None", ":", "return", "[", "]", "if", "not", "isinstance", "(", "patterns", ",", "list", ")", ":", "patterns", "=", "[", "patterns", "]", "# Allow dot to match \\n", "compile_flags", "=", "re", ".", "DOTALL", "if", "self", ".", "ignorecase", ":", "compile_flags", "=", "compile_flags", "|", "re", ".", "IGNORECASE", "compiled_pattern_list", "=", "[", "]", "for", "idx", ",", "p", "in", "enumerate", "(", "patterns", ")", ":", "if", "isinstance", "(", "p", ",", "self", ".", "allowed_string_types", ")", ":", "p", "=", "self", ".", "_coerce_expect_string", "(", "p", ")", "compiled_pattern_list", ".", "append", "(", "re", ".", "compile", "(", "p", ",", "compile_flags", ")", ")", "elif", "p", "is", "EOF", ":", "compiled_pattern_list", ".", "append", "(", "EOF", ")", "elif", "p", "is", "TIMEOUT", ":", "compiled_pattern_list", ".", "append", "(", "TIMEOUT", ")", "elif", "isinstance", "(", "p", ",", "type", "(", "re", ".", "compile", "(", "''", ")", ")", ")", ":", "compiled_pattern_list", ".", "append", "(", "p", ")", "else", ":", "self", ".", "_pattern_type_err", "(", "p", ")", "return", "compiled_pattern_list" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L192-L238
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/morestats.py
python
ansari
(x, y)
return AnsariResult(AB, pval)
Perform the Ansari-Bradley test for equal scale parameters The Ansari-Bradley test is a non-parametric test for the equality of the scale parameter of the distributions from which two samples were drawn. Parameters ---------- x, y : array_like arrays of sample data Returns ------- statistic : float The Ansari-Bradley test statistic pvalue : float The p-value of the hypothesis test See Also -------- fligner : A non-parametric test for the equality of k variances mood : A non-parametric test for the equality of two scale parameters Notes ----- The p-value given is exact when the sample sizes are both less than 55 and there are no ties, otherwise a normal approximation for the p-value is used. References ---------- .. [1] Sprent, Peter and N.C. Smeeton. Applied nonparametric statistical methods. 3rd ed. Chapman and Hall/CRC. 2001. Section 5.8.2.
Perform the Ansari-Bradley test for equal scale parameters
[ "Perform", "the", "Ansari", "-", "Bradley", "test", "for", "equal", "scale", "parameters" ]
def ansari(x, y): """ Perform the Ansari-Bradley test for equal scale parameters The Ansari-Bradley test is a non-parametric test for the equality of the scale parameter of the distributions from which two samples were drawn. Parameters ---------- x, y : array_like arrays of sample data Returns ------- statistic : float The Ansari-Bradley test statistic pvalue : float The p-value of the hypothesis test See Also -------- fligner : A non-parametric test for the equality of k variances mood : A non-parametric test for the equality of two scale parameters Notes ----- The p-value given is exact when the sample sizes are both less than 55 and there are no ties, otherwise a normal approximation for the p-value is used. References ---------- .. [1] Sprent, Peter and N.C. Smeeton. Applied nonparametric statistical methods. 3rd ed. Chapman and Hall/CRC. 2001. Section 5.8.2. """ x, y = asarray(x), asarray(y) n = len(x) m = len(y) if m < 1: raise ValueError("Not enough other observations.") if n < 1: raise ValueError("Not enough test observations.") N = m + n xy = r_[x, y] # combine rank = stats.rankdata(xy) symrank = amin(array((rank, N - rank + 1)), 0) AB = np.sum(symrank[:n], axis=0) uxy = unique(xy) repeats = (len(uxy) != len(xy)) exact = ((m < 55) and (n < 55) and not repeats) if repeats and (m < 55 or n < 55): warnings.warn("Ties preclude use of exact statistic.") if exact: astart, a1, ifault = statlib.gscale(n, m) ind = AB - astart total = np.sum(a1, axis=0) if ind < len(a1)/2.0: cind = int(ceil(ind)) if ind == cind: pval = 2.0 * np.sum(a1[:cind+1], axis=0) / total else: pval = 2.0 * np.sum(a1[:cind], axis=0) / total else: find = int(floor(ind)) if ind == floor(ind): pval = 2.0 * np.sum(a1[find:], axis=0) / total else: pval = 2.0 * np.sum(a1[find+1:], axis=0) / total return AnsariResult(AB, min(1.0, pval)) # otherwise compute normal approximation if N % 2: # N odd mnAB = n * (N+1.0)**2 / 4.0 / N varAB = n * m * (N+1.0) * (3+N**2) / (48.0 * N**2) else: mnAB = n * (N+2.0) / 4.0 varAB = m * n * (N+2) * (N-2.0) / 48 / (N-1.0) if repeats: # adjust variance estimates # compute np.sum(tj * rj**2,axis=0) fac = np.sum(symrank**2, axis=0) if N % 2: # N odd varAB = m * n * (16*N*fac - (N+1)**4) / (16.0 * N**2 * (N-1)) else: # N even varAB = m * n * (16*fac - N*(N+2)**2) / (16.0 * N * (N-1)) z = (AB - mnAB) / sqrt(varAB) pval = distributions.norm.sf(abs(z)) * 2.0 return AnsariResult(AB, pval)
[ "def", "ansari", "(", "x", ",", "y", ")", ":", "x", ",", "y", "=", "asarray", "(", "x", ")", ",", "asarray", "(", "y", ")", "n", "=", "len", "(", "x", ")", "m", "=", "len", "(", "y", ")", "if", "m", "<", "1", ":", "raise", "ValueError", "(", "\"Not enough other observations.\"", ")", "if", "n", "<", "1", ":", "raise", "ValueError", "(", "\"Not enough test observations.\"", ")", "N", "=", "m", "+", "n", "xy", "=", "r_", "[", "x", ",", "y", "]", "# combine", "rank", "=", "stats", ".", "rankdata", "(", "xy", ")", "symrank", "=", "amin", "(", "array", "(", "(", "rank", ",", "N", "-", "rank", "+", "1", ")", ")", ",", "0", ")", "AB", "=", "np", ".", "sum", "(", "symrank", "[", ":", "n", "]", ",", "axis", "=", "0", ")", "uxy", "=", "unique", "(", "xy", ")", "repeats", "=", "(", "len", "(", "uxy", ")", "!=", "len", "(", "xy", ")", ")", "exact", "=", "(", "(", "m", "<", "55", ")", "and", "(", "n", "<", "55", ")", "and", "not", "repeats", ")", "if", "repeats", "and", "(", "m", "<", "55", "or", "n", "<", "55", ")", ":", "warnings", ".", "warn", "(", "\"Ties preclude use of exact statistic.\"", ")", "if", "exact", ":", "astart", ",", "a1", ",", "ifault", "=", "statlib", ".", "gscale", "(", "n", ",", "m", ")", "ind", "=", "AB", "-", "astart", "total", "=", "np", ".", "sum", "(", "a1", ",", "axis", "=", "0", ")", "if", "ind", "<", "len", "(", "a1", ")", "/", "2.0", ":", "cind", "=", "int", "(", "ceil", "(", "ind", ")", ")", "if", "ind", "==", "cind", ":", "pval", "=", "2.0", "*", "np", ".", "sum", "(", "a1", "[", ":", "cind", "+", "1", "]", ",", "axis", "=", "0", ")", "/", "total", "else", ":", "pval", "=", "2.0", "*", "np", ".", "sum", "(", "a1", "[", ":", "cind", "]", ",", "axis", "=", "0", ")", "/", "total", "else", ":", "find", "=", "int", "(", "floor", "(", "ind", ")", ")", "if", "ind", "==", "floor", "(", "ind", ")", ":", "pval", "=", "2.0", "*", "np", ".", "sum", "(", "a1", "[", "find", ":", "]", ",", "axis", "=", "0", ")", "/", "total", "else", ":", "pval", "=", "2.0", "*", "np", ".", "sum", "(", "a1", "[", "find", "+", "1", ":", "]", ",", "axis", "=", "0", ")", "/", "total", "return", "AnsariResult", "(", "AB", ",", "min", "(", "1.0", ",", "pval", ")", ")", "# otherwise compute normal approximation", "if", "N", "%", "2", ":", "# N odd", "mnAB", "=", "n", "*", "(", "N", "+", "1.0", ")", "**", "2", "/", "4.0", "/", "N", "varAB", "=", "n", "*", "m", "*", "(", "N", "+", "1.0", ")", "*", "(", "3", "+", "N", "**", "2", ")", "/", "(", "48.0", "*", "N", "**", "2", ")", "else", ":", "mnAB", "=", "n", "*", "(", "N", "+", "2.0", ")", "/", "4.0", "varAB", "=", "m", "*", "n", "*", "(", "N", "+", "2", ")", "*", "(", "N", "-", "2.0", ")", "/", "48", "/", "(", "N", "-", "1.0", ")", "if", "repeats", ":", "# adjust variance estimates", "# compute np.sum(tj * rj**2,axis=0)", "fac", "=", "np", ".", "sum", "(", "symrank", "**", "2", ",", "axis", "=", "0", ")", "if", "N", "%", "2", ":", "# N odd", "varAB", "=", "m", "*", "n", "*", "(", "16", "*", "N", "*", "fac", "-", "(", "N", "+", "1", ")", "**", "4", ")", "/", "(", "16.0", "*", "N", "**", "2", "*", "(", "N", "-", "1", ")", ")", "else", ":", "# N even", "varAB", "=", "m", "*", "n", "*", "(", "16", "*", "fac", "-", "N", "*", "(", "N", "+", "2", ")", "**", "2", ")", "/", "(", "16.0", "*", "N", "*", "(", "N", "-", "1", ")", ")", "z", "=", "(", "AB", "-", "mnAB", ")", "/", "sqrt", "(", "varAB", ")", "pval", "=", "distributions", ".", "norm", ".", "sf", "(", "abs", "(", "z", ")", ")", "*", "2.0", "return", "AnsariResult", "(", "AB", ",", "pval", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/morestats.py#L2052-L2142
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSProject.py
python
Writer._GetSpecForConfiguration
(self, config_type, config_name, attrs, tools)
return specification
Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns:
Returns the specification for a configuration.
[ "Returns", "the", "specification", "for", "a", "configuration", "." ]
def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): """Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns: """ # Handle defaults if not attrs: attrs = {} if not tools: tools = [] # Add configuration node and its attributes node_attrs = attrs.copy() node_attrs['Name'] = config_name specification = [config_type, node_attrs] # Add tool nodes and their attributes if tools: for t in tools: if isinstance(t, Tool): specification.append(t._GetSpecification()) else: specification.append(Tool(t)._GetSpecification()) return specification
[ "def", "_GetSpecForConfiguration", "(", "self", ",", "config_type", ",", "config_name", ",", "attrs", ",", "tools", ")", ":", "# Handle defaults", "if", "not", "attrs", ":", "attrs", "=", "{", "}", "if", "not", "tools", ":", "tools", "=", "[", "]", "# Add configuration node and its attributes", "node_attrs", "=", "attrs", ".", "copy", "(", ")", "node_attrs", "[", "'Name'", "]", "=", "config_name", "specification", "=", "[", "config_type", ",", "node_attrs", "]", "# Add tool nodes and their attributes", "if", "tools", ":", "for", "t", "in", "tools", ":", "if", "isinstance", "(", "t", ",", "Tool", ")", ":", "specification", ".", "append", "(", "t", ".", "_GetSpecification", "(", ")", ")", "else", ":", "specification", ".", "append", "(", "Tool", "(", "t", ")", ".", "_GetSpecification", "(", ")", ")", "return", "specification" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSProject.py#L92-L120
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/pylib/utils/logdog_helper.py
python
get_viewer_url
(name)
return get_logdog_client().get_viewer_url(name)
Get Logdog viewer URL. Args: name: Name of the logdog stream. Returns: Link to view uploaded binary in logdog viewer.
Get Logdog viewer URL.
[ "Get", "Logdog", "viewer", "URL", "." ]
def get_viewer_url(name): """Get Logdog viewer URL. Args: name: Name of the logdog stream. Returns: Link to view uploaded binary in logdog viewer. """ return get_logdog_client().get_viewer_url(name)
[ "def", "get_viewer_url", "(", "name", ")", ":", "return", "get_logdog_client", "(", ")", ".", "get_viewer_url", "(", "name", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/utils/logdog_helper.py#L81-L90
herbstluftwm/herbstluftwm
23ef0274bd4d317208eae5fea72b21478a71431b
doc/gendoc.py
python
TokenStream.try_match
(self, *args)
return True
if the next tokens match the list in the *args then pop them from the stream, else do nothing. if one of the next tokens is not a string, the matching returns False.
if the next tokens match the list in the *args then pop them from the stream, else do nothing. if one of the next tokens is not a string, the matching returns False.
[ "if", "the", "next", "tokens", "match", "the", "list", "in", "the", "*", "args", "then", "pop", "them", "from", "the", "stream", "else", "do", "nothing", ".", "if", "one", "of", "the", "next", "tokens", "is", "not", "a", "string", "the", "matching", "returns", "False", "." ]
def try_match(self, *args): """if the next tokens match the list in the *args then pop them from the stream, else do nothing. if one of the next tokens is not a string, the matching returns False. """ for delta, pattern in enumerate(args): if self.pos + delta >= len(self.tokens): return False curtok = self.tokens[self.pos + delta] if isinstance(pattern, self.re_type): if not isinstance(curtok, str) or not pattern.match(curtok): return False elif isinstance(pattern, str): if pattern != curtok: return False elif isinstance(pattern, TokenStream.PatternArg): if not pattern.assign(curtok): return False else: raise Exception("unknown pattern type {}".format(type(pattern))) self.pos += len(args) return True
[ "def", "try_match", "(", "self", ",", "*", "args", ")", ":", "for", "delta", ",", "pattern", "in", "enumerate", "(", "args", ")", ":", "if", "self", ".", "pos", "+", "delta", ">=", "len", "(", "self", ".", "tokens", ")", ":", "return", "False", "curtok", "=", "self", ".", "tokens", "[", "self", ".", "pos", "+", "delta", "]", "if", "isinstance", "(", "pattern", ",", "self", ".", "re_type", ")", ":", "if", "not", "isinstance", "(", "curtok", ",", "str", ")", "or", "not", "pattern", ".", "match", "(", "curtok", ")", ":", "return", "False", "elif", "isinstance", "(", "pattern", ",", "str", ")", ":", "if", "pattern", "!=", "curtok", ":", "return", "False", "elif", "isinstance", "(", "pattern", ",", "TokenStream", ".", "PatternArg", ")", ":", "if", "not", "pattern", ".", "assign", "(", "curtok", ")", ":", "return", "False", "else", ":", "raise", "Exception", "(", "\"unknown pattern type {}\"", ".", "format", "(", "type", "(", "pattern", ")", ")", ")", "self", ".", "pos", "+=", "len", "(", "args", ")", "return", "True" ]
https://github.com/herbstluftwm/herbstluftwm/blob/23ef0274bd4d317208eae5fea72b21478a71431b/doc/gendoc.py#L205-L228
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlContainerCell.GetFirstChild
(*args, **kwargs)
return _html.HtmlContainerCell_GetFirstChild(*args, **kwargs)
GetFirstChild(self) -> HtmlCell
GetFirstChild(self) -> HtmlCell
[ "GetFirstChild", "(", "self", ")", "-", ">", "HtmlCell" ]
def GetFirstChild(*args, **kwargs): """GetFirstChild(self) -> HtmlCell""" return _html.HtmlContainerCell_GetFirstChild(*args, **kwargs)
[ "def", "GetFirstChild", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlContainerCell_GetFirstChild", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L861-L863
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/sparse/dlmc/utils.py
python
load_dlmc_dataset
(dataset_path, operation, hidden_size, sparsity, device, requires_grad, n_limit=math.inf)
load_dlmc_dataset loads a DLMC dataset for a matmul performance test. Args: dataset_path: path of the dataset from DLMC collection. operation: This value allows tensors for `sparse@sparse`|`sparse@dense`|`sparse@vector` operations. hidden_size This value allows tensors of varying sizes. sparsity: This value allows tensors of varying sparsities. device: Whether to place the Tensor on a GPU or CPU. requires_grad: Loads the dataset for backward test. n_limit: This value allows a dataset with some limit size.
load_dlmc_dataset loads a DLMC dataset for a matmul performance test. Args: dataset_path: path of the dataset from DLMC collection. operation: This value allows tensors for `sparse
[ "load_dlmc_dataset", "loads", "a", "DLMC", "dataset", "for", "a", "matmul", "performance", "test", ".", "Args", ":", "dataset_path", ":", "path", "of", "the", "dataset", "from", "DLMC", "collection", ".", "operation", ":", "This", "value", "allows", "tensors", "for", "sparse" ]
def load_dlmc_dataset(dataset_path, operation, hidden_size, sparsity, device, requires_grad, n_limit=math.inf): """load_dlmc_dataset loads a DLMC dataset for a matmul performance test. Args: dataset_path: path of the dataset from DLMC collection. operation: This value allows tensors for `sparse@sparse`|`sparse@dense`|`sparse@vector` operations. hidden_size This value allows tensors of varying sizes. sparsity: This value allows tensors of varying sparsities. device: Whether to place the Tensor on a GPU or CPU. requires_grad: Loads the dataset for backward test. n_limit: This value allows a dataset with some limit size. """ if operation == 'sparse@sparse' or operation == "sparse@dense": collection = load_spmm_dataset(dataset_path, hidden_size, sparsity, operation, device, n_limit) elif operation == 'sparse@vector': collection = load_spmv_dataset(dataset_path, hidden_size, sparsity, device, n_limit) scipy_vars = {} backward_vars = {} for x, y in collection: if device == 'cpu': scipy_vars = { "sx": to_coo_scipy(x) if x.is_sparse else x.numpy(), "sy": to_coo_scipy(y) if y.is_sparse else y.numpy(), } if not requires_grad: dx = x.to_dense() if x.is_sparse else x dy = y.to_dense() if y.is_sparse else y else: c = sparse_grad_output(x, y) backward_vars = { "sparse_grad_output": c, "grad_output": c.to_dense() if c.is_sparse else c, } x.requires_grad_(True) y.requires_grad_(True) dx = x.to_dense().detach() if x.is_sparse else x.clone().detach() dy = y.to_dense().detach() if y.is_sparse else y.clone().detach() dx.requires_grad_(True) dy.requires_grad_(True) yield { "x": x, "y": y, "dx": dx, "dy": dy, **scipy_vars, **backward_vars }
[ "def", "load_dlmc_dataset", "(", "dataset_path", ",", "operation", ",", "hidden_size", ",", "sparsity", ",", "device", ",", "requires_grad", ",", "n_limit", "=", "math", ".", "inf", ")", ":", "if", "operation", "==", "'sparse@sparse'", "or", "operation", "==", "\"sparse@dense\"", ":", "collection", "=", "load_spmm_dataset", "(", "dataset_path", ",", "hidden_size", ",", "sparsity", ",", "operation", ",", "device", ",", "n_limit", ")", "elif", "operation", "==", "'sparse@vector'", ":", "collection", "=", "load_spmv_dataset", "(", "dataset_path", ",", "hidden_size", ",", "sparsity", ",", "device", ",", "n_limit", ")", "scipy_vars", "=", "{", "}", "backward_vars", "=", "{", "}", "for", "x", ",", "y", "in", "collection", ":", "if", "device", "==", "'cpu'", ":", "scipy_vars", "=", "{", "\"sx\"", ":", "to_coo_scipy", "(", "x", ")", "if", "x", ".", "is_sparse", "else", "x", ".", "numpy", "(", ")", ",", "\"sy\"", ":", "to_coo_scipy", "(", "y", ")", "if", "y", ".", "is_sparse", "else", "y", ".", "numpy", "(", ")", ",", "}", "if", "not", "requires_grad", ":", "dx", "=", "x", ".", "to_dense", "(", ")", "if", "x", ".", "is_sparse", "else", "x", "dy", "=", "y", ".", "to_dense", "(", ")", "if", "y", ".", "is_sparse", "else", "y", "else", ":", "c", "=", "sparse_grad_output", "(", "x", ",", "y", ")", "backward_vars", "=", "{", "\"sparse_grad_output\"", ":", "c", ",", "\"grad_output\"", ":", "c", ".", "to_dense", "(", ")", "if", "c", ".", "is_sparse", "else", "c", ",", "}", "x", ".", "requires_grad_", "(", "True", ")", "y", ".", "requires_grad_", "(", "True", ")", "dx", "=", "x", ".", "to_dense", "(", ")", ".", "detach", "(", ")", "if", "x", ".", "is_sparse", "else", "x", ".", "clone", "(", ")", ".", "detach", "(", ")", "dy", "=", "y", ".", "to_dense", "(", ")", ".", "detach", "(", ")", "if", "y", ".", "is_sparse", "else", "y", ".", "clone", "(", ")", ".", "detach", "(", ")", "dx", ".", "requires_grad_", "(", "True", ")", "dy", ".", "requires_grad_", "(", "True", ")", "yield", "{", "\"x\"", ":", "x", ",", "\"y\"", ":", "y", ",", "\"dx\"", ":", "dx", ",", "\"dy\"", ":", "dy", ",", "*", "*", "scipy_vars", ",", "*", "*", "backward_vars", "}" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/sparse/dlmc/utils.py#L147-L199
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/__init__.py
python
Node.get_build_scanner_path
(self, scanner)
return self.get_executor().get_build_scanner_path(scanner)
Fetch the appropriate scanner path for this node.
Fetch the appropriate scanner path for this node.
[ "Fetch", "the", "appropriate", "scanner", "path", "for", "this", "node", "." ]
def get_build_scanner_path(self, scanner): """Fetch the appropriate scanner path for this node.""" return self.get_executor().get_build_scanner_path(scanner)
[ "def", "get_build_scanner_path", "(", "self", ",", "scanner", ")", ":", "return", "self", ".", "get_executor", "(", ")", ".", "get_build_scanner_path", "(", "scanner", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/__init__.py#L634-L636
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/protobuf.py
python
decode_message
(message_type, encoded_message)
return message
Decode protocol buffer to Message instance. Args: message_type: Message type to decode data to. encoded_message: Encoded version of message as string. Returns: Decoded instance of message_type. Raises: DecodeError if an error occurs during decoding, such as incompatible wire format for a field. messages.ValidationError if merged message is not initialized.
Decode protocol buffer to Message instance.
[ "Decode", "protocol", "buffer", "to", "Message", "instance", "." ]
def decode_message(message_type, encoded_message): """Decode protocol buffer to Message instance. Args: message_type: Message type to decode data to. encoded_message: Encoded version of message as string. Returns: Decoded instance of message_type. Raises: DecodeError if an error occurs during decoding, such as incompatible wire format for a field. messages.ValidationError if merged message is not initialized. """ message = message_type() message_array = array.array('B') message_array.fromstring(encoded_message) try: decoder = _Decoder(message_array, 0, len(message_array)) while decoder.avail() > 0: # Decode tag and variant information. encoded_tag = decoder.getVarInt32() tag = encoded_tag >> _WIRE_TYPE_BITS wire_type = encoded_tag & _WIRE_TYPE_MASK try: found_wire_type_decoder = _WIRE_TYPE_TO_DECODER_MAP[wire_type] except: raise messages.DecodeError('No such wire type %d' % wire_type) if tag < 1: raise messages.DecodeError('Invalid tag value %d' % tag) try: field = message.field_by_number(tag) except KeyError: # Unexpected tags are ok. field = None wire_type_decoder = found_wire_type_decoder else: expected_wire_type = _VARIANT_TO_WIRE_TYPE[field.variant] if expected_wire_type != wire_type: raise messages.DecodeError('Expected wire type %s but found %s' % ( _WIRE_TYPE_NAME[expected_wire_type], _WIRE_TYPE_NAME[wire_type])) wire_type_decoder = _VARIANT_TO_DECODER_MAP[field.variant] value = wire_type_decoder(decoder) # Save unknown fields and skip additional processing. if not field: # When saving this, save it under the tag number (which should # be unique), and set the variant and value so we know how to # interpret the value later. variant = _WIRE_TYPE_TO_VARIANT_MAP.get(wire_type) if variant: message.set_unrecognized_field(tag, value, variant) continue # Special case Enum and Message types. if isinstance(field, messages.EnumField): try: value = field.type(value) except TypeError: raise messages.DecodeError('Invalid enum value %s' % value) elif isinstance(field, messages.MessageField): value = decode_message(field.message_type, value) value = field.value_from_message(value) # Merge value in to message. if field.repeated: values = getattr(message, field.name) if values is None: setattr(message, field.name, [value]) else: values.append(value) else: setattr(message, field.name, value) except ProtocolBuffer.ProtocolBufferDecodeError as err: raise messages.DecodeError('Decoding error: %s' % str(err)) message.check_initialized() return message
[ "def", "decode_message", "(", "message_type", ",", "encoded_message", ")", ":", "message", "=", "message_type", "(", ")", "message_array", "=", "array", ".", "array", "(", "'B'", ")", "message_array", ".", "fromstring", "(", "encoded_message", ")", "try", ":", "decoder", "=", "_Decoder", "(", "message_array", ",", "0", ",", "len", "(", "message_array", ")", ")", "while", "decoder", ".", "avail", "(", ")", ">", "0", ":", "# Decode tag and variant information.", "encoded_tag", "=", "decoder", ".", "getVarInt32", "(", ")", "tag", "=", "encoded_tag", ">>", "_WIRE_TYPE_BITS", "wire_type", "=", "encoded_tag", "&", "_WIRE_TYPE_MASK", "try", ":", "found_wire_type_decoder", "=", "_WIRE_TYPE_TO_DECODER_MAP", "[", "wire_type", "]", "except", ":", "raise", "messages", ".", "DecodeError", "(", "'No such wire type %d'", "%", "wire_type", ")", "if", "tag", "<", "1", ":", "raise", "messages", ".", "DecodeError", "(", "'Invalid tag value %d'", "%", "tag", ")", "try", ":", "field", "=", "message", ".", "field_by_number", "(", "tag", ")", "except", "KeyError", ":", "# Unexpected tags are ok.", "field", "=", "None", "wire_type_decoder", "=", "found_wire_type_decoder", "else", ":", "expected_wire_type", "=", "_VARIANT_TO_WIRE_TYPE", "[", "field", ".", "variant", "]", "if", "expected_wire_type", "!=", "wire_type", ":", "raise", "messages", ".", "DecodeError", "(", "'Expected wire type %s but found %s'", "%", "(", "_WIRE_TYPE_NAME", "[", "expected_wire_type", "]", ",", "_WIRE_TYPE_NAME", "[", "wire_type", "]", ")", ")", "wire_type_decoder", "=", "_VARIANT_TO_DECODER_MAP", "[", "field", ".", "variant", "]", "value", "=", "wire_type_decoder", "(", "decoder", ")", "# Save unknown fields and skip additional processing.", "if", "not", "field", ":", "# When saving this, save it under the tag number (which should", "# be unique), and set the variant and value so we know how to", "# interpret the value later.", "variant", "=", "_WIRE_TYPE_TO_VARIANT_MAP", ".", "get", "(", "wire_type", ")", "if", "variant", ":", "message", ".", "set_unrecognized_field", "(", "tag", ",", "value", ",", "variant", ")", "continue", "# Special case Enum and Message types.", "if", "isinstance", "(", "field", ",", "messages", ".", "EnumField", ")", ":", "try", ":", "value", "=", "field", ".", "type", "(", "value", ")", "except", "TypeError", ":", "raise", "messages", ".", "DecodeError", "(", "'Invalid enum value %s'", "%", "value", ")", "elif", "isinstance", "(", "field", ",", "messages", ".", "MessageField", ")", ":", "value", "=", "decode_message", "(", "field", ".", "message_type", ",", "value", ")", "value", "=", "field", ".", "value_from_message", "(", "value", ")", "# Merge value in to message.", "if", "field", ".", "repeated", ":", "values", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "if", "values", "is", "None", ":", "setattr", "(", "message", ",", "field", ".", "name", ",", "[", "value", "]", ")", "else", ":", "values", ".", "append", "(", "value", ")", "else", ":", "setattr", "(", "message", ",", "field", ".", "name", ",", "value", ")", "except", "ProtocolBuffer", ".", "ProtocolBufferDecodeError", "as", "err", ":", "raise", "messages", ".", "DecodeError", "(", "'Decoding error: %s'", "%", "str", "(", "err", ")", ")", "message", ".", "check_initialized", "(", ")", "return", "message" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/protobuf.py#L275-L359
takemaru/graphillion
51879f92bb96b53ef8f914ef37a05252ce383617
graphillion/graphset.py
python
GraphSet.update
(self, *others)
return self
Updates `self`, adding graphs from all others. Examples: >>> graph1 = [] >>> graph2 = [(1, 2)] >>> graph3 = [(1, 2), (1, 4)] >>> gs1 = GraphSet([graph1, graph2]) >>> gs2 = GraphSet([graph2, graph3]) >>> gs1 |= gs2 >>> gs1 GraphSet([[], [(1, 2)], [(1, 2), (1, 4)]]) Returns: A new GraphSet object. See Also: union()
Updates `self`, adding graphs from all others.
[ "Updates", "self", "adding", "graphs", "from", "all", "others", "." ]
def update(self, *others): """Updates `self`, adding graphs from all others. Examples: >>> graph1 = [] >>> graph2 = [(1, 2)] >>> graph3 = [(1, 2), (1, 4)] >>> gs1 = GraphSet([graph1, graph2]) >>> gs2 = GraphSet([graph2, graph3]) >>> gs1 |= gs2 >>> gs1 GraphSet([[], [(1, 2)], [(1, 2), (1, 4)]]) Returns: A new GraphSet object. See Also: union() """ self._ss.update(*[gs._ss for gs in others]) return self
[ "def", "update", "(", "self", ",", "*", "others", ")", ":", "self", ".", "_ss", ".", "update", "(", "*", "[", "gs", ".", "_ss", "for", "gs", "in", "others", "]", ")", "return", "self" ]
https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L311-L331
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/execution_callbacks.py
python
InfOrNanError._get_error_message
(self)
return msg
Get the error message describing this InfOrNanError object.
Get the error message describing this InfOrNanError object.
[ "Get", "the", "error", "message", "describing", "this", "InfOrNanError", "object", "." ]
def _get_error_message(self): """Get the error message describing this InfOrNanError object.""" name_str = (("'%s'" % self._op_name) if self._op_name is not None else str(self._op_name)) msg = "Output %d of %d of TFE operation %s (name: %s) contains " % ( self._output_index + 1, self._num_outputs, self._op_type, name_str) if self._inf_count and self._nan_count: msg += "%d inf(s) and %d nan(s) " % (self._inf_count, self._nan_count) elif self._inf_count: msg += "%d inf(s) " % self._inf_count else: msg += "%d nan(s) " % self._nan_count msg += "out of a total of %d element(s). Tensor value: %s" % ( self._total_count, self._value) return msg
[ "def", "_get_error_message", "(", "self", ")", ":", "name_str", "=", "(", "(", "\"'%s'\"", "%", "self", ".", "_op_name", ")", "if", "self", ".", "_op_name", "is", "not", "None", "else", "str", "(", "self", ".", "_op_name", ")", ")", "msg", "=", "\"Output %d of %d of TFE operation %s (name: %s) contains \"", "%", "(", "self", ".", "_output_index", "+", "1", ",", "self", ".", "_num_outputs", ",", "self", ".", "_op_type", ",", "name_str", ")", "if", "self", ".", "_inf_count", "and", "self", ".", "_nan_count", ":", "msg", "+=", "\"%d inf(s) and %d nan(s) \"", "%", "(", "self", ".", "_inf_count", ",", "self", ".", "_nan_count", ")", "elif", "self", ".", "_inf_count", ":", "msg", "+=", "\"%d inf(s) \"", "%", "self", ".", "_inf_count", "else", ":", "msg", "+=", "\"%d nan(s) \"", "%", "self", ".", "_nan_count", "msg", "+=", "\"out of a total of %d element(s). Tensor value: %s\"", "%", "(", "self", ".", "_total_count", ",", "self", ".", "_value", ")", "return", "msg" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/execution_callbacks.py#L88-L102
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/datetime.py
python
date.replace
(self, year=None, month=None, day=None)
return type(self)(year, month, day)
Return a new date with new values for the specified fields.
Return a new date with new values for the specified fields.
[ "Return", "a", "new", "date", "with", "new", "values", "for", "the", "specified", "fields", "." ]
def replace(self, year=None, month=None, day=None): """Return a new date with new values for the specified fields.""" if year is None: year = self._year if month is None: month = self._month if day is None: day = self._day return type(self)(year, month, day)
[ "def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ")", ":", "if", "year", "is", "None", ":", "year", "=", "self", ".", "_year", "if", "month", "is", "None", ":", "month", "=", "self", ".", "_month", "if", "day", "is", "None", ":", "day", "=", "self", ".", "_day", "return", "type", "(", "self", ")", "(", "year", ",", "month", ",", "day", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/datetime.py#L1014-L1022
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBFrame.GetDescription
(self, *args)
return _lldb.SBFrame_GetDescription(self, *args)
GetDescription(self, SBStream description) -> bool
GetDescription(self, SBStream description) -> bool
[ "GetDescription", "(", "self", "SBStream", "description", ")", "-", ">", "bool" ]
def GetDescription(self, *args): """GetDescription(self, SBStream description) -> bool""" return _lldb.SBFrame_GetDescription(self, *args)
[ "def", "GetDescription", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBFrame_GetDescription", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L4743-L4745
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PropertyGridInterface.GetFirstChild
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetFirstChild(*args, **kwargs)
GetFirstChild(self, PGPropArg id) -> PGProperty
GetFirstChild(self, PGPropArg id) -> PGProperty
[ "GetFirstChild", "(", "self", "PGPropArg", "id", ")", "-", ">", "PGProperty" ]
def GetFirstChild(*args, **kwargs): """GetFirstChild(self, PGPropArg id) -> PGProperty""" return _propgrid.PropertyGridInterface_GetFirstChild(*args, **kwargs)
[ "def", "GetFirstChild", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetFirstChild", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1163-L1165