timezone_offset = value.find('<STR_LIT>')<EOL>if timezone_offset == -<NUM_LIT:1>:<EOL><INDENT>timezone_offset = value.find('<STR_LIT:+>')<EOL><DEDENT>if timezone_offset == -<NUM_LIT:1>:<EOL><INDENT>timezone_offset = value.rfind('<STR_LIT:->')<EOL><DEDENT>if timezone_offset == -<NUM_LIT:1>:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>')<EOL><DEDENT>time_value = value[<NUM_LIT:0>:timezone_offset]<EOL>point_position = time_value.find('<STR_LIT:.>')<EOL>if point_position == -<NUM_LIT:1>:<EOL><INDENT>second_value = time_value<EOL>nano_value = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>second_value = time_value[:point_position]<EOL>nano_value = time_value[point_position + <NUM_LIT:1>:]<EOL><DEDENT>date_object = datetime.strptime(second_value, _TIMESTAMPFOMAT)<EOL>td = date_object - datetime(<NUM_LIT>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>seconds = td.seconds + td.days * _SECONDS_PER_DAY<EOL>if len(nano_value) > <NUM_LIT:9>:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(nano_value))<EOL><DEDENT>if nano_value:<EOL><INDENT>nanos = round(float('<STR_LIT>' + nano_value) * <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>nanos = <NUM_LIT:0><EOL><DEDENT>if value[timezone_offset] == '<STR_LIT>':<EOL><INDENT>if len(value) != timezone_offset + <NUM_LIT:1>:<EOL><INDENT>raise ParseError('<STR_LIT>'<EOL>'<STR_LIT>'.format(value))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>timezone = value[timezone_offset:]<EOL>pos = timezone.find('<STR_LIT::>')<EOL>if pos == -<NUM_LIT:1>:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(timezone))<EOL><DEDENT>if timezone[<NUM_LIT:0>] == '<STR_LIT:+>':<EOL><INDENT>seconds -= (int(timezone[<NUM_LIT:1>:pos])*<NUM_LIT>+int(timezone[pos+<NUM_LIT:1>:]))*<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>seconds += (int(timezone[<NUM_LIT:1>:pos])*<NUM_LIT>+int(timezone[pos+<NUM_LIT:1>:]))*<NUM_LIT><EOL><DEDENT><DEDENT>self.seconds = int(seconds)<EOL>self.nanos = int(nanos)<EOL>

Parse a RFC 3339 date string format to Timestamp.

        Args:
          value: A date string. Any fractional digits (or none) and any offset are
              accepted as long as they fit into nano-seconds precision.
              Example of accepted format: '1972-01-01T10:00:20.021-05:00'

        Raises:
          ParseError: On parsing problems.


self.FromDatetime(datetime.utcnow())<EOL>


return self.seconds * _NANOS_PER_SECOND + self.nanos<EOL>

Converts Timestamp to nanoseconds since epoch.


return (self.seconds * _MICROS_PER_SECOND +<EOL>self.nanos // _NANOS_PER_MICROSECOND)<EOL>

Converts Timestamp to microseconds since epoch.


return (self.seconds * _MILLIS_PER_SECOND +<EOL>self.nanos // _NANOS_PER_MILLISECOND)<EOL>

Converts Timestamp to milliseconds since epoch.


return self.seconds<EOL>

Converts Timestamp to seconds since epoch.


self.seconds = nanos // _NANOS_PER_SECOND<EOL>self.nanos = nanos % _NANOS_PER_SECOND<EOL>

Converts nanoseconds since epoch to Timestamp.


self.seconds = micros // _MICROS_PER_SECOND<EOL>self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND<EOL>

Converts microseconds since epoch to Timestamp.


self.seconds = millis // _MILLIS_PER_SECOND<EOL>self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND<EOL>

Converts milliseconds since epoch to Timestamp.


self.seconds = seconds<EOL>self.nanos = <NUM_LIT:0><EOL>

Converts seconds since epoch to Timestamp.


return datetime.utcfromtimestamp(<EOL>self.seconds + self.nanos / float(_NANOS_PER_SECOND))<EOL>


td = dt - datetime(<NUM_LIT>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>self.seconds = td.seconds + td.days * _SECONDS_PER_DAY<EOL>self.nanos = td.microseconds * _NANOS_PER_MICROSECOND<EOL>


if self.seconds < <NUM_LIT:0> or self.nanos < <NUM_LIT:0>:<EOL><INDENT>result = '<STR_LIT:->'<EOL>seconds = - self.seconds + int((<NUM_LIT:0> - self.nanos) // <NUM_LIT>)<EOL>nanos = (<NUM_LIT:0> - self.nanos) % <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>result = '<STR_LIT>'<EOL>seconds = self.seconds + int(self.nanos // <NUM_LIT>)<EOL>nanos = self.nanos % <NUM_LIT><EOL><DEDENT>result += '<STR_LIT>' % seconds<EOL>if (nanos % <NUM_LIT>) == <NUM_LIT:0>:<EOL><INDENT>return result + '<STR_LIT:s>'<EOL><DEDENT>if (nanos % <NUM_LIT>) == <NUM_LIT:0>:<EOL><INDENT>return result + '<STR_LIT>' % (nanos / <NUM_LIT>)<EOL><DEDENT>if (nanos % <NUM_LIT>) == <NUM_LIT:0>:<EOL><INDENT>return result + '<STR_LIT>' % (nanos / <NUM_LIT>)<EOL><DEDENT>return result + '<STR_LIT>' % nanos<EOL>

Converts Duration to string format.

        Returns:
          A string converted from self. The string format will contains
          3, 6, or 9 fractional digits depending on the precision required to
          represent the exact Duration value. For example: "1s", "1.010s",
          "1.000000100s", "-3.100s"


if len(value) < <NUM_LIT:1> or value[-<NUM_LIT:1>] != '<STR_LIT:s>':<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(value))<EOL><DEDENT>try:<EOL><INDENT>pos = value.find('<STR_LIT:.>')<EOL>if pos == -<NUM_LIT:1>:<EOL><INDENT>self.seconds = int(value[:-<NUM_LIT:1>])<EOL>self.nanos = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>self.seconds = int(value[:pos])<EOL>if value[<NUM_LIT:0>] == '<STR_LIT:->':<EOL><INDENT>self.nanos = int(round(float('<STR_LIT>'.format(value[pos: -<NUM_LIT:1>])) *<NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>self.nanos = int(round(float('<STR_LIT>'.format(value[pos: -<NUM_LIT:1>])) *<NUM_LIT>))<EOL><DEDENT><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(value))<EOL><DEDENT>

Converts a string to Duration.

        Args:
          value: A string to be converted. The string must end with 's'. Any
              fractional digits (or none) are accepted as long as they fit into
              precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s

        Raises:
          ParseError: On parsing problems.


micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)<EOL>return self.seconds * _MICROS_PER_SECOND + micros<EOL>


millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND)<EOL>return self.seconds * _MILLIS_PER_SECOND + millis<EOL>


return self.seconds<EOL>


self._NormalizeDuration(nanos // _NANOS_PER_SECOND,<EOL>nanos % _NANOS_PER_SECOND)<EOL>


self._NormalizeDuration(<EOL>micros // _MICROS_PER_SECOND,<EOL>(micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)<EOL>


self._NormalizeDuration(<EOL>millis // _MILLIS_PER_SECOND,<EOL>(millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND)<EOL>


return timedelta(<EOL>seconds=self.seconds, microseconds=_RoundTowardZero(<EOL>self.nanos, _NANOS_PER_MICROSECOND))<EOL>


self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,<EOL>td.microseconds * _NANOS_PER_MICROSECOND)<EOL>


def _NormalizeDuration(self, seconds, nanos):

<EOL>if seconds < <NUM_LIT:0> and nanos > <NUM_LIT:0>:<EOL><INDENT>seconds += <NUM_LIT:1><EOL>nanos -= _NANOS_PER_SECOND<EOL><DEDENT>self.seconds = seconds<EOL>self.nanos = nanos<EOL>


return '<STR_LIT:U+002C>'.join(self.paths)<EOL>

Converts FieldMask to string according to proto3 JSON spec.


self.Clear()<EOL>for path in value.split('<STR_LIT:U+002C>'):<EOL><INDENT>self.paths.append(path)<EOL><DEDENT>

Converts string to FieldMask according to proto3 JSON spec.


for path in self.paths:<EOL><INDENT>if not _IsValidPath(message_descriptor, path):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Checks whether the FieldMask is valid for Message Descriptor.


self.Clear()<EOL>for field in message_descriptor.fields:<EOL><INDENT>self.paths.append(field.name)<EOL><DEDENT>

Gets all direct fields of Message Descriptor to FieldMask.


tree = _FieldMaskTree(mask)<EOL>tree.ToFieldMask(self)<EOL>

Converts a FieldMask to the canonical form.

        Removes paths that are covered by another path. For example,
        "foo.bar" is covered by "foo" and will be removed if "foo"
        is also in the FieldMask. Then sorts all paths in alphabetical order.

        Args:
          mask: The original FieldMask to be converted.


_CheckFieldMaskMessage(mask1)<EOL>_CheckFieldMaskMessage(mask2)<EOL>tree = _FieldMaskTree(mask1)<EOL>tree.MergeFromFieldMask(mask2)<EOL>tree.ToFieldMask(self)<EOL>

Merges mask1 and mask2 into this FieldMask.


_CheckFieldMaskMessage(mask1)<EOL>_CheckFieldMaskMessage(mask2)<EOL>tree = _FieldMaskTree(mask1)<EOL>intersection = _FieldMaskTree()<EOL>for path in mask2.paths:<EOL><INDENT>tree.IntersectPath(path, intersection)<EOL><DEDENT>intersection.ToFieldMask(self)<EOL>

Intersects mask1 and mask2 into this FieldMask.


def MergeMessage(<EOL>self, source, destination,<EOL>replace_message_field=False, replace_repeated_field=False):

tree = _FieldMaskTree(self)<EOL>tree.MergeMessage(<EOL>source, destination, replace_message_field, replace_repeated_field)<EOL>

Merges fields specified in FieldMask from source to destination.

        Args:
          source: Source message.
          destination: The destination message to be merged into.
          replace_message_field: Replace message field if True. Merge message
              field if False.
          replace_repeated_field: Replace repeated field if True. Append
              elements of repeated field if False.


self._root = {}<EOL>if field_mask:<EOL><INDENT>self.MergeFromFieldMask(field_mask)<EOL><DEDENT>


for path in field_mask.paths:<EOL><INDENT>self.AddPath(path)<EOL><DEDENT>


node = self._root<EOL>for name in path.split('<STR_LIT:.>'):<EOL><INDENT>if name not in node:<EOL><INDENT>node[name] = {}<EOL><DEDENT>elif not node[name]:<EOL><INDENT>return<EOL><DEDENT>node = node[name]<EOL><DEDENT>node.clear()<EOL>

Adds a field path into the tree.

        If the field path to add is a sub-path of an existing field path
        in the tree (i.e., a leaf node), it means the tree already matches
        the given path so nothing will be added to the tree. If the path
        matches an existing non-leaf node in the tree, that non-leaf node
        will be turned into a leaf node with all its children removed because
        the path matches all the node's children. Otherwise, a new path will
        be added.

        Args:
          path: The field path to add.


field_mask.Clear()<EOL>_AddFieldPaths(self._root, '<STR_LIT>', field_mask)<EOL>


def IntersectPath(self, path, intersection):

node = self._root<EOL>for name in path.split('<STR_LIT:.>'):<EOL><INDENT>if name not in node:<EOL><INDENT>return<EOL><DEDENT>elif not node[name]:<EOL><INDENT>intersection.AddPath(path)<EOL>return<EOL><DEDENT>node = node[name]<EOL><DEDENT>intersection.AddLeafNodes(path, node)<EOL>

Calculates the intersection part of a field path with this tree.

        Args:
          path: The field path to calculates.
          intersection: The out tree to record the intersection part.


if not node:<EOL><INDENT>self.AddPath(prefix)<EOL><DEDENT>for name in node:<EOL><INDENT>child_path = prefix + '<STR_LIT:.>' + name<EOL>self.AddLeafNodes(child_path, node[name])<EOL><DEDENT>

Adds leaf nodes begin with prefix to this tree.


def MergeMessage(<EOL>self, source, destination,<EOL>replace_message, replace_repeated):

_MergeMessage(<EOL>self._root, source, destination, replace_message, replace_repeated)<EOL>

Merge all fields specified by this tree from source to destination.


return self.fields[key].list_value<EOL>

Returns a list for this key, creating if it didn't exist already.


return self.fields[key].struct_value<EOL>

Returns a struct for this key, creating if it didn't exist already.


return _GetStructValue(self.values.__getitem__(index))<EOL>


return self.values.add().struct_value<EOL>

Appends and returns a struct value as the next value in the list.


return self.values.add().list_value<EOL>

Appends and returns a list value as the next value in the list.


if not <NUM_LIT:0> <= wire_type <= _WIRETYPE_MAX:<EOL><INDENT>raise message.EncodeError('<STR_LIT>' % wire_type)<EOL><DEDENT>return (field_number << TAG_TYPE_BITS) | wire_type<EOL>

Returns an unsigned 32-bit integer that encodes the field number and
    wire type information in standard protocol message wire format.

    Args:
      field_number: Expected to be an integer in the range [1, 1 << 29)
      wire_type: One of the WIRETYPE_* constants.


return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)<EOL>

The inverse of PackTag().  Given an unsigned 32-bit number,
    returns a (field_number, wire_type) tuple.


if value >= <NUM_LIT:0>:<EOL><INDENT>return value << <NUM_LIT:1><EOL><DEDENT>return (value << <NUM_LIT:1>) ^ (~<NUM_LIT:0>)<EOL>

ZigZag Transform:  Encodes signed integers so that they can be
    effectively used with varint encoding.  See wire_format.h for
    more details.


if not value & <NUM_LIT>:<EOL><INDENT>return value >> <NUM_LIT:1><EOL><DEDENT>return (value >> <NUM_LIT:1>) ^ (~<NUM_LIT:0>)<EOL>


<EOL>return _VarUInt64ByteSizeNoTag(PackTag(field_number, <NUM_LIT:0>))<EOL>

Returns the bytes required to serialize a tag with this field number.


if uint64 <= <NUM_LIT>: return <NUM_LIT:1><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:2><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:3><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:4><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:5><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:6><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:7><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:8><EOL>if uint64 <= <NUM_LIT>: return <NUM_LIT:9><EOL>if uint64 > UINT64_MAX:<EOL><INDENT>raise message.EncodeError('<STR_LIT>' % uint64)<EOL><DEDENT>return <NUM_LIT:10><EOL>

Returns the number of bytes required to serialize a single varint
    using boundary value comparisons. (unrolled loop optimization -WPierce)
    uint64 must be unsigned.


return field_type not in NON_PACKABLE_TYPES<EOL>

Return true iff packable = true is valid for fields of this type.

    Args:
      field_type: a FieldDescriptor::Type value.

    Returns:
      True iff fields of this type are packable.


self._enum_type = enum_type<EOL>self.DESCRIPTOR = enum_type<EOL>

Inits EnumTypeWrapper with an EnumDescriptor.


if number in self._enum_type.values_by_number:<EOL><INDENT>return self._enum_type.values_by_number[number].name<EOL><DEDENT>raise ValueError('<STR_LIT>' % (<EOL>self._enum_type.name, number))<EOL>

Returns a string containing the name of an enum value.


if name in self._enum_type.values_by_name:<EOL><INDENT>return self._enum_type.values_by_name[name].number<EOL><DEDENT>raise ValueError('<STR_LIT>' % (<EOL>self._enum_type.name, name))<EOL>

Returns the value coresponding to the given enum name.


return [value_descriptor.name<EOL>for value_descriptor in self._enum_type.values]<EOL>

Return a list of the string names in the enum.

        These are returned in the order they were defined in the .proto file.


return [value_descriptor.number<EOL>for value_descriptor in self._enum_type.values]<EOL>

Return a list of the integer values in the enum.

        These are returned in the order they were defined in the .proto file.


return [(value_descriptor.name, value_descriptor.number)<EOL>for value_descriptor in self._enum_type.values]<EOL>

Return a list of the (name, value) pairs of the enum.

        These are returned in the order they were defined in the .proto file.


if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and<EOL>field.type == _FieldDescriptor.TYPE_STRING):<EOL><INDENT>return UnicodeValueChecker()<EOL><DEDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:<EOL><INDENT>if SupportsOpenEnums(field):<EOL><INDENT>return _VALUE_CHECKERS[_FieldDescriptor.CPPTYPE_INT32]<EOL><DEDENT>else:<EOL><INDENT>return EnumValueChecker(field.enum_type)<EOL><DEDENT><DEDENT>return _VALUE_CHECKERS[field.cpp_type]<EOL>

Returns a type checker for a message field of the specified types.

    Args:
      field: FieldDescriptor object for this field.

    Returns:
      An instance of TypeChecker which can be used to verify the types
      of values assigned to a field of the specified type.


if not isinstance(proposed_value, self._acceptable_types):<EOL><INDENT>message = ('<STR_LIT>' %<EOL>(proposed_value, type(proposed_value), self._acceptable_types))<EOL>raise TypeError(message)<EOL><DEDENT>return proposed_value<EOL>

Type check the provided value and return it.

        The returned value might have been normalized to another type.


def DecodeVarint(buffer, pos):<EOL><INDENT>result = <NUM_LIT:0><EOL>shift = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>b = six.indexbytes(buffer, pos)<EOL>result |= ((b & <NUM_LIT>) << shift)<EOL>pos += <NUM_LIT:1><EOL>if not (b & <NUM_LIT>):<EOL><INDENT>result &= mask<EOL>result = result_type(result)<EOL>return (result, pos)<EOL><DEDENT>shift += <NUM_LIT:7><EOL>if shift >= <NUM_LIT:64>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return DecodeVarint<EOL>

Return an encoder for a basic varint value (does not include tag).

    Decoded values will be bitwise-anded with the given mask before being
    returned, e.g. to limit them to 32 bits.  The returned decoder does not
    take the usual "end" parameter -- the caller is expected to do bounds checking
    after the fact (often the caller can defer such checking until later).  The
    decoder returns a (value, new_pos) pair.


def DecodeVarint(buffer, pos):<EOL><INDENT>result = <NUM_LIT:0><EOL>shift = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>b = six.indexbytes(buffer, pos)<EOL>result |= ((b & <NUM_LIT>) << shift)<EOL>pos += <NUM_LIT:1><EOL>if not (b & <NUM_LIT>):<EOL><INDENT>if result > <NUM_LIT>:<EOL><INDENT>result -= (<NUM_LIT:1> << <NUM_LIT:64>)<EOL>result |= ~mask<EOL><DEDENT>else:<EOL><INDENT>result &= mask<EOL><DEDENT>result = result_type(result)<EOL>return (result, pos)<EOL><DEDENT>shift += <NUM_LIT:7><EOL>if shift >= <NUM_LIT:64>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return DecodeVarint<EOL>

Like _VarintDecoder() but decodes signed values.


start = pos<EOL>while six.indexbytes(buffer, pos) & <NUM_LIT>:<EOL><INDENT>pos += <NUM_LIT:1><EOL><DEDENT>pos += <NUM_LIT:1><EOL>return (buffer[start:pos], pos)<EOL>

Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.

    We return the raw bytes of the tag rather than decoding them.  The raw
    bytes can then be used to look up the proper decoder.  This effectively allows
    us to trade some work that would be done in pure-python (decoding a varint)
    for work that is done in C (searching for a byte string in a hash table).
    In a low-level language it would be much cheaper to decode the varint and
    use that, but not in Python.


def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default):<EOL><INDENT>if is_packed:<EOL><INDENT>local_DecodeVarint = _DecodeVarint<EOL>def DecodePackedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>(endpoint, pos) = local_DecodeVarint(buffer, pos)<EOL>endpoint += pos<EOL>if endpoint > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>while pos < endpoint:<EOL><INDENT>(element, pos) = decode_value(buffer, pos)<EOL>value.append(element)<EOL><DEDENT>if pos > endpoint:<EOL><INDENT>del value[-<NUM_LIT:1>]   <EOL>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL><DEDENT>return DecodePackedField<EOL><DEDENT>elif is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number, wire_type)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(element, new_pos) = decode_value(buffer, pos)<EOL>value.append(element)<EOL>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos >= end:<EOL><INDENT>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>(field_dict[key], pos) = decode_value(buffer, pos)<EOL>if pos > end:<EOL><INDENT>del field_dict[key]  <EOL>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL><DEDENT>return DecodeField<EOL><DEDENT><DEDENT>return SpecificDecoder<EOL>

