Build a Graphite message to send and return it as a byte string.
182435
def build_message(self, metric, value, timestamp, tags={}):
        """"""
        if not metric or metric.split(None, 1)[0] != metric:
            raise ValueError('"metric" must not have whitespace in it')
        if not isinstance(value, (int, float)):
            raise TypeError('"value" must be an int or a float, not a {}'.format(
                type(value).__name__))

        tags_suffix = ''.join(';{}={}'.format(x[0], x[1]) for x in sorted(tags.items()))

        message = u'{}{}{} {} {}\n'.format(
            self.prefix + '.' if self.prefix else '',
            metric,
            tags_suffix,
            value,
            int(round(timestamp))
        )
        message = message.encode('utf-8')
        return message
263489
def to_message(base):
    
    ctype, ctparams = base.get_content_type()

    if not ctype:
        if base.parts:
            ctype = 'multipart/mixed'
        else:
            ctype = 'text/plain'

    maintype, subtype = ctype.split('/')
    is_text = maintype == 'text'
    is_multipart = maintype == 'multipart'

    if base.parts and not is_multipart:
        raise RuntimeError(
            'Content type should be multipart, not %r' % ctype
            )

    body = base.get_body()
    ctenc = base.get_transfer_encoding()
    charset = ctparams.get('charset')

    if is_multipart:
        out = MIMEMultipart(subtype, **ctparams)
    else:
        out = MIMENonMultipart(maintype, subtype, **ctparams)
        if ctenc:
            out['Content-Transfer-Encoding'] = ctenc
        if isinstance(body, text_type):
            if not charset:
                if is_text:
                    charset, _ = best_charset(body)
                else:
                    charset = 'utf-8'
            if PY2:
                body = body.encode(charset)
            else: # pragma: no cover
                body = body.encode(charset, 'surrogateescape')
        if body is not None:
            if ctenc:
                body = transfer_encode(ctenc, body)
            if not PY2: # pragma: no cover
                body = body.decode(charset or 'ascii', 'replace')
        out.set_payload(body, charset) 

    for k in base.keys(): # returned sorted
        value = base[k]
        if not value:
            continue
        out[k] = value

    cdisp, cdisp_params = base.get_content_disposition()

    if cdisp:
        out.add_header('Content-Disposition', cdisp, **cdisp_params)

    # go through the children
    for part in base.parts:
        sub = to_message(part)
        out.attach(sub)

    return out
994968
public void push(String name, String value, long timestamp) throws IOException {
    graphiteSender.send(name, value, timestamp);
  }
1120389
def serialize(message):
        
        fmt = "!BBH"

        if message.token is None or message.token == "":
            tkl = 0
        else:
            tkl = len(message.token)
        tmp = (defines.VERSION << 2)
        tmp |= message.type
        tmp <<= 4
        tmp |= tkl

        values = [tmp, message.code, message.mid]

        if message.token is not None and tkl > 0:

            for b in str(message.token):
                fmt += "c"
                values.append(bytes(b, "utf-8"))

        options = Serializer.as_sorted_list(message.options)  # already sorted
        lastoptionnumber = 0
        for option in options:

            # write 4-bit option delta
            optiondelta = option.number - lastoptionnumber
            optiondeltanibble = Serializer.get_option_nibble(optiondelta)
            tmp = (optiondeltanibble << defines.OPTION_DELTA_BITS)

            # write 4-bit option length
            optionlength = option.length
            optionlengthnibble = Serializer.get_option_nibble(optionlength)
            tmp |= optionlengthnibble
            fmt += "B"
            values.append(tmp)

            # write extended option delta field (0 - 2 bytes)
            if optiondeltanibble == 13:
                fmt += "B"
                values.append(optiondelta - 13)
            elif optiondeltanibble == 14:
                fmt += "H"
                values.append(optiondelta - 269)

            # write extended option length field (0 - 2 bytes)
            if optionlengthnibble == 13:
                fmt += "B"
                values.append(optionlength - 13)
            elif optionlengthnibble == 14:
                fmt += "H"
                values.append(optionlength - 269)

            # write option value
            if optionlength > 0:
                opt_type = defines.OptionRegistry.LIST[option.number].value_type
                if opt_type == defines.INTEGER:
                    words = Serializer.int_to_words(option.value, optionlength, 8)
                    for num in range(0, optionlength):
                        fmt += "B"
                        values.append(words[num])
                elif opt_type == defines.STRING:
                    fmt += str(len(bytes(option.value, "utf-8"))) + "s"
                    values.append(bytes(option.value, "utf-8"))

                else:  # OPAQUE
                    for b in option.value:
                        fmt += "B"
                        values.append(b)

            # update last option number
            lastoptionnumber = option.number

        payload = message.payload

        if payload is not None and len(payload) > 0:
            # if payload is present and of non-zero length, it is prefixed by
            # an one-byte Payload Marker (0xFF) which indicates the end of
            # options and the start of the payload

            fmt += "B"
            values.append(defines.PAYLOAD_MARKER)

            if isinstance(payload, bytes):
                fmt += str(len(payload)) + "s"
                values.append(payload)
            else:
                fmt += str(len(bytes(payload, "utf-8"))) + "s"
                values.append(bytes(payload, "utf-8"))
            # for b in str(payload):
            #     fmt += "c"
            #     values.append(bytes(b, "utf-8"))

        datagram = None
        if values[1] is None:
            values[1] = 0
        if values[2] is None:
            values[2] = 0
        try:
            s = struct.Struct(fmt)
            datagram = ctypes.create_string_buffer(s.size)
            s.pack_into(datagram, 0, *values)
        except struct.error:
            # The .exception method will report on the exception encountered
            # and provide a traceback.
            logger.debug(fmt)
            logger.debug(values)
            logging.exception('Failed to pack structure')

        return datagram
