Instruction:
Can you tell what is the following Python 3 function doing
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

Response: Unpack oxm_field from oxm_field_and_mask.


Instruction:
Can you implement a function in Python 3 that
updates the length field with the packed version of the packed version of the data.

Response:
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)


Instruction:
How would you implement a function in Python 3 that
packs the object into a byte string.

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
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

Response: Return a valid integer value for oxm_field. Used while packing.


Instruction:
How would you explain what the following Python 3 function does
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}".')

Response: Pack and complete the last byte by padding.


Instruction:
Explain what the following Python 3 code does
def _complete_last_byte(self, packet):
        padded_size = self.get_size()
        padding_bytes = padded_size - len(packet)
        if padding_bytes > 0:
            packet += Pad(padding_bytes).pack()
        return packet

Response: Pad until the packet length is a multiple of 8 ( bytes.


Instruction:
Can you tell what is the following Python 3 function doing
def get_size(self, value=None):
        if isinstance(value, Match):
            return value.get_size()
        elif value is None:
            current_size = super().get_size()
            return ceil(current_size / 8) * 8
        raise ValueError(f'Invalid value "{value}" for Match.get_size()')

Response: Return the packet length including the padding.


Instruction:
Write a Python 3 script for
unpacking the class attributes from a buffer.

Response:
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)


Instruction:
How would you implement a function in Python 3 that
returns the value for the field_type field in oxm_match_fields.

Response:
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


Instruction:
Can you implement a function in Python 3 that
returns this type s value.

Response:
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


Instruction:
How would you code a function in Python 3 to
unpack the contents of the buffer into the object.

Response:
def unpack(self, buff, offset=0):
        """Unpack *buff* into this object.

        This method will convert a binary data into a readable value according
        to the attribute format.

        Args:
            buff (bytes): Binary buffer.
            offset (int): Where to begin unpacking.

        Raises:
            :exc:`~.exceptions.UnpackException`: If unpack fails.

        """
        try:
            self._value = struct.unpack_from(self._fmt, buff, offset)[0]
            if self.enum_ref:
                self._value = self.enum_ref(self._value)
        except (struct.error, TypeError, ValueError) as exception:
            msg = '{}; fmt = {}, buff = {}, offset = {}.'.format(exception,
                                                                 self._fmt,
                                                                 buff, offset)
            raise UnpackException(msg)


Instruction:
How would you implement a function in Python 3 that
updates the message type of the header.

Response:
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)


Instruction:
Explain what the following Python 3 code does
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

Response: Get the module pyof version based on the module fullname.


Instruction:
Explain what the following Python 3 code does
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)

Response: Replaces the OF Version of a module fullname with a new version.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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)

Response: r This method returns a class attribute on a different pyof version.


Instruction:
Write a Python 3 script for
validating the type of each attribute.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
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)

Response: Return a generator for class attributes names and values.


Instruction:
Write a Python 3 function for
returning a generator for instance attributes name and value.

Response:
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)


Instruction:
How would you code a function in Python 3 to
return a generator for instance and class attribute.

Response:
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())


Instruction:
Write a Python 3 function for
returning generator for attribute s name instance and class values.

Response:
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


Instruction:
Can you write a function in Python 3 where it
calculates the total size in bytes.

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
def pack(self, value=None):
        if value is None:
            if not self.is_valid():
                error_msg = "Error on validation prior to pack() on class "
                error_msg += "{}.".format(type(self).__name__)
                raise ValidationError(error_msg)
            else:
                message = b''
                # pylint: disable=no-member
                for attr_info in self._get_named_attributes():
                    name, instance_value, class_value = attr_info
                    try:
                        message += class_value.pack(instance_value)
                    except PackException as pack_exception:
                        cls = type(self).__name__
                        msg = f'{cls}.{name} - {pack_exception}'
                        raise PackException(msg)
                return message
        elif isinstance(value, type(self)):
            return value.pack()
        else:
            msg = "{} is not an instance of {}".format(value,
                                                       type(self).__name__)
            raise PackException(msg)

Response: Pack the struct into a binary representation.


Instruction:
Implement a function in Python 3 to
pack the message into a binary data.

Response:
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)


Instruction:
Write a Python 3 script to
unpack a binary message into this object s attributes based .

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary message into this object's attributes.

        Unpack the binary value *buff* and update this object attributes based
        on the results. It is an inplace method and it receives the binary data
        of the message **without the header**.

        Args:
            buff (bytes): Binary data package to be unpacked, without the
                header.
            offset (int): Where to begin unpacking.
        """
        begin = offset
        for name, value in self.get_class_attributes():
            if type(value).__name__ != "Header":
                size = self._unpack_attribute(name, value, buff, begin)
                begin += size


Instruction:
Write a Python 3 script for
listing of selected enum names.

Response:
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


Instruction:
Create a Python 3 function for
unpacking a binary message into this object s attributes based on the results.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary message into this object's attributes.

        Unpack the binary value *buff* and update this object attributes based
        on the results.

        Args:
            buff (bytes): Binary data package to be unpacked.
            offset (int): Where to begin unpacking.

        Raises:
            Exception: If there is a struct unpacking error.

        """
        self.action_type = UBInt16(enum_ref=ActionType)
        self.action_type.unpack(buff, offset)

        for cls in ActionHeader.__subclasses__():
            if self.action_type.value in cls.get_allowed_types():
                self.__class__ = cls
                break

        super().unpack(buff, offset)


Instruction:
Can you create a Python 3 function that
returns the body instance.

Response:
def _get_body_instance(self):
        """Return the body instance."""
        simple_body = {
            MultipartType.OFPMP_FLOW: FlowStatsRequest,
            MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest,
            MultipartType.OFPMP_PORT_STATS: PortStatsRequest,
            MultipartType.OFPMP_QUEUE: QueueStatsRequest,
            MultipartType.OFPMP_GROUP: GroupStatsRequest,
            MultipartType.OFPMP_METER: MeterMultipartRequest,
            MultipartType.OFPMP_EXPERIMENTER: ExperimenterMultipartHeader
        }

        array_of_bodies = {MultipartType.OFPMP_TABLE_FEATURES: TableFeatures}

        if isinstance(self.multipart_type, UBInt16):
            self.multipart_type = self.multipart_type.enum_ref(
                self.multipart_type.value)

        pyof_class = simple_body.get(self.multipart_type, None)
        if pyof_class:
            return pyof_class()

        array_of_class = array_of_bodies.get(self.multipart_type, None)
        if array_of_class:
            return FixedTypeList(pyof_class=array_of_class)

        return BinaryData(b'')