Return a constructor for a decoder for fields of a particular type.

    Args:
        wire_type:  The field's wire type.
        decode_value:  A function which decodes an individual value, e.g.
          _DecodeVarint()


def _ModifiedDecoder(wire_type, decode_value, modify_value):

<EOL>def InnerDecode(buffer, pos):<EOL><INDENT>(result, new_pos) = decode_value(buffer, pos)<EOL>return (modify_value(result), new_pos)<EOL><DEDENT>return _SimpleDecoder(wire_type, InnerDecode)<EOL>

Like SimpleDecoder but additionally invokes modify_value on every value
    before storing it.  Usually modify_value is ZigZagDecode.


value_size = struct.calcsize(format)<EOL>local_unpack = struct.unpack<EOL>def InnerDecode(buffer, pos):<EOL><INDENT>new_pos = pos + value_size<EOL>result = local_unpack(format, buffer[pos:new_pos])[<NUM_LIT:0>]<EOL>return (result, new_pos)<EOL><DEDENT>return _SimpleDecoder(wire_type, InnerDecode)<EOL>

Return a constructor for a decoder for a fixed-width field.

    Args:
        wire_type:  The field's wire type.
        format:  The format string to pass to struct.unpack().


local_unpack = struct.unpack<EOL>def InnerDecode(buffer, pos):<EOL><INDENT>new_pos = pos + <NUM_LIT:4><EOL>float_bytes = buffer[pos:new_pos]<EOL>if (float_bytes[<NUM_LIT:3>:<NUM_LIT:4>] in b'<STR_LIT>' and float_bytes[<NUM_LIT:2>:<NUM_LIT:3>] >= b'<STR_LIT>'):<EOL><INDENT>if float_bytes[<NUM_LIT:0>:<NUM_LIT:3>] != b'<STR_LIT>':<EOL><INDENT>return (_NAN, new_pos)<EOL><DEDENT>if float_bytes[<NUM_LIT:3>:<NUM_LIT:4>] == b'<STR_LIT>':<EOL><INDENT>return (_NEG_INF, new_pos)<EOL><DEDENT>return (_POS_INF, new_pos)<EOL><DEDENT>result = local_unpack('<STR_LIT>', float_bytes)[<NUM_LIT:0>]<EOL>return (result, new_pos)<EOL><DEDENT>return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)<EOL>

Returns a decoder for a float field.

    This code works around a bug in struct.unpack for non-finite 32-bit
    floating-point values.


local_unpack = struct.unpack<EOL>def InnerDecode(buffer, pos):<EOL><INDENT>new_pos = pos + <NUM_LIT:8><EOL>double_bytes = buffer[pos:new_pos]<EOL>if ((double_bytes[<NUM_LIT:7>:<NUM_LIT:8>] in b'<STR_LIT>')<EOL>and (double_bytes[<NUM_LIT:6>:<NUM_LIT:7>] >= b'<STR_LIT>')<EOL>and (double_bytes[<NUM_LIT:0>:<NUM_LIT:7>] != b'<STR_LIT>')):<EOL><INDENT>return (_NAN, new_pos)<EOL><DEDENT>result = local_unpack('<STR_LIT>', double_bytes)[<NUM_LIT:0>]<EOL>return (result, new_pos)<EOL><DEDENT>return _SimpleDecoder(wire_format.WIRETYPE_FIXED64, InnerDecode)<EOL>