918745
def reply_bytes(self, request):
        """"""
        flags = struct.pack("<i", self._flags)
        cursor_id = struct.pack("<q", self._cursor_id)
        starting_from = struct.pack("<i", self._starting_from)
        number_returned = struct.pack("<i", len(self._docs))
        reply_id = random.randint(0, 1000000)
        response_to = request.request_id

        data = b''.join([flags, cursor_id, starting_from, number_returned])
        data += b''.join([bson.BSON.encode(doc) for doc in self._docs])

        message = struct.pack("<i", 16 + len(data))
        message += struct.pack("<i", reply_id)
        message += struct.pack("<i", response_to)
        message += struct.pack("<i", OP_REPLY)
        return message + data
93987
def to_adb_message(self, data):
    """"""
    message = AdbMessage(AdbMessage.WIRE_TO_CMD.get(self.cmd),
                         self.arg0, self.arg1, data)
    if (len(data) != self.data_length or
        message.data_crc32 != self.data_checksum):
      raise usb_exceptions.AdbDataIntegrityError(
          '%s (%s) received invalid data: %s', message, self, repr(data))
    return message
36999
def _ipc_send(self, sock, message_type, payload):
        '''
        
        '''
        sock.sendall(self._pack(message_type, payload))
        data, msg_type = self._ipc_recv(sock)
        return data
724690
public void send(String msg) {
    try {
      Socket socket = new Socket(graphiteHost, graphitePort);

      try {
        Writer writer = new OutputStreamWriter(socket.getOutputStream());
        try {
          writer.write(msg);
          writer.flush();
        } finally {
          try {
            writer.close();
          } catch (IOException ioe) {
            //ignore, we want to see the outer exception if any
            LOGGER.info("could not close writer");
          }
        }
        if (connectionState != ConnectionState.SUCCESS) {
          LOGGER.info("Connection to graphite Host {}",
            ((connectionState == ConnectionState.UNKNOWN) ? "established" : "recovered"));
          connectionState = ConnectionState.SUCCESS;
        }

      } catch (IOException e) {
        String action = "write";
        handleException(e, action);
      } finally {
        socket.close();
      }
    } catch (IOException e) {
      String action = "connect";
      handleException(e, action);
    }
  }