Instruction:
How would you code a function in Python 3 to
pack a StatsReply using the object s attributes.

Response:
def pack(self, value=None):
        """Pack a StatsReply using the object's attributes.

        This method will pack the attribute body and body_type before pack the
        StatsReply object, then will return this struct as a binary data.

        Returns:
            bytes: Binary data with StatsReply packed.

        """
        buff = self.body
        if not value:
            value = self.body

        if value and hasattr(value, 'pack'):
            self.body = BinaryData(value.pack())
        stats_reply_packed = super().pack()

        self.body = buff
        return stats_reply_packed


Instruction:
Can you tell what is the following Python 3 function doing
def _get_body_instance(self):
        pyof_class = self._get_body_class()

        if pyof_class is None:
            return BinaryData(b'')
        elif pyof_class is DescStats:
            return pyof_class()

        return FixedTypeList(pyof_class=pyof_class)

Response: Return the body instance.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unpack(self, buff, offset=0):
        super().unpack(buff, offset)
        self.wildcards = UBInt32(value=FlowWildCards.OFPFW_ALL,
                                 enum_ref=FlowWildCards)
        self.wildcards.unpack(buff, offset)

Response: Unpack the contents of the n - tuple into this object.


Instruction:
Explain what the following Python 3 code does
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

Response: This method updates the wildcard attribute of the current instance.


Instruction:
Implement a function in Python 3 to
pack the value as a binary representation.

Response:
def pack(self, value=None):
        """Pack the value as a binary representation.

        Returns:
            bytes: The binary representation.

        Raises:
            struct.error: If the value does not fit the binary format.

        """
        if isinstance(value, type(self)):
            return value.pack()
        if value is None:
            value = self._value
        return struct.pack('!8B', *[int(v, 16) for v in value.split(':')])


Instruction:
Create a Python 3 function for
unpacking a binary message into this object s attributes based on the contents of the buffer buff and update the attributes based on the results.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary message into this object's attributes.

        Unpack the binary value *buff* and update this object attributes based
        on the results.

        Args:
            buff (bytes): Binary data package to be unpacked.
            offset (int): Where to begin unpacking.

        Raises:
            Exception: If there is a struct unpacking error.

        """
        begin = offset
        hexas = []
        while begin < offset + 8:
            number = struct.unpack("!B", buff[begin:begin+1])[0]
            hexas.append("%.2x" % number)
            begin += 1
        self._value = ':'.join(hexas)


Instruction:
Write a Python 3 function for
packing the value as a binary representation.

Response:
def pack(self, value=None):
        """Pack the value as a binary representation.

        Returns:
            bytes: The binary representation.

        Raises:
            struct.error: If the value does not fit the binary format.

        """
        if isinstance(value, type(self)):
            return value.pack()

        try:
            if value is None:
                value = self.value
            packed = struct.pack(self._fmt, bytes(value, 'ascii'))
            return packed[:-1] + b'\0'  # null-terminated
        except struct.error as err:
            msg = "Char Pack error. "
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
                                                         err)
            raise exceptions.PackException(msg)


Instruction:
How would you code a function in Python 3 to
unpack a binary message into this object s attributes based on the contents of the buffer buff.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary message into this object's attributes.

        Unpack the binary value *buff* and update this object attributes based
        on the results.

        Args:
            buff (bytes): Binary data package to be unpacked.
            offset (int): Where to begin unpacking.

        Raises:
            Exception: If there is a struct unpacking error.

        """
        try:
            begin = offset
            end = begin + self.length
            unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0]
        except struct.error:
            raise Exception("%s: %s" % (offset, buff))

        self._value = unpacked_data.decode('ascii').rstrip('\0')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unpack(self, buff, offset=0):
        try:
            unpacked_data = struct.unpack('!4B', buff[offset:offset+4])
            self._value = '.'.join([str(x) for x in unpacked_data])
        except struct.error as exception:
            raise exceptions.UnpackException('%s; %s: %s' % (exception,
                                                             offset, buff))

Response: Unpack a binary message into this object s attributes based on the contents of the buffer buff and update the object s attributes based on the results.


Instruction:
Make a summary of the following Python 3 code
def pack(self, value=None):
        if isinstance(value, type(self)):
            return value.pack()

        if value is None:
            value = self._value

        if value == 0:
            value = '00:00:00:00:00:00'

        value = value.split(':')

        try:
            return struct.pack('!6B', *[int(x, 16) for x in value])
        except struct.error as err:
            msg = "HWAddress error. "
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
                                                         err)
            raise exceptions.PackException(msg)

Response: Pack the value as a binary representation.