Returns a decoder for a double field.

    This code works around a bug in struct.unpack for not-a-number.


def StringDecoder(field_number, is_repeated, is_packed, key, new_default):

local_DecodeVarint = _DecodeVarint<EOL>local_unicode = six.text_type<EOL>def _ConvertToUnicode(byte_str):<EOL><INDENT>try:<EOL><INDENT>return local_unicode(byte_str, '<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeDecodeError as e:<EOL><INDENT>e.reason = '<STR_LIT>' % (e, key.full_name)<EOL>raise<EOL><DEDENT><DEDENT>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>value.append(_ConvertToUnicode(buffer[pos:new_pos]))<EOL>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos])<EOL>return new_pos<EOL><DEDENT>return DecodeField<EOL><DEDENT>


def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):

local_DecodeVarint = _DecodeVarint<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>value.append(buffer[pos:new_pos])<EOL>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>field_dict[key] = buffer[pos:new_pos]<EOL>return new_pos<EOL><DEDENT>return DecodeField<EOL><DEDENT>


def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):

end_tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_END_GROUP)<EOL>end_tag_len = len(end_tag_bytes)<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_START_GROUP)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>pos = value.add()._InternalParse(buffer, pos, end)<EOL>new_pos = pos+end_tag_len<EOL>if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>pos = value._InternalParse(buffer, pos, end)<EOL>new_pos = pos+end_tag_len<EOL>if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return new_pos<EOL><DEDENT>return DecodeField<EOL><DEDENT>


def MessageDecoder(field_number, is_repeated, is_packed, key, new_default):

local_DecodeVarint = _DecodeVarint<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if value.add()._InternalParse(buffer, pos, new_pos) != new_pos:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if value._InternalParse(buffer, pos, new_pos) != new_pos:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return new_pos<EOL><DEDENT>return DecodeField<EOL><DEDENT>


type_id_tag_bytes = encoder.TagBytes(<NUM_LIT:2>, wire_format.WIRETYPE_VARINT)<EOL>message_tag_bytes = encoder.TagBytes(<NUM_LIT:3>, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>item_end_tag_bytes = encoder.TagBytes(<NUM_LIT:1>, wire_format.WIRETYPE_END_GROUP)<EOL>local_ReadTag = ReadTag<EOL>local_DecodeVarint = _DecodeVarint<EOL>local_SkipField = SkipField<EOL>def DecodeItem(buffer, pos, end, message, field_dict):<EOL><INDENT>message_set_item_start = pos<EOL>type_id = -<NUM_LIT:1><EOL>message_start = -<NUM_LIT:1><EOL>message_end = -<NUM_LIT:1><EOL>while <NUM_LIT:1>:<EOL><INDENT>(tag_bytes, pos) = local_ReadTag(buffer, pos)<EOL>if tag_bytes == type_id_tag_bytes:<EOL><INDENT>(type_id, pos) = local_DecodeVarint(buffer, pos)<EOL><DEDENT>elif tag_bytes == message_tag_bytes:<EOL><INDENT>(size, message_start) = local_DecodeVarint(buffer, pos)<EOL>pos = message_end = message_start + size<EOL><DEDENT>elif tag_bytes == item_end_tag_bytes:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>pos = SkipField(buffer, pos, end, tag_bytes)<EOL>if pos == -<NUM_LIT:1>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if type_id == -<NUM_LIT:1>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if message_start == -<NUM_LIT:1>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>extension = extensions_by_number.get(type_id)<EOL>if extension is not None:<EOL><INDENT>value = field_dict.get(extension)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(<EOL>extension, extension.message_type._concrete_class())<EOL><DEDENT>if value._InternalParse(buffer, message_start,message_end) != message_end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not message._unknown_fields:<EOL><INDENT>message._unknown_fields = []<EOL><DEDENT>message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,<EOL>buffer[message_set_item_start:pos]))<EOL><DEDENT>return pos<EOL><DEDENT>return DecodeItem<EOL>

Returns a decoder for a MessageSet item.

    The parameter is the _extensions_by_number map for the message class.

    The message set message looks like this:
      message MessageSet {
        repeated group Item = 1 {
          required int32 type_id = 2;
          required string message = 3;
        }
      }


def MapDecoder(field_descriptor, new_default, is_message_map):

key = field_descriptor<EOL>tag_bytes = encoder.TagBytes(field_descriptor.number,<EOL>wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>tag_len = len(tag_bytes)<EOL>local_DecodeVarint = _DecodeVarint<EOL>message_type = field_descriptor.message_type<EOL>def DecodeMap(buffer, pos, end, message, field_dict):<EOL><INDENT>submsg = message_type._concrete_class()<EOL>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>submsg.Clear()<EOL>if submsg._InternalParse(buffer, pos, new_pos) != new_pos:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if is_message_map:<EOL><INDENT>value[submsg.key].MergeFrom(submsg.value)<EOL><DEDENT>else:<EOL><INDENT>value[submsg.key] = submsg.value<EOL><DEDENT>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeMap<EOL>


<EOL>while ord(buffer[pos:pos+<NUM_LIT:1>]) & <NUM_LIT>:<EOL><INDENT>pos += <NUM_LIT:1><EOL><DEDENT>pos += <NUM_LIT:1><EOL>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL>

Skip a varint value.  Returns the new position.


pos += <NUM_LIT:8><EOL>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL>

Skip a fixed64 value.  Returns the new position.


def _SkipLengthDelimited(buffer, pos, end):

(size, pos) = _DecodeVarint(buffer, pos)<EOL>pos += size<EOL>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL>

Skip a length-delimited value.  Returns the new position.


while <NUM_LIT:1>:<EOL><INDENT>(tag_bytes, pos) = ReadTag(buffer, pos)<EOL>new_pos = SkipField(buffer, pos, end, tag_bytes)<EOL>if new_pos == -<NUM_LIT:1>:<EOL><INDENT>return pos<EOL><DEDENT>pos = new_pos<EOL><DEDENT>

Skip sub-group.  Returns the new position.


return -<NUM_LIT:1><EOL>

Skipping an END_GROUP tag returns -1 to tell the parent loop to break.


pos += <NUM_LIT:4><EOL>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL>

Skip a fixed32 value.  Returns the new position.


def _RaiseInvalidWireType(buffer, pos, end):

raise _DecodeError('<STR_LIT>')<EOL>

Skip function for unknown wire types.  Raises an exception.


WIRETYPE_TO_SKIPPER = [<EOL>_SkipVarint,<EOL>_SkipFixed64,<EOL>_SkipLengthDelimited,<EOL>_SkipGroup,<EOL>_EndGroup,<EOL>_SkipFixed32,<EOL>_RaiseInvalidWireType,<EOL>_RaiseInvalidWireType,<EOL>]<EOL>wiretype_mask = wire_format.TAG_TYPE_MASK<EOL>def SkipField(buffer, pos, end, tag_bytes):<EOL><INDENT>"""<STR_LIT>"""<EOL>wire_type = ord(tag_bytes[<NUM_LIT:0>:<NUM_LIT:1>]) & wiretype_mask<EOL>return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)<EOL><DEDENT>return SkipField<EOL>


<EOL>return proto_field_name<EOL>

Returns the name of the public property attribute which
    clients can use to get and (in some cases) set the value
    of a protocol message field.

    Args:
      proto_field_name: The protocol message field name, exactly
        as it appears (or would appear) in a .proto file.


if not isinstance(extension_handle, _FieldDescriptor):<EOL><INDENT>raise KeyError('<STR_LIT>' %<EOL>extension_handle)<EOL><DEDENT>if not extension_handle.is_extension:<EOL><INDENT>raise KeyError('<STR_LIT>' % extension_handle.full_name)<EOL><DEDENT>if not extension_handle.containing_type:<EOL><INDENT>raise KeyError('<STR_LIT>'<EOL>% extension_handle.full_name)<EOL><DEDENT>if extension_handle.containing_type is not message.DESCRIPTOR:<EOL><INDENT>raise KeyError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(extension_handle.full_name,<EOL>extension_handle.containing_type.full_name,<EOL>message.DESCRIPTOR.full_name))<EOL><DEDENT>

Verify that the given extension handle is valid.


dictionary['<STR_LIT>'] = ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']<EOL>

Adds a __slots__ entry to dictionary, containing the names of all valid
    attributes for this message type.

    Args:
      message_descriptor: A Descriptor instance describing this message type.
      dictionary: Class dictionary to which we'll add a '__slots__' entry.


for enum_type in descriptor.enum_types:<EOL><INDENT>setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type))<EOL>for enum_value in enum_type.values:<EOL><INDENT>setattr(cls, enum_value.name, enum_value.number)<EOL><DEDENT><DEDENT>

Sets class-level attributes for all enum fields defined in this message.

    Also exporting a class-level object that can name enum values.

    Args:
      descriptor: Descriptor object for this message type.
      cls: Class we're constructing for this message type.


if _IsMapField(field):<EOL><INDENT>return _GetInitializeDefaultForMap(field)<EOL><DEDENT>if field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>if field.has_default_value and field.default_value != []:<EOL><INDENT>raise ValueError('<STR_LIT>' % (<EOL>field.default_value))<EOL><DEDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>message_type = field.message_type<EOL>def MakeRepeatedMessageDefault(message):<EOL><INDENT>return containers.RepeatedCompositeFieldContainer(<EOL>message._listener_for_children, field.message_type)<EOL><DEDENT>return MakeRepeatedMessageDefault<EOL><DEDENT>else:<EOL><INDENT>type_checker = type_checkers.GetTypeChecker(field)<EOL>def MakeRepeatedScalarDefault(message):<EOL><INDENT>return containers.RepeatedScalarFieldContainer(<EOL>message._listener_for_children, type_checker)<EOL><DEDENT>return MakeRepeatedScalarDefault<EOL><DEDENT><DEDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>message_type = field.message_type<EOL>def MakeSubMessageDefault(message):<EOL><INDENT>result = message_type._concrete_class()<EOL>result._SetListener(<EOL>_OneofListener(message, field)<EOL>if field.containing_oneof is not None<EOL>else message._listener_for_children)<EOL>return result<EOL><DEDENT>return MakeSubMessageDefault<EOL><DEDENT>def MakeScalarDefault(message):<EOL><INDENT>return field.default_value<EOL><DEDENT>return MakeScalarDefault<EOL>

Returns a function which returns a default value for a field.

    Args:
      field: FieldDescriptor object for this field.

    The returned function has one argument:
      message: Message instance containing this field, or a weakref proxy
        of same.

    That function in turn returns a default value for this field.  The default
      value may refer back to |message| via a weak reference.


exc = sys.exc_info()[<NUM_LIT:1>]<EOL>if len(exc.args) == <NUM_LIT:1> and type(exc) is TypeError:<EOL><INDENT>exc = TypeError('<STR_LIT>' % (str(exc), message_name, field_name))<EOL><DEDENT>six.reraise(type(exc), exc, sys.exc_info()[<NUM_LIT:2>])<EOL>

Re-raise the currently-handled TypeError with the field name added.


