Produce a Protobuf module from a string description.

    Return the module if successfully compiled, otherwise raise a BadProtobuf
    exception.
968080
def from_string(proto_str):
    '''
    
    '''
    _, proto_file = tempfile.mkstemp(suffix='.proto')

    with open(proto_file, 'w+') as proto_f:
        proto_f.write(proto_str)

    return from_file(proto_file)
1109426
def from_bytes(self, raw):
        ''''''
        if len(raw) < Arp._MINLEN:
            raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an Arp object".format(len(raw)))
        fields = struct.unpack(Arp._PACKFMT, raw[:Arp._MINLEN])
        try:
            self._hwtype = ArpHwType(fields[0])
            self._prototype = EtherType(fields[1])
            self._hwaddrlen = fields[2]
            self._protoaddrlen = fields[3]
            self.operation = ArpOperation(fields[4])
            self.senderhwaddr = EthAddr(fields[5])
            self.senderprotoaddr = IPAddr(fields[6])
            self.targethwaddr = EthAddr(fields[7])
            self.targetprotoaddr = IPAddr(fields[8])
        except Exception as e:
            raise Exception("Error constructing Arp packet object from raw bytes: {}".format(str(e)))
        return raw[Arp._MINLEN:]
632640
def _serialize(proto):  # type: (Union[bytes, google.protobuf.message.Message]) -> bytes
    '''
    
    '''
    if isinstance(proto, bytes):
        return proto
    elif hasattr(proto, 'SerializeToString') and callable(proto.SerializeToString):
        result = proto.SerializeToString()
        return result
    else:
        raise ValueError('No SerializeToString method is detected. '
                         'neither proto is a str.\ntype is {}'.format(type(proto)))
663959
def compile(node,
                uri,
                filename=None,
                default_filters=None,
                buffer_filters=None,
                imports=None,
                future_imports=None,
                source_encoding=None,
                generate_magic_comment=True,
                disable_unicode=False,
                strict_undefined=False,
                enable_loop=True,
                reserved_names=frozenset()):

    """"""

    # if on Py2K, push the "source_encoding" string to be
    # a bytestring itself, as we will be embedding it into
    # the generated source and we don't want to coerce the
    # result into a unicode object, in "disable_unicode" mode
    if not compat.py3k and isinstance(source_encoding, compat.text_type):
        source_encoding = source_encoding.encode(source_encoding)


    buf = util.FastEncodingBuffer()

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(printer,
                            _CompileContext(uri,
                                            filename,
                                            default_filters,
                                            buffer_filters,
                                            imports,
                                            future_imports,
                                            source_encoding,
                                            generate_magic_comment,
                                            disable_unicode,
                                            strict_undefined,
                                            enable_loop,
                                            reserved_names),
                                node)
    return buf.getvalue()
218477
def _strfactory(cls, line):
        

        assert type(line) == str, "this is a factory from string"

        line = line.rstrip().split()[1:] # the first component is the keyword "chain"
        tup = [t[0](t[1]) for t in zip([int, str, int, str, int, int, str, int, str, int, int, str], line)]
        return tuple.__new__(cls, tup)
217828
def _from_string(cls, serialized):
        
        # Allow access to _from_string protected method
        library_key = LibraryLocator._from_string(serialized)  # pylint: disable=protected-access
        parsed_parts = LibraryLocator.parse_url(serialized)

        block_id = parsed_parts.get('block_id', None)
        if block_id is None:
            raise InvalidKeyError(cls, serialized)

        block_type = parsed_parts.get('block_type')
        if block_type is None:
            raise InvalidKeyError(cls, serialized)

        return cls(library_key, parsed_parts.get('block_type'), block_id)
