_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q3200
JsonMarshaler.emit_map
train
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
{ "resource": "" }
q3201
Decoder.decode_list
train
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
{ "resource": "" }
q3202
Decoder.decode_string
train
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
{ "resource": "" }
q3203
UuidHandler.from_rep
train
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
{ "resource": "" }
q3204
PacketIn.in_port
train
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
{ "resource": "" }
q3205
PacketOut._update_actions_len
train
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
{ "resource": "" }
q3206
PacketOut._validate_in_port
train
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
{ "resource": "" }
q3207
new_message_from_message_type
train
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
{ "resource": "" }
q3208
new_message_from_header
train
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
{ "resource": "" }
q3209
unpack_message
train
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
{ "resource": "" }
q3210
MultipartReply._unpack_body
train
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
{ "resource": "" }
q3211
OxmTLV.unpack
train
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
{ "resource": "" }
q3212
OxmTLV._unpack_oxm_field
train
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
{ "resource": "" }
q3213
OxmTLV._update_length
train
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
{ "resource": "" }
q3214
OxmTLV.pack
train
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
{ "resource": "" }
q3215
OxmTLV._get_oxm_field_int
train
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
{ "resource": "" }
q3216
Match.pack
train
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
{ "resource": "" }
q3217
Match.unpack
train
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
{ "resource": "" }
q3218
Match.get_field
train
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
{ "resource": "" }
q3219
GenericType.value
train
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
{ "resource": "" }
q3220
GenericType.pack
train
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
{ "resource": "" }
q3221
MetaStruct._header_message_type_update
train
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
{ "resource": "" }
q3222
MetaStruct.get_pyof_version
train
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
{ "resource": "" }
q3223
MetaStruct.replace_pyof_version
train
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
{ "resource": "" }
q3224
MetaStruct.get_pyof_obj_new_version
train
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
{ "resource": "" }
q3225
GenericStruct._validate_attributes_type
train
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
{ "resource": "" }
q3226
GenericStruct.get_class_attributes
train
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
{ "resource": "" }
q3227
GenericStruct._get_instance_attributes
train
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
{ "resource": "" }
q3228
GenericStruct._get_attributes
train
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
{ "resource": "" }
q3229
GenericStruct._get_named_attributes
train
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
{ "resource": "" }
q3230
GenericStruct.get_size
train
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
{ "resource": "" }
q3231
GenericMessage.pack
train
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
{ "resource": "" }
q3232
GenericBitMask.names
train
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
{ "resource": "" }
q3233
Match.fill_wildcards
train
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
{ "resource": "" }
q3234
ActionSetField.pack
train
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
{ "resource": "" }
q3235
ActionSetField._update_length
train
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
{ "resource": "" }
q3236
VLAN._validate
train
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
{ "resource": "" }
q3237
Ethernet._get_vlan_length
train
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
{ "resource": "" }
q3238
GenericTLV.pack
train
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
{ "resource": "" }
q3239
GenericTLV.get_size
train
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
{ "resource": "" }
q3240
IPv4._update_checksum
train
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
{ "resource": "" }
q3241
TLVWithSubType.value
train
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
{ "resource": "" }
q3242
validate_packet
train
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
{ "resource": "" }
q3243
unpack
train
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
{ "resource": "" }
q3244
ErrorMsg.unpack
train
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
{ "resource": "" }
q3245
Bookmarks._createAction
train
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
{ "resource": "" }
q3246
Bookmarks.clear
train
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
{ "resource": "" }
q3247
BracketHighlighter._makeMatchSelection
train
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
{ "resource": "" }
q3248
BracketHighlighter._highlightBracket
train
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
{ "resource": "" }
q3249
BracketHighlighter.extraSelections
train
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
{ "resource": "" }
q3250
_cmpFormatRanges
train
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
{ "resource": "" }
q3251
SyntaxHighlighter.isCode
train
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
{ "resource": "" }
q3252
SyntaxHighlighter.isComment
train
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
{ "resource": "" }
q3253
SyntaxHighlighter.isBlockComment
train
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
{ "resource": "" }
q3254
SyntaxHighlighter.isHereDoc
train
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
{ "resource": "" }
q3255
Lines._atomicModification
train
def _atomicModification(func): """Decorator Make document modification atomic """ def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
python
{ "resource": "" }
q3256
Lines._checkAndConvertIndex
train
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
{ "resource": "" }
q3257
Lines.append
train
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
python
{ "resource": "" }
q3258
Lines.insert
train
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
{ "resource": "" }
q3259
IndentAlgRuby._isLastCodeColumn
train
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
{ "resource": "" }
q3260
IndentAlgRuby.findStmtStart
train
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
{ "resource": "" }
q3261
IndentAlgRuby._isValidTrigger
train
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
{ "resource": "" }
q3262
IndentAlgRuby.findPrevStmt
train
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
{ "resource": "" }
q3263
HTMLDelegate.paint
train
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
{ "resource": "" }
q3264
RectangularSelection.isDeleteKeyEvent
train
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
{ "resource": "" }
q3265
RectangularSelection.delete
train
def delete(self): """Del or Backspace pressed. Delete selection""" with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
python
{ "resource": "" }
q3266
RectangularSelection.isExpandKeyEvent
train
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
{ "resource": "" }
q3267
RectangularSelection.onExpandKeyEvent
train
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
{ "resource": "" }
q3268
RectangularSelection._realToVisibleColumn
train
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
{ "resource": "" }
q3269
RectangularSelection._visibleToRealColumn
train
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
{ "resource": "" }
q3270
RectangularSelection.cursors
train
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
{ "resource": "" }
q3271
RectangularSelection.selections
train
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
{ "resource": "" }
q3272
RectangularSelection.copy
train
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
{ "resource": "" }
q3273
RectangularSelection.cut
train
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
{ "resource": "" }
q3274
RectangularSelection._indentUpTo
train
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
{ "resource": "" }
q3275
RectangularSelection.paste
train
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
{ "resource": "" }
q3276
MarginBase.__allocateBits
train
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
{ "resource": "" }
q3277
MarginBase.__updateRequest
train
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
{ "resource": "" }
q3278
MarginBase.setBlockValue
train
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
{ "resource": "" }
q3279
MarginBase.getBlockValue
train
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
{ "resource": "" }
q3280
MarginBase.clear
train
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
{ "resource": "" }
q3281
SyntaxManager._getSyntaxByXmlFileName
train
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
{ "resource": "" }
q3282
SyntaxManager._getSyntaxByLanguageName
train
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
{ "resource": "" }
q3283
SyntaxManager._getSyntaxBySourceFileName
train
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
{ "resource": "" }
q3284
ContextStack.pop
train
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
{ "resource": "" }
q3285
ContextStack.append
train
def append(self, context, data): """Returns new context, which contains current stack and new frame """ return ContextStack(self._contexts + [context], self._data + [data])
python
{ "resource": "" }
q3286
ContextSwitcher.getNextContextStack
train
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
{ "resource": "" }
q3287
StringDetect._makeDynamicSubsctitutions
train
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
{ "resource": "" }
q3288
RegExpr._tryMatch
train
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
{ "resource": "" }
q3289
RegExpr._compileRegExp
train
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
{ "resource": "" }
q3290
AbstractNumberRule._countDigits
train
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
{ "resource": "" }
q3291
Parser.highlightBlock
train
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
{ "resource": "" }
q3292
IndentAlgCStyle.findLeftBrace
train
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
{ "resource": "" }
q3293
IndentAlgCStyle.trySwitchStatement
train
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
{ "resource": "" }
q3294
IndentAlgCStyle.indentLine
train
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
{ "resource": "" }
q3295
IndentAlgScheme._findExpressionEnd
train
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
{ "resource": "" }
q3296
IndentAlgScheme._lastWord
train
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
{ "resource": "" }
q3297
IndentAlgScheme._findExpressionStart
train
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
{ "resource": "" }
q3298
_getSmartIndenter
train
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
{ "resource": "" }
q3299
Indenter.autoIndentBlock
train
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
{ "resource": "" }