def _GetIntegerEnumValue(enum_type, value):<EOL><INDENT>"""<STR_LIT>"""<EOL>if isinstance(value, six.string_types):<EOL><INDENT>try:<EOL><INDENT>return enum_type.values_by_name[value].number<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>' % (<EOL>enum_type.full_name, value))<EOL><DEDENT><DEDENT>return value<EOL><DEDENT>def init(self, **kwargs):<EOL><INDENT>self._cached_byte_size = <NUM_LIT:0><EOL>self._cached_byte_size_dirty = len(kwargs) > <NUM_LIT:0><EOL>self._fields = {}<EOL>self._oneofs = {}<EOL>self._unknown_fields = ()<EOL>self._is_present_in_parent = False<EOL>self._listener = message_listener_mod.NullMessageListener()<EOL>self._listener_for_children = _Listener(self)<EOL>for field_name, field_value in kwargs.items():<EOL><INDENT>field = _GetFieldByName(message_descriptor, field_name)<EOL>if field is None:<EOL><INDENT>raise TypeError("<STR_LIT>" %<EOL>(message_descriptor.name, field_name))<EOL><DEDENT>if field_value is None:<EOL><INDENT>continue<EOL><DEDENT>if field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>copy = field._default_constructor(self)<EOL>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  <EOL><INDENT>if _IsMapField(field):<EOL><INDENT>if _IsMessageMapField(field):<EOL><INDENT>for key in field_value:<EOL><INDENT>copy[key].MergeFrom(field_value[key])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>copy.update(field_value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for val in field_value:<EOL><INDENT>if isinstance(val, dict):<EOL><INDENT>copy.add(**val)<EOL><DEDENT>else:<EOL><INDENT>copy.add().MergeFrom(val)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:  <EOL><INDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:<EOL><INDENT>field_value = [_GetIntegerEnumValue(field.enum_type, val)<EOL>for val in field_value]<EOL><DEDENT>copy.extend(field_value)<EOL><DEDENT>self._fields[field] = copy<EOL><DEDENT>elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>copy = field._default_constructor(self)<EOL>new_val = field_value<EOL>if isinstance(field_value, dict):<EOL><INDENT>new_val = field.message_type._concrete_class(**field_value)<EOL><DEDENT>try:<EOL><INDENT>copy.MergeFrom(new_val)<EOL><DEDENT>except TypeError:<EOL><INDENT>_ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)<EOL><DEDENT>self._fields[field] = copy<EOL><DEDENT>else:<EOL><INDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:<EOL><INDENT>field_value = _GetIntegerEnumValue(field.enum_type, field_value)<EOL><DEDENT>try:<EOL><INDENT>setattr(self, field_name, field_value)<EOL><DEDENT>except TypeError:<EOL><INDENT>_ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>init.__module__ = None<EOL>init.__doc__ = None<EOL>cls.__init__ = init<EOL>


try:<EOL><INDENT>return message_descriptor.fields_by_name[field_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(message_descriptor.name, field_name))<EOL><DEDENT>

Returns a field descriptor by field name.

    Args:
      message_descriptor: A Descriptor describing all fields in message.
      field_name: The name of the field to retrieve.
    Returns:
      The field descriptor associated with the field name.


for field in descriptor.fields:<EOL><INDENT>_AddPropertiesForField(field, cls)<EOL><DEDENT>if descriptor.is_extendable:<EOL><INDENT>cls.Extensions = property(lambda self: _ExtensionDict(self))<EOL><DEDENT>

Adds properties for all fields in this protocol message type.


<EOL>assert _FieldDescriptor.MAX_CPPTYPE == <NUM_LIT:10><EOL>constant_name = field.name.upper() + "<STR_LIT>"<EOL>setattr(cls, constant_name, field.number)<EOL>if field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>_AddPropertiesForRepeatedField(field, cls)<EOL><DEDENT>elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>_AddPropertiesForNonRepeatedCompositeField(field, cls)<EOL><DEDENT>else:<EOL><INDENT>_AddPropertiesForNonRepeatedScalarField(field, cls)<EOL><DEDENT>

Adds a public property for a protocol message field.
    Clients can use this property to get and (in the case
    of non-repeated scalar fields) directly set the value
    of a protocol message field.

    Args:
      field: A FieldDescriptor for this field.
      cls: The class we're constructing.


proto_field_name = field.name<EOL>property_name = _PropertyName(proto_field_name)<EOL>def getter(self):<EOL><INDENT>field_value = self._fields.get(field)<EOL>if field_value is None:<EOL><INDENT>field_value = field._default_constructor(self)<EOL>field_value = self._fields.setdefault(field, field_value)<EOL><DEDENT>return field_value<EOL><DEDENT>getter.__module__ = None<EOL>getter.__doc__ = '<STR_LIT>' % proto_field_name<EOL>def setter(self, new_value):<EOL><INDENT>raise AttributeError('<STR_LIT>'<EOL>'<STR_LIT>' % proto_field_name)<EOL><DEDENT>doc = '<STR_LIT>' % proto_field_name<EOL>setattr(cls, property_name, property(getter, setter, doc=doc))<EOL>

Adds a public property for a "repeated" protocol message field.  Clients
    can use this property to get the value of the field, which will be either a
    _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see
    below).

    Note that when clients add values to these containers, we perform
    type-checking in the case of repeated scalar fields, and we also set any
    necessary "has" bits as a side-effect.

    Args:
      field: A FieldDescriptor for this field.
      cls: The class we're constructing.


proto_field_name = field.name<EOL>property_name = _PropertyName(proto_field_name)<EOL>type_checker = type_checkers.GetTypeChecker(field)<EOL>default_value = field.default_value<EOL>valid_values = set()<EOL>is_proto3 = field.containing_type.syntax == "<STR_LIT>"<EOL>def getter(self):<EOL><INDENT>return self._fields.get(field, default_value)<EOL><DEDENT>getter.__module__ = None<EOL>getter.__doc__ = '<STR_LIT>' % proto_field_name<EOL>clear_when_set_to_default = is_proto3 and not field.containing_oneof<EOL>def field_setter(self, new_value):<EOL><INDENT>new_value = type_checker.CheckValue(new_value)<EOL>if clear_when_set_to_default and not new_value:<EOL><INDENT>self._fields.pop(field, None)<EOL><DEDENT>else:<EOL><INDENT>self._fields[field] = new_value<EOL><DEDENT>if not self._cached_byte_size_dirty:<EOL><INDENT>self._Modified()<EOL><DEDENT><DEDENT>if field.containing_oneof:<EOL><INDENT>def setter(self, new_value):<EOL><INDENT>field_setter(self, new_value)<EOL>self._UpdateOneofState(field)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>setter = field_setter<EOL><DEDENT>setter.__module__ = None<EOL>setter.__doc__ = '<STR_LIT>' % proto_field_name<EOL>doc = '<STR_LIT>' % proto_field_name<EOL>setattr(cls, property_name, property(getter, setter, doc=doc))<EOL>

Adds a public property for a nonrepeated, scalar protocol message field.
    Clients can use this property to get and directly set the value of the field.
    Note that when the client sets the value of a field by using this property,
    all necessary "has" bits are set as a side-effect, and we also perform
    type-checking.

    Args:
      field: A FieldDescriptor for this field.
      cls: The class we're constructing.


<EOL>proto_field_name = field.name<EOL>property_name = _PropertyName(proto_field_name)<EOL>def getter(self):<EOL><INDENT>field_value = self._fields.get(field)<EOL>if field_value is None:<EOL><INDENT>field_value = field._default_constructor(self)<EOL>field_value = self._fields.setdefault(field, field_value)<EOL><DEDENT>return field_value<EOL><DEDENT>getter.__module__ = None<EOL>getter.__doc__ = '<STR_LIT>' % proto_field_name<EOL>def setter(self, new_value):<EOL><INDENT>raise AttributeError('<STR_LIT>'<EOL>'<STR_LIT>' % proto_field_name)<EOL><DEDENT>doc = '<STR_LIT>' % proto_field_name<EOL>setattr(cls, property_name, property(getter, setter, doc=doc))<EOL>

Adds a public property for a nonrepeated, composite protocol message field.
    A composite field is a "group" or "message" field.

    Clients can use this property to get the value of the field, but cannot
    assign to the property directly.

    Args:
      field: A FieldDescriptor for this field.
      cls: The class we're constructing.


extension_dict = descriptor.extensions_by_name<EOL>for extension_name, extension_field in extension_dict.items():<EOL><INDENT>constant_name = extension_name.upper() + "<STR_LIT>"<EOL>setattr(cls, constant_name, extension_field.number)<EOL><DEDENT>


if item[<NUM_LIT:0>].label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>return bool(item[<NUM_LIT:1>])<EOL><DEDENT>elif item[<NUM_LIT:0>].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>return item[<NUM_LIT:1>]._is_present_in_parent<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>

Given a (FieldDescriptor, value) tuple from _fields, return true if the
    value should be included in the list returned by ListFields().


def ListFields(self):<EOL><INDENT>all_fields = [item for item in self._fields.items() if _IsPresent(item)]<EOL>all_fields.sort(key = lambda item: item[<NUM_LIT:0>].number)<EOL>return all_fields<EOL><DEDENT>cls.ListFields = ListFields<EOL>


is_proto3 = (message_descriptor.syntax == "<STR_LIT>")<EOL>error_msg = _Proto3HasError if is_proto3 else _Proto2HasError<EOL>hassable_fields = {}<EOL>for field in message_descriptor.fields:<EOL><INDENT>if field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>continue<EOL><DEDENT>if (is_proto3 and field.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE and<EOL>not field.containing_oneof):<EOL><INDENT>continue<EOL><DEDENT>hassable_fields[field.name] = field<EOL><DEDENT>if not is_proto3:<EOL><INDENT>for oneof in message_descriptor.oneofs:<EOL><INDENT>hassable_fields[oneof.name] = oneof<EOL><DEDENT><DEDENT>def HasField(self, field_name):<EOL><INDENT>try:<EOL><INDENT>field = hassable_fields[field_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError(error_msg % field_name)<EOL><DEDENT>if isinstance(field, descriptor_mod.OneofDescriptor):<EOL><INDENT>try:<EOL><INDENT>return HasField(self, self._oneofs[field].name)<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>value = self._fields.get(field)<EOL>return value is not None and value._is_present_in_parent<EOL><DEDENT>else:<EOL><INDENT>return field in self._fields<EOL><DEDENT><DEDENT><DEDENT>cls.HasField = HasField<EOL>


def ClearField(self, field_name):<EOL><INDENT>try:<EOL><INDENT>field = message_descriptor.fields_by_name[field_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>field = message_descriptor.oneofs_by_name[field_name]<EOL>if field in self._oneofs:<EOL><INDENT>field = self._oneofs[field]<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(message_descriptor.name, field_name))<EOL><DEDENT><DEDENT>if field in self._fields:<EOL><INDENT>if hasattr(self._fields[field], '<STR_LIT>'):<EOL><INDENT>self._fields[field].InvalidateIterators()<EOL><DEDENT>del self._fields[field]<EOL>if self._oneofs.get(field.containing_oneof, None) is field:<EOL><INDENT>del self._oneofs[field.containing_oneof]<EOL><DEDENT><DEDENT>self._Modified()<EOL><DEDENT>cls.ClearField = ClearField<EOL>


def ClearExtension(self, extension_handle):<EOL><INDENT>_VerifyExtensionHandle(self, extension_handle)<EOL>if extension_handle in self._fields:<EOL><INDENT>del self._fields[extension_handle]<EOL><DEDENT>self._Modified()<EOL><DEDENT>cls.ClearExtension = ClearExtension<EOL>


def HasExtension(self, extension_handle):<EOL><INDENT>_VerifyExtensionHandle(self, extension_handle)<EOL>if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>raise KeyError('<STR_LIT>' % extension_handle.full_name)<EOL><DEDENT>if extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>value = self._fields.get(extension_handle)<EOL>return value is not None and value._is_present_in_parent<EOL><DEDENT>else:<EOL><INDENT>return extension_handle in self._fields<EOL><DEDENT><DEDENT>cls.HasExtension = HasExtension<EOL>


type_url = msg.type_url<EOL>db = symbol_database.Default()<EOL>if not type_url:<EOL><INDENT>return None<EOL><DEDENT>type_name = type_url.split("<STR_LIT:/>")[-<NUM_LIT:1>]<EOL>descriptor = db.pool.FindMessageTypeByName(type_name)<EOL>if descriptor is None:<EOL><INDENT>return None<EOL><DEDENT>message_class = db.GetPrototype(descriptor)<EOL>message = message_class()<EOL>message.ParseFromString(msg.value)<EOL>return message<EOL>

Unpacks Any message and returns the unpacked message.

    This internal method is differnt from public Any Unpack method which takes
    the target message as argument. _InternalUnpackAny method does not have
    target message type and need to find the message type in descriptor pool.

    Args:
      msg: An Any message to be unpacked.

    Returns:
      The unpacked message.


def __eq__(self, other):<EOL><INDENT>if (not isinstance(other, message_mod.Message) or<EOL>other.DESCRIPTOR != self.DESCRIPTOR):<EOL><INDENT>return False<EOL><DEDENT>if self is other:<EOL><INDENT>return True<EOL><DEDENT>if self.DESCRIPTOR.full_name == _AnyFullTypeName:<EOL><INDENT>any_a = _InternalUnpackAny(self)<EOL>any_b = _InternalUnpackAny(other)<EOL>if any_a and any_b:<EOL><INDENT>return any_a == any_b<EOL><DEDENT><DEDENT>if not self.ListFields() == other.ListFields():<EOL><INDENT>return False<EOL><DEDENT>unknown_fields = list(self._unknown_fields)<EOL>unknown_fields.sort()<EOL>other_unknown_fields = list(other._unknown_fields)<EOL>other_unknown_fields.sort()<EOL>return unknown_fields == other_unknown_fields<EOL><DEDENT>cls.__eq__ = __eq__<EOL>


def __str__(self):<EOL><INDENT>return text_format.MessageToString(self)<EOL><DEDENT>cls.__str__ = __str__<EOL>


def __repr__(self):<EOL><INDENT>return text_format.MessageToString(self)<EOL><DEDENT>cls.__repr__ = __repr__<EOL>


def __unicode__(self):<EOL><INDENT>return text_format.MessageToString(self, as_utf8=True).decode('<STR_LIT:utf-8>')<EOL><DEDENT>cls.__unicode__ = __unicode__<EOL>


def _BytesForNonRepeatedElement(value, field_number, field_type):

try:<EOL><INDENT>fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type]<EOL>return fn(field_number, value)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise message_mod.EncodeError('<STR_LIT>' % field_type)<EOL><DEDENT>

