id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
3,200
cognitect/transit-python
transit/writer.py
JsonMarshaler.emit_map
def emit_map(self, m, _, cache): """Emits array as per default JSON spec.""" self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
python
def emit_map(self, m, _, cache): self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
[ "def", "emit_map", "(", "self", ",", "m", ",", "_", ",", "cache", ")", ":", "self", ".", "emit_array_start", "(", "None", ")", "self", ".", "marshal", "(", "MAP_AS_ARR", ",", "False", ",", "cache", ")", "for", "k", ",", "v", "in", "m", ".", "items", "(", ")", ":", "self", ".", "marshal", "(", "k", ",", "True", ",", "cache", ")", "self", ".", "marshal", "(", "v", ",", "False", ",", "cache", ")", "self", ".", "emit_array_end", "(", ")" ]
Emits array as per default JSON spec.
[ "Emits", "array", "as", "per", "default", "JSON", "spec", "." ]
59e27e7d322feaa3a7e8eb3de06ae96d8adb614f
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L353-L360
3,201
cognitect/transit-python
transit/decoder.py
Decoder.decode_list
def decode_list(self, node, cache, as_map_key): """Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function. """ if node: if node[0] == MAP_AS_ARR: # key must be decoded before value for caching to work. returned_dict = {} for k, v in pairs(node[1:]): key = self._decode(k, cache, True) val = self._decode(v, cache, as_map_key) returned_dict[key] = val return transit_types.frozendict(returned_dict) decoded = self._decode(node[0], cache, as_map_key) if isinstance(decoded, Tag): return self.decode_tag(decoded.tag, self._decode(node[1], cache, as_map_key)) return tuple(self._decode(x, cache, as_map_key) for x in node)
python
def decode_list(self, node, cache, as_map_key): if node: if node[0] == MAP_AS_ARR: # key must be decoded before value for caching to work. returned_dict = {} for k, v in pairs(node[1:]): key = self._decode(k, cache, True) val = self._decode(v, cache, as_map_key) returned_dict[key] = val return transit_types.frozendict(returned_dict) decoded = self._decode(node[0], cache, as_map_key) if isinstance(decoded, Tag): return self.decode_tag(decoded.tag, self._decode(node[1], cache, as_map_key)) return tuple(self._decode(x, cache, as_map_key) for x in node)
[ "def", "decode_list", "(", "self", ",", "node", ",", "cache", ",", "as_map_key", ")", ":", "if", "node", ":", "if", "node", "[", "0", "]", "==", "MAP_AS_ARR", ":", "# key must be decoded before value for caching to work.", "returned_dict", "=", "{", "}", "for", "k", ",", "v", "in", "pairs", "(", "node", "[", "1", ":", "]", ")", ":", "key", "=", "self", ".", "_decode", "(", "k", ",", "cache", ",", "True", ")", "val", "=", "self", ".", "_decode", "(", "v", ",", "cache", ",", "as_map_key", ")", "returned_dict", "[", "key", "]", "=", "val", "return", "transit_types", ".", "frozendict", "(", "returned_dict", ")", "decoded", "=", "self", ".", "_decode", "(", "node", "[", "0", "]", ",", "cache", ",", "as_map_key", ")", "if", "isinstance", "(", "decoded", ",", "Tag", ")", ":", "return", "self", ".", "decode_tag", "(", "decoded", ".", "tag", ",", "self", ".", "_decode", "(", "node", "[", "1", "]", ",", "cache", ",", "as_map_key", ")", ")", "return", "tuple", "(", "self", ".", "_decode", "(", "x", ",", "cache", ",", "as_map_key", ")", "for", "x", "in", "node", ")" ]
Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function.
[ "Special", "case", "decodes", "map", "-", "as", "-", "array", ".", "Otherwise", "lists", "are", "treated", "as", "Python", "lists", "." ]
59e27e7d322feaa3a7e8eb3de06ae96d8adb614f
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L100-L121
3,202
cognitect/transit-python
transit/decoder.py
Decoder.decode_string
def decode_string(self, string, cache, as_map_key): """Decode a string - arguments follow the same convention as the top-level 'decode' function. """ if is_cache_key(string): return self.parse_string(cache.decode(string, as_map_key), cache, as_map_key) if is_cacheable(string, as_map_key): cache.encode(string, as_map_key) return self.parse_string(string, cache, as_map_key)
python
def decode_string(self, string, cache, as_map_key): if is_cache_key(string): return self.parse_string(cache.decode(string, as_map_key), cache, as_map_key) if is_cacheable(string, as_map_key): cache.encode(string, as_map_key) return self.parse_string(string, cache, as_map_key)
[ "def", "decode_string", "(", "self", ",", "string", ",", "cache", ",", "as_map_key", ")", ":", "if", "is_cache_key", "(", "string", ")", ":", "return", "self", ".", "parse_string", "(", "cache", ".", "decode", "(", "string", ",", "as_map_key", ")", ",", "cache", ",", "as_map_key", ")", "if", "is_cacheable", "(", "string", ",", "as_map_key", ")", ":", "cache", ".", "encode", "(", "string", ",", "as_map_key", ")", "return", "self", ".", "parse_string", "(", "string", ",", "cache", ",", "as_map_key", ")" ]
Decode a string - arguments follow the same convention as the top-level 'decode' function.
[ "Decode", "a", "string", "-", "arguments", "follow", "the", "same", "convention", "as", "the", "top", "-", "level", "decode", "function", "." ]
59e27e7d322feaa3a7e8eb3de06ae96d8adb614f
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L123-L132
3,203
cognitect/transit-python
transit/read_handlers.py
UuidHandler.from_rep
def from_rep(u): """Given a string, return a UUID object.""" if isinstance(u, pyversion.string_types): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int=combined)
python
def from_rep(u): if isinstance(u, pyversion.string_types): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int=combined)
[ "def", "from_rep", "(", "u", ")", ":", "if", "isinstance", "(", "u", ",", "pyversion", ".", "string_types", ")", ":", "return", "uuid", ".", "UUID", "(", "u", ")", "# hack to remove signs", "a", "=", "ctypes", ".", "c_ulong", "(", "u", "[", "0", "]", ")", "b", "=", "ctypes", ".", "c_ulong", "(", "u", "[", "1", "]", ")", "combined", "=", "a", ".", "value", "<<", "64", "|", "b", ".", "value", "return", "uuid", ".", "UUID", "(", "int", "=", "combined", ")" ]
Given a string, return a UUID object.
[ "Given", "a", "string", "return", "a", "UUID", "object", "." ]
59e27e7d322feaa3a7e8eb3de06ae96d8adb614f
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/read_handlers.py#L78-L87
3,204
kytos/python-openflow
pyof/v0x04/asynchronous/packet_in.py
PacketIn.in_port
def in_port(self): """Retrieve the 'in_port' that generated the PacketIn. This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on the `oxm_match_fields` field from `match` field and return its value, if the OXM exists. Returns: The integer number of the 'in_port' that generated the PacketIn if it exists. Otherwise return None. """ in_port = self.match.get_field(OxmOfbMatchField.OFPXMT_OFB_IN_PORT) return int.from_bytes(in_port, 'big')
python
def in_port(self): in_port = self.match.get_field(OxmOfbMatchField.OFPXMT_OFB_IN_PORT) return int.from_bytes(in_port, 'big')
[ "def", "in_port", "(", "self", ")", ":", "in_port", "=", "self", ".", "match", ".", "get_field", "(", "OxmOfbMatchField", ".", "OFPXMT_OFB_IN_PORT", ")", "return", "int", ".", "from_bytes", "(", "in_port", ",", "'big'", ")" ]
Retrieve the 'in_port' that generated the PacketIn. This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on the `oxm_match_fields` field from `match` field and return its value, if the OXM exists. Returns: The integer number of the 'in_port' that generated the PacketIn if it exists. Otherwise return None.
[ "Retrieve", "the", "in_port", "that", "generated", "the", "PacketIn", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/asynchronous/packet_in.py#L88-L101
3,205
kytos/python-openflow
pyof/v0x01/controller2switch/packet_out.py
PacketOut._update_actions_len
def _update_actions_len(self): """Update the actions_len field based on actions value.""" if isinstance(self.actions, ListOfActions): self.actions_len = self.actions.get_size() else: self.actions_len = ListOfActions(self.actions).get_size()
python
def _update_actions_len(self): if isinstance(self.actions, ListOfActions): self.actions_len = self.actions.get_size() else: self.actions_len = ListOfActions(self.actions).get_size()
[ "def", "_update_actions_len", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "actions", ",", "ListOfActions", ")", ":", "self", ".", "actions_len", "=", "self", ".", "actions", ".", "get_size", "(", ")", "else", ":", "self", ".", "actions_len", "=", "ListOfActions", "(", "self", ".", "actions", ")", ".", "get_size", "(", ")" ]
Update the actions_len field based on actions value.
[ "Update", "the", "actions_len", "field", "based", "on", "actions", "value", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/packet_out.py#L107-L112
3,206
kytos/python-openflow
pyof/v0x01/controller2switch/packet_out.py
PacketOut._validate_in_port
def _validate_in_port(self): """Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: ValidationError: If in_port is an invalid port. """ is_valid_range = self.in_port > 0 and self.in_port <= Port.OFPP_MAX is_valid_virtual_in_ports = self.in_port in _VIRT_IN_PORTS if (is_valid_range or is_valid_virtual_in_ports) is False: raise ValidationError(f'{self.in_port} is not a valid input port.')
python
def _validate_in_port(self): is_valid_range = self.in_port > 0 and self.in_port <= Port.OFPP_MAX is_valid_virtual_in_ports = self.in_port in _VIRT_IN_PORTS if (is_valid_range or is_valid_virtual_in_ports) is False: raise ValidationError(f'{self.in_port} is not a valid input port.')
[ "def", "_validate_in_port", "(", "self", ")", ":", "is_valid_range", "=", "self", ".", "in_port", ">", "0", "and", "self", ".", "in_port", "<=", "Port", ".", "OFPP_MAX", "is_valid_virtual_in_ports", "=", "self", ".", "in_port", "in", "_VIRT_IN_PORTS", "if", "(", "is_valid_range", "or", "is_valid_virtual_in_ports", ")", "is", "False", ":", "raise", "ValidationError", "(", "f'{self.in_port} is not a valid input port.'", ")" ]
Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: ValidationError: If in_port is an invalid port.
[ "Validate", "in_port", "attribute", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/packet_out.py#L114-L131
3,207
kytos/python-openflow
pyof/v0x01/common/utils.py
new_message_from_message_type
def new_message_from_message_type(message_type): """Given an OpenFlow Message Type, return an empty message of that type. Args: messageType (:class:`~pyof.v0x01.common.header.Type`): Python-openflow message. Returns: Empty OpenFlow message of the requested message type. Raises: KytosUndefinedMessageType: Unkown Message_Type. """ message_type = str(message_type) if message_type not in MESSAGE_TYPES: raise ValueError('"{}" is not known.'.format(message_type)) message_class = MESSAGE_TYPES.get(message_type) message_instance = message_class() return message_instance
python
def new_message_from_message_type(message_type): message_type = str(message_type) if message_type not in MESSAGE_TYPES: raise ValueError('"{}" is not known.'.format(message_type)) message_class = MESSAGE_TYPES.get(message_type) message_instance = message_class() return message_instance
[ "def", "new_message_from_message_type", "(", "message_type", ")", ":", "message_type", "=", "str", "(", "message_type", ")", "if", "message_type", "not", "in", "MESSAGE_TYPES", ":", "raise", "ValueError", "(", "'\"{}\" is not known.'", ".", "format", "(", "message_type", ")", ")", "message_class", "=", "MESSAGE_TYPES", ".", "get", "(", "message_type", ")", "message_instance", "=", "message_class", "(", ")", "return", "message_instance" ]
Given an OpenFlow Message Type, return an empty message of that type. Args: messageType (:class:`~pyof.v0x01.common.header.Type`): Python-openflow message. Returns: Empty OpenFlow message of the requested message type. Raises: KytosUndefinedMessageType: Unkown Message_Type.
[ "Given", "an", "OpenFlow", "Message", "Type", "return", "an", "empty", "message", "of", "that", "type", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/utils.py#L66-L88
3,208
kytos/python-openflow
pyof/v0x01/common/utils.py
new_message_from_header
def new_message_from_header(header): """Given an OF Header, return an empty message of header's message_type. Args: header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header. Returns: Empty OpenFlow message of the same type of message_type attribute from the given header. The header attribute of the message will be populated. Raises: KytosUndefinedMessageType: Unkown Message_Type. """ message_type = header.message_type if not isinstance(message_type, Type): try: if isinstance(message_type, str): message_type = Type[message_type] elif isinstance(message_type, int): message_type = Type(message_type) except ValueError: raise ValueError message = new_message_from_message_type(message_type) message.header.xid = header.xid message.header.length = header.length return message
python
def new_message_from_header(header): message_type = header.message_type if not isinstance(message_type, Type): try: if isinstance(message_type, str): message_type = Type[message_type] elif isinstance(message_type, int): message_type = Type(message_type) except ValueError: raise ValueError message = new_message_from_message_type(message_type) message.header.xid = header.xid message.header.length = header.length return message
[ "def", "new_message_from_header", "(", "header", ")", ":", "message_type", "=", "header", ".", "message_type", "if", "not", "isinstance", "(", "message_type", ",", "Type", ")", ":", "try", ":", "if", "isinstance", "(", "message_type", ",", "str", ")", ":", "message_type", "=", "Type", "[", "message_type", "]", "elif", "isinstance", "(", "message_type", ",", "int", ")", ":", "message_type", "=", "Type", "(", "message_type", ")", "except", "ValueError", ":", "raise", "ValueError", "message", "=", "new_message_from_message_type", "(", "message_type", ")", "message", ".", "header", ".", "xid", "=", "header", ".", "xid", "message", ".", "header", ".", "length", "=", "header", ".", "length", "return", "message" ]
Given an OF Header, return an empty message of header's message_type. Args: header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header. Returns: Empty OpenFlow message of the same type of message_type attribute from the given header. The header attribute of the message will be populated. Raises: KytosUndefinedMessageType: Unkown Message_Type.
[ "Given", "an", "OF", "Header", "return", "an", "empty", "message", "of", "header", "s", "message_type", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/utils.py#L91-L120
3,209
kytos/python-openflow
pyof/v0x01/common/utils.py
unpack_message
def unpack_message(buffer): """Unpack the whole buffer, including header pack. Args: buffer (bytes): Bytes representation of a openflow message. Returns: object: Instance of openflow message. """ hdr_size = Header().get_size() hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:] header = Header() header.unpack(hdr_buff) message = new_message_from_header(header) message.unpack(msg_buff) return message
python
def unpack_message(buffer): hdr_size = Header().get_size() hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:] header = Header() header.unpack(hdr_buff) message = new_message_from_header(header) message.unpack(msg_buff) return message
[ "def", "unpack_message", "(", "buffer", ")", ":", "hdr_size", "=", "Header", "(", ")", ".", "get_size", "(", ")", "hdr_buff", ",", "msg_buff", "=", "buffer", "[", ":", "hdr_size", "]", ",", "buffer", "[", "hdr_size", ":", "]", "header", "=", "Header", "(", ")", "header", ".", "unpack", "(", "hdr_buff", ")", "message", "=", "new_message_from_header", "(", "header", ")", "message", ".", "unpack", "(", "msg_buff", ")", "return", "message" ]
Unpack the whole buffer, including header pack. Args: buffer (bytes): Bytes representation of a openflow message. Returns: object: Instance of openflow message.
[ "Unpack", "the", "whole", "buffer", "including", "header", "pack", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/utils.py#L123-L139
3,210
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
MultipartReply._unpack_body
def _unpack_body(self): """Unpack `body` replace it by the result.""" obj = self._get_body_instance() obj.unpack(self.body.value) self.body = obj
python
def _unpack_body(self): obj = self._get_body_instance() obj.unpack(self.body.value) self.body = obj
[ "def", "_unpack_body", "(", "self", ")", ":", "obj", "=", "self", ".", "_get_body_instance", "(", ")", "obj", ".", "unpack", "(", "self", ".", "body", ".", "value", ")", "self", ".", "body", "=", "obj" ]
Unpack `body` replace it by the result.
[ "Unpack", "body", "replace", "it", "by", "the", "result", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L133-L137
3,211
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV.unpack
def unpack(self, buff, offset=0): """Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, offset) # Recover field from field_and_hasmask. try: self.oxm_field = self._unpack_oxm_field() except ValueError as exception: raise UnpackException(exception) # The last bit of field_and_mask is oxm_hasmask self.oxm_hasmask = (self.oxm_field_and_mask & 1) == 1 # as boolean # Unpack oxm_value that has oxm_length bytes start = offset + 4 # 4 bytes: class, field_and_mask and length end = start + self.oxm_length self.oxm_value = buff[start:end]
python
def unpack(self, buff, offset=0): super().unpack(buff, offset) # Recover field from field_and_hasmask. try: self.oxm_field = self._unpack_oxm_field() except ValueError as exception: raise UnpackException(exception) # The last bit of field_and_mask is oxm_hasmask self.oxm_hasmask = (self.oxm_field_and_mask & 1) == 1 # as boolean # Unpack oxm_value that has oxm_length bytes start = offset + 4 # 4 bytes: class, field_and_mask and length end = start + self.oxm_length self.oxm_value = buff[start:end]
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "# Recover field from field_and_hasmask.", "try", ":", "self", ".", "oxm_field", "=", "self", ".", "_unpack_oxm_field", "(", ")", "except", "ValueError", "as", "exception", ":", "raise", "UnpackException", "(", "exception", ")", "# The last bit of field_and_mask is oxm_hasmask", "self", ".", "oxm_hasmask", "=", "(", "self", ".", "oxm_field_and_mask", "&", "1", ")", "==", "1", "# as boolean", "# Unpack oxm_value that has oxm_length bytes", "start", "=", "offset", "+", "4", "# 4 bytes: class, field_and_mask and length", "end", "=", "start", "+", "self", ".", "oxm_length", "self", ".", "oxm_value", "=", "buff", "[", "start", ":", "end", "]" ]
Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data.
[ "Unpack", "the", "buffer", "into", "a", "OxmTLV", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L214-L235
3,212
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV._unpack_oxm_field
def _unpack_oxm_field(self): """Unpack oxm_field from oxm_field_and_mask. Returns: :class:`OxmOfbMatchField`, int: oxm_field from oxm_field_and_mask. Raises: ValueError: If oxm_class is OFPXMC_OPENFLOW_BASIC but :class:`OxmOfbMatchField` has no such integer value. """ field_int = self.oxm_field_and_mask >> 1 # We know that the class below requires a subset of the ofb enum if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC: return OxmOfbMatchField(field_int) return field_int
python
def _unpack_oxm_field(self): field_int = self.oxm_field_and_mask >> 1 # We know that the class below requires a subset of the ofb enum if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC: return OxmOfbMatchField(field_int) return field_int
[ "def", "_unpack_oxm_field", "(", "self", ")", ":", "field_int", "=", "self", ".", "oxm_field_and_mask", ">>", "1", "# We know that the class below requires a subset of the ofb enum", "if", "self", ".", "oxm_class", "==", "OxmClass", ".", "OFPXMC_OPENFLOW_BASIC", ":", "return", "OxmOfbMatchField", "(", "field_int", ")", "return", "field_int" ]
Unpack oxm_field from oxm_field_and_mask. Returns: :class:`OxmOfbMatchField`, int: oxm_field from oxm_field_and_mask. Raises: ValueError: If oxm_class is OFPXMC_OPENFLOW_BASIC but :class:`OxmOfbMatchField` has no such integer value.
[ "Unpack", "oxm_field", "from", "oxm_field_and_mask", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L237-L252
3,213
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV._update_length
def _update_length(self): """Update length field. Update the oxm_length field with the packed payload length. """ payload = type(self).oxm_value.pack(self.oxm_value) self.oxm_length = len(payload)
python
def _update_length(self): payload = type(self).oxm_value.pack(self.oxm_value) self.oxm_length = len(payload)
[ "def", "_update_length", "(", "self", ")", ":", "payload", "=", "type", "(", "self", ")", ".", "oxm_value", ".", "pack", "(", "self", ".", "oxm_value", ")", "self", ".", "oxm_length", "=", "len", "(", "payload", ")" ]
Update length field. Update the oxm_length field with the packed payload length.
[ "Update", "length", "field", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L254-L261
3,214
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV.pack
def pack(self, value=None): """Join oxm_hasmask bit and 7-bit oxm_field.""" if value is not None: return value.pack() # Set oxm_field_and_mask instance attribute # 1. Move field integer one bit to the left try: field_int = self._get_oxm_field_int() except ValueError as exception: raise PackException(exception) field_bits = field_int << 1 # 2. hasmask bit hasmask_bit = self.oxm_hasmask & 1 # 3. Add hasmask bit to field value self.oxm_field_and_mask = field_bits + hasmask_bit self._update_length() return super().pack(value)
python
def pack(self, value=None): if value is not None: return value.pack() # Set oxm_field_and_mask instance attribute # 1. Move field integer one bit to the left try: field_int = self._get_oxm_field_int() except ValueError as exception: raise PackException(exception) field_bits = field_int << 1 # 2. hasmask bit hasmask_bit = self.oxm_hasmask & 1 # 3. Add hasmask bit to field value self.oxm_field_and_mask = field_bits + hasmask_bit self._update_length() return super().pack(value)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "value", ".", "pack", "(", ")", "# Set oxm_field_and_mask instance attribute", "# 1. Move field integer one bit to the left", "try", ":", "field_int", "=", "self", ".", "_get_oxm_field_int", "(", ")", "except", "ValueError", "as", "exception", ":", "raise", "PackException", "(", "exception", ")", "field_bits", "=", "field_int", "<<", "1", "# 2. hasmask bit", "hasmask_bit", "=", "self", ".", "oxm_hasmask", "&", "1", "# 3. Add hasmask bit to field value", "self", ".", "oxm_field_and_mask", "=", "field_bits", "+", "hasmask_bit", "self", ".", "_update_length", "(", ")", "return", "super", "(", ")", ".", "pack", "(", "value", ")" ]
Join oxm_hasmask bit and 7-bit oxm_field.
[ "Join", "oxm_hasmask", "bit", "and", "7", "-", "bit", "oxm_field", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L263-L281
3,215
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV._get_oxm_field_int
def _get_oxm_field_int(self): """Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and the enum has no such value. """ if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC: return OxmOfbMatchField(self.oxm_field).value elif not isinstance(self.oxm_field, int) or self.oxm_field > 127: raise ValueError('oxm_field above 127: "{self.oxm_field}".') return self.oxm_field
python
def _get_oxm_field_int(self): if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC: return OxmOfbMatchField(self.oxm_field).value elif not isinstance(self.oxm_field, int) or self.oxm_field > 127: raise ValueError('oxm_field above 127: "{self.oxm_field}".') return self.oxm_field
[ "def", "_get_oxm_field_int", "(", "self", ")", ":", "if", "self", ".", "oxm_class", "==", "OxmClass", ".", "OFPXMC_OPENFLOW_BASIC", ":", "return", "OxmOfbMatchField", "(", "self", ".", "oxm_field", ")", ".", "value", "elif", "not", "isinstance", "(", "self", ".", "oxm_field", ",", "int", ")", "or", "self", ".", "oxm_field", ">", "127", ":", "raise", "ValueError", "(", "'oxm_field above 127: \"{self.oxm_field}\".'", ")", "return", "self", ".", "oxm_field" ]
Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and the enum has no such value.
[ "Return", "a", "valid", "integer", "value", "for", "oxm_field", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L283-L301
3,216
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.pack
def pack(self, value=None): """Pack and complete the last byte by padding.""" if isinstance(value, Match): return value.pack() elif value is None: self._update_match_length() packet = super().pack() return self._complete_last_byte(packet) raise PackException(f'Match can\'t unpack "{value}".')
python
def pack(self, value=None): if isinstance(value, Match): return value.pack() elif value is None: self._update_match_length() packet = super().pack() return self._complete_last_byte(packet) raise PackException(f'Match can\'t unpack "{value}".')
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "Match", ")", ":", "return", "value", ".", "pack", "(", ")", "elif", "value", "is", "None", ":", "self", ".", "_update_match_length", "(", ")", "packet", "=", "super", "(", ")", ".", "pack", "(", ")", "return", "self", ".", "_complete_last_byte", "(", "packet", ")", "raise", "PackException", "(", "f'Match can\\'t unpack \"{value}\".'", ")" ]
Pack and complete the last byte by padding.
[ "Pack", "and", "complete", "the", "last", "byte", "by", "padding", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L360-L368
3,217
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.unpack
def unpack(self, buff, offset=0): """Discard padding bytes using the unpacked length attribute.""" begin = offset for name, value in list(self.get_class_attributes())[:-1]: size = self._unpack_attribute(name, value, buff, begin) begin += size self._unpack_attribute('oxm_match_fields', type(self).oxm_match_fields, buff[:offset+self.length], begin)
python
def unpack(self, buff, offset=0): begin = offset for name, value in list(self.get_class_attributes())[:-1]: size = self._unpack_attribute(name, value, buff, begin) begin += size self._unpack_attribute('oxm_match_fields', type(self).oxm_match_fields, buff[:offset+self.length], begin)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "begin", "=", "offset", "for", "name", ",", "value", "in", "list", "(", "self", ".", "get_class_attributes", "(", ")", ")", "[", ":", "-", "1", "]", ":", "size", "=", "self", ".", "_unpack_attribute", "(", "name", ",", "value", ",", "buff", ",", "begin", ")", "begin", "+=", "size", "self", ".", "_unpack_attribute", "(", "'oxm_match_fields'", ",", "type", "(", "self", ")", ".", "oxm_match_fields", ",", "buff", "[", ":", "offset", "+", "self", ".", "length", "]", ",", "begin", ")" ]
Discard padding bytes using the unpacked length attribute.
[ "Discard", "padding", "bytes", "using", "the", "unpacked", "length", "attribute", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L387-L394
3,218
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.get_field
def get_field(self, field_type): """Return the value for the 'field_type' field in oxm_match_fields. Args: field_type (~pyof.v0x04.common.flow_match.OxmOfbMatchField, ~pyof.v0x04.common.flow_match.OxmMatchFields): The type of the OXM field you want the value. Returns: The integer number of the 'field_type' if it exists. Otherwise return None. """ for field in self.oxm_match_fields: if field.oxm_field == field_type: return field.oxm_value return None
python
def get_field(self, field_type): for field in self.oxm_match_fields: if field.oxm_field == field_type: return field.oxm_value return None
[ "def", "get_field", "(", "self", ",", "field_type", ")", ":", "for", "field", "in", "self", ".", "oxm_match_fields", ":", "if", "field", ".", "oxm_field", "==", "field_type", ":", "return", "field", ".", "oxm_value", "return", "None" ]
Return the value for the 'field_type' field in oxm_match_fields. Args: field_type (~pyof.v0x04.common.flow_match.OxmOfbMatchField, ~pyof.v0x04.common.flow_match.OxmMatchFields): The type of the OXM field you want the value. Returns: The integer number of the 'field_type' if it exists. Otherwise return None.
[ "Return", "the", "value", "for", "the", "field_type", "field", "in", "oxm_match_fields", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L396-L413
3,219
kytos/python-openflow
pyof/foundation/base.py
GenericType.value
def value(self): """Return this type's value. Returns: object: The value of an enum, bitmask, etc. """ if self.isenum(): if isinstance(self._value, self.enum_ref): return self._value.value return self._value elif self.is_bitmask(): return self._value.bitmask else: return self._value
python
def value(self): if self.isenum(): if isinstance(self._value, self.enum_ref): return self._value.value return self._value elif self.is_bitmask(): return self._value.bitmask else: return self._value
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "isenum", "(", ")", ":", "if", "isinstance", "(", "self", ".", "_value", ",", "self", ".", "enum_ref", ")", ":", "return", "self", ".", "_value", ".", "value", "return", "self", ".", "_value", "elif", "self", ".", "is_bitmask", "(", ")", ":", "return", "self", ".", "_value", ".", "bitmask", "else", ":", "return", "self", ".", "_value" ]
Return this type's value. Returns: object: The value of an enum, bitmask, etc.
[ "Return", "this", "type", "s", "value", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L133-L147
3,220
kytos/python-openflow
pyof/foundation/base.py
GenericType.pack
def pack(self, value=None): r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() b'\x01' >>> objectA.pack(objectB) b'\x05' Args: value: If the value is None, then we will pack the value of the current instance. Otherwise, if value is an instance of the same type as the current instance, then we call the pack of the value object. Otherwise, we will use the current instance pack method on the passed value. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.BadValueException`: If the value does not fit the binary format. """ if isinstance(value, type(self)): return value.pack() if value is None: value = self.value elif 'value' in dir(value): # if it is enum or bitmask gets only the 'int' value value = value.value try: return struct.pack(self._fmt, value) except struct.error: expected_type = type(self).__name__ actual_type = type(value).__name__ msg_args = expected_type, value, actual_type msg = 'Expected {}, found value "{}" of type {}'.format(*msg_args) raise PackException(msg)
python
def pack(self, value=None): r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() b'\x01' >>> objectA.pack(objectB) b'\x05' Args: value: If the value is None, then we will pack the value of the current instance. Otherwise, if value is an instance of the same type as the current instance, then we call the pack of the value object. Otherwise, we will use the current instance pack method on the passed value. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.BadValueException`: If the value does not fit the binary format. """ if isinstance(value, type(self)): return value.pack() if value is None: value = self.value elif 'value' in dir(value): # if it is enum or bitmask gets only the 'int' value value = value.value try: return struct.pack(self._fmt, value) except struct.error: expected_type = type(self).__name__ actual_type = type(value).__name__ msg_args = expected_type, value, actual_type msg = 'Expected {}, found value "{}" of type {}'.format(*msg_args) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "pack", "(", ")", "if", "value", "is", "None", ":", "value", "=", "self", ".", "value", "elif", "'value'", "in", "dir", "(", "value", ")", ":", "# if it is enum or bitmask gets only the 'int' value", "value", "=", "value", ".", "value", "try", ":", "return", "struct", ".", "pack", "(", "self", ".", "_fmt", ",", "value", ")", "except", "struct", ".", "error", ":", "expected_type", "=", "type", "(", "self", ")", ".", "__name__", "actual_type", "=", "type", "(", "value", ")", ".", "__name__", "msg_args", "=", "expected_type", ",", "value", ",", "actual_type", "msg", "=", "'Expected {}, found value \"{}\" of type {}'", ".", "format", "(", "*", "msg_args", ")", "raise", "PackException", "(", "msg", ")" ]
r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() b'\x01' >>> objectA.pack(objectB) b'\x05' Args: value: If the value is None, then we will pack the value of the current instance. Otherwise, if value is an instance of the same type as the current instance, then we call the pack of the value object. Otherwise, we will use the current instance pack method on the passed value. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.BadValueException`: If the value does not fit the binary format.
[ "r", "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L149-L194
3,221
kytos/python-openflow
pyof/foundation/base.py
MetaStruct._header_message_type_update
def _header_message_type_update(obj, attr): """Update the message type on the header. Set the message_type of the header according to the message_type of the parent class. """ old_enum = obj.message_type new_header = attr[1] new_enum = new_header.__class__.message_type.enum_ref #: This 'if' will be removed on the future with an #: improved version of __init_subclass__ method of the #: GenericMessage class if old_enum: msg_type_name = old_enum.name new_type = new_enum[msg_type_name] new_header.message_type = new_type return (attr[0], new_header)
python
def _header_message_type_update(obj, attr): old_enum = obj.message_type new_header = attr[1] new_enum = new_header.__class__.message_type.enum_ref #: This 'if' will be removed on the future with an #: improved version of __init_subclass__ method of the #: GenericMessage class if old_enum: msg_type_name = old_enum.name new_type = new_enum[msg_type_name] new_header.message_type = new_type return (attr[0], new_header)
[ "def", "_header_message_type_update", "(", "obj", ",", "attr", ")", ":", "old_enum", "=", "obj", ".", "message_type", "new_header", "=", "attr", "[", "1", "]", "new_enum", "=", "new_header", ".", "__class__", ".", "message_type", ".", "enum_ref", "#: This 'if' will be removed on the future with an", "#: improved version of __init_subclass__ method of the", "#: GenericMessage class", "if", "old_enum", ":", "msg_type_name", "=", "old_enum", ".", "name", "new_type", "=", "new_enum", "[", "msg_type_name", "]", "new_header", ".", "message_type", "=", "new_type", "return", "(", "attr", "[", "0", "]", ",", "new_header", ")" ]
Update the message type on the header. Set the message_type of the header according to the message_type of the parent class.
[ "Update", "the", "message", "type", "on", "the", "header", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L347-L363
3,222
kytos/python-openflow
pyof/foundation/base.py
MetaStruct.get_pyof_version
def get_pyof_version(module_fullname): """Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow version, on the format 'v0x0?' if any. Or None if there isn't a version on the fullname. """ ver_module_re = re.compile(r'(pyof\.)(v0x\d+)(\..*)') matched = ver_module_re.match(module_fullname) if matched: version = matched.group(2) return version return None
python
def get_pyof_version(module_fullname): ver_module_re = re.compile(r'(pyof\.)(v0x\d+)(\..*)') matched = ver_module_re.match(module_fullname) if matched: version = matched.group(2) return version return None
[ "def", "get_pyof_version", "(", "module_fullname", ")", ":", "ver_module_re", "=", "re", ".", "compile", "(", "r'(pyof\\.)(v0x\\d+)(\\..*)'", ")", "matched", "=", "ver_module_re", ".", "match", "(", "module_fullname", ")", "if", "matched", ":", "version", "=", "matched", ".", "group", "(", "2", ")", "return", "version", "return", "None" ]
Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow version, on the format 'v0x0?' if any. Or None if there isn't a version on the fullname.
[ "Get", "the", "module", "pyof", "version", "based", "on", "the", "module", "fullname", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L366-L384
3,223
kytos/python-openflow
pyof/foundation/base.py
MetaStruct.replace_pyof_version
def replace_pyof_version(module_fullname, version): """Replace the OF Version of a module fullname. Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on a new 'version' (eg. 'pyof.v0x02.common.header'). Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) version (str): The version to be 'inserted' on the module fullname. Returns: str: module fullname The new module fullname, with the replaced version, on the format "pyof.v0x01.common.header". If the requested version is the same as the one of the module_fullname or if the module_fullname is not a 'OF version' specific module, returns None. """ module_version = MetaStruct.get_pyof_version(module_fullname) if not module_version or module_version == version: return None return module_fullname.replace(module_version, version)
python
def replace_pyof_version(module_fullname, version): module_version = MetaStruct.get_pyof_version(module_fullname) if not module_version or module_version == version: return None return module_fullname.replace(module_version, version)
[ "def", "replace_pyof_version", "(", "module_fullname", ",", "version", ")", ":", "module_version", "=", "MetaStruct", ".", "get_pyof_version", "(", "module_fullname", ")", "if", "not", "module_version", "or", "module_version", "==", "version", ":", "return", "None", "return", "module_fullname", ".", "replace", "(", "module_version", ",", "version", ")" ]
Replace the OF Version of a module fullname. Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on a new 'version' (eg. 'pyof.v0x02.common.header'). Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) version (str): The version to be 'inserted' on the module fullname. Returns: str: module fullname The new module fullname, with the replaced version, on the format "pyof.v0x01.common.header". If the requested version is the same as the one of the module_fullname or if the module_fullname is not a 'OF version' specific module, returns None.
[ "Replace", "the", "OF", "Version", "of", "a", "module", "fullname", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L387-L411
3,224
kytos/python-openflow
pyof/foundation/base.py
MetaStruct.get_pyof_obj_new_version
def get_pyof_obj_new_version(name, obj, new_version): r"""Return a class attribute on a different pyof version. This method receives the name of a class attribute, the class attribute itself (object) and an openflow version. The attribute will be evaluated and from it we will recover its class and the module where the class was defined. If the module is a "python-openflow version specific module" (starts with "pyof.v0"), then we will get it's version and if it is different from the 'new_version', then we will get the module on the 'new_version', look for the 'obj' class on the new module and return an instance of the new version of the 'obj'. Example: >>> from pyof.foundation.base import MetaStruct as ms >>> from pyof.v0x01.common.header import Header >>> name = 'header' >>> obj = Header() >>> new_version = 'v0x04' >>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version) >>> header 'header' >>> obj.version UBInt8(1) >>> obj2.version UBInt8(4) Args: name (str): the name of the class attribute being handled. obj (object): the class attribute itself new_version (string): the pyof version in which you want the object 'obj'. Return: (str, obj): Tuple with class name and object instance. A tuple in which the first item is the name of the class attribute (the same that was passed), and the second item is a instance of the passed class attribute. If the class attribute is not a pyof versioned attribute, then the same passed object is returned without any changes. Also, if the obj is a pyof versioned attribute, but it is already on the right version (same as new_version), then the passed obj is return. """ if new_version is None: return (name, obj) cls = obj.__class__ cls_name = cls.__name__ cls_mod = cls.__module__ #: If the module name does not starts with pyof.v0 then it is not a #: 'pyof versioned' module (OpenFlow specification defined), so we do #: not have anything to do with it. new_mod = MetaStruct.replace_pyof_version(cls_mod, new_version) if new_mod is not None: # Loads the module new_mod = importlib.import_module(new_mod) #: Get the class from the loaded module new_cls = getattr(new_mod, cls_name) #: return the tuple with the attribute name and the instance return (name, new_cls()) return (name, obj)
python
def get_pyof_obj_new_version(name, obj, new_version): r"""Return a class attribute on a different pyof version. This method receives the name of a class attribute, the class attribute itself (object) and an openflow version. The attribute will be evaluated and from it we will recover its class and the module where the class was defined. If the module is a "python-openflow version specific module" (starts with "pyof.v0"), then we will get it's version and if it is different from the 'new_version', then we will get the module on the 'new_version', look for the 'obj' class on the new module and return an instance of the new version of the 'obj'. Example: >>> from pyof.foundation.base import MetaStruct as ms >>> from pyof.v0x01.common.header import Header >>> name = 'header' >>> obj = Header() >>> new_version = 'v0x04' >>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version) >>> header 'header' >>> obj.version UBInt8(1) >>> obj2.version UBInt8(4) Args: name (str): the name of the class attribute being handled. obj (object): the class attribute itself new_version (string): the pyof version in which you want the object 'obj'. Return: (str, obj): Tuple with class name and object instance. A tuple in which the first item is the name of the class attribute (the same that was passed), and the second item is a instance of the passed class attribute. If the class attribute is not a pyof versioned attribute, then the same passed object is returned without any changes. Also, if the obj is a pyof versioned attribute, but it is already on the right version (same as new_version), then the passed obj is return. """ if new_version is None: return (name, obj) cls = obj.__class__ cls_name = cls.__name__ cls_mod = cls.__module__ #: If the module name does not starts with pyof.v0 then it is not a #: 'pyof versioned' module (OpenFlow specification defined), so we do #: not have anything to do with it. new_mod = MetaStruct.replace_pyof_version(cls_mod, new_version) if new_mod is not None: # Loads the module new_mod = importlib.import_module(new_mod) #: Get the class from the loaded module new_cls = getattr(new_mod, cls_name) #: return the tuple with the attribute name and the instance return (name, new_cls()) return (name, obj)
[ "def", "get_pyof_obj_new_version", "(", "name", ",", "obj", ",", "new_version", ")", ":", "if", "new_version", "is", "None", ":", "return", "(", "name", ",", "obj", ")", "cls", "=", "obj", ".", "__class__", "cls_name", "=", "cls", ".", "__name__", "cls_mod", "=", "cls", ".", "__module__", "#: If the module name does not starts with pyof.v0 then it is not a", "#: 'pyof versioned' module (OpenFlow specification defined), so we do", "#: not have anything to do with it.", "new_mod", "=", "MetaStruct", ".", "replace_pyof_version", "(", "cls_mod", ",", "new_version", ")", "if", "new_mod", "is", "not", "None", ":", "# Loads the module", "new_mod", "=", "importlib", ".", "import_module", "(", "new_mod", ")", "#: Get the class from the loaded module", "new_cls", "=", "getattr", "(", "new_mod", ",", "cls_name", ")", "#: return the tuple with the attribute name and the instance", "return", "(", "name", ",", "new_cls", "(", ")", ")", "return", "(", "name", ",", "obj", ")" ]
r"""Return a class attribute on a different pyof version. This method receives the name of a class attribute, the class attribute itself (object) and an openflow version. The attribute will be evaluated and from it we will recover its class and the module where the class was defined. If the module is a "python-openflow version specific module" (starts with "pyof.v0"), then we will get it's version and if it is different from the 'new_version', then we will get the module on the 'new_version', look for the 'obj' class on the new module and return an instance of the new version of the 'obj'. Example: >>> from pyof.foundation.base import MetaStruct as ms >>> from pyof.v0x01.common.header import Header >>> name = 'header' >>> obj = Header() >>> new_version = 'v0x04' >>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version) >>> header 'header' >>> obj.version UBInt8(1) >>> obj2.version UBInt8(4) Args: name (str): the name of the class attribute being handled. obj (object): the class attribute itself new_version (string): the pyof version in which you want the object 'obj'. Return: (str, obj): Tuple with class name and object instance. A tuple in which the first item is the name of the class attribute (the same that was passed), and the second item is a instance of the passed class attribute. If the class attribute is not a pyof versioned attribute, then the same passed object is returned without any changes. Also, if the obj is a pyof versioned attribute, but it is already on the right version (same as new_version), then the passed obj is return.
[ "r", "Return", "a", "class", "attribute", "on", "a", "different", "pyof", "version", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L414-L478
3,225
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._validate_attributes_type
def _validate_attributes_type(self): """Validate the type of each attribute.""" for _attr, _class in self._get_attributes(): if isinstance(_attr, _class): return True elif issubclass(_class, GenericType): if GenericStruct._attr_fits_into_class(_attr, _class): return True elif not isinstance(_attr, _class): return False return True
python
def _validate_attributes_type(self): for _attr, _class in self._get_attributes(): if isinstance(_attr, _class): return True elif issubclass(_class, GenericType): if GenericStruct._attr_fits_into_class(_attr, _class): return True elif not isinstance(_attr, _class): return False return True
[ "def", "_validate_attributes_type", "(", "self", ")", ":", "for", "_attr", ",", "_class", "in", "self", ".", "_get_attributes", "(", ")", ":", "if", "isinstance", "(", "_attr", ",", "_class", ")", ":", "return", "True", "elif", "issubclass", "(", "_class", ",", "GenericType", ")", ":", "if", "GenericStruct", ".", "_attr_fits_into_class", "(", "_attr", ",", "_class", ")", ":", "return", "True", "elif", "not", "isinstance", "(", "_attr", ",", "_class", ")", ":", "return", "False", "return", "True" ]
Validate the type of each attribute.
[ "Validate", "the", "type", "of", "each", "attribute", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L534-L544
3,226
kytos/python-openflow
pyof/foundation/base.py
GenericStruct.get_class_attributes
def get_class_attributes(cls): """Return a generator for class attributes' names and value. This method strict relies on the PEP 520 (Preserving Class Attribute Definition Order), implemented on Python 3.6. So, if this behaviour changes this whole lib can loose its functionality (since the attributes order are a strong requirement.) For the same reason, this lib will not work on python versions earlier than 3.6. .. code-block:: python3 for name, value in self.get_class_attributes(): print("attribute name: {}".format(name)) print("attribute type: {}".format(value)) Returns: generator: tuples with attribute name and value. """ #: see this method docstring for a important notice about the use of #: cls.__dict__ for name, value in cls.__dict__.items(): # gets only our (kytos) attributes. this ignores methods, dunder # methods and attributes, and common python type attributes. if GenericStruct._is_pyof_attribute(value): yield (name, value)
python
def get_class_attributes(cls): #: see this method docstring for a important notice about the use of #: cls.__dict__ for name, value in cls.__dict__.items(): # gets only our (kytos) attributes. this ignores methods, dunder # methods and attributes, and common python type attributes. if GenericStruct._is_pyof_attribute(value): yield (name, value)
[ "def", "get_class_attributes", "(", "cls", ")", ":", "#: see this method docstring for a important notice about the use of", "#: cls.__dict__", "for", "name", ",", "value", "in", "cls", ".", "__dict__", ".", "items", "(", ")", ":", "# gets only our (kytos) attributes. this ignores methods, dunder", "# methods and attributes, and common python type attributes.", "if", "GenericStruct", ".", "_is_pyof_attribute", "(", "value", ")", ":", "yield", "(", "name", ",", "value", ")" ]
Return a generator for class attributes' names and value. This method strict relies on the PEP 520 (Preserving Class Attribute Definition Order), implemented on Python 3.6. So, if this behaviour changes this whole lib can loose its functionality (since the attributes order are a strong requirement.) For the same reason, this lib will not work on python versions earlier than 3.6. .. code-block:: python3 for name, value in self.get_class_attributes(): print("attribute name: {}".format(name)) print("attribute type: {}".format(value)) Returns: generator: tuples with attribute name and value.
[ "Return", "a", "generator", "for", "class", "attributes", "names", "and", "value", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L547-L572
3,227
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._get_instance_attributes
def _get_instance_attributes(self): """Return a generator for instance attributes' name and value. .. code-block:: python3 for _name, _value in self._get_instance_attributes(): print("attribute name: {}".format(_name)) print("attribute value: {}".format(_value)) Returns: generator: tuples with attribute name and value. """ for name, value in self.__dict__.items(): if name in map((lambda x: x[0]), self.get_class_attributes()): yield (name, value)
python
def _get_instance_attributes(self): for name, value in self.__dict__.items(): if name in map((lambda x: x[0]), self.get_class_attributes()): yield (name, value)
[ "def", "_get_instance_attributes", "(", "self", ")", ":", "for", "name", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "name", "in", "map", "(", "(", "lambda", "x", ":", "x", "[", "0", "]", ")", ",", "self", ".", "get_class_attributes", "(", ")", ")", ":", "yield", "(", "name", ",", "value", ")" ]
Return a generator for instance attributes' name and value. .. code-block:: python3 for _name, _value in self._get_instance_attributes(): print("attribute name: {}".format(_name)) print("attribute value: {}".format(_value)) Returns: generator: tuples with attribute name and value.
[ "Return", "a", "generator", "for", "instance", "attributes", "name", "and", "value", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L574-L589
3,228
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._get_attributes
def _get_attributes(self): """Return a generator for instance and class attribute. .. code-block:: python3 for instance_attribute, class_attribute in self._get_attributes(): print("Instance Attribute: {}".format(instance_attribute)) print("Class Attribute: {}".format(class_attribute)) Returns: generator: Tuples with instance attribute and class attribute """ return map((lambda i, c: (i[1], c[1])), self._get_instance_attributes(), self.get_class_attributes())
python
def _get_attributes(self): return map((lambda i, c: (i[1], c[1])), self._get_instance_attributes(), self.get_class_attributes())
[ "def", "_get_attributes", "(", "self", ")", ":", "return", "map", "(", "(", "lambda", "i", ",", "c", ":", "(", "i", "[", "1", "]", ",", "c", "[", "1", "]", ")", ")", ",", "self", ".", "_get_instance_attributes", "(", ")", ",", "self", ".", "get_class_attributes", "(", ")", ")" ]
Return a generator for instance and class attribute. .. code-block:: python3 for instance_attribute, class_attribute in self._get_attributes(): print("Instance Attribute: {}".format(instance_attribute)) print("Class Attribute: {}".format(class_attribute)) Returns: generator: Tuples with instance attribute and class attribute
[ "Return", "a", "generator", "for", "instance", "and", "class", "attribute", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L591-L606
3,229
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._get_named_attributes
def _get_named_attributes(self): """Return generator for attribute's name, instance and class values. Add attribute name to meth:`_get_attributes` for a better debugging message, so user can find the error easier. Returns: generator: Tuple with attribute's name, instance and class values. """ for cls, instance in zip(self.get_class_attributes(), self._get_instance_attributes()): attr_name, cls_value = cls instance_value = instance[1] yield attr_name, instance_value, cls_value
python
def _get_named_attributes(self): for cls, instance in zip(self.get_class_attributes(), self._get_instance_attributes()): attr_name, cls_value = cls instance_value = instance[1] yield attr_name, instance_value, cls_value
[ "def", "_get_named_attributes", "(", "self", ")", ":", "for", "cls", ",", "instance", "in", "zip", "(", "self", ".", "get_class_attributes", "(", ")", ",", "self", ".", "_get_instance_attributes", "(", ")", ")", ":", "attr_name", ",", "cls_value", "=", "cls", "instance_value", "=", "instance", "[", "1", "]", "yield", "attr_name", ",", "instance_value", ",", "cls_value" ]
Return generator for attribute's name, instance and class values. Add attribute name to meth:`_get_attributes` for a better debugging message, so user can find the error easier. Returns: generator: Tuple with attribute's name, instance and class values.
[ "Return", "generator", "for", "attribute", "s", "name", "instance", "and", "class", "values", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L608-L622
3,230
kytos/python-openflow
pyof/foundation/base.py
GenericStruct.get_size
def get_size(self, value=None): """Calculate the total struct size in bytes. For each struct attribute, sum the result of each one's ``get_size()`` method. Args: value: In structs, the user can assign other value instead of a class' instance. Returns: int: Total number of bytes used by the struct. Raises: Exception: If the struct is not valid. """ if value is None: return sum(cls_val.get_size(obj_val) for obj_val, cls_val in self._get_attributes()) elif isinstance(value, type(self)): return value.get_size() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
python
def get_size(self, value=None): if value is None: return sum(cls_val.get_size(obj_val) for obj_val, cls_val in self._get_attributes()) elif isinstance(value, type(self)): return value.get_size() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
[ "def", "get_size", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "sum", "(", "cls_val", ".", "get_size", "(", "obj_val", ")", "for", "obj_val", ",", "cls_val", "in", "self", ".", "_get_attributes", "(", ")", ")", "elif", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "get_size", "(", ")", "else", ":", "msg", "=", "\"{} is not an instance of {}\"", ".", "format", "(", "value", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
Calculate the total struct size in bytes. For each struct attribute, sum the result of each one's ``get_size()`` method. Args: value: In structs, the user can assign other value instead of a class' instance. Returns: int: Total number of bytes used by the struct. Raises: Exception: If the struct is not valid.
[ "Calculate", "the", "total", "struct", "size", "in", "bytes", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L639-L664
3,231
kytos/python-openflow
pyof/foundation/base.py
GenericMessage.pack
def pack(self, value=None): """Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a switch, here we also call :meth:`update_header_length`. .. seealso:: This method call its parent's :meth:`GenericStruct.pack` after :meth:`update_header_length`. Returns: bytes: A binary data thats represents the Message. Raises: Exception: If there are validation errors. """ if value is None: self.update_header_length() return super().pack() elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
python
def pack(self, value=None): if value is None: self.update_header_length() return super().pack() elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "self", ".", "update_header_length", "(", ")", "return", "super", "(", ")", ".", "pack", "(", ")", "elif", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "pack", "(", ")", "else", ":", "msg", "=", "\"{} is not an instance of {}\"", ".", "format", "(", "value", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a switch, here we also call :meth:`update_header_length`. .. seealso:: This method call its parent's :meth:`GenericStruct.pack` after :meth:`update_header_length`. Returns: bytes: A binary data thats represents the Message. Raises: Exception: If there are validation errors.
[ "Pack", "the", "message", "into", "a", "binary", "data", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L784-L812
3,232
kytos/python-openflow
pyof/foundation/base.py
GenericBitMask.names
def names(self): """List of selected enum names. Returns: list: Enum names. """ result = [] for key, value in self.iteritems(): if value & self.bitmask: result.append(key) return result
python
def names(self): result = [] for key, value in self.iteritems(): if value & self.bitmask: result.append(key) return result
[ "def", "names", "(", "self", ")", ":", "result", "=", "[", "]", "for", "key", ",", "value", "in", "self", ".", "iteritems", "(", ")", ":", "if", "value", "&", "self", ".", "bitmask", ":", "result", ".", "append", "(", "key", ")", "return", "result" ]
List of selected enum names. Returns: list: Enum names.
[ "List", "of", "selected", "enum", "names", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L895-L906
3,233
kytos/python-openflow
pyof/v0x01/common/flow_match.py
Match.fill_wildcards
def fill_wildcards(self, field=None, value=0): """Update wildcards attribute. This method update a wildcards considering the attributes of the current instance. Args: field (str): Name of the updated field. value (GenericType): New value used in the field. """ if field in [None, 'wildcards'] or isinstance(value, Pad): return default_value = getattr(Match, field) if isinstance(default_value, IPAddress): if field == 'nw_dst': shift = FlowWildCards.OFPFW_NW_DST_SHIFT base_mask = FlowWildCards.OFPFW_NW_DST_MASK else: shift = FlowWildCards.OFPFW_NW_SRC_SHIFT base_mask = FlowWildCards.OFPFW_NW_SRC_MASK # First we clear the nw_dst/nw_src mask related bits on the current # wildcard by setting 0 on all of them while we keep all other bits # as they are. self.wildcards &= FlowWildCards.OFPFW_ALL ^ base_mask # nw_dst and nw_src wildcard fields have 6 bits each. # "base_mask" is the 'all ones' for those 6 bits. # Once we know the netmask, we can calculate the these 6 bits # wildcard value and reverse them in order to insert them at the # correct position in self.wildcards wildcard = (value.max_prefix - value.netmask) << shift self.wildcards |= wildcard else: wildcard_field = "OFPFW_{}".format(field.upper()) wildcard = getattr(FlowWildCards, wildcard_field) if value == default_value and not (self.wildcards & wildcard) or \ value != default_value and (self.wildcards & wildcard): self.wildcards ^= wildcard
python
def fill_wildcards(self, field=None, value=0): if field in [None, 'wildcards'] or isinstance(value, Pad): return default_value = getattr(Match, field) if isinstance(default_value, IPAddress): if field == 'nw_dst': shift = FlowWildCards.OFPFW_NW_DST_SHIFT base_mask = FlowWildCards.OFPFW_NW_DST_MASK else: shift = FlowWildCards.OFPFW_NW_SRC_SHIFT base_mask = FlowWildCards.OFPFW_NW_SRC_MASK # First we clear the nw_dst/nw_src mask related bits on the current # wildcard by setting 0 on all of them while we keep all other bits # as they are. self.wildcards &= FlowWildCards.OFPFW_ALL ^ base_mask # nw_dst and nw_src wildcard fields have 6 bits each. # "base_mask" is the 'all ones' for those 6 bits. # Once we know the netmask, we can calculate the these 6 bits # wildcard value and reverse them in order to insert them at the # correct position in self.wildcards wildcard = (value.max_prefix - value.netmask) << shift self.wildcards |= wildcard else: wildcard_field = "OFPFW_{}".format(field.upper()) wildcard = getattr(FlowWildCards, wildcard_field) if value == default_value and not (self.wildcards & wildcard) or \ value != default_value and (self.wildcards & wildcard): self.wildcards ^= wildcard
[ "def", "fill_wildcards", "(", "self", ",", "field", "=", "None", ",", "value", "=", "0", ")", ":", "if", "field", "in", "[", "None", ",", "'wildcards'", "]", "or", "isinstance", "(", "value", ",", "Pad", ")", ":", "return", "default_value", "=", "getattr", "(", "Match", ",", "field", ")", "if", "isinstance", "(", "default_value", ",", "IPAddress", ")", ":", "if", "field", "==", "'nw_dst'", ":", "shift", "=", "FlowWildCards", ".", "OFPFW_NW_DST_SHIFT", "base_mask", "=", "FlowWildCards", ".", "OFPFW_NW_DST_MASK", "else", ":", "shift", "=", "FlowWildCards", ".", "OFPFW_NW_SRC_SHIFT", "base_mask", "=", "FlowWildCards", ".", "OFPFW_NW_SRC_MASK", "# First we clear the nw_dst/nw_src mask related bits on the current", "# wildcard by setting 0 on all of them while we keep all other bits", "# as they are.", "self", ".", "wildcards", "&=", "FlowWildCards", ".", "OFPFW_ALL", "^", "base_mask", "# nw_dst and nw_src wildcard fields have 6 bits each.", "# \"base_mask\" is the 'all ones' for those 6 bits.", "# Once we know the netmask, we can calculate the these 6 bits", "# wildcard value and reverse them in order to insert them at the", "# correct position in self.wildcards", "wildcard", "=", "(", "value", ".", "max_prefix", "-", "value", ".", "netmask", ")", "<<", "shift", "self", ".", "wildcards", "|=", "wildcard", "else", ":", "wildcard_field", "=", "\"OFPFW_{}\"", ".", "format", "(", "field", ".", "upper", "(", ")", ")", "wildcard", "=", "getattr", "(", "FlowWildCards", ",", "wildcard_field", ")", "if", "value", "==", "default_value", "and", "not", "(", "self", ".", "wildcards", "&", "wildcard", ")", "or", "value", "!=", "default_value", "and", "(", "self", ".", "wildcards", "&", "wildcard", ")", ":", "self", ".", "wildcards", "^=", "wildcard" ]
Update wildcards attribute. This method update a wildcards considering the attributes of the current instance. Args: field (str): Name of the updated field. value (GenericType): New value used in the field.
[ "Update", "wildcards", "attribute", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/flow_match.py#L163-L203
3,234
kytos/python-openflow
pyof/v0x04/common/action.py
ActionSetField.pack
def pack(self, value=None): """Pack this structure updating the length and padding it.""" self._update_length() packet = super().pack() return self._complete_last_byte(packet)
python
def pack(self, value=None): self._update_length() packet = super().pack() return self._complete_last_byte(packet)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "self", ".", "_update_length", "(", ")", "packet", "=", "super", "(", ")", ".", "pack", "(", ")", "return", "self", ".", "_complete_last_byte", "(", "packet", ")" ]
Pack this structure updating the length and padding it.
[ "Pack", "this", "structure", "updating", "the", "length", "and", "padding", "it", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/action.py#L384-L388
3,235
kytos/python-openflow
pyof/v0x04/common/action.py
ActionSetField._update_length
def _update_length(self): """Update the length field of the struct.""" action_length = 4 + len(self.field.pack()) overflow = action_length % 8 self.length = action_length if overflow: self.length = action_length + 8 - overflow
python
def _update_length(self): action_length = 4 + len(self.field.pack()) overflow = action_length % 8 self.length = action_length if overflow: self.length = action_length + 8 - overflow
[ "def", "_update_length", "(", "self", ")", ":", "action_length", "=", "4", "+", "len", "(", "self", ".", "field", ".", "pack", "(", ")", ")", "overflow", "=", "action_length", "%", "8", "self", ".", "length", "=", "action_length", "if", "overflow", ":", "self", ".", "length", "=", "action_length", "+", "8", "-", "overflow" ]
Update the length field of the struct.
[ "Update", "the", "length", "field", "of", "the", "struct", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/action.py#L390-L396
3,236
kytos/python-openflow
pyof/foundation/network_types.py
VLAN._validate
def _validate(self): """Assure this is a valid VLAN header instance.""" if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
python
def _validate(self): if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
[ "def", "_validate", "(", "self", ")", ":", "if", "self", ".", "tpid", ".", "value", "not", "in", "(", "EtherType", ".", "VLAN", ",", "EtherType", ".", "VLAN_QINQ", ")", ":", "raise", "UnpackException", "return" ]
Assure this is a valid VLAN header instance.
[ "Assure", "this", "is", "a", "valid", "VLAN", "header", "instance", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L187-L191
3,237
kytos/python-openflow
pyof/foundation/network_types.py
Ethernet._get_vlan_length
def _get_vlan_length(buff): """Return the total length of VLAN tags in a given Ethernet buffer.""" length = 0 begin = 12 while(buff[begin:begin+2] in (EtherType.VLAN.to_bytes(2, 'big'), EtherType.VLAN_QINQ.to_bytes(2, 'big'))): length += 4 begin += 4 return length
python
def _get_vlan_length(buff): length = 0 begin = 12 while(buff[begin:begin+2] in (EtherType.VLAN.to_bytes(2, 'big'), EtherType.VLAN_QINQ.to_bytes(2, 'big'))): length += 4 begin += 4 return length
[ "def", "_get_vlan_length", "(", "buff", ")", ":", "length", "=", "0", "begin", "=", "12", "while", "(", "buff", "[", "begin", ":", "begin", "+", "2", "]", "in", "(", "EtherType", ".", "VLAN", ".", "to_bytes", "(", "2", ",", "'big'", ")", ",", "EtherType", ".", "VLAN_QINQ", ".", "to_bytes", "(", "2", ",", "'big'", ")", ")", ")", ":", "length", "+=", "4", "begin", "+=", "4", "return", "length" ]
Return the total length of VLAN tags in a given Ethernet buffer.
[ "Return", "the", "total", "length", "of", "VLAN", "tags", "in", "a", "given", "Ethernet", "buffer", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L294-L304
3,238
kytos/python-openflow
pyof/foundation/network_types.py
GenericTLV.pack
def pack(self, value=None): """Pack the TLV in a binary representation. Returns: bytes: Binary representation of the struct object. Raises: :exc:`~.exceptions.ValidationError`: If validation fails. """ if value is None: output = self.header.pack() output += self.value.pack() return output elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
python
def pack(self, value=None): if value is None: output = self.header.pack() output += self.value.pack() return output elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "output", "=", "self", ".", "header", ".", "pack", "(", ")", "output", "+=", "self", ".", "value", ".", "pack", "(", ")", "return", "output", "elif", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "pack", "(", ")", "else", ":", "msg", "=", "\"{} is not an instance of {}\"", ".", "format", "(", "value", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
Pack the TLV in a binary representation. Returns: bytes: Binary representation of the struct object. Raises: :exc:`~.exceptions.ValidationError`: If validation fails.
[ "Pack", "the", "TLV", "in", "a", "binary", "representation", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L398-L418
3,239
kytos/python-openflow
pyof/foundation/network_types.py
GenericTLV.get_size
def get_size(self, value=None): """Return struct size. Returns: int: Returns the struct size based on inner attributes. """ if isinstance(value, type(self)): return value.get_size() return 2 + self.length
python
def get_size(self, value=None): if isinstance(value, type(self)): return value.get_size() return 2 + self.length
[ "def", "get_size", "(", "self", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "get_size", "(", ")", "return", "2", "+", "self", ".", "length" ]
Return struct size. Returns: int: Returns the struct size based on inner attributes.
[ "Return", "struct", "size", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L441-L451
3,240
kytos/python-openflow
pyof/foundation/network_types.py
IPv4._update_checksum
def _update_checksum(self): """Update the packet checksum to enable integrity check.""" source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8) + source_list[1] source_lower = (source_list[2] << 8) + source_list[3] destination_upper = (destination_list[0] << 8) + destination_list[1] destination_lower = (destination_list[2] << 8) + destination_list[3] block_sum = ((self._version_ihl << 8 | self._dscp_ecn) + self.length + self.identification + self._flags_offset + (self.ttl << 8 | self.protocol) + source_upper + source_lower + destination_upper + destination_lower) while block_sum > 65535: carry = block_sum >> 16 block_sum = (block_sum & 65535) + carry self.checksum = ~block_sum & 65535
python
def _update_checksum(self): source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8) + source_list[1] source_lower = (source_list[2] << 8) + source_list[3] destination_upper = (destination_list[0] << 8) + destination_list[1] destination_lower = (destination_list[2] << 8) + destination_list[3] block_sum = ((self._version_ihl << 8 | self._dscp_ecn) + self.length + self.identification + self._flags_offset + (self.ttl << 8 | self.protocol) + source_upper + source_lower + destination_upper + destination_lower) while block_sum > 65535: carry = block_sum >> 16 block_sum = (block_sum & 65535) + carry self.checksum = ~block_sum & 65535
[ "def", "_update_checksum", "(", "self", ")", ":", "source_list", "=", "[", "int", "(", "octet", ")", "for", "octet", "in", "self", ".", "source", ".", "split", "(", "\".\"", ")", "]", "destination_list", "=", "[", "int", "(", "octet", ")", "for", "octet", "in", "self", ".", "destination", ".", "split", "(", "\".\"", ")", "]", "source_upper", "=", "(", "source_list", "[", "0", "]", "<<", "8", ")", "+", "source_list", "[", "1", "]", "source_lower", "=", "(", "source_list", "[", "2", "]", "<<", "8", ")", "+", "source_list", "[", "3", "]", "destination_upper", "=", "(", "destination_list", "[", "0", "]", "<<", "8", ")", "+", "destination_list", "[", "1", "]", "destination_lower", "=", "(", "destination_list", "[", "2", "]", "<<", "8", ")", "+", "destination_list", "[", "3", "]", "block_sum", "=", "(", "(", "self", ".", "_version_ihl", "<<", "8", "|", "self", ".", "_dscp_ecn", ")", "+", "self", ".", "length", "+", "self", ".", "identification", "+", "self", ".", "_flags_offset", "+", "(", "self", ".", "ttl", "<<", "8", "|", "self", ".", "protocol", ")", "+", "source_upper", "+", "source_lower", "+", "destination_upper", "+", "destination_lower", ")", "while", "block_sum", ">", "65535", ":", "carry", "=", "block_sum", ">>", "16", "block_sum", "=", "(", "block_sum", "&", "65535", ")", "+", "carry", "self", ".", "checksum", "=", "~", "block_sum", "&", "65535" ]
Update the packet checksum to enable integrity check.
[ "Update", "the", "packet", "checksum", "to", "enable", "integrity", "check", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L534-L553
3,241
kytos/python-openflow
pyof/foundation/network_types.py
TLVWithSubType.value
def value(self): """Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated. """ binary = UBInt8(self.sub_type).pack() + self.sub_value.pack() return BinaryData(binary)
python
def value(self): binary = UBInt8(self.sub_type).pack() + self.sub_value.pack() return BinaryData(binary)
[ "def", "value", "(", "self", ")", ":", "binary", "=", "UBInt8", "(", "self", ".", "sub_type", ")", ".", "pack", "(", ")", "+", "self", ".", "sub_value", ".", "pack", "(", ")", "return", "BinaryData", "(", "binary", ")" ]
Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated.
[ "Return", "sub", "type", "and", "sub", "value", "as", "binary", "data", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L640-L649
3,242
kytos/python-openflow
pyof/utils.py
validate_packet
def validate_packet(packet): """Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid. """ if not isinstance(packet, bytes): raise UnpackException('invalid packet') packet_length = len(packet) if packet_length < 8 or packet_length > 2**16: raise UnpackException('invalid packet') if packet_length != int.from_bytes(packet[2:4], byteorder='big'): raise UnpackException('invalid packet') version = packet[0] if version == 0 or version >= 128: raise UnpackException('invalid packet')
python
def validate_packet(packet): if not isinstance(packet, bytes): raise UnpackException('invalid packet') packet_length = len(packet) if packet_length < 8 or packet_length > 2**16: raise UnpackException('invalid packet') if packet_length != int.from_bytes(packet[2:4], byteorder='big'): raise UnpackException('invalid packet') version = packet[0] if version == 0 or version >= 128: raise UnpackException('invalid packet')
[ "def", "validate_packet", "(", "packet", ")", ":", "if", "not", "isinstance", "(", "packet", ",", "bytes", ")", ":", "raise", "UnpackException", "(", "'invalid packet'", ")", "packet_length", "=", "len", "(", "packet", ")", "if", "packet_length", "<", "8", "or", "packet_length", ">", "2", "**", "16", ":", "raise", "UnpackException", "(", "'invalid packet'", ")", "if", "packet_length", "!=", "int", ".", "from_bytes", "(", "packet", "[", "2", ":", "4", "]", ",", "byteorder", "=", "'big'", ")", ":", "raise", "UnpackException", "(", "'invalid packet'", ")", "version", "=", "packet", "[", "0", "]", "if", "version", "==", "0", "or", "version", ">=", "128", ":", "raise", "UnpackException", "(", "'invalid packet'", ")" ]
Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid.
[ "Check", "if", "packet", "is", "valid", "OF", "packet", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/utils.py#L15-L35
3,243
kytos/python-openflow
pyof/utils.py
unpack
def unpack(packet): """Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked. """ validate_packet(packet) version = packet[0] try: pyof_lib = PYOF_VERSION_LIBS[version] except KeyError: raise UnpackException('Version not supported') try: message = pyof_lib.common.utils.unpack_message(packet) return message except (UnpackException, ValueError) as exception: raise UnpackException(exception)
python
def unpack(packet): validate_packet(packet) version = packet[0] try: pyof_lib = PYOF_VERSION_LIBS[version] except KeyError: raise UnpackException('Version not supported') try: message = pyof_lib.common.utils.unpack_message(packet) return message except (UnpackException, ValueError) as exception: raise UnpackException(exception)
[ "def", "unpack", "(", "packet", ")", ":", "validate_packet", "(", "packet", ")", "version", "=", "packet", "[", "0", "]", "try", ":", "pyof_lib", "=", "PYOF_VERSION_LIBS", "[", "version", "]", "except", "KeyError", ":", "raise", "UnpackException", "(", "'Version not supported'", ")", "try", ":", "message", "=", "pyof_lib", ".", "common", ".", "utils", ".", "unpack_message", "(", "packet", ")", "return", "message", "except", "(", "UnpackException", ",", "ValueError", ")", "as", "exception", ":", "raise", "UnpackException", "(", "exception", ")" ]
Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked.
[ "Unpack", "the", "OpenFlow", "Packet", "and", "returns", "a", "message", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/utils.py#L38-L63
3,244
kytos/python-openflow
pyof/v0x04/asynchronous/error_msg.py
ErrorMsg.unpack
def unpack(self, buff, offset=0): """Unpack binary data into python object.""" super().unpack(buff, offset) code_class = ErrorType(self.error_type).get_class() self.code = code_class(self.code)
python
def unpack(self, buff, offset=0): super().unpack(buff, offset) code_class = ErrorType(self.error_type).get_class() self.code = code_class(self.code)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "code_class", "=", "ErrorType", "(", "self", ".", "error_type", ")", ".", "get_class", "(", ")", "self", ".", "code", "=", "code_class", "(", "self", ".", "code", ")" ]
Unpack binary data into python object.
[ "Unpack", "binary", "data", "into", "python", "object", "." ]
4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/asynchronous/error_msg.py#L474-L478
3,245
andreikop/qutepart
qutepart/bookmarks.py
Bookmarks._createAction
def _createAction(self, widget, iconFileName, text, shortcut, slot): """Create QAction with given parameters and add to the widget """ icon = qutepart.getIcon(iconFileName) action = QAction(icon, text, widget) action.setShortcut(QKeySequence(shortcut)) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) widget.addAction(action) return action
python
def _createAction(self, widget, iconFileName, text, shortcut, slot): icon = qutepart.getIcon(iconFileName) action = QAction(icon, text, widget) action.setShortcut(QKeySequence(shortcut)) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) widget.addAction(action) return action
[ "def", "_createAction", "(", "self", ",", "widget", ",", "iconFileName", ",", "text", ",", "shortcut", ",", "slot", ")", ":", "icon", "=", "qutepart", ".", "getIcon", "(", "iconFileName", ")", "action", "=", "QAction", "(", "icon", ",", "text", ",", "widget", ")", "action", ".", "setShortcut", "(", "QKeySequence", "(", "shortcut", ")", ")", "action", ".", "setShortcutContext", "(", "Qt", ".", "WidgetShortcut", ")", "action", ".", "triggered", ".", "connect", "(", "slot", ")", "widget", ".", "addAction", "(", "action", ")", "return", "action" ]
Create QAction with given parameters and add to the widget
[ "Create", "QAction", "with", "given", "parameters", "and", "add", "to", "the", "widget" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/bookmarks.py#L25-L36
3,246
andreikop/qutepart
qutepart/bookmarks.py
Bookmarks.clear
def clear(self, startBlock, endBlock): """Clear bookmarks on block range including start and end """ for block in qutepart.iterateBlocksFrom(startBlock): self._setBlockMarked(block, False) if block == endBlock: break
python
def clear(self, startBlock, endBlock): for block in qutepart.iterateBlocksFrom(startBlock): self._setBlockMarked(block, False) if block == endBlock: break
[ "def", "clear", "(", "self", ",", "startBlock", ",", "endBlock", ")", ":", "for", "block", "in", "qutepart", ".", "iterateBlocksFrom", "(", "startBlock", ")", ":", "self", ".", "_setBlockMarked", "(", "block", ",", "False", ")", "if", "block", "==", "endBlock", ":", "break" ]
Clear bookmarks on block range including start and end
[ "Clear", "bookmarks", "on", "block", "range", "including", "start", "and", "end" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/bookmarks.py#L46-L52
3,247
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._makeMatchSelection
def _makeMatchSelection(self, block, columnIndex, matched): """Make matched or unmatched QTextEdit.ExtraSelection """ selection = QTextEdit.ExtraSelection() if matched: bgColor = Qt.green else: bgColor = Qt.red selection.format.setBackground(bgColor) selection.cursor = QTextCursor(block) selection.cursor.setPosition(block.position() + columnIndex) selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) return selection
python
def _makeMatchSelection(self, block, columnIndex, matched): selection = QTextEdit.ExtraSelection() if matched: bgColor = Qt.green else: bgColor = Qt.red selection.format.setBackground(bgColor) selection.cursor = QTextCursor(block) selection.cursor.setPosition(block.position() + columnIndex) selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) return selection
[ "def", "_makeMatchSelection", "(", "self", ",", "block", ",", "columnIndex", ",", "matched", ")", ":", "selection", "=", "QTextEdit", ".", "ExtraSelection", "(", ")", "if", "matched", ":", "bgColor", "=", "Qt", ".", "green", "else", ":", "bgColor", "=", "Qt", ".", "red", "selection", ".", "format", ".", "setBackground", "(", "bgColor", ")", "selection", ".", "cursor", "=", "QTextCursor", "(", "block", ")", "selection", ".", "cursor", ".", "setPosition", "(", "block", ".", "position", "(", ")", "+", "columnIndex", ")", "selection", ".", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "Right", ",", "QTextCursor", ".", "KeepAnchor", ")", "return", "selection" ]
Make matched or unmatched QTextEdit.ExtraSelection
[ "Make", "matched", "or", "unmatched", "QTextEdit", ".", "ExtraSelection" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L98-L113
3,248
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter._highlightBracket
def _highlightBracket(self, bracket, qpart, block, columnIndex): """Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's """ try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _TimeoutException: # not found, time is over return[] # highlight nothing if matchedBlock is not None: self.currentMatchedBrackets = ((block, columnIndex), (matchedBlock, matchedColumnIndex)) return [self._makeMatchSelection(block, columnIndex, True), self._makeMatchSelection(matchedBlock, matchedColumnIndex, True)] else: self.currentMatchedBrackets = None return [self._makeMatchSelection(block, columnIndex, False)]
python
def _highlightBracket(self, bracket, qpart, block, columnIndex): try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _TimeoutException: # not found, time is over return[] # highlight nothing if matchedBlock is not None: self.currentMatchedBrackets = ((block, columnIndex), (matchedBlock, matchedColumnIndex)) return [self._makeMatchSelection(block, columnIndex, True), self._makeMatchSelection(matchedBlock, matchedColumnIndex, True)] else: self.currentMatchedBrackets = None return [self._makeMatchSelection(block, columnIndex, False)]
[ "def", "_highlightBracket", "(", "self", ",", "bracket", ",", "qpart", ",", "block", ",", "columnIndex", ")", ":", "try", ":", "matchedBlock", ",", "matchedColumnIndex", "=", "self", ".", "_findMatchingBracket", "(", "bracket", ",", "qpart", ",", "block", ",", "columnIndex", ")", "except", "_TimeoutException", ":", "# not found, time is over", "return", "[", "]", "# highlight nothing", "if", "matchedBlock", "is", "not", "None", ":", "self", ".", "currentMatchedBrackets", "=", "(", "(", "block", ",", "columnIndex", ")", ",", "(", "matchedBlock", ",", "matchedColumnIndex", ")", ")", "return", "[", "self", ".", "_makeMatchSelection", "(", "block", ",", "columnIndex", ",", "True", ")", ",", "self", ".", "_makeMatchSelection", "(", "matchedBlock", ",", "matchedColumnIndex", ",", "True", ")", "]", "else", ":", "self", ".", "currentMatchedBrackets", "=", "None", "return", "[", "self", ".", "_makeMatchSelection", "(", "block", ",", "columnIndex", ",", "False", ")", "]" ]
Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's
[ "Highlight", "bracket", "and", "matching", "bracket", "Return", "tuple", "of", "QTextEdit", ".", "ExtraSelection", "s" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L115-L130
3,249
andreikop/qutepart
qutepart/brackethlighter.py
BracketHighlighter.extraSelections
def extraSelections(self, qpart, block, columnIndex): """List of QTextEdit.ExtraSelection's, which highlighte brackets """ blockText = block.text() if columnIndex < len(blockText) and \ blockText[columnIndex] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex): return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex) elif columnIndex > 0 and \ blockText[columnIndex - 1] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex - 1): return self._highlightBracket(blockText[columnIndex - 1], qpart, block, columnIndex - 1) else: self.currentMatchedBrackets = None return []
python
def extraSelections(self, qpart, block, columnIndex): blockText = block.text() if columnIndex < len(blockText) and \ blockText[columnIndex] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex): return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex) elif columnIndex > 0 and \ blockText[columnIndex - 1] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex - 1): return self._highlightBracket(blockText[columnIndex - 1], qpart, block, columnIndex - 1) else: self.currentMatchedBrackets = None return []
[ "def", "extraSelections", "(", "self", ",", "qpart", ",", "block", ",", "columnIndex", ")", ":", "blockText", "=", "block", ".", "text", "(", ")", "if", "columnIndex", "<", "len", "(", "blockText", ")", "and", "blockText", "[", "columnIndex", "]", "in", "self", ".", "_ALL_BRACKETS", "and", "qpart", ".", "isCode", "(", "block", ",", "columnIndex", ")", ":", "return", "self", ".", "_highlightBracket", "(", "blockText", "[", "columnIndex", "]", ",", "qpart", ",", "block", ",", "columnIndex", ")", "elif", "columnIndex", ">", "0", "and", "blockText", "[", "columnIndex", "-", "1", "]", "in", "self", ".", "_ALL_BRACKETS", "and", "qpart", ".", "isCode", "(", "block", ",", "columnIndex", "-", "1", ")", ":", "return", "self", ".", "_highlightBracket", "(", "blockText", "[", "columnIndex", "-", "1", "]", ",", "qpart", ",", "block", ",", "columnIndex", "-", "1", ")", "else", ":", "self", ".", "currentMatchedBrackets", "=", "None", "return", "[", "]" ]
List of QTextEdit.ExtraSelection's, which highlighte brackets
[ "List", "of", "QTextEdit", ".", "ExtraSelection", "s", "which", "highlighte", "brackets" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/brackethlighter.py#L132-L147
3,250
andreikop/qutepart
qutepart/syntaxhlighter.py
_cmpFormatRanges
def _cmpFormatRanges(a, b): """PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance """ if a.format == b.format and \ a.start == b.start and \ a.length == b.length: return 0 else: return cmp(id(a), id(b))
python
def _cmpFormatRanges(a, b): if a.format == b.format and \ a.start == b.start and \ a.length == b.length: return 0 else: return cmp(id(a), id(b))
[ "def", "_cmpFormatRanges", "(", "a", ",", "b", ")", ":", "if", "a", ".", "format", "==", "b", ".", "format", "and", "a", ".", "start", "==", "b", ".", "start", "and", "a", ".", "length", "==", "b", ".", "length", ":", "return", "0", "else", ":", "return", "cmp", "(", "id", "(", "a", ")", ",", "id", "(", "b", ")", ")" ]
PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance
[ "PyQt", "does", "not", "define", "proper", "comparison", "for", "QTextLayout", ".", "FormatRange", "Define", "it", "to", "check", "correctly", "if", "formats", "has", "changed", ".", "It", "is", "important", "for", "the", "performance" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L14-L24
3,251
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isCode
def isCode(self, block, column): """Check if character at column is a a code """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isCode(data, column)
python
def isCode(self, block, column): dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isCode(data, column)
[ "def", "isCode", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isCode", "(", "data", ",", "column", ")" ]
Check if character at column is a a code
[ "Check", "if", "character", "at", "column", "is", "a", "a", "code" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L143-L148
3,252
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isComment
def isComment(self, block, column): """Check if character at column is a comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isComment(data, column)
python
def isComment(self, block, column): dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isComment(data, column)
[ "def", "isComment", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isComment", "(", "data", ",", "column", ")" ]
Check if character at column is a comment
[ "Check", "if", "character", "at", "column", "is", "a", "comment" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L150-L155
3,253
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isBlockComment
def isBlockComment(self, block, column): """Check if character at column is a block comment """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isBlockComment(data, column)
python
def isBlockComment(self, block, column): dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isBlockComment(data, column)
[ "def", "isBlockComment", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isBlockComment", "(", "data", ",", "column", ")" ]
Check if character at column is a block comment
[ "Check", "if", "character", "at", "column", "is", "a", "block", "comment" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L157-L162
3,254
andreikop/qutepart
qutepart/syntaxhlighter.py
SyntaxHighlighter.isHereDoc
def isHereDoc(self, block, column): """Check if character at column is a here document """ dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
python
def isHereDoc(self, block, column): dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
[ "def", "isHereDoc", "(", "self", ",", "block", ",", "column", ")", ":", "dataObject", "=", "block", ".", "userData", "(", ")", "data", "=", "dataObject", ".", "data", "if", "dataObject", "is", "not", "None", "else", "None", "return", "self", ".", "_syntax", ".", "isHereDoc", "(", "data", ",", "column", ")" ]
Check if character at column is a here document
[ "Check", "if", "character", "at", "column", "is", "a", "here", "document" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntaxhlighter.py#L164-L169
3,255
andreikop/qutepart
qutepart/lines.py
Lines._atomicModification
def _atomicModification(func): """Decorator Make document modification atomic """ def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
python
def _atomicModification(func): def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
[ "def", "_atomicModification", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "with", "self", ".", "_qpart", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Decorator Make document modification atomic
[ "Decorator", "Make", "document", "modification", "atomic" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L21-L29
3,256
andreikop/qutepart
qutepart/lines.py
Lines._checkAndConvertIndex
def _checkAndConvertIndex(self, index): """Check integer index, convert from less than zero notation """ if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
python
def _checkAndConvertIndex(self, index): if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
[ "def", "_checkAndConvertIndex", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", ":", "index", "=", "len", "(", "self", ")", "+", "index", "if", "index", "<", "0", "or", "index", ">=", "self", ".", "_doc", ".", "blockCount", "(", ")", ":", "raise", "IndexError", "(", "'Invalid block index'", ",", "index", ")", "return", "index" ]
Check integer index, convert from less than zero notation
[ "Check", "integer", "index", "convert", "from", "less", "than", "zero", "notation" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L47-L54
3,257
andreikop/qutepart
qutepart/lines.py
Lines.append
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
python
def append(self, text): cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
[ "def", "append", "(", "self", ",", "text", ")", ":", "cursor", "=", "QTextCursor", "(", "self", ".", "_doc", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "End", ")", "cursor", ".", "insertBlock", "(", ")", "cursor", ".", "insertText", "(", "text", ")" ]
Append line to the end
[ "Append", "line", "to", "the", "end" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L153-L159
3,258
andreikop/qutepart
qutepart/lines.py
Lines.insert
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.blockCount(): # not the last cursor = QTextCursor(self._doc.findBlockByNumber(index).previous()) cursor.movePosition(QTextCursor.EndOfBlock) cursor.insertBlock() cursor.insertText(text) else: # last append to the end self.append(text)
python
def insert(self, index, text): if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.blockCount(): # not the last cursor = QTextCursor(self._doc.findBlockByNumber(index).previous()) cursor.movePosition(QTextCursor.EndOfBlock) cursor.insertBlock() cursor.insertText(text) else: # last append to the end self.append(text)
[ "def", "insert", "(", "self", ",", "index", ",", "text", ")", ":", "if", "index", "<", "0", "or", "index", ">", "self", ".", "_doc", ".", "blockCount", "(", ")", ":", "raise", "IndexError", "(", "'Invalid block index'", ",", "index", ")", "if", "index", "==", "0", ":", "# first", "cursor", "=", "QTextCursor", "(", "self", ".", "_doc", ".", "firstBlock", "(", ")", ")", "cursor", ".", "insertText", "(", "text", ")", "cursor", ".", "insertBlock", "(", ")", "elif", "index", "!=", "self", ".", "_doc", ".", "blockCount", "(", ")", ":", "# not the last", "cursor", "=", "QTextCursor", "(", "self", ".", "_doc", ".", "findBlockByNumber", "(", "index", ")", ".", "previous", "(", ")", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "EndOfBlock", ")", "cursor", ".", "insertBlock", "(", ")", "cursor", ".", "insertText", "(", "text", ")", "else", ":", "# last append to the end", "self", ".", "append", "(", "text", ")" ]
Insert line to the document
[ "Insert", "line", "to", "the", "document" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/lines.py#L162-L178
3,259
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby._isLastCodeColumn
def _isLastCodeColumn(self, block, column): """Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment. """ return column >= self._lastColumn(block) or \ self._isComment(block, self._nextNonSpaceColumn(block, column + 1))
python
def _isLastCodeColumn(self, block, column): return column >= self._lastColumn(block) or \ self._isComment(block, self._nextNonSpaceColumn(block, column + 1))
[ "def", "_isLastCodeColumn", "(", "self", ",", "block", ",", "column", ")", ":", "return", "column", ">=", "self", ".", "_lastColumn", "(", "block", ")", "or", "self", ".", "_isComment", "(", "block", ",", "self", ".", "_nextNonSpaceColumn", "(", "block", ",", "column", "+", "1", ")", ")" ]
Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment.
[ "Return", "true", "if", "the", "given", "column", "is", "at", "least", "equal", "to", "the", "column", "that", "contains", "the", "last", "non", "-", "whitespace", "character", "at", "the", "given", "line", "or", "if", "the", "rest", "of", "the", "line", "is", "a", "comment", "." ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L90-L96
3,260
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby.findStmtStart
def findStmtStart(self, block): """Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0 """ prevBlock = self._prevNonCommentBlock(block) while prevBlock.isValid() and \ (((prevBlock == block.previous()) and self._isBlockContinuing(prevBlock)) or \ self.isStmtContinuing(prevBlock)): block = prevBlock prevBlock = self._prevNonCommentBlock(block) return block
python
def findStmtStart(self, block): prevBlock = self._prevNonCommentBlock(block) while prevBlock.isValid() and \ (((prevBlock == block.previous()) and self._isBlockContinuing(prevBlock)) or \ self.isStmtContinuing(prevBlock)): block = prevBlock prevBlock = self._prevNonCommentBlock(block) return block
[ "def", "findStmtStart", "(", "self", ",", "block", ")", ":", "prevBlock", "=", "self", ".", "_prevNonCommentBlock", "(", "block", ")", "while", "prevBlock", ".", "isValid", "(", ")", "and", "(", "(", "(", "prevBlock", "==", "block", ".", "previous", "(", ")", ")", "and", "self", ".", "_isBlockContinuing", "(", "prevBlock", ")", ")", "or", "self", ".", "isStmtContinuing", "(", "prevBlock", ")", ")", ":", "block", "=", "prevBlock", "prevBlock", "=", "self", ".", "_prevNonCommentBlock", "(", "block", ")", "return", "block" ]
Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0
[ "Return", "the", "first", "line", "that", "is", "not", "preceded", "by", "a", "continuing", "line", ".", "Return", "currBlock", "if", "currBlock", "<", "=", "0" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L153-L163
3,261
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby._isValidTrigger
def _isValidTrigger(block, ch): """check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user """ if ch == "" or ch == "\n": return True # Explicit align or new line match = rxUnindent.match(block.text()) return match is not None and \ match.group(3) == ""
python
def _isValidTrigger(block, ch): if ch == "" or ch == "\n": return True # Explicit align or new line match = rxUnindent.match(block.text()) return match is not None and \ match.group(3) == ""
[ "def", "_isValidTrigger", "(", "block", ",", "ch", ")", ":", "if", "ch", "==", "\"\"", "or", "ch", "==", "\"\\n\"", ":", "return", "True", "# Explicit align or new line", "match", "=", "rxUnindent", ".", "match", "(", "block", ".", "text", "(", ")", ")", "return", "match", "is", "not", "None", "and", "match", ".", "group", "(", "3", ")", "==", "\"\"" ]
check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user
[ "check", "if", "the", "trigger", "characters", "are", "in", "the", "right", "context", "otherwise", "running", "the", "indenter", "might", "be", "annoying", "to", "the", "user" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L166-L175
3,262
andreikop/qutepart
qutepart/indenter/ruby.py
IndentAlgRuby.findPrevStmt
def findPrevStmt(self, block): """Returns a tuple that contains the first and last line of the previous statement before line. """ stmtEnd = self._prevNonCommentBlock(block) stmtStart = self.findStmtStart(stmtEnd) return Statement(self._qpart, stmtStart, stmtEnd)
python
def findPrevStmt(self, block): stmtEnd = self._prevNonCommentBlock(block) stmtStart = self.findStmtStart(stmtEnd) return Statement(self._qpart, stmtStart, stmtEnd)
[ "def", "findPrevStmt", "(", "self", ",", "block", ")", ":", "stmtEnd", "=", "self", ".", "_prevNonCommentBlock", "(", "block", ")", "stmtStart", "=", "self", ".", "findStmtStart", "(", "stmtEnd", ")", "return", "Statement", "(", "self", ".", "_qpart", ",", "stmtStart", ",", "stmtEnd", ")" ]
Returns a tuple that contains the first and last line of the previous statement before line.
[ "Returns", "a", "tuple", "that", "contains", "the", "first", "and", "last", "line", "of", "the", "previous", "statement", "before", "line", "." ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/ruby.py#L177-L183
3,263
andreikop/qutepart
qutepart/htmldelegate.py
HTMLDelegate.paint
def paint(self, painter, option, index): """QStyledItemDelegate.paint implementation """ option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItem(option) self.initStyleOption(options,index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) if options.widget is not None: doc.setDefaultFont(options.widget.font()) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter); ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) """Original example contained line painter.setClipRect(textRect.translated(-textRect.topLeft())) but text is drawn clipped with it on kubuntu 12.04 """ doc.documentLayout().draw(painter, ctx) painter.restore()
python
def paint(self, painter, option, index): option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItem(option) self.initStyleOption(options,index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) if options.widget is not None: doc.setDefaultFont(options.widget.font()) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter); ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) """Original example contained line painter.setClipRect(textRect.translated(-textRect.topLeft())) but text is drawn clipped with it on kubuntu 12.04 """ doc.documentLayout().draw(painter, ctx) painter.restore()
[ "def", "paint", "(", "self", ",", "painter", ",", "option", ",", "index", ")", ":", "option", ".", "state", "&=", "~", "QStyle", ".", "State_HasFocus", "# never draw focus rect", "options", "=", "QStyleOptionViewItem", "(", "option", ")", "self", ".", "initStyleOption", "(", "options", ",", "index", ")", "style", "=", "QApplication", ".", "style", "(", ")", "if", "options", ".", "widget", "is", "None", "else", "options", ".", "widget", ".", "style", "(", ")", "doc", "=", "QTextDocument", "(", ")", "doc", ".", "setDocumentMargin", "(", "1", ")", "doc", ".", "setHtml", "(", "options", ".", "text", ")", "if", "options", ".", "widget", "is", "not", "None", ":", "doc", ".", "setDefaultFont", "(", "options", ".", "widget", ".", "font", "(", ")", ")", "# bad long (multiline) strings processing doc.setTextWidth(options.rect.width())", "options", ".", "text", "=", "\"\"", "style", ".", "drawControl", "(", "QStyle", ".", "CE_ItemViewItem", ",", "options", ",", "painter", ")", "ctx", "=", "QAbstractTextDocumentLayout", ".", "PaintContext", "(", ")", "# Highlighting text if item is selected", "if", "option", ".", "state", "&", "QStyle", ".", "State_Selected", ":", "ctx", ".", "palette", ".", "setColor", "(", "QPalette", ".", "Text", ",", "option", ".", "palette", ".", "color", "(", "QPalette", ".", "Active", ",", "QPalette", ".", "HighlightedText", ")", ")", "textRect", "=", "style", ".", "subElementRect", "(", "QStyle", ".", "SE_ItemViewItemText", ",", "options", ")", "painter", ".", "save", "(", ")", "painter", ".", "translate", "(", "textRect", ".", "topLeft", "(", ")", ")", "\"\"\"Original example contained line\n painter.setClipRect(textRect.translated(-textRect.topLeft()))\n but text is drawn clipped with it on kubuntu 12.04\n \"\"\"", "doc", ".", "documentLayout", "(", ")", ".", "draw", "(", "painter", ",", "ctx", ")", "painter", ".", "restore", "(", ")" ]
QStyledItemDelegate.paint implementation
[ "QStyledItemDelegate", ".", "paint", "implementation" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/htmldelegate.py#L36-L71
3,264
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.isDeleteKeyEvent
def isDeleteKeyEvent(self, keyEvent): """Check if key event should be handled as Delete command""" return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
python
def isDeleteKeyEvent(self, keyEvent): return self._start is not None and \ (keyEvent.matches(QKeySequence.Delete) or \ (keyEvent.key() == Qt.Key_Backspace and keyEvent.modifiers() == Qt.NoModifier))
[ "def", "isDeleteKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "return", "self", ".", "_start", "is", "not", "None", "and", "(", "keyEvent", ".", "matches", "(", "QKeySequence", ".", "Delete", ")", "or", "(", "keyEvent", ".", "key", "(", ")", "==", "Qt", ".", "Key_Backspace", "and", "keyEvent", ".", "modifiers", "(", ")", "==", "Qt", ".", "NoModifier", ")", ")" ]
Check if key event should be handled as Delete command
[ "Check", "if", "key", "event", "should", "be", "handled", "as", "Delete", "command" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L35-L39
3,265
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.delete
def delete(self): """Del or Backspace pressed. Delete selection""" with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
python
def delete(self): with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
[ "def", "delete", "(", "self", ")", ":", "with", "self", ".", "_qpart", ":", "for", "cursor", "in", "self", ".", "cursors", "(", ")", ":", "if", "cursor", ".", "hasSelection", "(", ")", ":", "cursor", ".", "deleteChar", "(", ")" ]
Del or Backspace pressed. Delete selection
[ "Del", "or", "Backspace", "pressed", ".", "Delete", "selection" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L41-L46
3,266
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.isExpandKeyEvent
def isExpandKeyEvent(self, keyEvent): """Check if key event should expand rectangular selection""" return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown, Qt.Key_Home, Qt.Key_End)
python
def isExpandKeyEvent(self, keyEvent): return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, Qt.Key_PageUp, Qt.Key_PageDown, Qt.Key_Home, Qt.Key_End)
[ "def", "isExpandKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "return", "keyEvent", ".", "modifiers", "(", ")", "&", "Qt", ".", "ShiftModifier", "and", "keyEvent", ".", "modifiers", "(", ")", "&", "Qt", ".", "AltModifier", "and", "keyEvent", ".", "key", "(", ")", "in", "(", "Qt", ".", "Key_Left", ",", "Qt", ".", "Key_Right", ",", "Qt", ".", "Key_Down", ",", "Qt", ".", "Key_Up", ",", "Qt", ".", "Key_PageUp", ",", "Qt", ".", "Key_PageDown", ",", "Qt", ".", "Key_Home", ",", "Qt", ".", "Key_End", ")" ]
Check if key event should expand rectangular selection
[ "Check", "if", "key", "event", "should", "expand", "rectangular", "selection" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L48-L53
3,267
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.onExpandKeyEvent
def onExpandKeyEvent(self, keyEvent): """One of expand selection key events""" if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpart.cursorPosition[1]) self._start = (line, visibleColumn) modifiersWithoutAltShift = keyEvent.modifiers() & ( ~ (Qt.AltModifier | Qt.ShiftModifier)) newEvent = QKeyEvent(keyEvent.type(), keyEvent.key(), modifiersWithoutAltShift, keyEvent.text(), keyEvent.isAutoRepeat(), keyEvent.count()) self._qpart.cursorPositionChanged.disconnect(self._reset) self._qpart.selectionChanged.disconnect(self._reset) super(self._qpart.__class__, self._qpart).keyPressEvent(newEvent) self._qpart.cursorPositionChanged.connect(self._reset) self._qpart.selectionChanged.connect(self._reset)
python
def onExpandKeyEvent(self, keyEvent): if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpart.cursorPosition[1]) self._start = (line, visibleColumn) modifiersWithoutAltShift = keyEvent.modifiers() & ( ~ (Qt.AltModifier | Qt.ShiftModifier)) newEvent = QKeyEvent(keyEvent.type(), keyEvent.key(), modifiersWithoutAltShift, keyEvent.text(), keyEvent.isAutoRepeat(), keyEvent.count()) self._qpart.cursorPositionChanged.disconnect(self._reset) self._qpart.selectionChanged.disconnect(self._reset) super(self._qpart.__class__, self._qpart).keyPressEvent(newEvent) self._qpart.cursorPositionChanged.connect(self._reset) self._qpart.selectionChanged.connect(self._reset)
[ "def", "onExpandKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "if", "self", ".", "_start", "is", "None", ":", "currentBlockText", "=", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "text", "(", ")", "line", "=", "self", ".", "_qpart", ".", "cursorPosition", "[", "0", "]", "visibleColumn", "=", "self", ".", "_realToVisibleColumn", "(", "currentBlockText", ",", "self", ".", "_qpart", ".", "cursorPosition", "[", "1", "]", ")", "self", ".", "_start", "=", "(", "line", ",", "visibleColumn", ")", "modifiersWithoutAltShift", "=", "keyEvent", ".", "modifiers", "(", ")", "&", "(", "~", "(", "Qt", ".", "AltModifier", "|", "Qt", ".", "ShiftModifier", ")", ")", "newEvent", "=", "QKeyEvent", "(", "keyEvent", ".", "type", "(", ")", ",", "keyEvent", ".", "key", "(", ")", ",", "modifiersWithoutAltShift", ",", "keyEvent", ".", "text", "(", ")", ",", "keyEvent", ".", "isAutoRepeat", "(", ")", ",", "keyEvent", ".", "count", "(", ")", ")", "self", ".", "_qpart", ".", "cursorPositionChanged", ".", "disconnect", "(", "self", ".", "_reset", ")", "self", ".", "_qpart", ".", "selectionChanged", ".", "disconnect", "(", "self", ".", "_reset", ")", "super", "(", "self", ".", "_qpart", ".", "__class__", ",", "self", ".", "_qpart", ")", ".", "keyPressEvent", "(", "newEvent", ")", "self", ".", "_qpart", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "_reset", ")", "self", ".", "_qpart", ".", "selectionChanged", ".", "connect", "(", "self", ".", "_reset", ")" ]
One of expand selection key events
[ "One", "of", "expand", "selection", "key", "events" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L55-L74
3,268
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection._realToVisibleColumn
def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and visible position differs This function converts real to visible """ generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(generator) val = next(generator) return val
python
def _realToVisibleColumn(self, text, realColumn): generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(generator) val = next(generator) return val
[ "def", "_realToVisibleColumn", "(", "self", ",", "text", ",", "realColumn", ")", ":", "generator", "=", "self", ".", "_visibleCharPositionGenerator", "(", "text", ")", "for", "i", "in", "range", "(", "realColumn", ")", ":", "val", "=", "next", "(", "generator", ")", "val", "=", "next", "(", "generator", ")", "return", "val" ]
If \t is used, real position of symbol in block and visible position differs This function converts real to visible
[ "If", "\\", "t", "is", "used", "real", "position", "of", "symbol", "in", "block", "and", "visible", "position", "differs", "This", "function", "converts", "real", "to", "visible" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L90-L98
3,269
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection._visibleToRealColumn
def _visibleToRealColumn(self, text, visiblePos): """If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short """ if visiblePos == 0: return 0 elif not '\t' in text: return visiblePos else: currentIndex = 1 for currentVisiblePos in self._visibleCharPositionGenerator(text): if currentVisiblePos >= visiblePos: return currentIndex - 1 currentIndex += 1 return None
python
def _visibleToRealColumn(self, text, visiblePos): if visiblePos == 0: return 0 elif not '\t' in text: return visiblePos else: currentIndex = 1 for currentVisiblePos in self._visibleCharPositionGenerator(text): if currentVisiblePos >= visiblePos: return currentIndex - 1 currentIndex += 1 return None
[ "def", "_visibleToRealColumn", "(", "self", ",", "text", ",", "visiblePos", ")", ":", "if", "visiblePos", "==", "0", ":", "return", "0", "elif", "not", "'\\t'", "in", "text", ":", "return", "visiblePos", "else", ":", "currentIndex", "=", "1", "for", "currentVisiblePos", "in", "self", ".", "_visibleCharPositionGenerator", "(", "text", ")", ":", "if", "currentVisiblePos", ">=", "visiblePos", ":", "return", "currentIndex", "-", "1", "currentIndex", "+=", "1", "return", "None" ]
If \t is used, real position of symbol in block and visible position differs This function converts visible to real. Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short
[ "If", "\\", "t", "is", "used", "real", "position", "of", "symbol", "in", "block", "and", "visible", "position", "differs", "This", "function", "converts", "visible", "to", "real", ".", "Bigger", "value", "is", "returned", "if", "visiblePos", "is", "in", "the", "middle", "of", "\\", "t", "None", "if", "text", "is", "too", "short" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L100-L116
3,270
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.cursors
def cursors(self): """Cursors for rectangular selection. 1 cursor for every line """ cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - currentLine) > self._MAX_SIZE or \ abs(startVisibleCol - currentCol) > self._MAX_SIZE: # Too big rectangular selection freezes the GUI self._qpart.userWarning.emit('Rectangular selection area is too big') self._start = None return [] currentBlockText = self._qpart.textCursor().block().text() currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol) for lineNumber in range(min(startLine, currentLine), max(startLine, currentLine) + 1): block = self._qpart.document().findBlockByNumber(lineNumber) cursor = QTextCursor(block) realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol) realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol) if realStartCol is None: realStartCol = block.length() # out of range value if realCurrentCol is None: realCurrentCol = block.length() # out of range value cursor.setPosition(cursor.block().position() + min(realStartCol, block.length() - 1)) cursor.setPosition(cursor.block().position() + min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
python
def cursors(self): cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - currentLine) > self._MAX_SIZE or \ abs(startVisibleCol - currentCol) > self._MAX_SIZE: # Too big rectangular selection freezes the GUI self._qpart.userWarning.emit('Rectangular selection area is too big') self._start = None return [] currentBlockText = self._qpart.textCursor().block().text() currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol) for lineNumber in range(min(startLine, currentLine), max(startLine, currentLine) + 1): block = self._qpart.document().findBlockByNumber(lineNumber) cursor = QTextCursor(block) realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol) realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol) if realStartCol is None: realStartCol = block.length() # out of range value if realCurrentCol is None: realCurrentCol = block.length() # out of range value cursor.setPosition(cursor.block().position() + min(realStartCol, block.length() - 1)) cursor.setPosition(cursor.block().position() + min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
[ "def", "cursors", "(", "self", ")", ":", "cursors", "=", "[", "]", "if", "self", ".", "_start", "is", "not", "None", ":", "startLine", ",", "startVisibleCol", "=", "self", ".", "_start", "currentLine", ",", "currentCol", "=", "self", ".", "_qpart", ".", "cursorPosition", "if", "abs", "(", "startLine", "-", "currentLine", ")", ">", "self", ".", "_MAX_SIZE", "or", "abs", "(", "startVisibleCol", "-", "currentCol", ")", ">", "self", ".", "_MAX_SIZE", ":", "# Too big rectangular selection freezes the GUI", "self", ".", "_qpart", ".", "userWarning", ".", "emit", "(", "'Rectangular selection area is too big'", ")", "self", ".", "_start", "=", "None", "return", "[", "]", "currentBlockText", "=", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "text", "(", ")", "currentVisibleCol", "=", "self", ".", "_realToVisibleColumn", "(", "currentBlockText", ",", "currentCol", ")", "for", "lineNumber", "in", "range", "(", "min", "(", "startLine", ",", "currentLine", ")", ",", "max", "(", "startLine", ",", "currentLine", ")", "+", "1", ")", ":", "block", "=", "self", ".", "_qpart", ".", "document", "(", ")", ".", "findBlockByNumber", "(", "lineNumber", ")", "cursor", "=", "QTextCursor", "(", "block", ")", "realStartCol", "=", "self", ".", "_visibleToRealColumn", "(", "block", ".", "text", "(", ")", ",", "startVisibleCol", ")", "realCurrentCol", "=", "self", ".", "_visibleToRealColumn", "(", "block", ".", "text", "(", ")", ",", "currentVisibleCol", ")", "if", "realStartCol", "is", "None", ":", "realStartCol", "=", "block", ".", "length", "(", ")", "# out of range value", "if", "realCurrentCol", "is", "None", ":", "realCurrentCol", "=", "block", ".", "length", "(", ")", "# out of range value", "cursor", ".", "setPosition", "(", "cursor", ".", "block", "(", ")", ".", "position", "(", ")", "+", "min", "(", "realStartCol", ",", "block", ".", "length", "(", ")", "-", "1", ")", ")", "cursor", ".", "setPosition", "(", "cursor", ".", "block", "(", ")", ".", "position", "(", ")", "+", "min", "(", "realCurrentCol", ",", "block", ".", "length", "(", ")", "-", "1", ")", ",", "QTextCursor", ".", "KeepAnchor", ")", "cursors", ".", "append", "(", "cursor", ")", "return", "cursors" ]
Cursors for rectangular selection. 1 cursor for every line
[ "Cursors", "for", "rectangular", "selection", ".", "1", "cursor", "for", "every", "line" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L118-L152
3,271
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.selections
def selections(self): """Build list of extra selections for rectangular selection""" selections = [] cursors = self.cursors() if cursors: background = self._qpart.palette().color(QPalette.Highlight) foreground = self._qpart.palette().color(QPalette.HighlightedText) for cursor in cursors: selection = QTextEdit.ExtraSelection() selection.format.setBackground(background) selection.format.setForeground(foreground) selection.cursor = cursor selections.append(selection) return selections
python
def selections(self): selections = [] cursors = self.cursors() if cursors: background = self._qpart.palette().color(QPalette.Highlight) foreground = self._qpart.palette().color(QPalette.HighlightedText) for cursor in cursors: selection = QTextEdit.ExtraSelection() selection.format.setBackground(background) selection.format.setForeground(foreground) selection.cursor = cursor selections.append(selection) return selections
[ "def", "selections", "(", "self", ")", ":", "selections", "=", "[", "]", "cursors", "=", "self", ".", "cursors", "(", ")", "if", "cursors", ":", "background", "=", "self", ".", "_qpart", ".", "palette", "(", ")", ".", "color", "(", "QPalette", ".", "Highlight", ")", "foreground", "=", "self", ".", "_qpart", ".", "palette", "(", ")", ".", "color", "(", "QPalette", ".", "HighlightedText", ")", "for", "cursor", "in", "cursors", ":", "selection", "=", "QTextEdit", ".", "ExtraSelection", "(", ")", "selection", ".", "format", ".", "setBackground", "(", "background", ")", "selection", ".", "format", ".", "setForeground", "(", "foreground", ")", "selection", ".", "cursor", "=", "cursor", "selections", ".", "append", "(", "selection", ")", "return", "selections" ]
Build list of extra selections for rectangular selection
[ "Build", "list", "of", "extra", "selections", "for", "rectangular", "selection" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L154-L169
3,272
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.copy
def copy(self): """Copy to the clipboard""" data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
python
def copy(self): data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
[ "def", "copy", "(", "self", ")", ":", "data", "=", "QMimeData", "(", ")", "text", "=", "'\\n'", ".", "join", "(", "[", "cursor", ".", "selectedText", "(", ")", "for", "cursor", "in", "self", ".", "cursors", "(", ")", "]", ")", "data", ".", "setText", "(", "text", ")", "data", ".", "setData", "(", "self", ".", "MIME_TYPE", ",", "text", ".", "encode", "(", "'utf8'", ")", ")", "QApplication", ".", "clipboard", "(", ")", ".", "setMimeData", "(", "data", ")" ]
Copy to the clipboard
[ "Copy", "to", "the", "clipboard" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L175-L182
3,273
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.cut
def cut(self): """Cut action. Copy and delete """ cursorPos = self._qpart.cursorPosition topLeft = (min(self._start[0], cursorPos[0]), min(self._start[1], cursorPos[1])) self.copy() self.delete() """Move cursor to top-left corner of the selection, so that if text gets pasted again, original text will be restored""" self._qpart.cursorPosition = topLeft
python
def cut(self): cursorPos = self._qpart.cursorPosition topLeft = (min(self._start[0], cursorPos[0]), min(self._start[1], cursorPos[1])) self.copy() self.delete() """Move cursor to top-left corner of the selection, so that if text gets pasted again, original text will be restored""" self._qpart.cursorPosition = topLeft
[ "def", "cut", "(", "self", ")", ":", "cursorPos", "=", "self", ".", "_qpart", ".", "cursorPosition", "topLeft", "=", "(", "min", "(", "self", ".", "_start", "[", "0", "]", ",", "cursorPos", "[", "0", "]", ")", ",", "min", "(", "self", ".", "_start", "[", "1", "]", ",", "cursorPos", "[", "1", "]", ")", ")", "self", ".", "copy", "(", ")", "self", ".", "delete", "(", ")", "\"\"\"Move cursor to top-left corner of the selection,\n so that if text gets pasted again, original text will be restored\"\"\"", "self", ".", "_qpart", ".", "cursorPosition", "=", "topLeft" ]
Cut action. Copy and delete
[ "Cut", "action", ".", "Copy", "and", "delete" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L184-L195
3,274
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection._indentUpTo
def _indentUpTo(self, text, width): """Add space to text, so text width will be at least width. Return text, which must be added """ visibleTextWidth = self._realToVisibleColumn(text, len(text)) diff = width - visibleTextWidth if diff <= 0: return '' elif self._qpart.indentUseTabs and \ all([char == '\t' for char in text]): # if using tabs and only tabs in text return '\t' * (diff // self._qpart.indentWidth) + \ ' ' * (diff % self._qpart.indentWidth) else: return ' ' * int(diff)
python
def _indentUpTo(self, text, width): visibleTextWidth = self._realToVisibleColumn(text, len(text)) diff = width - visibleTextWidth if diff <= 0: return '' elif self._qpart.indentUseTabs and \ all([char == '\t' for char in text]): # if using tabs and only tabs in text return '\t' * (diff // self._qpart.indentWidth) + \ ' ' * (diff % self._qpart.indentWidth) else: return ' ' * int(diff)
[ "def", "_indentUpTo", "(", "self", ",", "text", ",", "width", ")", ":", "visibleTextWidth", "=", "self", ".", "_realToVisibleColumn", "(", "text", ",", "len", "(", "text", ")", ")", "diff", "=", "width", "-", "visibleTextWidth", "if", "diff", "<=", "0", ":", "return", "''", "elif", "self", ".", "_qpart", ".", "indentUseTabs", "and", "all", "(", "[", "char", "==", "'\\t'", "for", "char", "in", "text", "]", ")", ":", "# if using tabs and only tabs in text", "return", "'\\t'", "*", "(", "diff", "//", "self", ".", "_qpart", ".", "indentWidth", ")", "+", "' '", "*", "(", "diff", "%", "self", ".", "_qpart", ".", "indentWidth", ")", "else", ":", "return", "' '", "*", "int", "(", "diff", ")" ]
Add space to text, so text width will be at least width. Return text, which must be added
[ "Add", "space", "to", "text", "so", "text", "width", "will", "be", "at", "least", "width", ".", "Return", "text", "which", "must", "be", "added" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L197-L210
3,275
andreikop/qutepart
qutepart/rectangularselection.py
RectangularSelection.paste
def paste(self, mimeData): """Paste recrangular selection. Add space at the beginning of line, if necessary """ if self.isActive(): self.delete() elif self._qpart.textCursor().hasSelection(): self._qpart.textCursor().deleteChar() text = bytes(mimeData.data(self.MIME_TYPE)).decode('utf8') lines = text.splitlines() cursorLine, cursorCol = self._qpart.cursorPosition if cursorLine + len(lines) > len(self._qpart.lines): for i in range(cursorLine + len(lines) - len(self._qpart.lines)): self._qpart.lines.append('') with self._qpart: for index, line in enumerate(lines): currentLine = self._qpart.lines[cursorLine + index] newLine = currentLine[:cursorCol] + \ self._indentUpTo(currentLine, cursorCol) + \ line + \ currentLine[cursorCol:] self._qpart.lines[cursorLine + index] = newLine self._qpart.cursorPosition = cursorLine, cursorCol
python
def paste(self, mimeData): if self.isActive(): self.delete() elif self._qpart.textCursor().hasSelection(): self._qpart.textCursor().deleteChar() text = bytes(mimeData.data(self.MIME_TYPE)).decode('utf8') lines = text.splitlines() cursorLine, cursorCol = self._qpart.cursorPosition if cursorLine + len(lines) > len(self._qpart.lines): for i in range(cursorLine + len(lines) - len(self._qpart.lines)): self._qpart.lines.append('') with self._qpart: for index, line in enumerate(lines): currentLine = self._qpart.lines[cursorLine + index] newLine = currentLine[:cursorCol] + \ self._indentUpTo(currentLine, cursorCol) + \ line + \ currentLine[cursorCol:] self._qpart.lines[cursorLine + index] = newLine self._qpart.cursorPosition = cursorLine, cursorCol
[ "def", "paste", "(", "self", ",", "mimeData", ")", ":", "if", "self", ".", "isActive", "(", ")", ":", "self", ".", "delete", "(", ")", "elif", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "hasSelection", "(", ")", ":", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "deleteChar", "(", ")", "text", "=", "bytes", "(", "mimeData", ".", "data", "(", "self", ".", "MIME_TYPE", ")", ")", ".", "decode", "(", "'utf8'", ")", "lines", "=", "text", ".", "splitlines", "(", ")", "cursorLine", ",", "cursorCol", "=", "self", ".", "_qpart", ".", "cursorPosition", "if", "cursorLine", "+", "len", "(", "lines", ")", ">", "len", "(", "self", ".", "_qpart", ".", "lines", ")", ":", "for", "i", "in", "range", "(", "cursorLine", "+", "len", "(", "lines", ")", "-", "len", "(", "self", ".", "_qpart", ".", "lines", ")", ")", ":", "self", ".", "_qpart", ".", "lines", ".", "append", "(", "''", ")", "with", "self", ".", "_qpart", ":", "for", "index", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "currentLine", "=", "self", ".", "_qpart", ".", "lines", "[", "cursorLine", "+", "index", "]", "newLine", "=", "currentLine", "[", ":", "cursorCol", "]", "+", "self", ".", "_indentUpTo", "(", "currentLine", ",", "cursorCol", ")", "+", "line", "+", "currentLine", "[", "cursorCol", ":", "]", "self", ".", "_qpart", ".", "lines", "[", "cursorLine", "+", "index", "]", "=", "newLine", "self", ".", "_qpart", ".", "cursorPosition", "=", "cursorLine", ",", "cursorCol" ]
Paste recrangular selection. Add space at the beginning of line, if necessary
[ "Paste", "recrangular", "selection", ".", "Add", "space", "at", "the", "beginning", "of", "line", "if", "necessary" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L212-L236
3,276
andreikop/qutepart
qutepart/margins.py
MarginBase.__allocateBits
def __allocateBits(self): """Allocates the bit range depending on the required bit count """ if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return # Build a list of occupied ranges margins = self._qpart.getMargins() occupiedRanges = [] for margin in margins: bitRange = margin.getBitRange() if bitRange is not None: # pick the right position added = False for index in range( len( occupiedRanges ) ): r = occupiedRanges[ index ] if bitRange[ 1 ] < r[ 0 ]: occupiedRanges.insert(index, bitRange) added = True break if not added: occupiedRanges.append(bitRange) vacant = 0 for r in occupiedRanges: if r[ 0 ] - vacant >= self._bit_count: self._bitRange = (vacant, vacant + self._bit_count - 1) return vacant = r[ 1 ] + 1 # Not allocated, i.e. grab the tail bits self._bitRange = (vacant, vacant + self._bit_count - 1)
python
def __allocateBits(self): if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return # Build a list of occupied ranges margins = self._qpart.getMargins() occupiedRanges = [] for margin in margins: bitRange = margin.getBitRange() if bitRange is not None: # pick the right position added = False for index in range( len( occupiedRanges ) ): r = occupiedRanges[ index ] if bitRange[ 1 ] < r[ 0 ]: occupiedRanges.insert(index, bitRange) added = True break if not added: occupiedRanges.append(bitRange) vacant = 0 for r in occupiedRanges: if r[ 0 ] - vacant >= self._bit_count: self._bitRange = (vacant, vacant + self._bit_count - 1) return vacant = r[ 1 ] + 1 # Not allocated, i.e. grab the tail bits self._bitRange = (vacant, vacant + self._bit_count - 1)
[ "def", "__allocateBits", "(", "self", ")", ":", "if", "self", ".", "_bit_count", "<", "0", ":", "raise", "Exception", "(", "\"A margin cannot request negative number of bits\"", ")", "if", "self", ".", "_bit_count", "==", "0", ":", "return", "# Build a list of occupied ranges", "margins", "=", "self", ".", "_qpart", ".", "getMargins", "(", ")", "occupiedRanges", "=", "[", "]", "for", "margin", "in", "margins", ":", "bitRange", "=", "margin", ".", "getBitRange", "(", ")", "if", "bitRange", "is", "not", "None", ":", "# pick the right position", "added", "=", "False", "for", "index", "in", "range", "(", "len", "(", "occupiedRanges", ")", ")", ":", "r", "=", "occupiedRanges", "[", "index", "]", "if", "bitRange", "[", "1", "]", "<", "r", "[", "0", "]", ":", "occupiedRanges", ".", "insert", "(", "index", ",", "bitRange", ")", "added", "=", "True", "break", "if", "not", "added", ":", "occupiedRanges", ".", "append", "(", "bitRange", ")", "vacant", "=", "0", "for", "r", "in", "occupiedRanges", ":", "if", "r", "[", "0", "]", "-", "vacant", ">=", "self", ".", "_bit_count", ":", "self", ".", "_bitRange", "=", "(", "vacant", ",", "vacant", "+", "self", ".", "_bit_count", "-", "1", ")", "return", "vacant", "=", "r", "[", "1", "]", "+", "1", "# Not allocated, i.e. grab the tail bits", "self", ".", "_bitRange", "=", "(", "vacant", ",", "vacant", "+", "self", ".", "_bit_count", "-", "1", ")" ]
Allocates the bit range depending on the required bit count
[ "Allocates", "the", "bit", "range", "depending", "on", "the", "required", "bit", "count" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L32-L65
3,277
andreikop/qutepart
qutepart/margins.py
MarginBase.__updateRequest
def __updateRequest(self, rect, dy): """Repaint line number area if necessary """ if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): # if block height not added to rect, last line number sometimes is not drawn blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height() self.update(0, rect.y(), self.width(), rect.height() + blockHeight) self._countCache = (self._qpart.blockCount(), self._qpart.textCursor().block().lineCount()) if rect.contains(self._qpart.viewport().rect()): self._qpart.updateViewportMargins()
python
def __updateRequest(self, rect, dy): if dy: self.scroll(0, dy) elif self._countCache[0] != self._qpart.blockCount() or \ self._countCache[1] != self._qpart.textCursor().block().lineCount(): # if block height not added to rect, last line number sometimes is not drawn blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height() self.update(0, rect.y(), self.width(), rect.height() + blockHeight) self._countCache = (self._qpart.blockCount(), self._qpart.textCursor().block().lineCount()) if rect.contains(self._qpart.viewport().rect()): self._qpart.updateViewportMargins()
[ "def", "__updateRequest", "(", "self", ",", "rect", ",", "dy", ")", ":", "if", "dy", ":", "self", ".", "scroll", "(", "0", ",", "dy", ")", "elif", "self", ".", "_countCache", "[", "0", "]", "!=", "self", ".", "_qpart", ".", "blockCount", "(", ")", "or", "self", ".", "_countCache", "[", "1", "]", "!=", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "lineCount", "(", ")", ":", "# if block height not added to rect, last line number sometimes is not drawn", "blockHeight", "=", "self", ".", "_qpart", ".", "blockBoundingRect", "(", "self", ".", "_qpart", ".", "firstVisibleBlock", "(", ")", ")", ".", "height", "(", ")", "self", ".", "update", "(", "0", ",", "rect", ".", "y", "(", ")", ",", "self", ".", "width", "(", ")", ",", "rect", ".", "height", "(", ")", "+", "blockHeight", ")", "self", ".", "_countCache", "=", "(", "self", ".", "_qpart", ".", "blockCount", "(", ")", ",", "self", ".", "_qpart", ".", "textCursor", "(", ")", ".", "block", "(", ")", ".", "lineCount", "(", ")", ")", "if", "rect", ".", "contains", "(", "self", ".", "_qpart", ".", "viewport", "(", ")", ".", "rect", "(", ")", ")", ":", "self", ".", "_qpart", ".", "updateViewportMargins", "(", ")" ]
Repaint line number area if necessary
[ "Repaint", "line", "number", "area", "if", "necessary" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L67-L82
3,278
andreikop/qutepart
qutepart/margins.py
MarginBase.setBlockValue
def setBlockValue(self, block, value): """Sets the required value to the block without damaging the other bits """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") if value < 0: raise Exception( "The margin '" + self._name + "' must be a positive integer" ) if value >= 2 ** self._bit_count: raise Exception( "The margin '" + self._name + "' value exceeds the allocated bit range" ) newMarginValue = value << self._bitRange[ 0 ] currentUserState = block.userState() if currentUserState in [ 0, -1 ]: block.setUserState(newMarginValue) else: marginMask = 2 ** self._bit_count - 1 otherMarginsValue = currentUserState & ~marginMask block.setUserState(newMarginValue | otherMarginsValue)
python
def setBlockValue(self, block, value): if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") if value < 0: raise Exception( "The margin '" + self._name + "' must be a positive integer" ) if value >= 2 ** self._bit_count: raise Exception( "The margin '" + self._name + "' value exceeds the allocated bit range" ) newMarginValue = value << self._bitRange[ 0 ] currentUserState = block.userState() if currentUserState in [ 0, -1 ]: block.setUserState(newMarginValue) else: marginMask = 2 ** self._bit_count - 1 otherMarginsValue = currentUserState & ~marginMask block.setUserState(newMarginValue | otherMarginsValue)
[ "def", "setBlockValue", "(", "self", ",", "block", ",", "value", ")", ":", "if", "self", ".", "_bit_count", "==", "0", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' did not allocate any bits for the values\"", ")", "if", "value", "<", "0", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' must be a positive integer\"", ")", "if", "value", ">=", "2", "**", "self", ".", "_bit_count", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' value exceeds the allocated bit range\"", ")", "newMarginValue", "=", "value", "<<", "self", ".", "_bitRange", "[", "0", "]", "currentUserState", "=", "block", ".", "userState", "(", ")", "if", "currentUserState", "in", "[", "0", ",", "-", "1", "]", ":", "block", ".", "setUserState", "(", "newMarginValue", ")", "else", ":", "marginMask", "=", "2", "**", "self", ".", "_bit_count", "-", "1", "otherMarginsValue", "=", "currentUserState", "&", "~", "marginMask", "block", ".", "setUserState", "(", "newMarginValue", "|", "otherMarginsValue", ")" ]
Sets the required value to the block without damaging the other bits
[ "Sets", "the", "required", "value", "to", "the", "block", "without", "damaging", "the", "other", "bits" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L95-L117
3,279
andreikop/qutepart
qutepart/margins.py
MarginBase.getBlockValue
def getBlockValue(self, block): """Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided. """ if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") val = block.userState() if val in [ 0, -1 ]: return 0 # Shift the value to the right val >>= self._bitRange[ 0 ] # Apply the mask to the value mask = 2 ** self._bit_count - 1 val &= mask return val
python
def getBlockValue(self, block): if self._bit_count == 0: raise Exception( "The margin '" + self._name + "' did not allocate any bits for the values") val = block.userState() if val in [ 0, -1 ]: return 0 # Shift the value to the right val >>= self._bitRange[ 0 ] # Apply the mask to the value mask = 2 ** self._bit_count - 1 val &= mask return val
[ "def", "getBlockValue", "(", "self", ",", "block", ")", ":", "if", "self", ".", "_bit_count", "==", "0", ":", "raise", "Exception", "(", "\"The margin '\"", "+", "self", ".", "_name", "+", "\"' did not allocate any bits for the values\"", ")", "val", "=", "block", ".", "userState", "(", ")", "if", "val", "in", "[", "0", ",", "-", "1", "]", ":", "return", "0", "# Shift the value to the right", "val", ">>=", "self", ".", "_bitRange", "[", "0", "]", "# Apply the mask to the value", "mask", "=", "2", "**", "self", ".", "_bit_count", "-", "1", "val", "&=", "mask", "return", "val" ]
Provides the previously set block value respecting the bits range. 0 value and not marked block are treated the same way and 0 is provided.
[ "Provides", "the", "previously", "set", "block", "value", "respecting", "the", "bits", "range", ".", "0", "value", "and", "not", "marked", "block", "are", "treated", "the", "same", "way", "and", "0", "is", "provided", "." ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L119-L137
3,280
andreikop/qutepart
qutepart/margins.py
MarginBase.clear
def clear(self): """Convenience method to reset all the block values to 0 """ if self._bit_count == 0: return block = self._qpart.document().begin() while block.isValid(): if self.getBlockValue(block): self.setBlockValue(block, 0) block = block.next()
python
def clear(self): if self._bit_count == 0: return block = self._qpart.document().begin() while block.isValid(): if self.getBlockValue(block): self.setBlockValue(block, 0) block = block.next()
[ "def", "clear", "(", "self", ")", ":", "if", "self", ".", "_bit_count", "==", "0", ":", "return", "block", "=", "self", ".", "_qpart", ".", "document", "(", ")", ".", "begin", "(", ")", "while", "block", ".", "isValid", "(", ")", ":", "if", "self", ".", "getBlockValue", "(", "block", ")", ":", "self", ".", "setBlockValue", "(", "block", ",", "0", ")", "block", "=", "block", ".", "next", "(", ")" ]
Convenience method to reset all the block values to 0
[ "Convenience", "method", "to", "reset", "all", "the", "block", "values", "to", "0" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/margins.py#L175-L185
3,281
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxByXmlFileName
def _getSyntaxByXmlFileName(self, xmlFileName): """Get syntax by its xml file name """ import qutepart.syntax.loader # delayed import for avoid cross-imports problem with self._loadedSyntaxesLock: if not xmlFileName in self._loadedSyntaxes: xmlFilePath = os.path.join(os.path.dirname(__file__), "data", "xml", xmlFileName) syntax = Syntax(self) self._loadedSyntaxes[xmlFileName] = syntax qutepart.syntax.loader.loadSyntax(syntax, xmlFilePath) return self._loadedSyntaxes[xmlFileName]
python
def _getSyntaxByXmlFileName(self, xmlFileName): import qutepart.syntax.loader # delayed import for avoid cross-imports problem with self._loadedSyntaxesLock: if not xmlFileName in self._loadedSyntaxes: xmlFilePath = os.path.join(os.path.dirname(__file__), "data", "xml", xmlFileName) syntax = Syntax(self) self._loadedSyntaxes[xmlFileName] = syntax qutepart.syntax.loader.loadSyntax(syntax, xmlFilePath) return self._loadedSyntaxes[xmlFileName]
[ "def", "_getSyntaxByXmlFileName", "(", "self", ",", "xmlFileName", ")", ":", "import", "qutepart", ".", "syntax", ".", "loader", "# delayed import for avoid cross-imports problem", "with", "self", ".", "_loadedSyntaxesLock", ":", "if", "not", "xmlFileName", "in", "self", ".", "_loadedSyntaxes", ":", "xmlFilePath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"data\"", ",", "\"xml\"", ",", "xmlFileName", ")", "syntax", "=", "Syntax", "(", "self", ")", "self", ".", "_loadedSyntaxes", "[", "xmlFileName", "]", "=", "syntax", "qutepart", ".", "syntax", ".", "loader", ".", "loadSyntax", "(", "syntax", ",", "xmlFilePath", ")", "return", "self", ".", "_loadedSyntaxes", "[", "xmlFileName", "]" ]
Get syntax by its xml file name
[ "Get", "syntax", "by", "its", "xml", "file", "name" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L170-L182
3,282
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxByLanguageName
def _getSyntaxByLanguageName(self, syntaxName): """Get syntax by its name. Name is defined in the xml file """ xmlFileName = self._syntaxNameToXmlFileName[syntaxName] return self._getSyntaxByXmlFileName(xmlFileName)
python
def _getSyntaxByLanguageName(self, syntaxName): xmlFileName = self._syntaxNameToXmlFileName[syntaxName] return self._getSyntaxByXmlFileName(xmlFileName)
[ "def", "_getSyntaxByLanguageName", "(", "self", ",", "syntaxName", ")", ":", "xmlFileName", "=", "self", ".", "_syntaxNameToXmlFileName", "[", "syntaxName", "]", "return", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")" ]
Get syntax by its name. Name is defined in the xml file
[ "Get", "syntax", "by", "its", "name", ".", "Name", "is", "defined", "in", "the", "xml", "file" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L184-L188
3,283
andreikop/qutepart
qutepart/syntax/__init__.py
SyntaxManager._getSyntaxBySourceFileName
def _getSyntaxBySourceFileName(self, name): """Get syntax by source name of file, which is going to be highlighted """ for regExp, xmlFileName in self._extensionToXmlFileName.items(): if regExp.match(name): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + name)
python
def _getSyntaxBySourceFileName(self, name): for regExp, xmlFileName in self._extensionToXmlFileName.items(): if regExp.match(name): return self._getSyntaxByXmlFileName(xmlFileName) else: raise KeyError("No syntax for " + name)
[ "def", "_getSyntaxBySourceFileName", "(", "self", ",", "name", ")", ":", "for", "regExp", ",", "xmlFileName", "in", "self", ".", "_extensionToXmlFileName", ".", "items", "(", ")", ":", "if", "regExp", ".", "match", "(", "name", ")", ":", "return", "self", ".", "_getSyntaxByXmlFileName", "(", "xmlFileName", ")", "else", ":", "raise", "KeyError", "(", "\"No syntax for \"", "+", "name", ")" ]
Get syntax by source name of file, which is going to be highlighted
[ "Get", "syntax", "by", "source", "name", "of", "file", "which", "is", "going", "to", "be", "highlighted" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L190-L197
3,284
andreikop/qutepart
qutepart/syntax/parser.py
ContextStack.pop
def pop(self, count): """Returns new context stack, which doesn't contain few levels """ if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], self._data[:1]) else: return self return ContextStack(self._contexts[:-count], self._data[:-count])
python
def pop(self, count): if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], self._data[:1]) else: return self return ContextStack(self._contexts[:-count], self._data[:-count])
[ "def", "pop", "(", "self", ",", "count", ")", ":", "if", "len", "(", "self", ".", "_contexts", ")", "-", "1", "<", "count", ":", "_logger", ".", "error", "(", "\"#pop value is too big %d\"", ",", "len", "(", "self", ".", "_contexts", ")", ")", "if", "len", "(", "self", ".", "_contexts", ")", ">", "1", ":", "return", "ContextStack", "(", "self", ".", "_contexts", "[", ":", "1", "]", ",", "self", ".", "_data", "[", ":", "1", "]", ")", "else", ":", "return", "self", "return", "ContextStack", "(", "self", ".", "_contexts", "[", ":", "-", "count", "]", ",", "self", ".", "_data", "[", ":", "-", "count", "]", ")" ]
Returns new context stack, which doesn't contain few levels
[ "Returns", "new", "context", "stack", "which", "doesn", "t", "contain", "few", "levels" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L32-L42
3,285
andreikop/qutepart
qutepart/syntax/parser.py
ContextStack.append
def append(self, context, data): """Returns new context, which contains current stack and new frame """ return ContextStack(self._contexts + [context], self._data + [data])
python
def append(self, context, data): return ContextStack(self._contexts + [context], self._data + [data])
[ "def", "append", "(", "self", ",", "context", ",", "data", ")", ":", "return", "ContextStack", "(", "self", ".", "_contexts", "+", "[", "context", "]", ",", "self", ".", "_data", "+", "[", "data", "]", ")" ]
Returns new context, which contains current stack and new frame
[ "Returns", "new", "context", "which", "contains", "current", "stack", "and", "new", "frame" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L44-L47
3,286
andreikop/qutepart
qutepart/syntax/parser.py
ContextSwitcher.getNextContextStack
def getNextContextStack(self, contextStack, data=None): """Apply modification to the contextStack. This method never modifies input parameter list """ if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: if not self._contextToSwitch.dynamic: data = None contextStack = contextStack.append(self._contextToSwitch, data) return contextStack
python
def getNextContextStack(self, contextStack, data=None): if self._popsCount: contextStack = contextStack.pop(self._popsCount) if self._contextToSwitch is not None: if not self._contextToSwitch.dynamic: data = None contextStack = contextStack.append(self._contextToSwitch, data) return contextStack
[ "def", "getNextContextStack", "(", "self", ",", "contextStack", ",", "data", "=", "None", ")", ":", "if", "self", ".", "_popsCount", ":", "contextStack", "=", "contextStack", ".", "pop", "(", "self", ".", "_popsCount", ")", "if", "self", ".", "_contextToSwitch", "is", "not", "None", ":", "if", "not", "self", ".", "_contextToSwitch", ".", "dynamic", ":", "data", "=", "None", "contextStack", "=", "contextStack", ".", "append", "(", "self", ".", "_contextToSwitch", ",", "data", ")", "return", "contextStack" ]
Apply modification to the contextStack. This method never modifies input parameter list
[ "Apply", "modification", "to", "the", "contextStack", ".", "This", "method", "never", "modifies", "input", "parameter", "list" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L72-L84
3,287
andreikop/qutepart
qutepart/syntax/parser.py
StringDetect._makeDynamicSubsctitutions
def _makeDynamicSubsctitutions(string, contextData): """For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension. """ def _replaceFunc(escapeMatchObject): stringIndex = escapeMatchObject.group(0)[1] index = int(stringIndex) if index < len(contextData): return contextData[index] else: return escapeMatchObject.group(0) # no any replacements, return original value return _numSeqReplacer.sub(_replaceFunc, string)
python
def _makeDynamicSubsctitutions(string, contextData): def _replaceFunc(escapeMatchObject): stringIndex = escapeMatchObject.group(0)[1] index = int(stringIndex) if index < len(contextData): return contextData[index] else: return escapeMatchObject.group(0) # no any replacements, return original value return _numSeqReplacer.sub(_replaceFunc, string)
[ "def", "_makeDynamicSubsctitutions", "(", "string", ",", "contextData", ")", ":", "def", "_replaceFunc", "(", "escapeMatchObject", ")", ":", "stringIndex", "=", "escapeMatchObject", ".", "group", "(", "0", ")", "[", "1", "]", "index", "=", "int", "(", "stringIndex", ")", "if", "index", "<", "len", "(", "contextData", ")", ":", "return", "contextData", "[", "index", "]", "else", ":", "return", "escapeMatchObject", ".", "group", "(", "0", ")", "# no any replacements, return original value", "return", "_numSeqReplacer", ".", "sub", "(", "_replaceFunc", ",", "string", ")" ]
For dynamic rules, replace %d patterns with actual strings Python function, which is used by C extension.
[ "For", "dynamic", "rules", "replace", "%d", "patterns", "with", "actual", "strings", "Python", "function", "which", "is", "used", "by", "C", "extension", "." ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L304-L316
3,288
andreikop/qutepart
qutepart/syntax/parser.py
RegExpr._tryMatch
def _tryMatch(self, textToMatchObject): """Tries to parse text. If matched - saves data for dynamic context """ # Special case. if pattern starts with \b, we have to check it manually, # because string is passed to .match(..) without beginning if self.wordStart and \ (not textToMatchObject.isWordStart): return None #Special case. If pattern starts with ^ - check column number manually if self.lineStart and \ textToMatchObject.currentColumnIndex > 0: return None if self.dynamic: string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData) regExp = self._compileRegExp(string, self.insensitive, self.minimal) else: regExp = self.regExp if regExp is None: return None wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text) if wholeMatch is not None: count = len(wholeMatch) return RuleTryMatchResult(self, count, groups) else: return None
python
def _tryMatch(self, textToMatchObject): # Special case. if pattern starts with \b, we have to check it manually, # because string is passed to .match(..) without beginning if self.wordStart and \ (not textToMatchObject.isWordStart): return None #Special case. If pattern starts with ^ - check column number manually if self.lineStart and \ textToMatchObject.currentColumnIndex > 0: return None if self.dynamic: string = self._makeDynamicSubsctitutions(self.string, textToMatchObject.contextData) regExp = self._compileRegExp(string, self.insensitive, self.minimal) else: regExp = self.regExp if regExp is None: return None wholeMatch, groups = self._matchPattern(regExp, textToMatchObject.text) if wholeMatch is not None: count = len(wholeMatch) return RuleTryMatchResult(self, count, groups) else: return None
[ "def", "_tryMatch", "(", "self", ",", "textToMatchObject", ")", ":", "# Special case. if pattern starts with \\b, we have to check it manually,", "# because string is passed to .match(..) without beginning", "if", "self", ".", "wordStart", "and", "(", "not", "textToMatchObject", ".", "isWordStart", ")", ":", "return", "None", "#Special case. If pattern starts with ^ - check column number manually", "if", "self", ".", "lineStart", "and", "textToMatchObject", ".", "currentColumnIndex", ">", "0", ":", "return", "None", "if", "self", ".", "dynamic", ":", "string", "=", "self", ".", "_makeDynamicSubsctitutions", "(", "self", ".", "string", ",", "textToMatchObject", ".", "contextData", ")", "regExp", "=", "self", ".", "_compileRegExp", "(", "string", ",", "self", ".", "insensitive", ",", "self", ".", "minimal", ")", "else", ":", "regExp", "=", "self", ".", "regExp", "if", "regExp", "is", "None", ":", "return", "None", "wholeMatch", ",", "groups", "=", "self", ".", "_matchPattern", "(", "regExp", ",", "textToMatchObject", ".", "text", ")", "if", "wholeMatch", "is", "not", "None", ":", "count", "=", "len", "(", "wholeMatch", ")", "return", "RuleTryMatchResult", "(", "self", ",", "count", ",", "groups", ")", "else", ":", "return", "None" ]
Tries to parse text. If matched - saves data for dynamic context
[ "Tries", "to", "parse", "text", ".", "If", "matched", "-", "saves", "data", "for", "dynamic", "context" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L400-L428
3,289
andreikop/qutepart
qutepart/syntax/parser.py
RegExpr._compileRegExp
def _compileRegExp(string, insensitive, minimal): """Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE """ flags = 0 if insensitive: flags = re.IGNORECASE string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser string = string.replace('[:digit:]', '\\d') string = string.replace('[:blank:]', '\\s') try: return re.compile(string, flags) except (re.error, AssertionError) as ex: _logger.warning("Invalid pattern '%s': %s", string, str(ex)) return None
python
def _compileRegExp(string, insensitive, minimal): flags = 0 if insensitive: flags = re.IGNORECASE string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser string = string.replace('[:digit:]', '\\d') string = string.replace('[:blank:]', '\\s') try: return re.compile(string, flags) except (re.error, AssertionError) as ex: _logger.warning("Invalid pattern '%s': %s", string, str(ex)) return None
[ "def", "_compileRegExp", "(", "string", ",", "insensitive", ",", "minimal", ")", ":", "flags", "=", "0", "if", "insensitive", ":", "flags", "=", "re", ".", "IGNORECASE", "string", "=", "string", ".", "replace", "(", "'[_[:alnum:]]'", ",", "'[\\\\w\\\\d]'", ")", "# ad-hoc fix for C++ parser", "string", "=", "string", ".", "replace", "(", "'[:digit:]'", ",", "'\\\\d'", ")", "string", "=", "string", ".", "replace", "(", "'[:blank:]'", ",", "'\\\\s'", ")", "try", ":", "return", "re", ".", "compile", "(", "string", ",", "flags", ")", "except", "(", "re", ".", "error", ",", "AssertionError", ")", "as", "ex", ":", "_logger", ".", "warning", "(", "\"Invalid pattern '%s': %s\"", ",", "string", ",", "str", "(", "ex", ")", ")", "return", "None" ]
Compile regular expression. Python function, used by C code NOTE minimal flag is not supported here, but supported on PCRE
[ "Compile", "regular", "expression", ".", "Python", "function", "used", "by", "C", "code" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L447-L465
3,290
andreikop/qutepart
qutepart/syntax/parser.py
AbstractNumberRule._countDigits
def _countDigits(self, text): """Count digits at start of text """ index = 0 while index < len(text): if not text[index].isdigit(): break index += 1 return index
python
def _countDigits(self, text): index = 0 while index < len(text): if not text[index].isdigit(): break index += 1 return index
[ "def", "_countDigits", "(", "self", ",", "text", ")", ":", "index", "=", "0", "while", "index", "<", "len", "(", "text", ")", ":", "if", "not", "text", "[", "index", "]", ".", "isdigit", "(", ")", ":", "break", "index", "+=", "1", "return", "index" ]
Count digits at start of text
[ "Count", "digits", "at", "start", "of", "text" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L518-L526
3,291
andreikop/qutepart
qutepart/syntax/parser.py
Parser.highlightBlock
def highlightBlock(self, text, prevContextStack): """Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters """ if prevContextStack is not None: contextStack = prevContextStack else: contextStack = self._defaultContextStack highlightedSegments = [] lineContinue = False currentColumnIndex = 0 textTypeMap = [] if len(text) > 0: while currentColumnIndex < len(text): _logger.debug('In context %s', contextStack.currentContext().name) length, newContextStack, segments, textTypeMapPart, lineContinue = \ contextStack.currentContext().parseBlock(contextStack, currentColumnIndex, text) highlightedSegments += segments contextStack = newContextStack textTypeMap += textTypeMapPart currentColumnIndex += length if not lineContinue: while contextStack.currentContext().lineEndContext is not None: oldStack = contextStack contextStack = contextStack.currentContext().lineEndContext.getNextContextStack(contextStack) if oldStack == contextStack: # avoid infinite while loop if nothing to switch break # this code is not tested, because lineBeginContext is not defined by any xml file if contextStack.currentContext().lineBeginContext is not None: contextStack = contextStack.currentContext().lineBeginContext.getNextContextStack(contextStack) elif contextStack.currentContext().lineEmptyContext is not None: contextStack = contextStack.currentContext().lineEmptyContext.getNextContextStack(contextStack) lineData = (contextStack, textTypeMap) return lineData, highlightedSegments
python
def highlightBlock(self, text, prevContextStack): if prevContextStack is not None: contextStack = prevContextStack else: contextStack = self._defaultContextStack highlightedSegments = [] lineContinue = False currentColumnIndex = 0 textTypeMap = [] if len(text) > 0: while currentColumnIndex < len(text): _logger.debug('In context %s', contextStack.currentContext().name) length, newContextStack, segments, textTypeMapPart, lineContinue = \ contextStack.currentContext().parseBlock(contextStack, currentColumnIndex, text) highlightedSegments += segments contextStack = newContextStack textTypeMap += textTypeMapPart currentColumnIndex += length if not lineContinue: while contextStack.currentContext().lineEndContext is not None: oldStack = contextStack contextStack = contextStack.currentContext().lineEndContext.getNextContextStack(contextStack) if oldStack == contextStack: # avoid infinite while loop if nothing to switch break # this code is not tested, because lineBeginContext is not defined by any xml file if contextStack.currentContext().lineBeginContext is not None: contextStack = contextStack.currentContext().lineBeginContext.getNextContextStack(contextStack) elif contextStack.currentContext().lineEmptyContext is not None: contextStack = contextStack.currentContext().lineEmptyContext.getNextContextStack(contextStack) lineData = (contextStack, textTypeMap) return lineData, highlightedSegments
[ "def", "highlightBlock", "(", "self", ",", "text", ",", "prevContextStack", ")", ":", "if", "prevContextStack", "is", "not", "None", ":", "contextStack", "=", "prevContextStack", "else", ":", "contextStack", "=", "self", ".", "_defaultContextStack", "highlightedSegments", "=", "[", "]", "lineContinue", "=", "False", "currentColumnIndex", "=", "0", "textTypeMap", "=", "[", "]", "if", "len", "(", "text", ")", ">", "0", ":", "while", "currentColumnIndex", "<", "len", "(", "text", ")", ":", "_logger", ".", "debug", "(", "'In context %s'", ",", "contextStack", ".", "currentContext", "(", ")", ".", "name", ")", "length", ",", "newContextStack", ",", "segments", ",", "textTypeMapPart", ",", "lineContinue", "=", "contextStack", ".", "currentContext", "(", ")", ".", "parseBlock", "(", "contextStack", ",", "currentColumnIndex", ",", "text", ")", "highlightedSegments", "+=", "segments", "contextStack", "=", "newContextStack", "textTypeMap", "+=", "textTypeMapPart", "currentColumnIndex", "+=", "length", "if", "not", "lineContinue", ":", "while", "contextStack", ".", "currentContext", "(", ")", ".", "lineEndContext", "is", "not", "None", ":", "oldStack", "=", "contextStack", "contextStack", "=", "contextStack", ".", "currentContext", "(", ")", ".", "lineEndContext", ".", "getNextContextStack", "(", "contextStack", ")", "if", "oldStack", "==", "contextStack", ":", "# avoid infinite while loop if nothing to switch", "break", "# this code is not tested, because lineBeginContext is not defined by any xml file", "if", "contextStack", ".", "currentContext", "(", ")", ".", "lineBeginContext", "is", "not", "None", ":", "contextStack", "=", "contextStack", ".", "currentContext", "(", ")", ".", "lineBeginContext", ".", "getNextContextStack", "(", "contextStack", ")", "elif", "contextStack", ".", "currentContext", "(", ")", ".", "lineEmptyContext", "is", "not", "None", ":", "contextStack", "=", "contextStack", ".", "currentContext", "(", ")", ".", "lineEmptyContext", ".", "getNextContextStack", "(", "contextStack", ")", "lineData", "=", "(", "contextStack", ",", "textTypeMap", ")", "return", "lineData", ",", "highlightedSegments" ]
Parse block and return ParseBlockFullResult return (lineData, highlightedSegments) where lineData is (contextStack, textTypeMap) where textTypeMap is a string of textType characters
[ "Parse", "block", "and", "return", "ParseBlockFullResult" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L948-L991
3,292
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.findLeftBrace
def findLeftBrace(self, block, column): """Search for a corresponding '{' and return its indentation If not found return None """ block, column = self.findBracketBackward(block, column, '{') # raise ValueError if not found try: block, column = self.tryParenthesisBeforeBrace(block, column) except ValueError: pass # leave previous values return self._blockIndent(block)
python
def findLeftBrace(self, block, column): block, column = self.findBracketBackward(block, column, '{') # raise ValueError if not found try: block, column = self.tryParenthesisBeforeBrace(block, column) except ValueError: pass # leave previous values return self._blockIndent(block)
[ "def", "findLeftBrace", "(", "self", ",", "block", ",", "column", ")", ":", "block", ",", "column", "=", "self", ".", "findBracketBackward", "(", "block", ",", "column", ",", "'{'", ")", "# raise ValueError if not found", "try", ":", "block", ",", "column", "=", "self", ".", "tryParenthesisBeforeBrace", "(", "block", ",", "column", ")", "except", "ValueError", ":", "pass", "# leave previous values", "return", "self", ".", "_blockIndent", "(", "block", ")" ]
Search for a corresponding '{' and return its indentation If not found return None
[ "Search", "for", "a", "corresponding", "{", "and", "return", "its", "indentation", "If", "not", "found", "return", "None" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L66-L76
3,293
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.trySwitchStatement
def trySwitchStatement(self, block): """Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found. """ if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): return None for block in self.iterateBlocksBackFrom(block.previous()): text = block.text() if re.match(r"^\s*(default\s*|case\b.*):", text): dbg("trySwitchStatement: success in line %d" % block.blockNumber()) return self._lineIndent(text) elif re.match(r"^\s*switch\b", text): if CFG_INDENT_CASE: return self._increaseIndent(self._lineIndent(text)) else: return self._lineIndent(text) return None
python
def trySwitchStatement(self, block): if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): return None for block in self.iterateBlocksBackFrom(block.previous()): text = block.text() if re.match(r"^\s*(default\s*|case\b.*):", text): dbg("trySwitchStatement: success in line %d" % block.blockNumber()) return self._lineIndent(text) elif re.match(r"^\s*switch\b", text): if CFG_INDENT_CASE: return self._increaseIndent(self._lineIndent(text)) else: return self._lineIndent(text) return None
[ "def", "trySwitchStatement", "(", "self", ",", "block", ")", ":", "if", "not", "re", ".", "match", "(", "r'^\\s*(default\\s*|case\\b.*):'", ",", "block", ".", "text", "(", ")", ")", ":", "return", "None", "for", "block", "in", "self", ".", "iterateBlocksBackFrom", "(", "block", ".", "previous", "(", ")", ")", ":", "text", "=", "block", ".", "text", "(", ")", "if", "re", ".", "match", "(", "r\"^\\s*(default\\s*|case\\b.*):\"", ",", "text", ")", ":", "dbg", "(", "\"trySwitchStatement: success in line %d\"", "%", "block", ".", "blockNumber", "(", ")", ")", "return", "self", ".", "_lineIndent", "(", "text", ")", "elif", "re", ".", "match", "(", "r\"^\\s*switch\\b\"", ",", "text", ")", ":", "if", "CFG_INDENT_CASE", ":", "return", "self", ".", "_increaseIndent", "(", "self", ".", "_lineIndent", "(", "text", ")", ")", "else", ":", "return", "self", ".", "_lineIndent", "(", "text", ")", "return", "None" ]
Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found.
[ "Check", "for", "default", "and", "case", "keywords", "and", "assume", "we", "are", "in", "a", "switch", "statement", ".", "Try", "to", "find", "a", "previous", "default", "case", "or", "switch", "and", "return", "its", "indentation", "or", "None", "if", "not", "found", "." ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L90-L109
3,294
andreikop/qutepart
qutepart/indenter/cstyle.py
IndentAlgCStyle.indentLine
def indentLine(self, block, autoIndent): """ Indent line. Return filler or null. """ indent = None if indent is None: indent = self.tryMatchedAnchor(block, autoIndent) if indent is None: indent = self.tryCComment(block) if indent is None and not autoIndent: indent = self.tryCppComment(block) if indent is None: indent = self.trySwitchStatement(block) if indent is None: indent = self.tryAccessModifiers(block) if indent is None: indent = self.tryBrace(block) if indent is None: indent = self.tryCKeywords(block, block.text().lstrip().startswith('{')) if indent is None: indent = self.tryCondition(block) if indent is None: indent = self.tryStatement(block) if indent is not None: return indent else: dbg("Nothing matched") return self._prevNonEmptyBlockIndent(block)
python
def indentLine(self, block, autoIndent): indent = None if indent is None: indent = self.tryMatchedAnchor(block, autoIndent) if indent is None: indent = self.tryCComment(block) if indent is None and not autoIndent: indent = self.tryCppComment(block) if indent is None: indent = self.trySwitchStatement(block) if indent is None: indent = self.tryAccessModifiers(block) if indent is None: indent = self.tryBrace(block) if indent is None: indent = self.tryCKeywords(block, block.text().lstrip().startswith('{')) if indent is None: indent = self.tryCondition(block) if indent is None: indent = self.tryStatement(block) if indent is not None: return indent else: dbg("Nothing matched") return self._prevNonEmptyBlockIndent(block)
[ "def", "indentLine", "(", "self", ",", "block", ",", "autoIndent", ")", ":", "indent", "=", "None", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryMatchedAnchor", "(", "block", ",", "autoIndent", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryCComment", "(", "block", ")", "if", "indent", "is", "None", "and", "not", "autoIndent", ":", "indent", "=", "self", ".", "tryCppComment", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "trySwitchStatement", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryAccessModifiers", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryBrace", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryCKeywords", "(", "block", ",", "block", ".", "text", "(", ")", ".", "lstrip", "(", ")", ".", "startswith", "(", "'{'", ")", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryCondition", "(", "block", ")", "if", "indent", "is", "None", ":", "indent", "=", "self", ".", "tryStatement", "(", "block", ")", "if", "indent", "is", "not", "None", ":", "return", "indent", "else", ":", "dbg", "(", "\"Nothing matched\"", ")", "return", "self", ".", "_prevNonEmptyBlockIndent", "(", "block", ")" ]
Indent line. Return filler or null.
[ "Indent", "line", ".", "Return", "filler", "or", "null", "." ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/cstyle.py#L540-L568
3,295
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme._findExpressionEnd
def _findExpressionEnd(self, block): """Find end of the last expression """ while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
python
def _findExpressionEnd(self, block): while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
[ "def", "_findExpressionEnd", "(", "self", ",", "block", ")", ":", "while", "block", ".", "isValid", "(", ")", ":", "column", "=", "self", ".", "_lastColumn", "(", "block", ")", "if", "column", ">", "0", ":", "return", "block", ",", "column", "block", "=", "block", ".", "previous", "(", ")", "raise", "UserWarning", "(", ")" ]
Find end of the last expression
[ "Find", "end", "of", "the", "last", "expression" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L15-L23
3,296
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme._lastWord
def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: return text
python
def _lastWord(self, text): for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: return text
[ "def", "_lastWord", "(", "self", ",", "text", ")", ":", "for", "index", ",", "char", "in", "enumerate", "(", "text", "[", ":", ":", "-", "1", "]", ")", ":", "if", "char", ".", "isspace", "(", ")", "or", "char", "in", "(", "'('", ",", "')'", ")", ":", "return", "text", "[", "len", "(", "text", ")", "-", "index", ":", "]", "else", ":", "return", "text" ]
Move backward to the start of the word at the end of a string. Return the word
[ "Move", "backward", "to", "the", "start", "of", "the", "word", "at", "the", "end", "of", "a", "string", ".", "Return", "the", "word" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L25-L34
3,297
andreikop/qutepart
qutepart/indenter/scheme.py
IndentAlgScheme._findExpressionStart
def _findExpressionStart(self, block): """Find start of not finished expression Raise UserWarning, if not found """ # raise expession on next level, if not found expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] if text.endswith(')'): try: return self.findBracketBackward(expEndBlock, expEndColumn, '(') except ValueError: raise UserWarning() else: return expEndBlock, len(text) - len(self._lastWord(text))
python
def _findExpressionStart(self, block): # raise expession on next level, if not found expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] if text.endswith(')'): try: return self.findBracketBackward(expEndBlock, expEndColumn, '(') except ValueError: raise UserWarning() else: return expEndBlock, len(text) - len(self._lastWord(text))
[ "def", "_findExpressionStart", "(", "self", ",", "block", ")", ":", "# raise expession on next level, if not found", "expEndBlock", ",", "expEndColumn", "=", "self", ".", "_findExpressionEnd", "(", "block", ")", "text", "=", "expEndBlock", ".", "text", "(", ")", "[", ":", "expEndColumn", "+", "1", "]", "if", "text", ".", "endswith", "(", "')'", ")", ":", "try", ":", "return", "self", ".", "findBracketBackward", "(", "expEndBlock", ",", "expEndColumn", ",", "'('", ")", "except", "ValueError", ":", "raise", "UserWarning", "(", ")", "else", ":", "return", "expEndBlock", ",", "len", "(", "text", ")", "-", "len", "(", "self", ".", "_lastWord", "(", "text", ")", ")" ]
Find start of not finished expression Raise UserWarning, if not found
[ "Find", "start", "of", "not", "finished", "expression", "Raise", "UserWarning", "if", "not", "found" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/scheme.py#L36-L51
3,298
andreikop/qutepart
qutepart/indenter/__init__.py
_getSmartIndenter
def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter)
python
def _getSmartIndenter(indenterName, qpart, indenter): indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter)
[ "def", "_getSmartIndenter", "(", "indenterName", ",", "qpart", ",", "indenter", ")", ":", "indenterName", "=", "indenterName", ".", "lower", "(", ")", "if", "indenterName", "in", "(", "'haskell'", ",", "'lilypond'", ")", ":", "# not supported yet", "logger", ".", "warning", "(", "'Smart indentation for %s not supported yet. But you could be a hero who implemented it'", "%", "indenterName", ")", "from", "qutepart", ".", "indenter", ".", "base", "import", "IndentAlgNormal", "as", "indenterClass", "elif", "'none'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "base", "import", "IndentAlgBase", "as", "indenterClass", "elif", "'normal'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "base", "import", "IndentAlgNormal", "as", "indenterClass", "elif", "'cstyle'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "cstyle", "import", "IndentAlgCStyle", "as", "indenterClass", "elif", "'python'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "python", "import", "IndentAlgPython", "as", "indenterClass", "elif", "'ruby'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "ruby", "import", "IndentAlgRuby", "as", "indenterClass", "elif", "'xml'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "xmlindent", "import", "IndentAlgXml", "as", "indenterClass", "elif", "'haskell'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "haskell", "import", "IndenterHaskell", "as", "indenterClass", "elif", "'lilypond'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "lilypond", "import", "IndenterLilypond", "as", "indenterClass", "elif", "'lisp'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "lisp", "import", "IndentAlgLisp", "as", "indenterClass", "elif", "'scheme'", "==", "indenterName", ":", "from", "qutepart", ".", "indenter", ".", "scheme", "import", "IndentAlgScheme", "as", "indenterClass", "else", ":", "raise", "KeyError", "(", "\"Indenter %s not found\"", "%", "indenterName", ")", "return", "indenterClass", "(", "qpart", ",", "indenter", ")" ]
Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols
[ "Get", "indenter", "by", "name", ".", "Available", "indenters", "are", "none", "normal", "cstyle", "haskell", "lilypond", "lisp", "python", "ruby", "xml", "Indenter", "name", "is", "not", "case", "sensitive", "Raise", "KeyError", "if", "not", "found", "indentText", "is", "indentation", "which", "shall", "be", "used", ".", "i", ".", "e", ".", "\\", "t", "for", "tabs", "for", "4", "space", "symbols" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L13-L48
3,299
andreikop/qutepart
qutepart/indenter/__init__.py
Indenter.autoIndentBlock
def autoIndentBlock(self, block, char='\n'): """Indent block after Enter pressed or trigger character typed """ currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent)
python
def autoIndentBlock(self, block, char='\n'): currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent)
[ "def", "autoIndentBlock", "(", "self", ",", "block", ",", "char", "=", "'\\n'", ")", ":", "currentText", "=", "block", ".", "text", "(", ")", "spaceAtStartLen", "=", "len", "(", "currentText", ")", "-", "len", "(", "currentText", ".", "lstrip", "(", ")", ")", "currentIndent", "=", "currentText", "[", ":", "spaceAtStartLen", "]", "indent", "=", "self", ".", "_smartIndenter", ".", "computeIndent", "(", "block", ",", "char", ")", "if", "indent", "is", "not", "None", "and", "indent", "!=", "currentIndent", ":", "self", ".", "_qpart", ".", "replaceText", "(", "block", ".", "position", "(", ")", ",", "spaceAtStartLen", ",", "indent", ")" ]
Indent block after Enter pressed or trigger character typed
[ "Indent", "block", "after", "Enter", "pressed", "or", "trigger", "character", "typed" ]
109d76b239751318bcef06f39b2fbbf18687a40b
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/indenter/__init__.py#L85-L93