Instruction:
Write a Python 3 script to
unpack a binary message into this object s attributes based on the contents of the buffer buff and update the attributes based on the results.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary message into this object's attributes.

        Unpack the binary value *buff* and update this object attributes based
        on the results.

        Args:
            buff (bytes): Binary data package to be unpacked.
            offset (int): Where to begin unpacking.

        Raises:
            Exception: If there is a struct unpacking error.

        """
        def _int2hex(number):
            return "{0:0{1}x}".format(number, 2)

        try:
            unpacked_data = struct.unpack('!6B', buff[offset:offset+6])
        except struct.error as exception:
            raise exceptions.UnpackException('%s; %s: %s' % (exception,
                                                             offset, buff))

        transformed_data = ':'.join([_int2hex(x) for x in unpacked_data])
        self._value = transformed_data


Instruction:
Given the following Python 3 function, write the documentation
def pack(self, value=None):
        if value is None:
            value = self._value

        if hasattr(value, 'pack') and callable(value.pack):
            return value.pack()
        elif isinstance(value, bytes):
            return value
        elif value is None:
            return b''
        else:
            raise ValueError(f"BinaryData can't be {type(value)} = '{value}'")

Response: Pack the value as a binary representation.


Instruction:
Make a summary of the following Python 3 code
def get_size(self, value=None):
        if value is None:
            value = self._value

        if hasattr(value, 'get_size'):
            return value.get_size()

        return len(self.pack(value))

Response: Return the size in bytes.


Instruction:
Can you create a Python 3 function that
packs the value as a binary representation.

Response:
def pack(self, value=None):
        """Pack the value as a binary representation.

        Returns:
            bytes: The binary representation.

        """
        if isinstance(value, type(self)):
            return value.pack()

        if value is None:
            value = self
        else:
            container = type(self)(items=None)
            container.extend(value)
            value = container

        bin_message = b''
        try:
            for item in value:
                bin_message += item.pack()
            return bin_message
        except exceptions.PackException as err:
            msg = "{} pack error: {}".format(type(self).__name__, err)
            raise exceptions.PackException(msg)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unpack(self, buff, item_class, offset=0):
        begin = offset
        limit_buff = len(buff)

        while begin < limit_buff:
            item = item_class()
            item.unpack(buff, begin)
            self.append(item)
            begin += item.get_size()

Response: Unpack the elements of the list.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_size(self, value=None):
        if value is None:
            if not self:
                # If this is a empty list, then returns zero
                return 0
            elif issubclass(type(self[0]), GenericType):
                # If the type of the elements is GenericType, then returns the
                # length of the list multiplied by the size of the GenericType.
                return len(self) * self[0].get_size()

            # Otherwise iter over the list accumulating the sizes.
            return sum(item.get_size() for item in self)

        return type(self)(value).get_size()

Response: Return the size in bytes.


Instruction:
Implement a Python 3 function for
appending one item to the list.

Response:
def append(self, item):
        """Append one item to the list.

        Args:
            item: Item to be appended. Its type must match the one defined in
                the constructor.

        Raises:
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
                type than the one specified in the constructor.

        """
        if isinstance(item, list):
            self.extend(item)
        elif issubclass(item.__class__, self._pyof_class):
            list.append(self, item)
        else:
            raise exceptions.WrongListItemType(item.__class__.__name__,
                                               self._pyof_class.__name__)


Instruction:
Can you implement a function in Python 3 that
inserts an item at the specified index.

Response:
def insert(self, index, item):
        """Insert an item at the specified index.

        Args:
            index (int): Position to insert the item.
            item: Item to be inserted. It must have the type specified in the
                constructor.

        Raises:
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
                type than the one specified in the constructor.

        """
        if issubclass(item.__class__, self._pyof_class):
            list.insert(self, index, item)
        else:
            raise exceptions.WrongListItemType(item.__class__.__name__,
                                               self._pyof_class.__name__)


Instruction:
Write a Python 3 script to
unpack the elements of the list.

Response:
def unpack(self, buff, offset=0):  # pylint: disable=arguments-differ
        """Unpack the elements of the list.

        This unpack method considers that all elements have the same size.
        To use this class with a pyof_class that accepts elements with
        different sizes, you must reimplement the unpack method.

        Args:
            buff (bytes): The binary data to be unpacked.
            offset (int): If we need to shift the beginning of the data.
        """
        super().unpack(buff, self._pyof_class, offset)


Instruction:
Can you create a Python 3 function that
appends one item to the list.

Response:
def append(self, item):
        """Append one item to the list.

        Args:
            item: Item to be appended.

        Raises:
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
                type than the first item to be stored.

        """
        if isinstance(item, list):
            self.extend(item)
        elif not self:
            list.append(self, item)
        elif item.__class__ == self[0].__class__:
            list.append(self, item)
        else:
            raise exceptions.WrongListItemType(item.__class__.__name__,
                                               self[0].__class__.__name__)


Instruction:
Can you implement a function in Python 3 that
inserts an item at the specified index.

Response:
def insert(self, index, item):
        """Insert an item at the specified index.

        Args:
            index (int): Position to insert the item.
            item: Item to be inserted.

        Raises:
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
                type than the first item to be stored.

        """
        if not self:
            list.append(self, item)
        elif item.__class__ == self[0].__class__:
            list.insert(self, index, item)
        else:
            raise exceptions.WrongListItemType(item.__class__.__name__,
                                               self[0].__class__.__name__)


Instruction:
Given the following Python 3 function, write the documentation
def get_size(self, value=None):
        if isinstance(value, ActionHeader):
            return value.get_size()
        elif value is None:
            current_size = super().get_size()
            return ceil(current_size / 8) * 8
        raise ValueError(f'Invalid value "{value}" for Action*.get_size()')

Response: Return the action length including the padding.


Instruction:
Write a Python 3 function for
packing this structure updating the length and padding it.

Response:
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)


Instruction:
Implement a function in Python 3 to
update the length field of the struct.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
def unpack(self, buff, offset=0):
        super().unpack(buff, offset)
        if not self.is_valid():
            raise UnpackException("Unsupported protocols in ARP packet")

Response: Unpack a binary struct into this object s attributes.


Instruction:
Create a Python 3 function to
pack the instance into a binary representation.

Response:
def pack(self, value=None):
        """Pack the struct in a binary representation.

        Merge some fields to ensure correct packing.

        If no arguments are set for a particular instance, it is interpreted as
        abscence of VLAN information, and the pack() method will return an
        empty binary string.

        Returns:
            bytes: Binary representation of this instance.

        """
        if isinstance(value, type(self)):
            return value.pack()

        if self.pcp is None and self.cfi is None and self.vid is None:
            return b''
        self.pcp = self.pcp if self.pcp is not None else 0
        self.cfi = self.cfi if self.cfi is not None else 0
        self.vid = self.vid if self.vid is not None else 0
        self._tci = self.pcp << 13 | self.cfi << 12 | self.vid
        return super().pack()


Instruction:
Given the following Python 3 function, write the documentation
def _validate(self):
        if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ):
            raise UnpackException
        return

Response: Assure this is a valid VLAN header instance.


Instruction:
Write a Python 3 function for
unpacking a binary struct into this object s attributes.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary struct into this object's attributes.

        Return the values instead of the lib's basic types.

        After unpacking, the abscence of a `tpid` value causes the assignment
        of None to the field values to indicate that there is no VLAN
        information.

        Args:
            buff (bytes): Binary buffer.
            offset (int): Where to begin unpacking.

        Raises:
            :exc:`~.exceptions.UnpackException`: If unpack fails.

        """
        super().unpack(buff, offset)
        if self.tpid.value:
            self._validate()
            self.tpid = self.tpid.value
            self.pcp = self._tci.value >> 13
            self.cfi = (self._tci.value >> 12) & 1
            self.vid = self._tci.value & 4095
        else:
            self.tpid = EtherType.VLAN
            self.pcp = None
            self.cfi = None
            self.vid = None


Instruction:
Write a Python 3 script for
returning the total length of VLAN tags in a given Ethernet buffer.

Response:
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