Returns the number of bytes needed to serialize a non-repeated element.
    The returned byte count includes space for tag information and any
    other additional space associated with serializing value.

    Args:
      value: Value we're serializing.
      field_number: Field number of this value.  (Since the field number
        is stored as part of a varint-encoded tag, this has an impact
        on the total bytes required to serialize the value).
      field_type: The type of the field.  One of the TYPE_* constants
        within FieldDescriptor.


def ByteSize(self):<EOL><INDENT>if not self._cached_byte_size_dirty:<EOL><INDENT>return self._cached_byte_size<EOL><DEDENT>size = <NUM_LIT:0><EOL>for field_descriptor, field_value in self.ListFields():<EOL><INDENT>size += field_descriptor._sizer(field_value)<EOL><DEDENT>for tag_bytes, value_bytes in self._unknown_fields:<EOL><INDENT>size += len(tag_bytes) + len(value_bytes)<EOL><DEDENT>self._cached_byte_size = size<EOL>self._cached_byte_size_dirty = False<EOL>self._listener_for_children.dirty = False<EOL>return size<EOL><DEDENT>cls.ByteSize = ByteSize<EOL>


def SerializeToString(self):<EOL><INDENT>errors = []<EOL>if not self.IsInitialized():<EOL><INDENT>raise message_mod.EncodeError(<EOL>'<STR_LIT>' % (<EOL>self.DESCRIPTOR.full_name, '<STR_LIT:U+002C>'.join(self.FindInitializationErrors())))<EOL><DEDENT>return self.SerializePartialToString()<EOL><DEDENT>cls.SerializeToString = SerializeToString<EOL>


def SerializePartialToString(self):<EOL><INDENT>out = BytesIO()<EOL>self._InternalSerialize(out.write)<EOL>return out.getvalue()<EOL><DEDENT>cls.SerializePartialToString = SerializePartialToString<EOL>def InternalSerialize(self, write_bytes):<EOL><INDENT>for field_descriptor, field_value in self.ListFields():<EOL><INDENT>field_descriptor._encoder(write_bytes, field_value)<EOL><DEDENT>for tag_bytes, value_bytes in self._unknown_fields:<EOL><INDENT>write_bytes(tag_bytes)<EOL>write_bytes(value_bytes)<EOL><DEDENT><DEDENT>cls._InternalSerialize = InternalSerialize<EOL>


def MergeFromString(self, serialized):<EOL><INDENT>length = len(serialized)<EOL>try:<EOL><INDENT>if self._InternalParse(serialized, <NUM_LIT:0>, length) != length:<EOL><INDENT>raise message_mod.DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT>except (IndexError, TypeError):<EOL><INDENT>raise message_mod.DecodeError('<STR_LIT>')<EOL><DEDENT>except struct.error as e:<EOL><INDENT>raise message_mod.DecodeError(e)<EOL><DEDENT>return length   <EOL><DEDENT>cls.MergeFromString = MergeFromString<EOL>local_ReadTag = decoder.ReadTag<EOL>local_SkipField = decoder.SkipField<EOL>decoders_by_tag = cls._decoders_by_tag<EOL>is_proto3 = message_descriptor.syntax == "<STR_LIT>"<EOL>def InternalParse(self, buffer, pos, end):<EOL><INDENT>self._Modified()<EOL>field_dict = self._fields<EOL>unknown_field_list = self._unknown_fields<EOL>while pos != end:<EOL><INDENT>(tag_bytes, new_pos) = local_ReadTag(buffer, pos)<EOL>field_decoder, field_desc = decoders_by_tag.get(tag_bytes, (None, None))<EOL>if field_decoder is None:<EOL><INDENT>value_start_pos = new_pos<EOL>new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)<EOL>if new_pos == -<NUM_LIT:1>:<EOL><INDENT>return pos<EOL><DEDENT>if not is_proto3:<EOL><INDENT>if not unknown_field_list:<EOL><INDENT>unknown_field_list = self._unknown_fields = []<EOL><DEDENT>unknown_field_list.append(<EOL>(tag_bytes, buffer[value_start_pos:new_pos]))<EOL><DEDENT>pos = new_pos<EOL><DEDENT>else:<EOL><INDENT>pos = field_decoder(buffer, new_pos, end, self, field_dict)<EOL>if field_desc:<EOL><INDENT>self._UpdateOneofState(field_desc)<EOL><DEDENT><DEDENT><DEDENT>return pos<EOL><DEDENT>cls._InternalParse = InternalParse<EOL>


required_fields = [field for field in message_descriptor.fields<EOL>if field.label == _FieldDescriptor.LABEL_REQUIRED]<EOL>def IsInitialized(self, errors=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>for field in required_fields:<EOL><INDENT>if (field not in self._fields or<EOL>(field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and<EOL>not self._fields[field]._is_present_in_parent)):<EOL><INDENT>if errors is not None:<EOL><INDENT>errors.extend(self.FindInitializationErrors())<EOL><DEDENT>return False<EOL><DEDENT><DEDENT>for field, value in list(self._fields.items()):  <EOL><INDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>if field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>if (field.message_type.has_options and<EOL>field.message_type.GetOptions().map_entry):<EOL><INDENT>continue<EOL><DEDENT>for element in value:<EOL><INDENT>if not element.IsInitialized():<EOL><INDENT>if errors is not None:<EOL><INDENT>errors.extend(self.FindInitializationErrors())<EOL><DEDENT>return False<EOL><DEDENT><DEDENT><DEDENT>elif value._is_present_in_parent and not value.IsInitialized():<EOL><INDENT>if errors is not None:<EOL><INDENT>errors.extend(self.FindInitializationErrors())<EOL><DEDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL><DEDENT>cls.IsInitialized = IsInitialized<EOL>def FindInitializationErrors(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>errors = []  <EOL>for field in required_fields:<EOL><INDENT>if not self.HasField(field.name):<EOL><INDENT>errors.append(field.name)<EOL><DEDENT><DEDENT>for field, value in self.ListFields():<EOL><INDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>if field.is_extension:<EOL><INDENT>name = "<STR_LIT>" % field.full_name<EOL><DEDENT>else:<EOL><INDENT>name = field.name<EOL><DEDENT>if _IsMapField(field):<EOL><INDENT>if _IsMessageMapField(field):<EOL><INDENT>for key in value:<EOL><INDENT>element = value[key]<EOL>prefix = "<STR_LIT>" % (name, key)<EOL>sub_errors = element.FindInitializationErrors()<EOL>errors += [prefix + error for error in sub_errors]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>for i in range(len(value)):<EOL><INDENT>element = value[i]<EOL>prefix = "<STR_LIT>" % (name, i)<EOL>sub_errors = element.FindInitializationErrors()<EOL>errors += [prefix + error for error in sub_errors]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>prefix = name + "<STR_LIT:.>"<EOL>sub_errors = value.FindInitializationErrors()<EOL>errors += [prefix + error for error in sub_errors]<EOL><DEDENT><DEDENT><DEDENT>return errors<EOL><DEDENT>cls.FindInitializationErrors = FindInitializationErrors<EOL>

Adds the IsInitialized and FindInitializationError methods to the
    protocol message class.


_AddListFieldsMethod(message_descriptor, cls)<EOL>_AddHasFieldMethod(message_descriptor, cls)<EOL>_AddClearFieldMethod(message_descriptor, cls)<EOL>if message_descriptor.is_extendable:<EOL><INDENT>_AddClearExtensionMethod(cls)<EOL>_AddHasExtensionMethod(cls)<EOL><DEDENT>_AddEqualsMethod(message_descriptor, cls)<EOL>_AddStrMethod(message_descriptor, cls)<EOL>_AddReprMethod(message_descriptor, cls)<EOL>_AddUnicodeMethod(message_descriptor, cls)<EOL>_AddByteSizeMethod(message_descriptor, cls)<EOL>_AddSerializeToStringMethod(message_descriptor, cls)<EOL>_AddSerializePartialToStringMethod(message_descriptor, cls)<EOL>_AddMergeFromStringMethod(message_descriptor, cls)<EOL>_AddIsInitializedMethod(message_descriptor, cls)<EOL>_AddMergeFromMethod(cls)<EOL>_AddWhichOneofMethod(message_descriptor, cls)<EOL>cls.Clear = _Clear<EOL>cls.DiscardUnknownFields = _DiscardUnknownFields<EOL>cls._SetListener = _SetListener<EOL>

Adds implementations of all Message methods to cls.


def Modified(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not self._cached_byte_size_dirty:<EOL><INDENT>self._cached_byte_size_dirty = True<EOL>self._listener_for_children.dirty = True<EOL>self._is_present_in_parent = True<EOL>self._listener.Modified()<EOL><DEDENT><DEDENT>def _UpdateOneofState(self, field):<EOL><INDENT>"""<STR_LIT>"""<EOL>other_field = self._oneofs.setdefault(field.containing_oneof, field)<EOL>if other_field is not field:<EOL><INDENT>del self._fields[other_field]<EOL>self._oneofs[field.containing_oneof] = field<EOL><DEDENT><DEDENT>cls._Modified = Modified<EOL>cls.SetInParent = Modified<EOL>cls._UpdateOneofState = _UpdateOneofState<EOL>

Adds implementation of private helper methods to cls.


def __new__(cls, name, bases, dictionary):

descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]<EOL>if descriptor.full_name in well_known_types.WKTBASES:<EOL><INDENT>bases += (well_known_types.WKTBASES[descriptor.full_name],)<EOL><DEDENT>_AddClassAttributesForNestedExtensions(descriptor, dictionary)<EOL>_AddSlots(descriptor, dictionary)<EOL>superclass = super(GeneratedProtocolMessageType, cls)<EOL>new_class = superclass.__new__(cls, name, bases, dictionary)<EOL>return new_class<EOL>

Custom allocation for runtime-generated class types.

        We override __new__ because this is apparently the only place
        where we can meaningfully set __slots__ on the class we're creating(?).
        (The interplay between metaclasses and slots is not very well-documented).

        Args:
          name: Name of the class (ignored, but required by the
            metaclass protocol).
          bases: Base classes of the class we're constructing.
            (Should be message.Message).  We ignore this field, but
            it's required by the metaclass protocol
          dictionary: The class dictionary of the class we're
            constructing.  dictionary[_DESCRIPTOR_KEY] must contain
            a Descriptor object describing this protocol message
            type.

        Returns:
          Newly-allocated class.


def __init__(cls, name, bases, dictionary):

descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]<EOL>cls._decoders_by_tag = {}<EOL>cls._extensions_by_name = {}<EOL>cls._extensions_by_number = {}<EOL>if (descriptor.has_options and<EOL>descriptor.GetOptions().message_set_wire_format):<EOL><INDENT>cls._decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = (<EOL>decoder.MessageSetItemDecoder(cls._extensions_by_number), None)<EOL><DEDENT>for field in descriptor.fields:<EOL><INDENT>_AttachFieldHelpers(cls, field)<EOL><DEDENT>descriptor._concrete_class = cls  <EOL>_AddEnumValues(descriptor, cls)<EOL>_AddInitMethod(descriptor, cls)<EOL>_AddPropertiesForFields(descriptor, cls)<EOL>_AddPropertiesForExtensions(descriptor, cls)<EOL>_AddStaticMethods(cls)<EOL>_AddMessageMethods(descriptor, cls)<EOL>_AddPrivateHelperMethods(descriptor, cls)<EOL>copyreg.pickle(cls, lambda obj: (cls, (), obj.__getstate__()))<EOL>superclass = super(GeneratedProtocolMessageType, cls)<EOL>superclass.__init__(name, bases, dictionary)<EOL>

Here we perform the majority of our work on the class.
        We add enum getters, an __init__ method, implementations
        of all Message methods, and properties for all fields
        in the protocol type.

        Args:
          name: Name of the class (ignored, but required by the
            metaclass protocol).
          bases: Base classes of the class we're constructing.
            (Should be message.Message).  We ignore this field, but
            it's required by the metaclass protocol
          dictionary: The class dictionary of the class we're
            constructing.  dictionary[_DESCRIPTOR_KEY] must contain
            a Descriptor object describing this protocol message
            type.


<EOL>if isinstance(parent_message, weakref.ProxyType):<EOL><INDENT>self._parent_message_weakref = parent_message<EOL><DEDENT>else:<EOL><INDENT>self._parent_message_weakref = weakref.proxy(parent_message)<EOL><DEDENT>self.dirty = False<EOL>

Args:
          parent_message: The message whose _Modified() method we should call when
            we receive Modified() messages.


def __init__(self, parent_message, field):

super(_OneofListener, self).__init__(parent_message)<EOL>self._field = field<EOL>

Args:
          parent_message: The message whose _Modified() method we should call when
            we receive Modified() messages.
          field: The descriptor of the field being set in the parent message.


try:<EOL><INDENT>self._parent_message_weakref._UpdateOneofState(self._field)<EOL>super(_OneofListener, self).Modified()<EOL><DEDENT>except ReferenceError:<EOL><INDENT>pass<EOL><DEDENT>

Also updates the state of the containing oneof in the parent message.


self._extended_message = extended_message<EOL>

extended_message: Message instance for which we are the Extensions dict.


_VerifyExtensionHandle(self._extended_message, extension_handle)<EOL>result = self._extended_message._fields.get(extension_handle)<EOL>if result is not None:<EOL><INDENT>return result<EOL><DEDENT>if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>result = extension_handle._default_constructor(self._extended_message)<EOL><DEDENT>elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>result = extension_handle.message_type._concrete_class()<EOL>try:<EOL><INDENT>result._SetListener(self._extended_message._listener_for_children)<EOL><DEDENT>except ReferenceError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return extension_handle.default_value<EOL><DEDENT>result = self._extended_message._fields.setdefault(<EOL>extension_handle, result)<EOL>return result<EOL>

Returns the current value of the given extension handle.


def __setitem__(self, extension_handle, value):

_VerifyExtensionHandle(self._extended_message, extension_handle)<EOL>if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or<EOL>extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % extension_handle.full_name)<EOL><DEDENT>type_checker = type_checkers.GetTypeChecker(extension_handle)<EOL>self._extended_message._fields[extension_handle] = (<EOL>type_checker.CheckValue(value))<EOL>self._extended_message._Modified()<EOL>

