code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
field_int = self.oxm_field_and_mask >> 1
# We know that the class below requires a subset of the ofb enum
if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC:
return OxmOfbMatchField(field_int)
return field_int
|
def _unpack_oxm_field(self)
|
Unpack oxm_field from oxm_field_and_mask.
Returns:
:class:`OxmOfbMatchField`, int: oxm_field from oxm_field_and_mask.
Raises:
ValueError: If oxm_class is OFPXMC_OPENFLOW_BASIC but
:class:`OxmOfbMatchField` has no such integer value.
| 8.383427 | 5.645774 | 1.484903 |
payload = type(self).oxm_value.pack(self.oxm_value)
self.oxm_length = len(payload)
|
def _update_length(self)
|
Update length field.
Update the oxm_length field with the packed payload length.
| 9.743044 | 4.453185 | 2.187882 |
if value is not None:
return value.pack()
# Set oxm_field_and_mask instance attribute
# 1. Move field integer one bit to the left
try:
field_int = self._get_oxm_field_int()
except ValueError as exception:
raise PackException(exception)
field_bits = field_int << 1
# 2. hasmask bit
hasmask_bit = self.oxm_hasmask & 1
# 3. Add hasmask bit to field value
self.oxm_field_and_mask = field_bits + hasmask_bit
self._update_length()
return super().pack(value)
|
def pack(self, value=None)
|
Join oxm_hasmask bit and 7-bit oxm_field.
| 5.465629 | 4.629199 | 1.180686 |
if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC:
return OxmOfbMatchField(self.oxm_field).value
elif not isinstance(self.oxm_field, int) or self.oxm_field > 127:
raise ValueError('oxm_field above 127: "{self.oxm_field}".')
return self.oxm_field
|
def _get_oxm_field_int(self)
|
Return a valid integer value for oxm_field.
Used while packing.
Returns:
int: valid oxm_field value.
Raises:
ValueError: If :attribute:`oxm_field` is bigger than 7 bits or
should be :class:`OxmOfbMatchField` and the enum has no such
value.
| 3.317669 | 3.097348 | 1.071132 |
if isinstance(value, Match):
return value.pack()
elif value is None:
self._update_match_length()
packet = super().pack()
return self._complete_last_byte(packet)
raise PackException(f'Match can\'t unpack "{value}".')
|
def pack(self, value=None)
|
Pack and complete the last byte by padding.
| 7.877416 | 5.894649 | 1.336367 |
padded_size = self.get_size()
padding_bytes = padded_size - len(packet)
if padding_bytes > 0:
packet += Pad(padding_bytes).pack()
return packet
|
def _complete_last_byte(self, packet)
|
Pad until the packet length is a multiple of 8 (bytes).
| 3.916147 | 3.282469 | 1.193049 |
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()')
|
def get_size(self, value=None)
|
Return the packet length including the padding (multiple of 8).
| 4.364499 | 3.91069 | 1.116043 |
begin = offset
for name, value in list(self.get_class_attributes())[:-1]:
size = self._unpack_attribute(name, value, buff, begin)
begin += size
self._unpack_attribute('oxm_match_fields', type(self).oxm_match_fields,
buff[:offset+self.length], begin)
|
def unpack(self, buff, offset=0)
|
Discard padding bytes using the unpacked length attribute.
| 6.094276 | 5.594334 | 1.089366 |
for field in self.oxm_match_fields:
if field.oxm_field == field_type:
return field.oxm_value
return None
|
def get_field(self, field_type)
|
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.
| 5.008411 | 2.910704 | 1.720687 |
if self.isenum():
if isinstance(self._value, self.enum_ref):
return self._value.value
return self._value
elif self.is_bitmask():
return self._value.bitmask
else:
return self._value
|
def value(self)
|
Return this type's value.
Returns:
object: The value of an enum, bitmask, etc.
| 4.340264 | 3.776051 | 1.149419 |
r
if isinstance(value, type(self)):
return value.pack()
if value is None:
value = self.value
elif 'value' in dir(value):
# if it is enum or bitmask gets only the 'int' value
value = value.value
try:
return struct.pack(self._fmt, value)
except struct.error:
expected_type = type(self).__name__
actual_type = type(value).__name__
msg_args = expected_type, value, actual_type
msg = 'Expected {}, found value "{}" of type {}'.format(*msg_args)
raise PackException(msg)
|
def pack(self, value=None)
|
r"""Pack the value as a binary representation.
Considering an example with UBInt8 class, that inherits from
GenericType:
>>> from pyof.foundation.basic_types import UBInt8
>>> objectA = UBInt8(1)
>>> objectB = 5
>>> objectA.pack()
b'\x01'
>>> objectA.pack(objectB)
b'\x05'
Args:
value: If the value is None, then we will pack the value of the
current instance. Otherwise, if value is an instance of the
same type as the current instance, then we call the pack of the
value object. Otherwise, we will use the current instance pack
method on the passed value.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.exceptions.BadValueException`: If the value does not
fit the binary format.
| 4.724863 | 4.767684 | 0.991019 |
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)
|
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.
| 3.359459 | 3.251508 | 1.0332 |
old_enum = obj.message_type
new_header = attr[1]
new_enum = new_header.__class__.message_type.enum_ref
#: This 'if' will be removed on the future with an
#: improved version of __init_subclass__ method of the
#: GenericMessage class
if old_enum:
msg_type_name = old_enum.name
new_type = new_enum[msg_type_name]
new_header.message_type = new_type
return (attr[0], new_header)
|
def _header_message_type_update(obj, attr)
|
Update the message type on the header.
Set the message_type of the header according to the message_type of
the parent class.
| 6.021913 | 5.885553 | 1.023169 |
ver_module_re = re.compile(r'(pyof\.)(v0x\d+)(\..*)')
matched = ver_module_re.match(module_fullname)
if matched:
version = matched.group(2)
return version
return None
|
def get_pyof_version(module_fullname)
|
Get the module pyof version based on the module fullname.
Args:
module_fullname (str): The fullname of the module
(e.g.: pyof.v0x01.common.header)
Returns:
str: openflow version.
The openflow version, on the format 'v0x0?' if any. Or None
if there isn't a version on the fullname.
| 4.397032 | 3.579152 | 1.228512 |
module_version = MetaStruct.get_pyof_version(module_fullname)
if not module_version or module_version == version:
return None
return module_fullname.replace(module_version, version)
|
def replace_pyof_version(module_fullname, version)
|
Replace the OF Version of a module fullname.
Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on
a new 'version' (eg. 'pyof.v0x02.common.header').
Args:
module_fullname (str): The fullname of the module
(e.g.: pyof.v0x01.common.header)
version (str): The version to be 'inserted' on the module fullname.
Returns:
str: module fullname
The new module fullname, with the replaced version,
on the format "pyof.v0x01.common.header". If the requested
version is the same as the one of the module_fullname or if
the module_fullname is not a 'OF version' specific module,
returns None.
| 3.975087 | 4.472719 | 0.888741 |
r
if new_version is None:
return (name, obj)
cls = obj.__class__
cls_name = cls.__name__
cls_mod = cls.__module__
#: If the module name does not starts with pyof.v0 then it is not a
#: 'pyof versioned' module (OpenFlow specification defined), so we do
#: not have anything to do with it.
new_mod = MetaStruct.replace_pyof_version(cls_mod, new_version)
if new_mod is not None:
# Loads the module
new_mod = importlib.import_module(new_mod)
#: Get the class from the loaded module
new_cls = getattr(new_mod, cls_name)
#: return the tuple with the attribute name and the instance
return (name, new_cls())
return (name, obj)
|
def get_pyof_obj_new_version(name, obj, new_version)
|
r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will recover its class
and the module where the class was defined.
If the module is a "python-openflow version specific module" (starts
with "pyof.v0"), then we will get it's version and if it is different
from the 'new_version', then we will get the module on the
'new_version', look for the 'obj' class on the new module and return
an instance of the new version of the 'obj'.
Example:
>>> from pyof.foundation.base import MetaStruct as ms
>>> from pyof.v0x01.common.header import Header
>>> name = 'header'
>>> obj = Header()
>>> new_version = 'v0x04'
>>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version)
>>> header
'header'
>>> obj.version
UBInt8(1)
>>> obj2.version
UBInt8(4)
Args:
name (str): the name of the class attribute being handled.
obj (object): the class attribute itself
new_version (string): the pyof version in which you want the object
'obj'.
Return:
(str, obj): Tuple with class name and object instance.
A tuple in which the first item is the name of the class
attribute (the same that was passed), and the second item is a
instance of the passed class attribute. If the class attribute
is not a pyof versioned attribute, then the same passed object
is returned without any changes. Also, if the obj is a pyof
versioned attribute, but it is already on the right version
(same as new_version), then the passed obj is return.
| 4.739469 | 3.744191 | 1.265819 |
for _attr, _class in self._get_attributes():
if isinstance(_attr, _class):
return True
elif issubclass(_class, GenericType):
if GenericStruct._attr_fits_into_class(_attr, _class):
return True
elif not isinstance(_attr, _class):
return False
return True
|
def _validate_attributes_type(self)
|
Validate the type of each attribute.
| 5.774721 | 5.023049 | 1.149645 |
#: see this method docstring for a important notice about the use of
#: cls.__dict__
for name, value in cls.__dict__.items():
# gets only our (kytos) attributes. this ignores methods, dunder
# methods and attributes, and common python type attributes.
if GenericStruct._is_pyof_attribute(value):
yield (name, value)
|
def get_class_attributes(cls)
|
Return a generator for class attributes' names and value.
This method strict relies on the PEP 520 (Preserving Class Attribute
Definition Order), implemented on Python 3.6. So, if this behaviour
changes this whole lib can loose its functionality (since the
attributes order are a strong requirement.) For the same reason, this
lib will not work on python versions earlier than 3.6.
.. code-block:: python3
for name, value in self.get_class_attributes():
print("attribute name: {}".format(name))
print("attribute type: {}".format(value))
Returns:
generator: tuples with attribute name and value.
| 22.325735 | 21.479021 | 1.039421 |
for name, value in self.__dict__.items():
if name in map((lambda x: x[0]), self.get_class_attributes()):
yield (name, value)
|
def _get_instance_attributes(self)
|
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.
| 4.368962 | 5.025745 | 0.869316 |
return map((lambda i, c: (i[1], c[1])),
self._get_instance_attributes(),
self.get_class_attributes())
|
def _get_attributes(self)
|
Return a generator for instance and class attribute.
.. code-block:: python3
for instance_attribute, class_attribute in self._get_attributes():
print("Instance Attribute: {}".format(instance_attribute))
print("Class Attribute: {}".format(class_attribute))
Returns:
generator: Tuples with instance attribute and class attribute
| 9.288342 | 7.305624 | 1.271396 |
for cls, instance in zip(self.get_class_attributes(),
self._get_instance_attributes()):
attr_name, cls_value = cls
instance_value = instance[1]
yield attr_name, instance_value, cls_value
|
def _get_named_attributes(self)
|
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.
| 4.929834 | 4.042174 | 1.2196 |
if value is None:
return sum(cls_val.get_size(obj_val) for obj_val, cls_val in
self._get_attributes())
elif isinstance(value, type(self)):
return value.get_size()
else:
msg = "{} is not an instance of {}".format(value,
type(self).__name__)
raise PackException(msg)
|
def get_size(self, value=None)
|
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.
| 4.279128 | 3.9344 | 1.087619 |
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)
|
def pack(self, value=None)
|
Pack the struct in a binary representation.
Iterate over the class attributes, according to the
order of definition, and then convert each attribute to its byte
representation using its own ``pack`` method.
Returns:
bytes: Binary representation of the struct object.
Raises:
:exc:`~.exceptions.ValidationError`: If validation fails.
| 3.359564 | 3.294927 | 1.019617 |
if value is None:
self.update_header_length()
return super().pack()
elif isinstance(value, type(self)):
return value.pack()
else:
msg = "{} is not an instance of {}".format(value,
type(self).__name__)
raise PackException(msg)
|
def pack(self, value=None)
|
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.
| 3.728247 | 3.310796 | 1.126088 |
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
|
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.
| 6.165063 | 7.366247 | 0.836934 |
result = []
for key, value in self.iteritems():
if value & self.bitmask:
result.append(key)
return result
|
def names(self)
|
List of selected enum names.
Returns:
list: Enum names.
| 5.636436 | 5.889371 | 0.957052 |
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)
|
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.
| 4.389292 | 5.045666 | 0.869913 |
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'')
|
def _get_body_instance(self)
|
Return the body instance.
| 2.740803 | 2.684518 | 1.020966 |
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
|
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.
| 6.468979 | 5.250091 | 1.232165 |
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)
|
def _get_body_instance(self)
|
Return the body instance.
| 6.454335 | 5.683758 | 1.135575 |
super().unpack(buff, offset)
self.wildcards = UBInt32(value=FlowWildCards.OFPFW_ALL,
enum_ref=FlowWildCards)
self.wildcards.unpack(buff, offset)
|
def unpack(self, buff, offset=0)
|
Unpack *buff* into this object.
Do nothing, since the _length is already defined and it is just a Pad.
Keep buff and offset just for compability with other unpack methods.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: If unpack fails.
| 7.060421 | 8.421941 | 0.838337 |
if field in [None, 'wildcards'] or isinstance(value, Pad):
return
default_value = getattr(Match, field)
if isinstance(default_value, IPAddress):
if field == 'nw_dst':
shift = FlowWildCards.OFPFW_NW_DST_SHIFT
base_mask = FlowWildCards.OFPFW_NW_DST_MASK
else:
shift = FlowWildCards.OFPFW_NW_SRC_SHIFT
base_mask = FlowWildCards.OFPFW_NW_SRC_MASK
# First we clear the nw_dst/nw_src mask related bits on the current
# wildcard by setting 0 on all of them while we keep all other bits
# as they are.
self.wildcards &= FlowWildCards.OFPFW_ALL ^ base_mask
# nw_dst and nw_src wildcard fields have 6 bits each.
# "base_mask" is the 'all ones' for those 6 bits.
# Once we know the netmask, we can calculate the these 6 bits
# wildcard value and reverse them in order to insert them at the
# correct position in self.wildcards
wildcard = (value.max_prefix - value.netmask) << shift
self.wildcards |= wildcard
else:
wildcard_field = "OFPFW_{}".format(field.upper())
wildcard = getattr(FlowWildCards, wildcard_field)
if value == default_value and not (self.wildcards & wildcard) or \
value != default_value and (self.wildcards & wildcard):
self.wildcards ^= wildcard
|
def fill_wildcards(self, field=None, value=0)
|
Update wildcards attribute.
This method update a wildcards considering the attributes of the
current instance.
Args:
field (str): Name of the updated field.
value (GenericType): New value used in the field.
| 4.828935 | 4.861182 | 0.993366 |
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(':')])
|
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.
| 3.510399 | 3.903933 | 0.899196 |
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)
|
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.
| 3.922638 | 5.08991 | 0.770669 |
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)
|
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.
| 4.878989 | 5.181899 | 0.941545 |
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')
|
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.
| 4.085661 | 4.165996 | 0.980717 |
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))
|
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.
| 4.059963 | 4.495535 | 0.90311 |
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)
|
def pack(self, value=None)
|
Pack the value as a binary representation.
If the passed value (or the self._value) is zero (int), then the pack
will assume that the value to be packed is '00:00:00:00:00:00'.
Returns
bytes: The binary representation.
Raises:
struct.error: If the value does not fit the binary format.
| 3.606327 | 3.180954 | 1.133725 |
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
|
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.
| 4.052299 | 4.319527 | 0.938135 |
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}'")
|
def pack(self, value=None)
|
Pack the value as a binary representation.
Returns:
bytes: The binary representation.
Raises:
ValueError: If value can't be represented with bytes
| 3.145052 | 3.34727 | 0.939587 |
if value is None:
value = self._value
if hasattr(value, 'get_size'):
return value.get_size()
return len(self.pack(value))
|
def get_size(self, value=None)
|
Return the size in bytes.
Args:
value (bytes): In structs, the user can assign other value instead
of this class' instance. Here, in such cases, ``self`` is a
class attribute of the struct.
Returns:
int: The address size in bytes.
| 3.552142 | 4.016293 | 0.884433 |
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)
|
def pack(self, value=None)
|
Pack the value as a binary representation.
Returns:
bytes: The binary representation.
| 3.3657 | 3.401239 | 0.989551 |
begin = offset
limit_buff = len(buff)
while begin < limit_buff:
item = item_class()
item.unpack(buff, begin)
self.append(item)
begin += item.get_size()
|
def unpack(self, buff, item_class, offset=0)
|
Unpack the elements of the list.
Args:
buff (bytes): The binary data to be unpacked.
item_class (:obj:`type`): Class of the expected items on this list.
offset (int): If we need to shift the beginning of the data.
| 3.48334 | 3.792255 | 0.918541 |
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()
|
def get_size(self, value=None)
|
Return the size in bytes.
Args:
value: In structs, the user can assign other value instead of
this class' instance. Here, in such cases, ``self`` is a class
attribute of the struct.
Returns:
int: The size in bytes.
| 4.462822 | 4.740142 | 0.941495 |
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__)
|
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.
| 4.306952 | 3.539176 | 1.216936 |
if issubclass(item.__class__, self._pyof_class):
list.insert(self, index, item)
else:
raise exceptions.WrongListItemType(item.__class__.__name__,
self._pyof_class.__name__)
|
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.
| 5.108157 | 4.04448 | 1.262995 |
def unpack(self, buff, offset=0): # pylint: disable=arguments-differ
super().unpack(buff, self._pyof_class, offset)
|
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.
| null | null | null |
|
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__)
|
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.
| 3.375015 | 2.696835 | 1.251473 |
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__)
|
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.
| 3.885068 | 3.008832 | 1.291221 |
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()')
|
def get_size(self, value=None)
|
Return the action length including the padding (multiple of 8).
| 5.339352 | 4.261005 | 1.253073 |
self._update_length()
packet = super().pack()
return self._complete_last_byte(packet)
|
def pack(self, value=None)
|
Pack this structure updating the length and padding it.
| 14.13411 | 9.036143 | 1.564175 |
action_length = 4 + len(self.field.pack())
overflow = action_length % 8
self.length = action_length
if overflow:
self.length = action_length + 8 - overflow
|
def _update_length(self)
|
Update the length field of the struct.
| 6.853869 | 5.310986 | 1.290508 |
super().unpack(buff, offset)
if not self.is_valid():
raise UnpackException("Unsupported protocols in ARP packet")
|
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.
Check if the protocols involved are Ethernet and IPv4. Other protocols
are currently not supported.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: If unpack fails.
| 11.533863 | 8.15219 | 1.414818 |
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()
|
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.
| 2.717813 | 2.344412 | 1.159273 |
if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ):
raise UnpackException
return
|
def _validate(self)
|
Assure this is a valid VLAN header instance.
| 13.374357 | 7.536973 | 1.7745 |
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
|
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.
| 3.572555 | 3.193418 | 1.118725 |
length = 0
begin = 12
while(buff[begin:begin+2] in (EtherType.VLAN.to_bytes(2, 'big'),
EtherType.VLAN_QINQ.to_bytes(2, 'big'))):
length += 4
begin += 4
return length
|
def _get_vlan_length(buff)
|
Return the total length of VLAN tags in a given Ethernet buffer.
| 4.102768 | 3.410357 | 1.203032 |
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()
|
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.
| 3.935405 | 3.76696 | 1.044717 |
if value is None:
output = self.header.pack()
output += self.value.pack()
return output
elif isinstance(value, type(self)):
return value.pack()
else:
msg = "{} is not an instance of {}".format(value,
type(self).__name__)
raise PackException(msg)
|
def pack(self, value=None)
|
Pack the TLV in a binary representation.
Returns:
bytes: Binary representation of the struct object.
Raises:
:exc:`~.exceptions.ValidationError`: If validation fails.
| 3.370992 | 3.791016 | 0.889206 |
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])
|
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.
| 4.188161 | 5.033881 | 0.831994 |
if isinstance(value, type(self)):
return value.get_size()
return 2 + self.length
|
def get_size(self, value=None)
|
Return struct size.
Returns:
int: Returns the struct size based on inner attributes.
| 7.596492 | 8.29588 | 0.915695 |
source_list = [int(octet) for octet in self.source.split(".")]
destination_list = [int(octet) for octet in
self.destination.split(".")]
source_upper = (source_list[0] << 8) + source_list[1]
source_lower = (source_list[2] << 8) + source_list[3]
destination_upper = (destination_list[0] << 8) + destination_list[1]
destination_lower = (destination_list[2] << 8) + destination_list[3]
block_sum = ((self._version_ihl << 8 | self._dscp_ecn) + self.length +
self.identification + self._flags_offset +
(self.ttl << 8 | self.protocol) + source_upper +
source_lower + destination_upper + destination_lower)
while block_sum > 65535:
carry = block_sum >> 16
block_sum = (block_sum & 65535) + carry
self.checksum = ~block_sum & 65535
|
def _update_checksum(self)
|
Update the packet checksum to enable integrity check.
| 2.388454 | 2.178308 | 1.096472 |
# 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()
|
def pack(self, value=None)
|
Pack the struct in a binary representation.
Merge some fields to ensure correct packing.
Returns:
bytes: Binary representation of this instance.
| 4.216593 | 4.158116 | 1.014063 |
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''
|
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.
| 2.006174 | 2.088351 | 0.96065 |
binary = UBInt8(self.sub_type).pack() + self.sub_value.pack()
return BinaryData(binary)
|
def value(self)
|
Return sub type and sub value as binary data.
Returns:
:class:`~pyof.foundation.basic_types.BinaryData`:
BinaryData calculated.
| 11.456223 | 6.398577 | 1.790433 |
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])
|
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.
| 2.965861 | 3.343001 | 0.887185 |
if not isinstance(packet, bytes):
raise UnpackException('invalid packet')
packet_length = len(packet)
if packet_length < 8 or packet_length > 2**16:
raise UnpackException('invalid packet')
if packet_length != int.from_bytes(packet[2:4], byteorder='big'):
raise UnpackException('invalid packet')
version = packet[0]
if version == 0 or version >= 128:
raise UnpackException('invalid packet')
|
def validate_packet(packet)
|
Check if packet is valid OF packet.
Raises:
UnpackException: If the packet is invalid.
| 2.57829 | 2.355994 | 1.094353 |
validate_packet(packet)
version = packet[0]
try:
pyof_lib = PYOF_VERSION_LIBS[version]
except KeyError:
raise UnpackException('Version not supported')
try:
message = pyof_lib.common.utils.unpack_message(packet)
return message
except (UnpackException, ValueError) as exception:
raise UnpackException(exception)
|
def unpack(packet)
|
Unpack the OpenFlow Packet and returns a message.
Args:
packet: buffer with the openflow packet.
Returns:
GenericMessage: Message unpacked based on openflow packet.
Raises:
UnpackException: if the packet can't be unpacked.
| 4.955664 | 4.608276 | 1.075383 |
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)
|
def get_class(self)
|
Return a Code class based on current ErrorType value.
Returns:
enum.IntEnum: class referenced by current error type.
| 1.677833 | 1.536384 | 1.092066 |
super().unpack(buff, offset)
code_class = ErrorType(self.error_type).get_class()
self.code = code_class(self.code)
|
def unpack(self, buff, offset=0)
|
Unpack binary data into python object.
| 5.730001 | 5.599963 | 1.023221 |
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)
|
def get_class(self)
|
Return a Code class based on current ErrorType value.
Returns:
enum.IntEnum: class referenced by current error type.
| 2.802546 | 2.291971 | 1.222766 |
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)
|
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.
| 2.655389 | 2.561334 | 1.036721 |
icon = qutepart.getIcon(iconFileName)
action = QAction(icon, text, widget)
action.setShortcut(QKeySequence(shortcut))
action.setShortcutContext(Qt.WidgetShortcut)
action.triggered.connect(slot)
widget.addAction(action)
return action
|
def _createAction(self, widget, iconFileName, text, shortcut, slot)
|
Create QAction with given parameters and add to the widget
| 2.601144 | 2.413193 | 1.077885 |
for block in qutepart.iterateBlocksFrom(startBlock):
self._setBlockMarked(block, False)
if block == endBlock:
break
|
def clear(self, startBlock, endBlock)
|
Clear bookmarks on block range including start and end
| 11.135091 | 12.210793 | 0.911906 |
for block in qutepart.iterateBlocksBackFrom(self._qpart.textCursor().block().previous()):
if self.isBlockMarked(block):
self._qpart.setTextCursor(QTextCursor(block))
return
|
def _onPrevBookmark(self)
|
Previous Bookmark action triggered. Move cursor
| 9.455732 | 9.025444 | 1.047675 |
for block in qutepart.iterateBlocksFrom(self._qpart.textCursor().block().next()):
if self.isBlockMarked(block):
self._qpart.setTextCursor(QTextCursor(block))
return
|
def _onNextBookmark(self)
|
Previous Bookmark action triggered. Move cursor
| 8.533087 | 8.228267 | 1.037045 |
# 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()
|
def _iterateDocumentCharsForward(self, block, startColumnIndex)
|
Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
| 4.750523 | 3.515059 | 1.351477 |
# 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()
|
def _iterateDocumentCharsBackward(self, block, startColumnIndex)
|
Traverse document forward. Yield (block, columnIndex, char)
Raise _TimeoutException if time is over
| 4.21651 | 3.110909 | 1.355395 |
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
|
def _findMatchingBracket(self, bracket, qpart, block, columnIndex)
|
Find matching bracket for the bracket.
Return (block, columnIndex) or (None, None)
Raise _TimeoutException, if time is over
| 3.813597 | 3.915547 | 0.973963 |
selection = QTextEdit.ExtraSelection()
if matched:
bgColor = Qt.green
else:
bgColor = Qt.red
selection.format.setBackground(bgColor)
selection.cursor = QTextCursor(block)
selection.cursor.setPosition(block.position() + columnIndex)
selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
return selection
|
def _makeMatchSelection(self, block, columnIndex, matched)
|
Make matched or unmatched QTextEdit.ExtraSelection
| 2.142805 | 1.881727 | 1.138744 |
try:
matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex)
except _TimeoutException: # not found, time is over
return[] # highlight nothing
if matchedBlock is not None:
self.currentMatchedBrackets = ((block, columnIndex), (matchedBlock, matchedColumnIndex))
return [self._makeMatchSelection(block, columnIndex, True),
self._makeMatchSelection(matchedBlock, matchedColumnIndex, True)]
else:
self.currentMatchedBrackets = None
return [self._makeMatchSelection(block, columnIndex, False)]
|
def _highlightBracket(self, bracket, qpart, block, columnIndex)
|
Highlight bracket and matching bracket
Return tuple of QTextEdit.ExtraSelection's
| 3.973464 | 3.811101 | 1.042603 |
blockText = block.text()
if columnIndex < len(blockText) and \
blockText[columnIndex] in self._ALL_BRACKETS and \
qpart.isCode(block, columnIndex):
return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex)
elif columnIndex > 0 and \
blockText[columnIndex - 1] in self._ALL_BRACKETS and \
qpart.isCode(block, columnIndex - 1):
return self._highlightBracket(blockText[columnIndex - 1], qpart, block, columnIndex - 1)
else:
self.currentMatchedBrackets = None
return []
|
def extraSelections(self, qpart, block, columnIndex)
|
List of QTextEdit.ExtraSelection's, which highlighte brackets
| 2.940439 | 2.722139 | 1.080194 |
if a.format == b.format and \
a.start == b.start and \
a.length == b.length:
return 0
else:
return cmp(id(a), id(b))
|
def _cmpFormatRanges(a, b)
|
PyQt does not define proper comparison for QTextLayout.FormatRange
Define it to check correctly, if formats has changed.
It is important for the performance
| 2.521149 | 2.769732 | 0.91025 |
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isCode(data, column)
|
def isCode(self, block, column)
|
Check if character at column is a a code
| 7.808517 | 8.199626 | 0.952302 |
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isComment(data, column)
|
def isComment(self, block, column)
|
Check if character at column is a comment
| 7.876111 | 7.937848 | 0.992223 |
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isBlockComment(data, column)
|
def isBlockComment(self, block, column)
|
Check if character at column is a block comment
| 7.283656 | 7.624322 | 0.955318 |
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isHereDoc(data, column)
|
def isHereDoc(self, block, column)
|
Check if character at column is a here document
| 7.783542 | 8.368964 | 0.930048 |
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:
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
documentLayout = self._textEdit.document().documentLayout()
documentLayout.documentSizeChanged.emit(documentLayout.documentSize())
|
def _highlighBlocks(self, fromBlock, atLeastUntilBlock, timeout)
|
Emit sizeChanged when highlighting finished, because document size might change.
See andreikop/enki issue #191
| 3.336718 | 3.104952 | 1.074644 |
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))
|
def computeSmartIndent(self, block, ch)
|
special rules: ;;; -> indent 0
;; -> align with next line, if possible
; -> usually on the same line as code -> ignore
| 5.471166 | 4.918432 | 1.11238 |
def wrapper(*args, **kwargs):
self = args[0]
with self._qpart:
func(*args, **kwargs)
return wrapper
|
def _atomicModification(func)
|
Decorator
Make document modification atomic
| 4.735753 | 5.046943 | 0.938341 |
if index < 0:
index = len(self) + index
if index < 0 or index >= self._doc.blockCount():
raise IndexError('Invalid block index', index)
return index
|
def _checkAndConvertIndex(self, index)
|
Check integer index, convert from less than zero notation
| 4.460642 | 3.919117 | 1.138175 |
cursor = QTextCursor(self._doc)
cursor.movePosition(QTextCursor.End)
cursor.insertBlock()
cursor.insertText(text)
|
def append(self, text)
|
Append line to the end
| 3.367366 | 3.442956 | 0.978045 |
if index < 0 or index > self._doc.blockCount():
raise IndexError('Invalid block index', index)
if index == 0: # first
cursor = QTextCursor(self._doc.firstBlock())
cursor.insertText(text)
cursor.insertBlock()
elif index != self._doc.blockCount(): # not the last
cursor = QTextCursor(self._doc.findBlockByNumber(index).previous())
cursor.movePosition(QTextCursor.EndOfBlock)
cursor.insertBlock()
cursor.insertText(text)
else: # last append to the end
self.append(text)
|
def insert(self, index, text)
|
Insert line to the document
| 2.957508 | 2.88342 | 1.025695 |
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)
|
def computeSmartIndent(self, block, char)
|
Compute indent for the block
| 4.011034 | 3.953453 | 1.014565 |
block = self._prevNonEmptyBlock(block)
while block.isValid() and self._isCommentBlock(block):
block = self._prevNonEmptyBlock(block)
return block
|
def _prevNonCommentBlock(self, block)
|
Return the closest non-empty line, ignoring comments
(result <= line). Return -1 if the document
| 3.09581 | 3.484935 | 0.888341 |
return column >= self._lastColumn(block) or \
self._isComment(block, self._nextNonSpaceColumn(block, column + 1))
|
def _isLastCodeColumn(self, block, column)
|
Return true if the given column is at least equal to the column that
contains the last non-whitespace character at the given line, or if
the rest of the line is a comment.
| 6.580703 | 5.064176 | 1.299462 |
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
|
def lastAnchor(self, block, column)
|
Find the last open bracket before the current line.
Return (block, column, char) or (None, None, None)
| 3.580777 | 3.226116 | 1.109934 |
prevBlock = self._prevNonCommentBlock(block)
while prevBlock.isValid() and \
(((prevBlock == block.previous()) and self._isBlockContinuing(prevBlock)) or \
self.isStmtContinuing(prevBlock)):
block = prevBlock
prevBlock = self._prevNonCommentBlock(block)
return block
|
def findStmtStart(self, block)
|
Return the first line that is not preceded by a "continuing" line.
Return currBlock if currBlock <= 0
| 4.485328 | 4.029511 | 1.11312 |
if ch == "" or ch == "\n":
return True # Explicit align or new line
match = rxUnindent.match(block.text())
return match is not None and \
match.group(3) == ""
|
def _isValidTrigger(block, ch)
|
check if the trigger characters are in the right context,
otherwise running the indenter might be annoying to the user
| 12.724175 | 11.679955 | 1.089403 |
stmtEnd = self._prevNonCommentBlock(block)
stmtStart = self.findStmtStart(stmtEnd)
return Statement(self._qpart, stmtStart, stmtEnd)
|
def findPrevStmt(self, block)
|
Returns a tuple that contains the first and last line of the
previous statement before line.
| 8.804711 | 9.072548 | 0.970478 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.