Instruction:
How would you implement a function in Python 3 that
unpacks a binary message into this object s attributes based on the attributes found in the Ethernet headers.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary message into this object's attributes.

        Unpack the binary value *buff* and update this object attributes based
        on the results.

        Ethernet headers may have VLAN tags. If no VLAN tag is found, a
        'wildcard VLAN tag' is inserted to assure correct unpacking.

        Args:
            buff (bytes): Binary data package to be unpacked.
            offset (int): Where to begin unpacking.

        Raises:
            UnpackException: If there is a struct unpacking error.

        """
        begin = offset

        vlan_length = self._get_vlan_length(buff)

        for attribute_name, class_attribute in self.get_class_attributes():
            attribute = deepcopy(class_attribute)
            if attribute_name == 'vlans':
                attribute.unpack(buff[begin:begin+vlan_length])
            else:
                attribute.unpack(buff, begin)
            setattr(self, attribute_name, attribute)
            begin += attribute.get_size()


Instruction:
Explain what the following Python 3 code does
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)

Response: Pack the TLV in a binary representation.


Instruction:
Can you tell what is the following Python 3 function doing
def unpack(self, buff, offset=0):
        header = UBInt16()
        header.unpack(buff[offset:offset+2])
        self.tlv_type = header.value >> 9
        length = header.value & 511
        begin, end = offset + 2, offset + 2 + length
        self._value = BinaryData(buff[begin:end])

Response: Unpack a binary message into this object s attributes based on the contents of the buffer buff and update the attributes based on the results.


Instruction:
How would you explain what the following Python 3 function does
def get_size(self, value=None):
        if isinstance(value, type(self)):
            return value.get_size()

        return 2 + self.length

Response: Returns the size of the structure based on inner attributes.


Instruction:
Can you implement a function in Python 3 that
updates the checksum to enable integrity check.

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pack(self, value=None):
        # Set the correct IHL based on options size
        if self.options:
            self.ihl += int(len(self.options) / 4)

        # Set the correct packet length based on header length and data
        self.length = int(self.ihl * 4 + len(self.data))

        self._version_ihl = self.version << 4 | self.ihl
        self._dscp_ecn = self.dscp << 2 | self.ecn
        self._flags_offset = self.flags << 13 | self.offset

        # Set the checksum field before packing
        self._update_checksum()

        return super().pack()

Response: Pack the structure into a binary representation.


Instruction:
Write a Python 3 function for
unpacking a binary struct into this object s attributes.

Response:
def unpack(self, buff, offset=0):
        """Unpack a binary struct into this object's attributes.

        Return the values instead of the lib's basic types.

        Args:
            buff (bytes): Binary buffer.
            offset (int): Where to begin unpacking.

        Raises:
            :exc:`~.exceptions.UnpackException`: If unpack fails.

        """
        super().unpack(buff, offset)

        self.version = self._version_ihl.value >> 4
        self.ihl = self._version_ihl.value & 15
        self.dscp = self._dscp_ecn.value >> 2
        self.ecn = self._dscp_ecn.value & 3
        self.length = self.length.value
        self.identification = self.identification.value
        self.flags = self._flags_offset.value >> 13
        self.offset = self._flags_offset.value & 8191
        self.ttl = self.ttl.value
        self.protocol = self.protocol.value
        self.checksum = self.checksum.value
        self.source = self.source.value
        self.destination = self.destination.value

        if self.ihl > 5:
            options_size = (self.ihl - 5) * 4
            self.data = self.options.value[options_size:]
            self.options = self.options.value[:options_size]
        else:
            self.data = self.options.value
            self.options = b''


Instruction:
Write a Python 3 function for
returning sub type and sub value as binary data.

Response:
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)


Instruction:
Can you tell what is the following Python 3 function doing
def unpack(self, buff, offset=0):
        header = UBInt16()
        header.unpack(buff[offset:offset+2])
        self.tlv_type = header.value >> 9
        length = header.value & 511
        begin, end = offset + 2, offset + 2 + length
        sub_type = UBInt8()
        sub_type.unpack(buff[begin:begin+1])
        self.sub_type = sub_type.value
        self.sub_value = BinaryData(buff[begin+1:end])

Response: Unpack a binary message into this object s attributes based on the results.


Instruction:
How would you implement a function in Python 3 that
checks if packet is valid OF packet. Raises UnpackException if the packet is invalid.

Response:
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')


Instruction:
Can you generate a brief explanation for the following Python 3 code
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)

Response: Unpack the OpenFlow Packet and returns a GenericMessage.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_class(self):
        classes = {'OFPET_HELLO_FAILED': HelloFailedCode,
                   'OFPET_BAD_REQUEST': BadRequestCode,
                   'OFPET_BAD_ACTION': BadActionCode,
                   'OFPET_BAD_INSTRUCTION': BadInstructionCode,
                   'OFPET_BAD_MATCH': BadMatchCode,
                   'OFPET_FLOW_MOD_FAILED': FlowModFailedCode,
                   'OFPET_GROUP_MOD_FAILED': GroupModFailedCode,
                   'OFPET_PORT_MOD_FAILED': PortModFailedCode,
                   'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode,
                   'OFPET_SWITCH_CONFIG_FAILED': SwitchConfigFailedCode,
                   'OFPET_ROLE_REQUEST_FAILED': RoleRequestFailedCode,
                   'OFPET_METER_MOD_FAILED': MeterModFailedCode,
                   'OFPET_TABLE_MOD_FAILED': TableModFailedCode,
                   'OFPET_TABLE_FEATURES_FAILED': TableFeaturesFailedCode}
        return classes.get(self.name, GenericFailedCode)

Response: Return a Code class based on current ErrorType value.


Instruction:
Explain what the following Python 3 code does
def unpack(self, buff, offset=0):
        super().unpack(buff, offset)
        code_class = ErrorType(self.error_type).get_class()
        self.code = code_class(self.code)

Response: Unpack binary data into python object.


Instruction:
Can you implement a function in Python 3 that
returns a Code class based on current ErrorType value.

Response:
def get_class(self):
        """Return a Code class based on current ErrorType value.

        Returns:
            enum.IntEnum: class referenced by current error type.

        """
        classes = {'OFPET_HELLO_FAILED': HelloFailedCode,
                   'OFPET_BAD_REQUEST': BadRequestCode,
                   'OFPET_BAD_ACTION': BadActionCode,
                   'OFPET_FLOW_MOD_FAILED': FlowModFailedCode,
                   'OFPET_PORT_MOD_FAILED': PortModFailedCode,
                   'OFPET_QUEUE_OP_FAILED': QueueOpFailedCode}
        return classes.get(self.name, GenericFailedCode)


Instruction:
Implement a Python 3 function for
packing the value as a binary representation.

Response:
def pack(self, value=None):
        """Pack the value as a binary representation.

        :attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
        After that, :attr:`data`'s value is restored.

        Returns:
            bytes: The binary representation.

        Raises:
            :exc:`~.exceptions.PackException`: If pack fails.

        """
        if value is None:
            data_backup = None
            if self.data is not None and not isinstance(self.data, bytes):
                data_backup = self.data
                self.data = self.data.pack()
            packed = super().pack()
            if data_backup is not None:
                self.data = data_backup
            return packed
        elif isinstance(value, type(self)):
            return value.pack()
        else:
            msg = "{} is not an instance of {}".format(value,
                                                       type(self).__name__)
            raise PackException(msg)


Instruction:
Explain what the following Python 3 code does
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

Response: Create QAction with given parameters and add to the widget


Instruction:
Can you implement a function in Python 3 that
clears bookmarks on a range including start and endBlock.

Response:
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


Instruction:
Write a Python 3 function for
traversing document forward. Yield block columnIndex char

Response:
def _iterateDocumentCharsForward(self, block, startColumnIndex):
        """Traverse document forward. Yield (block, columnIndex, char)
        Raise _TimeoutException if time is over
        """
        # Chars in the start line
        endTime = time.time() + self._MAX_SEARCH_TIME_SEC
        for columnIndex, char in list(enumerate(block.text()))[startColumnIndex:]:
            yield block, columnIndex, char
        block = block.next()

        # Next lines
        while block.isValid():
            for columnIndex, char in enumerate(block.text()):
                yield block, columnIndex, char

            if time.time() > endTime:
                raise _TimeoutException('Time is over')

            block = block.next()


Instruction:
How would you code a function in Python 3 to
traverse document forward. Yield block columnIndex char

Response:
def _iterateDocumentCharsBackward(self, block, startColumnIndex):
        """Traverse document forward. Yield (block, columnIndex, char)
        Raise _TimeoutException if time is over
        """
        # Chars in the start line
        endTime = time.time() + self._MAX_SEARCH_TIME_SEC
        for columnIndex, char in reversed(list(enumerate(block.text()[:startColumnIndex]))):
            yield block, columnIndex, char
        block = block.previous()

        # Next lines
        while block.isValid():
            for columnIndex, char in reversed(list(enumerate(block.text()))):
                yield block, columnIndex, char

            if time.time() > endTime:
                raise _TimeoutException('Time is over')

            block = block.previous()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _findMatchingBracket(self, bracket, qpart, block, columnIndex):
        if bracket in self._START_BRACKETS:
            charsGenerator = self._iterateDocumentCharsForward(block, columnIndex + 1)
        else:
            charsGenerator = self._iterateDocumentCharsBackward(block, columnIndex)

        depth = 1
        oposite = self._OPOSITE_BRACKET[bracket]
        for block, columnIndex, char in charsGenerator:
            if qpart.isCode(block, columnIndex):
                if char == oposite:
                    depth -= 1
                    if depth == 0:
                        return block, columnIndex
                elif char == bracket:
                    depth += 1
        else:
            return None, None

Response: Find the matching bracket for the column.


Instruction:
Given the following Python 3 function, write the documentation
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

Response: Make matched or unmatched QTextEdit. ExtraSelection


Instruction:
Can you tell what is the following Python 3 function doing
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)]

Response:
Highlights a bracket and matching bracket
            returns tuple of QTextEdit. ExtraSelection s


Instruction:
How would you implement a function in Python 3 that
lists of QTextEdit. ExtraSelection s which highlight brackets

Response:
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 []


Instruction:
Create a Python 3 function for
checking if character at column is a code

Response:
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)


Instruction:
Given the following Python 3 function, write the documentation
def isComment(self, block, column):
        dataObject = block.userData()
        data = dataObject.data if dataObject is not None else None
        return self._syntax.isComment(data, column)

Response: Check if character at column is a comment.


Instruction:
Explain what the following Python 3 code does
def isBlockComment(self, block, column):
        dataObject = block.userData()
        data = dataObject.data if dataObject is not None else None
        return self._syntax.isBlockComment(data, column)

Response: Check if character at column is a block comment.


Instruction:
Write a Python 3 script to
check if character at column is a here document.

Response:
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)


Instruction:
Make a summary of the following Python 3 code
def _highlighBlocks(self, fromBlock, atLeastUntilBlock, timeout):
        endTime = time.time() + timeout

        block = fromBlock
        lineData = self._lineData(block.previous())

        while block.isValid() and block != atLeastUntilBlock:
            if time.time() >= endTime:  # time is over, schedule parsing later and release event loop
                self._pendingBlockNumber = block.blockNumber()
                self._pendingAtLeastUntilBlockNumber = atLeastUntilBlock.blockNumber()
                self._globalTimer.scheduleCallback(self._onContinueHighlighting)
                return

            contextStack = lineData[0] if lineData is not None else None
            if block.length() < 4096:
                lineData, highlightedSegments = self._syntax.highlightBlock(block.text(), contextStack)
            else:
                """Parser freezes for a long time, if line is too long
                invalid parsing results are still better, than freeze
                """
                lineData, highlightedSegments = None, []
            if lineData is not None:
                block.setUserData(_TextBlockUserData(lineData))
            else:
                block.setUserData(None)

            self._applyHighlightedSegments(block, highlightedSegments)
            block = block.next()

        # reached atLeastUntilBlock, now parse next only while data changed
        prevLineData = self._lineData(block)
        while block.isValid():
            if time.time() >= endTime:  # time is over, schedule parsing later and release event loop
                self._pendingBlockNumber = block.blockNumber()
                self._pendingAtLeastUntilBlockNumber = atLeastUntilBlock.blockNumber()
                self._globalTimer.scheduleCallback(self._onContinueHighlighting)
                return
            contextStack = lineData[0] if lineData is not None else None
            lineData, highlightedSegments = self._syntax.highlightBlock(block.text(), contextStack)
            if lineData is not None:
                block.setUserData(_TextBlockUserData(lineData))
            else:
                block.setUserData(None)

            self._applyHighlightedSegments(block, highlightedSegments)
            if prevLineData == lineData:
                break

            block = block.next()
            prevLineData = self._lineData(block)

        # sucessfully finished, reset pending tasks
        self._pendingBlockNumber = None
        self._pendingAtLeastUntilBlockNumber = None

        """Emit sizeChanged when highlighting finished, because document size might change.
        See andreikop/enki issue #191
        """
        documentLayout = self._textEdit.document().documentLayout()
        documentLayout.documentSizeChanged.emit(documentLayout.documentSize())

Response: Highlighs the blocks in the given block until the given time.


Instruction:
Can you tell what is the following Python 3 function doing
def computeSmartIndent(self, block, ch):
        if re.search(r'^\s*;;;', block.text()):
            return ''
        elif re.search(r'^\s*;;', block.text()):
            #try to align with the next line
            nextBlock = self._nextNonEmptyBlock(block)
            if nextBlock.isValid():
                return self._blockIndent(nextBlock)

        try:
            foundBlock, foundColumn = self.findBracketBackward(block, 0, '(')
        except ValueError:
            return ''
        else:
            return self._increaseIndent(self._blockIndent(foundBlock))

Response: computeSmartIndent - computes the indentation of a single line of code


Instruction:
Can you generate the documentation for the following Python 3 function
def _atomicModification(func):
        def wrapper(*args, **kwargs):
            self = args[0]
            with self._qpart:
                func(*args, **kwargs)
        return wrapper

Response: Decorator for making document modification atomic


Instruction:
Create a Python 3 function for
checking integer index convert from less than zero notation

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def append(self, text):
        cursor = QTextCursor(self._doc)
        cursor.movePosition(QTextCursor.End)
        cursor.insertBlock()
        cursor.insertText(text)

Response: Append text to the end of the document.


Instruction:
Write a Python 3 function that can
insert a line to the document.

Response:
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)


Instruction:
Can you create a Python 3 function that
computes the indentation for the block.

Response:
def computeSmartIndent(self, block, char):
        """Compute indent for the block
        """
        lineText = block.text()
        prevLineText = self._prevNonEmptyBlock(block).text()

        alignOnly = char == ''

        if alignOnly:
            # XML might be all in one line, in which case we want to break that up.
            tokens = re.split(r'>\s*<', lineText)

            if len(tokens) > 1:

                prevIndent = self._lineIndent(prevLineText)

                for index, newLine in enumerate(tokens):
                    if index > 0:
                        newLine = '<' + newLine

                    if index < len(tokens) - 1:
                        newLine = newLine + '>'
                    if re.match(r'^\s*</', newLine):
                        char = '/'
                    elif re.match(r'\\>[^<>]*$', newLine):
                        char = '>'
                    else:
                        char = '\n'

                    indentation = self.processChar(newLine, prevLineText, char)
                    newLine = indentation + newLine

                    tokens[index] = newLine
                    prevLineText = newLine;

                self._qpart.lines[block.blockNumber()] =  '\n'.join(tokens)
                return None
            else:  # no tokens, do not split line, just compute indent
                if re.search(r'^\s*</', lineText):
                    char = '/'
                elif re.search(r'>[^<>]*', lineText):
                    char = '>'
                else:
                    char = '\n'

        return self.processChar(lineText, prevLineText, char)


Instruction:
Can you generate the documentation for the following Python 3 function
def _prevNonCommentBlock(self, block):
        block = self._prevNonEmptyBlock(block)
        while block.isValid() and self._isCommentBlock(block):
            block = self._prevNonEmptyBlock(block)
        return block

Response: Return the closest non - empty line ignoring comments


Instruction:
Explain what the following Python 3 code does
def _isLastCodeColumn(self, block, column):
        return column >= self._lastColumn(block) or \
               self._isComment(block, self._nextNonSpaceColumn(block, column + 1))

Response: Return true if the given column is at least equal to the last non - whitespace character at the given line.


Instruction:
Write a Python 3 script to
find the last open bracket before the current line. Return None if no bracket was found.

Response:
def lastAnchor(self, block, column):
        """Find the last open bracket before the current line.
        Return (block, column, char) or (None, None, None)
        """
        currentPos = -1
        currentBlock = None
        currentColumn = None
        currentChar = None
        for char in '({[':
            try:
                foundBlock, foundColumn = self.findBracketBackward(block, column, char)
            except ValueError:
                continue
            else:
                pos = foundBlock.position() + foundColumn
                if pos > currentPos:
                    currentBlock = foundBlock
                    currentColumn = foundColumn
                    currentChar = char
                    currentPos = pos

        return currentBlock, currentColumn, currentChar


Instruction:
How would you code a function in Python 3 to
find the first line that is not preceded by a continuing line. Return the first line that is not preceded by a continuing line.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
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) == ""

Response: check if the trigger characters are in the right context


Instruction:
How would you explain what the following Python 3 function does
def findPrevStmt(self, block):
        stmtEnd = self._prevNonCommentBlock(block)
        stmtStart = self.findStmtStart(stmtEnd)
        return Statement(self._qpart, stmtStart, stmtEnd)

Response:
Returns a tuple that contains the first and last line of the
        previous statement before line.


Instruction:
Can you write a function in Python 3 where it
computes the indentation of a single line or a single line.

Response:
def computeSmartIndent(self, block, ch):
        """indent gets three arguments: line, indentWidth in spaces,
        typed character indent
        """
        if not self._isValidTrigger(block, ch):
            return None

        prevStmt = self.findPrevStmt(block)
        if not prevStmt.endBlock.isValid():
            return None  # Can't indent the first line

        prevBlock = self._prevNonEmptyBlock(block)

        # HACK Detect here documents
        if self._qpart.isHereDoc(prevBlock.blockNumber(), prevBlock.length() - 2):
          return None

        # HACK Detect embedded comments
        if self._qpart.isBlockComment(prevBlock.blockNumber(), prevBlock.length() - 2):
            return None

        prevStmtCnt = prevStmt.content()
        prevStmtInd = prevStmt.indent()

        # Are we inside a parameter list, array or hash?
        foundBlock, foundColumn, foundChar = self.lastAnchor(block, 0)
        if foundBlock is not None:
            shouldIndent = foundBlock == prevStmt.endBlock or \
                           self.testAtEnd(prevStmt, re.compile(',\s*'))
            if (not self._isLastCodeColumn(foundBlock, foundColumn)) or \
                self.lastAnchor(foundBlock, foundColumn)[0] is not None:
                # TODO This is alignment, should force using spaces instead of tabs:
                if shouldIndent:
                    foundColumn += 1
                    nextCol = self._nextNonSpaceColumn(foundBlock, foundColumn)
                    if nextCol > 0 and \
                       (not self._isComment(foundBlock, nextCol)):
                        foundColumn = nextCol

                # Keep indent of previous statement, while aligning to the anchor column
                if len(prevStmtInd) > foundColumn:
                    return prevStmtInd
                else:
                    return self._makeIndentAsColumn(foundBlock, foundColumn)
            else:
                indent = self._blockIndent(foundBlock)
                if shouldIndent:
                    indent = self._increaseIndent(indent)
                return indent

        # Handle indenting of multiline statements.
        if (prevStmt.endBlock == block.previous() and \
             self._isBlockContinuing(prevStmt.endBlock)) or \
           self.isStmtContinuing(prevStmt.endBlock):
            if prevStmt.startBlock == prevStmt.endBlock:
                if ch == '' and \
                   len(self._blockIndent(block)) > len(self._blockIndent(prevStmt.endBlock)):
                    return None  # Don't force a specific indent level when aligning manually
                return self._increaseIndent(self._increaseIndent(prevStmtInd))
            else:
                return self._blockIndent(prevStmt.endBlock)

        if rxUnindent.match(block.text()):
            startStmt = self.findBlockStart(block)
            if startStmt.startBlock.isValid():
                return startStmt.indent()
            else:
                return None

        if self.isBlockStart(prevStmt) and not rxBlockEnd.search(prevStmt.content()):
            return self._increaseIndent(prevStmtInd)
        elif re.search(r'[\[\{]\s*$', prevStmtCnt) is not None:
            return self._increaseIndent(prevStmtInd)

        # Keep current
        return prevStmtInd


Instruction:
Given the following Python 3 function, write the documentation
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))

Response: Check if key event should be handled as Delete command


Instruction:
Make a summary of the following Python 3 code
def delete(self):
        with self._qpart:
            for cursor in self.cursors():
                if cursor.hasSelection():
                    cursor.deleteChar()

Response: Del or Backspace pressed. Delete selection


Instruction:
Create a Python 3 function to
check if the given key event should expand rectangular selection

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
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)

Response: One of expand selection key events


Instruction:
How would you explain what the following Python 3 function does
def _realToVisibleColumn(self, text, realColumn):
        generator = self._visibleCharPositionGenerator(text)
        for i in range(realColumn):
            val = next(generator)
        val = next(generator)
        return val

Response: This function converts real position of symbol in block to visible position


Instruction:
Make a summary of the following Python 3 code
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

Response: This function converts visible to real column.


Instruction:
How would you code a function in Python 3 to
build list of extra selections for rectangular selection

Response:
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


Instruction:
Make a summary of the following Python 3 code
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)

Response: Copy to the clipboard


Instruction:
Write a Python 3 script for
cutting the cursor and delete the current entry

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
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)

Response: Add space to text so text width will be at least width.


Instruction:
Can you write a function in Python 3 where it
pastes recrangular selection. Add space at the beginning of line, if necessary

Response:
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


Instruction:
How would you explain what the following Python 3 function does
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)

Response: Allocates the bit range depending on the required bit count


Instruction:
Write a Python 3 function for
updating the line number area if necessary

Response:
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()


Instruction:
Write a Python 3 function for
setting the required value to the block without damaging the other bits

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
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

Response: Provides the previously set block value respecting the bits range.


Instruction:
Given the following Python 3 function, write the documentation
def hide(self):
        if not self.isHidden():
            QWidget.hide(self)
            self._qpart.updateViewport()

Response:
Override the QWidget. hide method to properly recalculate the the
           editor viewport.


Instruction:
How would you implement a function in Python 3 that
overrides the QWidget. show method to properly recalculate the the editor viewport.

Response:
def show(self):
        """Override the QWidget::show() method to properly recalculate the
           editor viewport.
        """
        if self.isHidden():
            QWidget.show(self)
            self._qpart.updateViewport()


Instruction:
Write a Python 3 script for
overriding the QWidget. setVisible method to properly properly recalculate the editor viewport.

Response:
def setVisible(self, val):
        """Override the QWidget::setVisible(bool) method to properly
           recalculate the editor viewport.
        """
        if val != self.isVisible():
            if val:
                QWidget.setVisible(self, True)
            else:
                QWidget.setVisible(self, False)
            self._qpart.updateViewport()


Instruction:
Can you generate a brief explanation for the following Python 3 code
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()

Response: Convenience method to reset all the block values to 0


Instruction:
Write a Python 3 function for
getting text type of the current entry in the table.

Response:
def _getTextType(self, lineData, column):
        """Get text type (letter)
        """
        if lineData is None:
            return ' '  # default is code

        textTypeMap = lineData[1]
        if column >= len(textTypeMap):  # probably, not actual data, not updated yet
            return ' '

        return textTypeMap[column]


Instruction:
Can you create a Python 3 function that
gets syntax by its xml file name.

Response:
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]


Instruction:
Can you implement a function in Python 3 that
gets a syntax by its name.

Response:
def _getSyntaxByLanguageName(self, syntaxName):
        """Get syntax by its name. Name is defined in the xml file
        """
        xmlFileName = self._syntaxNameToXmlFileName[syntaxName]
        return self._getSyntaxByXmlFileName(xmlFileName)


Instruction:
Can you tell what is the following Python 3 function doing
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)

Response: Get syntax by source name of file.


Instruction:
Given the following Python 3 function, write the documentation
def _getSyntaxByMimeType(self, mimeType):
        xmlFileName = self._mimeTypeToXmlFileName[mimeType]
        return self._getSyntaxByXmlFileName(xmlFileName)

Response: Get the syntax by MIME type.


Instruction:
Write a Python 3 function for
getting the syntax for the first line of the file.

Response:
def _getSyntaxByFirstLine(self, firstLine):
        """Get syntax by first line of the file
        """
        for pattern, xmlFileName in self._firstLineToXmlFileName.items():
            if fnmatch.fnmatch(firstLine, pattern):
                return self._getSyntaxByXmlFileName(xmlFileName)
        else:
            raise KeyError("No syntax for " + firstLine)


Instruction:
Write a Python 3 function for
getting the syntax of a specific language.

Response:
def getSyntax(self,
                  xmlFileName=None,
                  mimeType=None,
                  languageName=None,
                  sourceFilePath=None,
                  firstLine=None):
        """Get syntax by one of parameters:
            * xmlFileName
            * mimeType
            * languageName
            * sourceFilePath
        First parameter in the list has biggest priority
        """
        syntax = None

        if syntax is None and xmlFileName is not None:
            try:
                syntax = self._getSyntaxByXmlFileName(xmlFileName)
            except KeyError:
                _logger.warning('No xml definition %s' % xmlFileName)

        if syntax is None and mimeType is not None:
            try:
                syntax = self._getSyntaxByMimeType(mimeType)
            except KeyError:
                _logger.warning('No syntax for mime type %s' % mimeType)

        if syntax is None and languageName is not None:
            try:
                syntax = self._getSyntaxByLanguageName(languageName)
            except KeyError:
                _logger.warning('No syntax for language %s' % languageName)

        if syntax is None and sourceFilePath is not None:
            baseName = os.path.basename(sourceFilePath)
            try:
                syntax = self._getSyntaxBySourceFileName(baseName)
            except KeyError:
                pass

        if syntax is None and firstLine is not None:
            try:
                syntax = self._getSyntaxByFirstLine(firstLine)
            except KeyError:
                pass

        return syntax


Instruction:
Can you generate the documentation for the following Python 3 function
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])

Response: Returns new context stack which doesn t contain few levels


Instruction:
Implement a function in Python 3 to
return new context which contains current stack and new frame

Response:
def append(self, context, data):
        """Returns new context, which contains current stack and new frame
        """
        return ContextStack(self._contexts + [context], self._data + [data])


Instruction:
Can you generate the documentation for the following Python 3 function
def tryMatch(self, textToMatchObject):
        # Skip if column doesn't match
        if self.column != -1 and \
           self.column != textToMatchObject.currentColumnIndex:
            return None

        if self.firstNonSpace and \
           (not textToMatchObject.firstNonSpace):
            return None

        return self._tryMatch(textToMatchObject)

Response: Try to find themselves in the text.


Instruction:
Explain what the following Python 3 code does
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)

Response:
For dynamic rules replace %d patterns with actual strings
        Python function which is used by C extension.


Instruction:
Here you have a function in Python 3, explain what it does
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

Response: Tries to parse text. If matched - saves data for dynamic context


Instruction:
Can you create a Python 3 function that
compiles regular expression. A simple wrapper around compileRegExp.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
def _matchPattern(regExp, string):
        match = regExp.match(string)
        if match is not None and match.group(0):
            return match.group(0), (match.group(0), ) + match.groups()
        else:
            return None, None

Response:
Try to match pattern.
        Returns tuple of match groups or None


Instruction:
Can you create a Python 3 function that
tries to find themselves in the text.

Response:
def _tryMatch(self, textToMatchObject):
        """Try to find themselves in the text.
        Returns (count, matchedRule) or (None, None) if doesn't match
        """

        # andreikop: This check is not described in kate docs, and I haven't found it in the code
        if not textToMatchObject.isWordStart:
            return None

        index = self._tryMatchText(textToMatchObject.text)
        if index is None:
            return None

        if textToMatchObject.currentColumnIndex + index < len(textToMatchObject.wholeLineText):
            newTextToMatchObject = TextToMatchObject(textToMatchObject.currentColumnIndex + index,
                                                      textToMatchObject.wholeLineText,
                                                      self.parentContext.parser.deliminatorSet,
                                                      textToMatchObject.contextData)
            for rule in self.childRules:
                ruleTryMatchResult = rule.tryMatch(newTextToMatchObject)
                if ruleTryMatchResult is not None:
                    index += ruleTryMatchResult.length
                    break
                # child rule context and attribute ignored

        return RuleTryMatchResult(self, index)


Instruction:
How would you explain what the following Python 3 function does
def _countDigits(self, text):
        index = 0
        while index < len(text):
            if not text[index].isdigit():
                break
            index += 1
        return index

Response: Count digits at start of text.


Instruction:
Can you tell what is the following Python 3 function doing
def _tryMatch(self, textToMatchObject):
        for rule in self.context.rules:
            ruleTryMatchResult = rule.tryMatch(textToMatchObject)
            if ruleTryMatchResult is not None:
                _logger.debug('\tmatched rule %s at %d in included context %s/%s',
                              rule.shortId(),
                              textToMatchObject.currentColumnIndex,
                              self.context.parser.syntax.name,
                              self.context.name)
                return ruleTryMatchResult
        else:
            return None

Response: Try to find themselves in the text.


Instruction:
Create a Python 3 function to
search for a needle and return the block and column

Response:
def findTextBackward(self, block, column, needle):
        """Search for a needle and return (block, column)
        Raise ValueError, if not found
        """
        if column is not None:
            index = block.text()[:column].rfind(needle)
        else:
            index = block.text().rfind(needle)

        if index != -1:
            return block, index

        for block in self.iterateBlocksBackFrom(block.previous()):
            column = block.text().rfind(needle)
            if column != -1:
                return block, column

        raise ValueError('Not found')


Instruction:
Can you create a Python 3 function that
searches for a corresponding '{' and return its indentation

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
def tryParenthesisBeforeBrace(self, block, column):
        text = block.text()[:column - 1].rstrip()
        if not text.endswith(')'):
            raise ValueError()
        return self.findBracketBackward(block, len(text) - 1, '(')

Response: Try to find the right indentation of a tag before a brace.


Instruction:
Create a Python 3 function to
try to find a previous default case or switch and return its indentation or None if not found.

Response:
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


Instruction:
Create a Python 3 function for
trying to find a previous private protected public or signals or return its indentation or None if not found.

Response:
def tryAccessModifiers(self, block):
        """Check for private, protected, public, signals etc... and assume we are in a
        class definition. Try to find a previous private/protected/private... or
        class and return its indentation or null if not found.
        """

        if CFG_ACCESS_MODIFIERS < 0:
            return None

        if not re.match(r'^\s*((public|protected|private)\s*(slots|Q_SLOTS)?|(signals|Q_SIGNALS)\s*):\s*$', block.text()):
            return None

        try:
            block, notUsedColumn = self.findBracketBackward(block, 0, '{')
        except ValueError:
            return None

        indentation = self._blockIndent(block)
        for i in range(CFG_ACCESS_MODIFIERS):
            indentation = self._increaseIndent(indentation)

        dbg("tryAccessModifiers: success in line %d" % block.blockNumber())
        return indentation