If extension_handle specifies a non-repeated, scalar extension
        field, sets the value of that field.


return self._extended_message._extensions_by_name.get(name, None)<EOL>

Tries to find a known extension with the specified name.

        Args:
          name: Extension full name.

        Returns:
          Extension field descriptor.


return self._extended_message._extensions_by_number.get(number, None)<EOL>

Tries to find a known extension with the field number.

        Args:
          number: Extension field number.

        Returns:
          Extension field descriptor.


self._message_listener = message_listener<EOL>self._values = []<EOL>

Args:
  message_listener: A MessageListener implementation.
    The RepeatedScalarFieldContainer will call this object's
    Modified() method when it is modified.


return self._values[key]<EOL>


return len(self._values)<EOL>

Returns the number of elements in the container.


<EOL>return not self == other<EOL>

Checks if another instance isn't equal to this one.


def __init__(self, message_listener, type_checker):

super(RepeatedScalarFieldContainer, self).__init__(message_listener)<EOL>self._type_checker = type_checker<EOL>

Args:
  message_listener: A MessageListener implementation.
    The RepeatedScalarFieldContainer will call this object's
    Modified() method when it is modified.
  type_checker: A type_checkers.ValueChecker instance to run on elements
    inserted into this container.


self._values.append(self._type_checker.CheckValue(value))<EOL>if not self._message_listener.dirty:<EOL><INDENT>self._message_listener.Modified()<EOL><DEDENT>

Appends an item to the list. Similar to list.append().


self._values.insert(key, self._type_checker.CheckValue(value))<EOL>if not self._message_listener.dirty:<EOL><INDENT>self._message_listener.Modified()<EOL><DEDENT>

Inserts the item at the specified position. Similar to list.insert().


if elem_seq is None:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>elem_seq_iter = iter(elem_seq)<EOL><DEDENT>except TypeError:<EOL><INDENT>if not elem_seq:<EOL><INDENT>return<EOL><DEDENT>raise<EOL><DEDENT>new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]<EOL>if new_values:<EOL><INDENT>self._values.extend(new_values)<EOL>self._message_listener.Modified()<EOL><DEDENT>

Extends by appending the given iterable. Similar to list.extend().


self._values.extend(other._values)<EOL>self._message_listener.Modified()<EOL>

Appends the contents of another repeated field of the same type to this
        one. We do not check the types of the individual fields.


self._values.remove(elem)<EOL>self._message_listener.Modified()<EOL>

Removes an item from the list. Similar to list.remove().


value = self._values[key]<EOL>self.__delitem__(key)<EOL>return value<EOL>

Removes and returns an item at a given index. Similar to list.pop().


if isinstance(key, slice):  <EOL><INDENT>if key.step is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.__setslice__(key.start, key.stop, value)<EOL><DEDENT>else:<EOL><INDENT>self._values[key] = self._type_checker.CheckValue(value)<EOL>self._message_listener.Modified()<EOL><DEDENT>

Sets the item on the specified position.


return self._values[start:stop]<EOL>

Retrieves the subset of items from between the specified indices.


def __setslice__(self, start, stop, values):

new_values = []<EOL>for value in values:<EOL><INDENT>new_values.append(self._type_checker.CheckValue(value))<EOL><DEDENT>self._values[start:stop] = new_values<EOL>self._message_listener.Modified()<EOL>

Sets the subset of items from between the specified indices.


del self._values[key]<EOL>self._message_listener.Modified()<EOL>

Deletes the item at the specified position.


del self._values[start:stop]<EOL>self._message_listener.Modified()<EOL>

Deletes the subset of items from between the specified indices.


if self is other:<EOL><INDENT>return True<EOL><DEDENT>if isinstance(other, self.__class__):<EOL><INDENT>return other._values == self._values<EOL><DEDENT>return other == self._values<EOL>

Compares the current instance with another one.


def __init__(self, message_listener, message_descriptor):

super(RepeatedCompositeFieldContainer, self).__init__(message_listener)<EOL>self._message_descriptor = message_descriptor<EOL>

Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
haven't yet necessarily initialized the type that will be contained in the
container.

Args:
  message_listener: A MessageListener implementation.
    The RepeatedCompositeFieldContainer will call this object's
    Modified() method when it is modified.
  message_descriptor: A Descriptor instance describing the protocol type
    that should be present in this container.  We'll use the
    _concrete_class field of this descriptor when the client calls add().


new_element = self._message_descriptor._concrete_class(**kwargs)<EOL>new_element._SetListener(self._message_listener)<EOL>self._values.append(new_element)<EOL>if not self._message_listener.dirty:<EOL><INDENT>self._message_listener.Modified()<EOL><DEDENT>return new_element<EOL>

Adds a new element at the end of the list and returns it. Keyword
        arguments may be used to initialize the element.


message_class = self._message_descriptor._concrete_class<EOL>listener = self._message_listener<EOL>values = self._values<EOL>for message in elem_seq:<EOL><INDENT>new_element = message_class()<EOL>new_element._SetListener(listener)<EOL>new_element.MergeFrom(message)<EOL>values.append(new_element)<EOL><DEDENT>listener.Modified()<EOL>

Extends by appending the given sequence of elements of the same type
        as this one, copying each individual message.


Appends the contents of another repeated field of the same type to this
        one, copying each individual message.


return self._values[start:stop]<EOL>


if self is other:<EOL><INDENT>return True<EOL><DEDENT>if not isinstance(other, self.__class__):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return self._values == other._values<EOL>


def __init__(self, message_listener, key_checker, value_checker):

self._message_listener = message_listener<EOL>self._key_checker = key_checker<EOL>self._value_checker = value_checker<EOL>self._values = {}<EOL>

Args:
  message_listener: A MessageListener implementation.
    The ScalarMap will call this object's Modified() method when it
    is modified.
  key_checker: A type_checkers.ValueChecker instance to run on keys
    inserted into this container.
  value_checker: A type_checkers.ValueChecker instance to run on values
    inserted into this container.


def __init__(self, message_listener, message_descriptor, key_checker):

self._message_listener = message_listener<EOL>self._message_descriptor = message_descriptor<EOL>self._key_checker = key_checker<EOL>self._values = {}<EOL>


return self[key]<EOL>

get_or_create() is an alias for getitem (ie. map[key]).

        Args:
          key: The key to get or create in the map.

        This is useful in cases where you want to be explicit that the call is
        mutating the map.  This can avoid lint errors for statements like this
        that otherwise would appear to be pointless statements:

          msg.my_map[key]


def MessageToString(message, as_utf8=False, as_one_line=False,<EOL>pointy_brackets=False, use_index_order=False,<EOL>float_format=None, use_field_number=False):

out = TextWriter(as_utf8)<EOL>printer = _Printer(out, <NUM_LIT:0>, as_utf8, as_one_line,<EOL>pointy_brackets, use_index_order, float_format,<EOL>use_field_number)<EOL>printer.PrintMessage(message)<EOL>result = out.getvalue()<EOL>out.close()<EOL>if as_one_line:<EOL><INDENT>return result.rstrip()<EOL><DEDENT>return result<EOL>

Convert protobuf message to text format.

    Floating point values can be formatted compactly with 15 digits of
    precision (which is the most that IEEE 754 "double" can guarantee)
    using float_format='.15g'. To ensure that converting to text and back to a
    proto will result in an identical value, float_format='.17g' should be used.

    Args:
      message: The protocol buffers message.
      as_utf8: Produce text output in UTF8 format.
      as_one_line: Don't introduce newlines between fields.
      pointy_brackets: If True, use angle brackets instead of curly braces for
        nesting.
      use_index_order: If True, print fields of a proto message using the order
        defined in source code instead of the field number. By default, use the
        field number order.
      float_format: If set, use this to specify floating point number formatting
        (per the "Format Specification Mini-Language"); otherwise, str() is used.
      use_field_number: If True, print field numbers instead of names.

    Returns:
      A string of the text formatted protocol buffer message.