408378
def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
  """"""

  local_DecodeVarint = _DecodeVarint
  local_unicode = six.text_type

  def _ConvertToUnicode(byte_str):
    try:
      return local_unicode(byte_str, 'utf-8')
    except UnicodeDecodeError as e:
      # add more information to the error message and re-raise it.
      e.reason = '%s in field: %s' % (e, key.full_name)
      raise

  assert not is_packed
  if is_repeated:
    tag_bytes = encoder.TagBytes(field_number,
                                 wire_format.WIRETYPE_LENGTH_DELIMITED)
    tag_len = len(tag_bytes)
    def DecodeRepeatedField(buffer, pos, end, message, field_dict):
      value = field_dict.get(key)
      if value is None:
        value = field_dict.setdefault(key, new_default(message))
      while 1:
        (size, pos) = local_DecodeVarint(buffer, pos)
        new_pos = pos + size
        if new_pos > end:
          raise _DecodeError('Truncated string.')
        value.append(_ConvertToUnicode(buffer[pos:new_pos]))
        # Predict that the next tag is another copy of the same repeated field.
        pos = new_pos + tag_len
        if buffer[new_pos:pos] != tag_bytes or new_pos == end:
          # Prediction failed.  Return.
          return new_pos
    return DecodeRepeatedField
  else:
    def DecodeField(buffer, pos, end, message, field_dict):
      (size, pos) = local_DecodeVarint(buffer, pos)
      new_pos = pos + size
      if new_pos > end:
        raise _DecodeError('Truncated string.')
      field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos])
      return new_pos
    return DecodeField
38916
def from_string(self, source, globals=None, template_class=None):
        
        globals = self.make_globals(globals)
        cls = template_class or self.template_class
        return cls.from_code(self, self.compile(source), globals, None)
56563
def ub_to_str(string):
    
    if not isinstance(string, str):
        if six.PY2:
            return str(string)
        else:
            return string.decode()
    return string
1278026
def get_pymodule(self):
        """"""
        msg = None
        code = self.code
        tries = 0
        while True:
            try:
                if tries == 0 and self.resource is not None and \
                   self.resource.read() == code:
                    return self.project.get_pymodule(self.resource,
                                                     force_errors=True)
                return libutils.get_string_module(
                    self.project, code, resource=self.resource,
                    force_errors=True)
            except exceptions.ModuleSyntaxError as e:
                if msg is None:
                    msg = '%s:%s %s' % (e.filename, e.lineno, e.message_)
                if tries < self.maxfixes:
                    tries += 1
                    self.commenter.comment(e.lineno)
                    code = '\n'.join(self.commenter.lines)
                else:
                    raise exceptions.ModuleSyntaxError(
                        e.filename, e.lineno,
                        'Failed to fix error: {0}'.format(msg))
896434
@Nonnull
    public static <Message extends PMessage<Message, Field>, Field extends PField>
    String debugString(Message message) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEBUG_STRING_SERIALIZER.serialize(baos, message);
        return new String(baos.toByteArray(), UTF_8);
    }
625475
def get_string_module(project, code, resource=None, force_errors=False):
    
    return pyobjectsdef.PyModule(project.pycore, code, resource,
                                 force_errors=force_errors)
12524
def _compile_proto(full_path, dest):
    ''
    proto_path = os.path.dirname(full_path)
    protoc_args = [find_protoc(),
                   '--python_out={}'.format(dest),
                   '--proto_path={}'.format(proto_path),
                   full_path]
    proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    try:
        outs, errs = proc.communicate(timeout=5)
    except subprocess.TimeoutExpired:
        proc.kill()
        outs, errs = proc.communicate()
        return False

    if proc.returncode != 0:
        msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format(
            full_path, errs.decode('utf-8'), outs.decode('utf-8'))
        raise BadProtobuf(msg)

    return True
592301
def python_portable_string(string, encoding='utf-8'):
  
  if isinstance(string, six.string_types):
    return string

  if six.PY3:
    return string.decode(encoding)

  raise ValueError('Unsupported type %s' % str(type(string)))
1308707
function (string) {
    var modules = string.split(".");
    if (modules.length == 1) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    } else {
      var m = [];
      for (var i=0; i<modules.length; i++) {
        m.push(this.classize(modules[i]));
      }
      return m.join("\\");
    }
  }
228399
def from_string(value):
        
        if value == None or len(value) == 0:
            return None
                
        tokens = value.split(":")
        if len(tokens) != 5:
            raise ConfigException(
                None, "BAD_DESCRIPTOR", "Descriptor " + str(value) + " is in wrong format"
            ).with_details("descriptor", value)
            
        return Descriptor(tokens[0].strip(), tokens[1].strip(), tokens[2].strip(), tokens[3].strip(), tokens[4].strip())
378561
def import_from_string(value):
    """"""
    value = value.replace('-', '_')
    try:
        module_path, class_name = value.rsplit('.', 1)
        module = import_module(module_path)
        return getattr(module, class_name)
    except (ImportError, AttributeError) as ex:
        raise ImportError("Could not import '{}'. {}: {}.".format(
            value, ex.__class__.__name__, ex))