176636
def _dispatch_send(self, message):
        

        if self.dryrun:
            return message

        if not self.socket:
            raise GraphiteSendException(
                "Socket was not created before send"
            )

        sending_function = self._send
        if self._autoreconnect:
            sending_function = self._send_and_reconnect

        try:
            if self.asynchronous and gevent:
                gevent.spawn(sending_function, message)
            else:
                sending_function(message)
        except Exception as e:
            self._handle_send_error(e)

        return "sent {0} long message: {1}".format(len(message), message[:75])
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)))
1139630
def build(self, message):
        
        context = None

        if message.message_type in [Types.CALL_REQ,
                                    Types.CALL_RES]:
            self.verify_message(message)

            context = self.build_context(message)
            # streaming message
            if message.flags == common.FlagsType.fragment:
                self.message_buffer[message.id] = context

            # find the incompleted stream
            num = 0
            for i, arg in enumerate(context.argstreams):
                if arg.state != StreamState.completed:
                    num = i
                    break

            self.close_argstream(context, num)
            return context

        elif message.message_type in [Types.CALL_REQ_CONTINUE,
                                      Types.CALL_RES_CONTINUE]:
            context = self.message_buffer.get(message.id)
            if context is None:
                # missing call msg before continue msg
                raise FatalProtocolError(
                    "missing call message after receiving continue message",
                    message.id,
                )

            # find the incompleted stream
            dst = 0
            for i, arg in enumerate(context.argstreams):
                if arg.state != StreamState.completed:
                    dst = i
                    break

            try:
                self.verify_message(message)
            except InvalidChecksumError as e:
                context.argstreams[dst].set_exception(e)
                raise

            src = 0
            while src < len(message.args):
                context.argstreams[dst].write(message.args[src])
                dst += 1
                src += 1

            if message.flags != FlagsType.fragment:
                # get last fragment. mark it as completed
                assert (len(context.argstreams) ==
                        CallContinueMessage.max_args_num)
                self.message_buffer.pop(message.id, None)
                context.flags = FlagsType.none

            self.close_argstream(context, dst - 1)
            return None
        elif message.message_type == Types.ERROR:
            context = self.message_buffer.pop(message.id, None)
            if context is None:
                log.info('Unconsumed error %s', message)
                return None
            else:
                error = TChannelError.from_code(
                    message.code,
                    description=message.description,
                    tracing=context.tracing,
                )

                context.set_exception(error)
                return error
        else:
            return message
1225597
def create(rawmessage):
    """"""
    rawmessage = _trim_buffer_garbage(rawmessage)

    if len(rawmessage) < 2:
        return (None, rawmessage)

    code = rawmessage[1]
    msgclass = _get_msg_class(code)

    msg = None

    remaining_data = rawmessage
    if msgclass is None:
        _LOGGER.debug('Did not find message class 0x%02x', rawmessage[1])
        rawmessage = rawmessage[1:]
        rawmessage = _trim_buffer_garbage(rawmessage, False)
        if rawmessage:
            _LOGGER.debug('Create: %s', create)
            _LOGGER.debug('rawmessage: %s', binascii.hexlify(rawmessage))
            msg, remaining_data = create(rawmessage)
        else:
            remaining_data = rawmessage
    else:
        if iscomplete(rawmessage):
            msg = msgclass.from_raw_message(rawmessage)
            if msg:
                remaining_data = rawmessage[len(msg.bytes):]
    # _LOGGER.debug("Returning msg: %s", msg)
    # _LOGGER.debug('Returning buffer: %s', binascii.hexlify(remaining_data))
    return (msg, remaining_data)
1070809
def make_message(message, binary=False):
    """"""
    if isinstance(message, str):
        message = message.encode('utf-8')

    if binary:
        return _make_frame(message, OPCODE_BINARY)
    else:
        return _make_frame(message, OPCODE_TEXT)
925331
def cli():
    
    import argparse

    parser = argparse.ArgumentParser(description='Send data to graphite')

    # Core of the application is to accept a metric and a value.
    parser.add_argument('metric', metavar='metric', type=str,
                        help='name.of.metric')
    parser.add_argument('value', metavar='value', type=int,
                        help='value of metric as int')

    args = parser.parse_args()
    metric = args.metric
    value = args.value

    graphitesend_instance = init()
    graphitesend_instance.send(metric, value)
285798
def send(self, message):
        """"""
        if not message or not self.protocol or not self.protocol.transport:
            return
        if not self.can_log:
            _LOGGER.debug('Sending %s', message.strip())
        try:
            self.protocol.transport.write(message.encode())
        except OSError as exc:
            _LOGGER.error(
                'Failed writing to transport %s: %s',
                self.protocol.transport, exc)
            self.protocol.transport.close()
            self.protocol.conn_lost_callback()
20263
def message_from_bytes(s, *args, **kws):
    
    from future.backports.email.parser import BytesParser
    return BytesParser(*args, **kws).parsebytes(s)
769331
def send_bytes(self):
        """"""
        data = b''.join(self.bytes_to_send)
        self.bytes_to_send = []
        return data