def PrintField(field, value, out, indent=<NUM_LIT:0>, as_utf8=False, as_one_line=False,<EOL>pointy_brackets=False, use_index_order=False, float_format=None):

printer = _Printer(out, indent, as_utf8, as_one_line,<EOL>pointy_brackets, use_index_order, float_format)<EOL>printer.PrintField(field, value)<EOL>


def PrintFieldValue(field, value, out, indent=<NUM_LIT:0>, as_utf8=False,<EOL>as_one_line=False, pointy_brackets=False,<EOL>use_index_order=False,<EOL>float_format=None):

printer = _Printer(out, indent, as_utf8, as_one_line,<EOL>pointy_brackets, use_index_order, float_format)<EOL>printer.PrintFieldValue(field, value)<EOL>

Print a single field value (not including name).


def Parse(text, message,<EOL>allow_unknown_extension=False, allow_field_number=False):

if not isinstance(text, str):<EOL><INDENT>text = text.decode('<STR_LIT:utf-8>')<EOL><DEDENT>return ParseLines(text.split('<STR_LIT:\n>'), message, allow_unknown_extension,<EOL>allow_field_number)<EOL>

Parses an text representation of a protocol message into a message.

    Args:
      text: Message text representation.
      message: A protocol buffer message to merge into.
      allow_unknown_extension: if True, skip over missing extensions and keep
        parsing
      allow_field_number: if True, both field number and field name are allowed.

    Returns:
      The same message passed as argument.

    Raises:
      ParseError: On text parsing problems.


def Merge(text, message, allow_unknown_extension=False,<EOL>allow_field_number=False):

return MergeLines(text.split('<STR_LIT:\n>'), message, allow_unknown_extension,<EOL>allow_field_number)<EOL>

Parses an text representation of a protocol message into a message.

    Like Parse(), but allows repeated values for a non-repeated field, and uses
    the last one.

    Args:
      text: Message text representation.
      message: A protocol buffer message to merge into.
      allow_unknown_extension: if True, skip over missing extensions and keep
        parsing
      allow_field_number: if True, both field number and field name are allowed.

    Returns:
      The same message passed as argument.

    Raises:
      ParseError: On text parsing problems.


def ParseLines(lines, message, allow_unknown_extension=False,<EOL>allow_field_number=False):

parser = _Parser(allow_unknown_extension, allow_field_number)<EOL>return parser.ParseLines(lines, message)<EOL>

Parses an text representation of a protocol message into a message.

    Args:
      lines: An iterable of lines of a message's text representation.
      message: A protocol buffer message to merge into.
      allow_unknown_extension: if True, skip over missing extensions and keep
        parsing
      allow_field_number: if True, both field number and field name are allowed.

    Returns:
      The same message passed as argument.

    Raises:
      ParseError: On text parsing problems.


def MergeLines(lines, message, allow_unknown_extension=False,<EOL>allow_field_number=False):

parser = _Parser(allow_unknown_extension, allow_field_number)<EOL>return parser.MergeLines(lines, message)<EOL>


<EOL>if tokenizer.TryConsume('<STR_LIT::>') and not tokenizer.LookingAt(<EOL>'<STR_LIT:{>') and not tokenizer.LookingAt('<STR_LIT:<>'):<EOL><INDENT>_SkipFieldValue(tokenizer)<EOL><DEDENT>else:<EOL><INDENT>_SkipFieldMessage(tokenizer)<EOL><DEDENT>

Skips over contents (value or message) of a field.

    Args:
      tokenizer: A tokenizer to parse the field name and values.


Skips over a complete field (name and value/message).

    Args:
      tokenizer: A tokenizer to parse the field name and values.


if tokenizer.TryConsume('<STR_LIT:<>'):<EOL><INDENT>delimiter = '<STR_LIT:>>'<EOL><DEDENT>else:<EOL><INDENT>tokenizer.Consume('<STR_LIT:{>')<EOL>delimiter = '<STR_LIT:}>'<EOL><DEDENT>while not tokenizer.LookingAt('<STR_LIT:>>') and not tokenizer.LookingAt('<STR_LIT:}>'):<EOL><INDENT>_SkipField(tokenizer)<EOL><DEDENT>tokenizer.Consume(delimiter)<EOL>

Skips over a field message.

    Args:
      tokenizer: A tokenizer to parse the field name and values.


<EOL>if tokenizer.TryConsumeByteString():<EOL><INDENT>while tokenizer.TryConsumeByteString():<EOL><INDENT>pass<EOL><DEDENT>return<EOL><DEDENT>if (not tokenizer.TryConsumeIdentifier() and<EOL>not tokenizer.TryConsumeInt64() and<EOL>not tokenizer.TryConsumeUint64() and<EOL>not tokenizer.TryConsumeFloat()):<EOL><INDENT>raise ParseError('<STR_LIT>' + tokenizer.token)<EOL><DEDENT>

Skips over a field value.

    Args:
      tokenizer: A tokenizer to parse the field name and values.

    Raises:
      ParseError: In case an invalid field value is found.


def ParseInteger(text, is_signed=False, is_long=False):

<EOL>try:<EOL><INDENT>if is_long:<EOL><INDENT>result = long(text, <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>result = int(text, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>' % text)<EOL><DEDENT>checker = _INTEGER_CHECKERS[<NUM_LIT:2> * int(is_long) + int(is_signed)]<EOL>checker.CheckValue(result)<EOL>return result<EOL>

Parses an integer.

    Args:
      text: The text to parse.
      is_signed: True if a signed integer must be parsed.
      is_long: True if a long integer must be parsed.

    Returns:
      The integer value.

    Raises:
      ValueError: Thrown Iff the text is not a valid integer.


try:<EOL><INDENT>return float(text)<EOL><DEDENT>except ValueError:<EOL><INDENT>if _FLOAT_INFINITY.match(text):<EOL><INDENT>if text[<NUM_LIT:0>] == '<STR_LIT:->':<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT><DEDENT>elif _FLOAT_NAN.match(text):<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return float(text.rstrip('<STR_LIT:f>'))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>' % text)<EOL><DEDENT><DEDENT><DEDENT>

Parse a floating point number.

    Args:
      text: Text to parse.

    Returns:
      The number parsed.

    Raises:
      ValueError: If a floating point number couldn't be parsed.


if text in ('<STR_LIT:true>', '<STR_LIT:t>', '<STR_LIT:1>'):<EOL><INDENT>return True<EOL><DEDENT>elif text in ('<STR_LIT:false>', '<STR_LIT:f>', '<STR_LIT:0>'):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

Parse a boolean value.

    Args:
      text: Text to parse.

    Returns:
      Boolean values parsed

    Raises:
      ValueError: If text is not a valid boolean.


enum_descriptor = field.enum_type<EOL>try:<EOL><INDENT>number = int(value, <NUM_LIT:0>)<EOL><DEDENT>except ValueError:<EOL><INDENT>enum_value = enum_descriptor.values_by_name.get(value, None)<EOL>if enum_value is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (<EOL>enum_descriptor.full_name, value))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>enum_value = enum_descriptor.values_by_number.get(number, None)<EOL>if enum_value is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (<EOL>enum_descriptor.full_name, number))<EOL><DEDENT><DEDENT>return enum_value.number<EOL>

Parse an enum value.

    The value can be specified by a number (the enum value), or by
    a string literal (the enum name).

    Args:
      field: Enum field descriptor.
      value: String value.

    Returns:
      Enum value number.

    Raises:
      ValueError: If the enum value could not be parsed.


def __init__(self, out, indent=<NUM_LIT:0>, as_utf8=False, as_one_line=False,<EOL>pointy_brackets=False, use_index_order=False, float_format=None,<EOL>use_field_number=False):

self.out = out<EOL>self.indent = indent<EOL>self.as_utf8 = as_utf8<EOL>self.as_one_line = as_one_line<EOL>self.pointy_brackets = pointy_brackets<EOL>self.use_index_order = use_index_order<EOL>self.float_format = float_format<EOL>self.use_field_number = use_field_number<EOL>

Initialize the Printer.

        Floating point values can be formatted compactly with 15 digits of
        precision (which is the most that IEEE 754 "double" can guarantee)
        using float_format='.15g'. To ensure that converting to text and back to a
        proto will result in an identical value, float_format='.17g' should be used.

        Args:
          out: To record the text format result.
          indent: The indent level for pretty print.
          as_utf8: Produce text output in UTF8 format.
          as_one_line: Don't introduce newlines between fields.
          pointy_brackets: If True, use angle brackets instead of curly braces for
            nesting.
          use_index_order: If True, print fields of a proto message using the order
            defined in source code instead of the field number. By default, use the
            field number order.
          float_format: If set, use this to specify floating point number formatting
            (per the "Format Specification Mini-Language"); otherwise, str() is
            used.
          use_field_number: If True, print field numbers instead of names.


fields = message.ListFields()<EOL>if self.use_index_order:<EOL><INDENT>fields.sort(key=lambda x: x[<NUM_LIT:0>].index)<EOL><DEDENT>for field, value in fields:<EOL><INDENT>if _IsMapEntry(field):<EOL><INDENT>for key in sorted(value):<EOL><INDENT>entry_submsg = field.message_type._concrete_class(<EOL>key=key, value=value[key])<EOL>self.PrintField(field, entry_submsg)<EOL><DEDENT><DEDENT>elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>for element in value:<EOL><INDENT>self.PrintField(field, element)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.PrintField(field, value)<EOL><DEDENT><DEDENT>

Convert protobuf message to text format.

        Args:
          message: The protocol buffers message.


out = self.out<EOL>out.write('<STR_LIT:U+0020>' * self.indent)<EOL>if self.use_field_number:<EOL><INDENT>out.write(str(field.number))<EOL><DEDENT>else:<EOL><INDENT>if field.is_extension:<EOL><INDENT>out.write('<STR_LIT:[>')<EOL>if (field.containing_type.GetOptions().message_set_wire_format and<EOL>field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and<EOL>field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):<EOL><INDENT>out.write(field.message_type.full_name)<EOL><DEDENT>else:<EOL><INDENT>out.write(field.full_name)<EOL><DEDENT>out.write('<STR_LIT:]>')<EOL><DEDENT>elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:<EOL><INDENT>out.write(field.message_type.name)<EOL><DEDENT>else:<EOL><INDENT>out.write(field.name)<EOL><DEDENT><DEDENT>if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>out.write('<STR_LIT>')<EOL><DEDENT>self.PrintFieldValue(field, value)<EOL>if self.as_one_line:<EOL><INDENT>out.write('<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>out.write('<STR_LIT:\n>')<EOL><DEDENT>


def PrintFieldValue(self, field, value):

out = self.out<EOL>if self.pointy_brackets:<EOL><INDENT>openb = '<STR_LIT:<>'<EOL>closeb = '<STR_LIT:>>'<EOL><DEDENT>else:<EOL><INDENT>openb = '<STR_LIT:{>'<EOL>closeb = '<STR_LIT:}>'<EOL><DEDENT>if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>if self.as_one_line:<EOL><INDENT>out.write('<STR_LIT>' % openb)<EOL>self.PrintMessage(value)<EOL>out.write(closeb)<EOL><DEDENT>else:<EOL><INDENT>out.write('<STR_LIT>' % openb)<EOL>self.indent += <NUM_LIT:2><EOL>self.PrintMessage(value)<EOL>self.indent -= <NUM_LIT:2><EOL>out.write('<STR_LIT:U+0020>' * self.indent + closeb)<EOL><DEDENT><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:<EOL><INDENT>enum_value = field.enum_type.values_by_number.get(value, None)<EOL>if enum_value is not None:<EOL><INDENT>out.write(enum_value.name)<EOL><DEDENT>else:<EOL><INDENT>out.write(str(value))<EOL><DEDENT><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:<EOL><INDENT>out.write('<STR_LIT>')<EOL>if isinstance(value, six.text_type):<EOL><INDENT>out_value = value.encode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>out_value = value<EOL><DEDENT>if field.type == descriptor.FieldDescriptor.TYPE_BYTES:<EOL><INDENT>out_as_utf8 = False<EOL><DEDENT>else:<EOL><INDENT>out_as_utf8 = self.as_utf8<EOL><DEDENT>out.write(text_encoding.CEscape(out_value, out_as_utf8))<EOL>out.write('<STR_LIT>')<EOL><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:<EOL><INDENT>if value:<EOL><INDENT>out.write('<STR_LIT:true>')<EOL><DEDENT>else:<EOL><INDENT>out.write('<STR_LIT:false>')<EOL><DEDENT><DEDENT>elif field.cpp_type in _FLOAT_TYPES and self.float_format is not None:<EOL><INDENT>out.write('<STR_LIT>'.format(self.float_format, value))<EOL><DEDENT>else:<EOL><INDENT>out.write(str(value))<EOL><DEDENT>

Print a single field value (not including name).

        For repeated fields, the value should be a single element.

        Args:
          field: The descriptor of the field to be printed.
          value: The value of the field.


def ParseFromString(self, text, message):

if not isinstance(text, str):<EOL><INDENT>text = text.decode('<STR_LIT:utf-8>')<EOL><DEDENT>return self.ParseLines(text.split('<STR_LIT:\n>'), message)<EOL>

Parses an text representation of a protocol message into a message.


self._allow_multiple_scalars = False<EOL>self._ParseOrMerge(lines, message)<EOL>return message<EOL>


def MergeFromString(self, text, message):

return self._MergeLines(text.split('<STR_LIT:\n>'), message)<EOL>

Merges an text representation of a protocol message into a message.


self._allow_multiple_scalars = True<EOL>self._ParseOrMerge(lines, message)<EOL>return message<EOL>


def _ParseOrMerge(self, lines, message):

tokenizer = _Tokenizer(lines)<EOL>while not tokenizer.AtEnd():<EOL><INDENT>self._MergeField(tokenizer, message)<EOL><DEDENT>

Converts an text representation of a protocol message into a message.

        Args:
          lines: Lines of a message's text representation.
          message: A protocol buffer message to merge into.

        Raises:
          ParseError: On text parsing problems.


def _MergeField(self, tokenizer, message):

message_descriptor = message.DESCRIPTOR<EOL>if (hasattr(message_descriptor, '<STR_LIT>') and<EOL>message_descriptor.syntax == '<STR_LIT>'):<EOL><INDENT>self._allow_multiple_scalars = True<EOL><DEDENT>if tokenizer.TryConsume('<STR_LIT:[>'):<EOL><INDENT>name = [tokenizer.ConsumeIdentifier()]<EOL>while tokenizer.TryConsume('<STR_LIT:.>'):<EOL><INDENT>name.append(tokenizer.ConsumeIdentifier())<EOL><DEDENT>name = '<STR_LIT:.>'.join(name)<EOL>if not message_descriptor.is_extendable:<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>' %<EOL>message_descriptor.full_name)<EOL><DEDENT>field = message.Extensions._FindExtensionByName(name)<EOL>if not field:<EOL><INDENT>if self.allow_unknown_extension:<EOL><INDENT>field = None<EOL><DEDENT>else:<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>' % name)<EOL><DEDENT><DEDENT>elif message_descriptor != field.containing_type:<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>' % (<EOL>name, message_descriptor.full_name))<EOL><DEDENT>tokenizer.Consume('<STR_LIT:]>')<EOL><DEDENT>else:<EOL><INDENT>name = tokenizer.ConsumeIdentifier()<EOL>if self.allow_field_number and name.isdigit():<EOL><INDENT>number = ParseInteger(name, True, True)<EOL>field = message_descriptor.fields_by_number.get(number, None)<EOL>if not field and message_descriptor.is_extendable:<EOL><INDENT>field = message.Extensions._FindExtensionByNumber(number)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>field = message_descriptor.fields_by_name.get(name, None)<EOL>if not field:<EOL><INDENT>field = message_descriptor.fields_by_name.get(name.lower(), None)<EOL>if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:<EOL><INDENT>field = None<EOL><DEDENT><DEDENT>if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and<EOL>field.message_type.name != name):<EOL><INDENT>field = None<EOL><DEDENT><DEDENT>if not field:<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>' % (<EOL>message_descriptor.full_name, name))<EOL><DEDENT><DEDENT>if field:<EOL><INDENT>if not self._allow_multiple_scalars and field.containing_oneof:<EOL><INDENT>which_oneof = message.WhichOneof(field.containing_oneof.name)<EOL>if which_oneof is not None and which_oneof != field.name:<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (<EOL>field.name, which_oneof, field.containing_oneof.name,<EOL>message_descriptor.full_name))<EOL><DEDENT><DEDENT>if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>tokenizer.TryConsume('<STR_LIT::>')<EOL>merger = self._MergeMessageField<EOL><DEDENT>else:<EOL><INDENT>tokenizer.Consume('<STR_LIT::>')<EOL>merger = self._MergeScalarField<EOL><DEDENT>if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED<EOL>and tokenizer.TryConsume('<STR_LIT:[>')):<EOL><INDENT>while True:<EOL><INDENT>merger(tokenizer, message, field)<EOL>if tokenizer.TryConsume('<STR_LIT:]>'): break<EOL>tokenizer.Consume('<STR_LIT:U+002C>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>merger(tokenizer, message, field)<EOL><DEDENT><DEDENT>else:  <EOL><INDENT>assert self.allow_unknown_extension<EOL>_SkipFieldContents(tokenizer)<EOL><DEDENT>if not tokenizer.TryConsume('<STR_LIT:U+002C>'):<EOL><INDENT>tokenizer.TryConsume('<STR_LIT:;>')<EOL><DEDENT>

Merges a single protocol message field into a message.

        Args:
          tokenizer: A tokenizer to parse the field name and values.
          message: A protocol message to record the data.

        Raises:
          ParseError: In case of text parsing problems.


def _MergeMessageField(self, tokenizer, message, field):

is_map_entry = _IsMapEntry(field)<EOL>if tokenizer.TryConsume('<STR_LIT:<>'):<EOL><INDENT>end_token = '<STR_LIT:>>'<EOL><DEDENT>else:<EOL><INDENT>tokenizer.Consume('<STR_LIT:{>')<EOL>end_token = '<STR_LIT:}>'<EOL><DEDENT>if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>if field.is_extension:<EOL><INDENT>sub_message = message.Extensions[field].add()<EOL><DEDENT>elif is_map_entry:<EOL><INDENT>sub_message = field.message_type._concrete_class()<EOL><DEDENT>else:<EOL><INDENT>sub_message = getattr(message, field.name).add()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if field.is_extension:<EOL><INDENT>sub_message = message.Extensions[field]<EOL><DEDENT>else:<EOL><INDENT>sub_message = getattr(message, field.name)<EOL><DEDENT>sub_message.SetInParent()<EOL><DEDENT>while not tokenizer.TryConsume(end_token):<EOL><INDENT>if tokenizer.AtEnd():<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken('<STR_LIT>' % (end_token,))<EOL><DEDENT>self._MergeField(tokenizer, sub_message)<EOL><DEDENT>if is_map_entry:<EOL><INDENT>value_cpptype = field.message_type.fields_by_name['<STR_LIT:value>'].cpp_type<EOL>if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>value = getattr(message, field.name)[sub_message.key]<EOL>value.MergeFrom(sub_message.value)<EOL><DEDENT>else:<EOL><INDENT>getattr(message, field.name)[sub_message.key] = sub_message.value<EOL><DEDENT><DEDENT>

Merges a single scalar field into a message.

        Args:
          tokenizer: A tokenizer to parse the field value.
          message: The message of which field is a member.
          field: The descriptor of the field to be merged.

        Raises:
          ParseError: In case of text parsing problems.


def _MergeScalarField(self, tokenizer, message, field):

_ = self.allow_unknown_extension<EOL>value = None<EOL>if field.type in (descriptor.FieldDescriptor.TYPE_INT32,<EOL>descriptor.FieldDescriptor.TYPE_SINT32,<EOL>descriptor.FieldDescriptor.TYPE_SFIXED32):<EOL><INDENT>value = tokenizer.ConsumeInt32()<EOL><DEDENT>elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,<EOL>descriptor.FieldDescriptor.TYPE_SINT64,<EOL>descriptor.FieldDescriptor.TYPE_SFIXED64):<EOL><INDENT>value = tokenizer.ConsumeInt64()<EOL><DEDENT>elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,<EOL>descriptor.FieldDescriptor.TYPE_FIXED32):<EOL><INDENT>value = tokenizer.ConsumeUint32()<EOL><DEDENT>elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,<EOL>descriptor.FieldDescriptor.TYPE_FIXED64):<EOL><INDENT>value = tokenizer.ConsumeUint64()<EOL><DEDENT>elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,<EOL>descriptor.FieldDescriptor.TYPE_DOUBLE):<EOL><INDENT>value = tokenizer.ConsumeFloat()<EOL><DEDENT>elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:<EOL><INDENT>value = tokenizer.ConsumeBool()<EOL><DEDENT>elif field.type == descriptor.FieldDescriptor.TYPE_STRING:<EOL><INDENT>value = tokenizer.ConsumeString()<EOL><DEDENT>elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:<EOL><INDENT>value = tokenizer.ConsumeByteString()<EOL><DEDENT>elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:<EOL><INDENT>value = tokenizer.ConsumeEnum(field)<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>' % field.type)<EOL><DEDENT>if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>if field.is_extension:<EOL><INDENT>message.Extensions[field].append(value)<EOL><DEDENT>else:<EOL><INDENT>getattr(message, field.name).append(value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if field.is_extension:<EOL><INDENT>if not self._allow_multiple_scalars and message.HasExtension(field):<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>' %<EOL>(message.DESCRIPTOR.full_name, field.full_name))<EOL><DEDENT>else:<EOL><INDENT>message.Extensions[field] = value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not self._allow_multiple_scalars and message.HasField(field.name):<EOL><INDENT>raise tokenizer.ParseErrorPreviousToken(<EOL>'<STR_LIT>' %<EOL>(message.DESCRIPTOR.full_name, field.name))<EOL><DEDENT>else:<EOL><INDENT>setattr(message, field.name, value)<EOL><DEDENT><DEDENT><DEDENT>

Merges a single scalar field into a message.

        Args:
          tokenizer: A tokenizer to parse the field value.
          message: A protocol message to record the data.
          field: The descriptor of the field to be merged.

        Raises:
          ParseError: In case of text parsing problems.
          RuntimeError: On runtime errors.


return not self.token<EOL>

Checks the end of the text was reached.

        Returns:
          True iff the end was reached.


if self.token == token:<EOL><INDENT>self.NextToken()<EOL>return True<EOL><DEDENT>return False<EOL>

Tries to consume a given piece of text.

        Args:
          token: Text to consume.

        Returns:
          True iff the text was consumed.


if not self.TryConsume(token):<EOL><INDENT>raise self._ParseError('<STR_LIT>' % token)<EOL><DEDENT>

Consumes a piece of text.

        Args:
          token: Text to consume.

        Raises:
          ParseError: If the text couldn't be consumed.


result = self.token<EOL>if not self._IDENTIFIER.match(result):<EOL><INDENT>raise self._ParseError('<STR_LIT>')<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes protocol message field identifier.

        Returns:
          Identifier string.

        Raises:
          ParseError: If an identifier couldn't be consumed.


try:<EOL><INDENT>result = ParseInteger(self.token, is_signed=True, is_long=False)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes a signed 32bit integer number.

        Returns:
          The integer parsed.

        Raises:
          ParseError: If a signed 32bit integer couldn't be consumed.


try:<EOL><INDENT>result = ParseInteger(self.token, is_signed=False, is_long=False)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes an unsigned 32bit integer number.

        Returns:
          The integer parsed.

        Raises:
          ParseError: If an unsigned 32bit integer couldn't be consumed.


try:<EOL><INDENT>result = ParseInteger(self.token, is_signed=True, is_long=True)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes a signed 64bit integer number.

        Returns:
          The integer parsed.

        Raises:
          ParseError: If a signed 64bit integer couldn't be consumed.