With any data, serialize it and encapsulate it in a AMQP
        message with the proper headers set.
495730
def create_message(self, message_data, delivery_mode=None, priority=None,
                       content_type=None, content_encoding=None,
                       serializer=None):
        """"""

        delivery_mode = delivery_mode or self.delivery_mode

        # No content_type? Then we're serializing the data internally.
        if not content_type:
            serializer = serializer or self.serializer
            (content_type, content_encoding,
             message_data) = serialization.encode(message_data,
                                                  serializer=serializer)
        else:
            # If the programmer doesn't want us to serialize,
            # make sure content_encoding is set.
            if isinstance(message_data, unicode):
                if not content_encoding:
                    content_encoding = 'utf-8'
                message_data = message_data.encode(content_encoding)

            # If they passed in a string, we can't know anything
            # about it.  So assume it's binary data.
            elif not content_encoding:
                content_encoding = 'binary'

        return self.backend.prepare_message(message_data, delivery_mode,
                                            priority=priority,
                                            content_type=content_type,
                                            content_encoding=content_encoding)
374011
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
    # check if closed!!!!!! XXX
    
    if isinstance(contents, text_type):
        contents = [contents]
    if isinstance(attachments, text_type):
        attachments = [attachments]

    # merge contents and attachments for now.
    if attachments is not None:
        for a in attachments:
            if not os.path.isfile(a):
                raise TypeError("'{0}' is not a valid filepath".format(a))
        contents = attachments if contents is None else contents + attachments

    has_included_images, content_objects = prepare_contents(contents, encoding)
    msg = MIMEMultipart()
    if headers is not None:
        # Strangely, msg does not have an update method, so then manually.
        for k, v in headers.items():
            msg[k] = v
    if headers is None or "Date" not in headers:
        msg["Date"] = formatdate()

    msg_alternative = MIMEMultipart("alternative")
    msg_related = MIMEMultipart("related")
    msg_related.attach("-- HTML goes here --")
    msg.attach(msg_alternative)
    add_subject(msg, subject)
    add_recipients_headers(user, useralias, msg, addresses)
    htmlstr = ""
    altstr = []
    if has_included_images:
        msg.preamble = "This message is best displayed using a MIME capable email reader."

    if contents is not None:
        for content_object, content_string in zip(content_objects, contents):
            if content_object["main_type"] == "image":
                # all image objects need base64 encoding, so do it now
                email.encoders.encode_base64(content_object["mime_object"])
                # aliased image {'path' : 'alias'}
                if isinstance(content_string, dict) and len(content_string) == 1:
                    for key in content_string:
                        hashed_ref = str(abs(hash(key)))
                        alias = content_string[key]
                    # pylint: disable=undefined-loop-variable
                    content_string = key
                else:
                    alias = os.path.basename(str(content_string))
                    hashed_ref = str(abs(hash(alias)))

                # TODO: I should probably remove inline now that there is "attachments"
                # if string is `inline`, inline, else, attach
                # pylint: disable=unidiomatic-typecheck
                if type(content_string) == inline:
                    htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
                    content_object["mime_object"].add_header(
                        "Content-ID", "<{0}>".format(hashed_ref)
                    )
                    altstr.append("-- img {0} should be here -- ".format(alias))
                    # inline images should be in related MIME block
                    msg_related.attach(content_object["mime_object"])
                else:
                    # non-inline images get attached like any other attachment
                    msg.attach(content_object["mime_object"])

            else:
                if content_object["encoding"] == "base64":
                    email.encoders.encode_base64(content_object["mime_object"])
                    msg.attach(content_object["mime_object"])
                elif content_object["sub_type"] not in ["html", "plain"]:
                    msg.attach(content_object["mime_object"])
                else:
                    if newline_to_break:
                        content_string = content_string.replace("\n", "<br>")
                    try:
                        htmlstr += "<div>{0}</div>".format(content_string)
                    except UnicodeEncodeError:
                        htmlstr += u"<div>{0}</div>".format(content_string)
                    altstr.append(content_string)

    msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
    msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
    msg_alternative.attach(msg_related)
    return msg
1033951
def serialize(self):
        

        self.data = bytearray()
        r = self.protocols[::-1]
        for i, p in enumerate(r):
            if isinstance(p, packet_base.PacketBase):
                if i == len(r) - 1:
                    prev = None
                else:
                    prev = r[i + 1]
                data = p.serialize(self.data, prev)
            else:
                data = six.binary_type(p)
            self.data = bytearray(data + self.data)
736015
protected final void serializeTo( RawDataBuffer out )
    {
    	// Level 1 - Always unserialized
    	byte lvl1Flags = (byte)((priority & 0x0F)+
    	                        (redelivered ? (1 << 4) : 0)+
    	                        (deliveryMode == DeliveryMode.PERSISTENT ? (1 << 5) : 0)+
    	                        (expiration != 0 ? (1 << 6) : 0)+ // Expiration value present
    	                        (id != null ? (1 << 7) : 0)); // ID value present
    	out.writeByte(lvl1Flags);
    	if (expiration != 0)
    		out.writeLong(expiration);
    	if (id != null)
    		out.writeUTF(id);
    	DestinationSerializer.serializeTo(destination, out);
    	
        // Level 2 - Unserialized if required by a message selector
    	byte lvl2Flags = (byte)((correlId != null ? (1 << 0) : 0)+
    	                        (replyTo != null ? (1 << 1) : 0)+
    	                        (timestamp != 0 ? (1 << 2) : 0)+
    	                        (type != null ? (1 << 3) : 0)+
    	                        (propertyMap != null && !propertyMap.isEmpty() ? (1 << 4) : 0));
    	out.writeByte(lvl2Flags);
    	if (correlId != null)
    		out.writeUTF(correlId);
    	if (replyTo != null)
    		DestinationSerializer.serializeTo(replyTo, out);
    	if (timestamp != 0)
    		out.writeLong(timestamp);
    	if (type != null)
    		out.writeUTF(type);
    	if (propertyMap != null && !propertyMap.isEmpty())
    		writeMapTo(propertyMap, out);
        
        // Level 3 - Body - Only unserialized on the client side
        serializeBodyTo(out);
    }
709561
def _wrap_data(data: Union[str, bytes]):
        
        MsgType = TextMessage if isinstance(data, str) else BytesMessage
        return MsgType(data=data, frame_finished=True, message_finished=True)
121600
def create_header(cls, request_id=None):
        ''' 

        '''
        header = {
            'msgid'   : bkserial.make_id(),
            'msgtype' : cls.msgtype
        }
        if request_id is not None:
            header['reqid'] = request_id
        return header
919013
def serialize(self, data):
        
        return json.dumps(self._serialize_datetime(data), ensure_ascii=False)
752457
private static Map<String, List<String>> getOrCreateProtocolHeader(
            Message message) {
        Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message
                .get(Message.PROTOCOL_HEADERS));
        if (headers == null) {
            headers = new HashMap<String, List<String>>();
            message.put(Message.PROTOCOL_HEADERS, headers);
        }
        return headers;
    }
159948
def prepare(cls, value, length=0, position=0, is_last_data=True):
        
        hstruct = WriteLobHeader.header_struct
        lob_option_dataincluded = WriteLobHeader.LOB_OPTION_DATAINCLUDED if length > 0 else 0
        lob_option_lastdata = WriteLobHeader.LOB_OPTION_LASTDATA if is_last_data else 0
        options = lob_option_dataincluded | lob_option_lastdata
        pfield = hstruct.pack(cls.type_code, options, length, position)
        return pfield
1293446
def serialize_detail(self, data):
        
        if data is None:
            return ''

        # Check for a ``Data``-like object. We should assume ``True`` (all
        # data gets prepared) unless it's explicitly marked as not.
        if not getattr(data, 'should_prepare', True):
            prepped_data = data.value
        else:
            prepped_data = self.prepare(data)

        return self.serializer.serialize(prepped_data)
192977
def encode_request(name, values):
    
    client_message = ClientMessage(payload_size=calculate_size(name, values))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_int(len(values))
    for values_item in values:
        client_message.append_data(values_item)
    client_message.update_frame_length()
    return client_message
421246
function createContext(message) {

	var message = message || {},
		context = {}
	
	context.headers$ = _.omit(message.properties || {}, 'headers')
	context.amqp$    = message.fields     || {}
	context.req      = {}
	context.res      = {}

	if (message.content) {
		if (message.content instanceof Buffer)
			context.req = JSON.parse(message.content.toString())
		else 
			context.req = message.content
	}

	if (message.properties.headers)
		_.merge(context.headers$, message.properties.headers)

	context.service  = this
	context.invoke   = this.invoke.bind(this)
	context.command  = this.command.bind(this)
	context.publish  = this.publish.bind(this)
	context.sleep    = this.sleep.bind(this)
	context.log      = this.log

	return context
}
167741
def FromData(cls, stream, json_data, http, auto_transfer=None,
                 gzip_encoded=False, **kwds):
        """"""
        info = json.loads(json_data)
        missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys())
        if missing_keys:
            raise exceptions.InvalidDataError(
                'Invalid serialization data, missing keys: %s' % (
                    ', '.join(missing_keys)))
        if 'total_size' in kwds:
            raise exceptions.InvalidUserInputError(
                'Cannot override total_size on serialized Upload')
        upload = cls.FromStream(stream, info['mime_type'],
                                total_size=info.get('total_size'),
                                gzip_encoded=gzip_encoded, **kwds)
        if isinstance(stream, io.IOBase) and not stream.seekable():
            raise exceptions.InvalidUserInputError(
                'Cannot restart resumable upload on non-seekable stream')
        if auto_transfer is not None:
            upload.auto_transfer = auto_transfer
        else:
            upload.auto_transfer = info['auto_transfer']
        upload.strategy = RESUMABLE_UPLOAD
        upload._Initialize(  # pylint: disable=protected-access
            http, info['url'])
        upload.RefreshResumableUploadState()
        upload.EnsureInitialized()
        if upload.auto_transfer:
            upload.StreamInChunks()
        return upload
321286
def create(self, data):
        
        data = values.of({'Data': serialize.object(data), })

        payload = self._version.create(
            'POST',
            self._uri,
            data=data,
        )

        return StreamMessageInstance(
            self._version,
            payload,
            service_sid=self._solution['service_sid'],
            stream_sid=self._solution['stream_sid'],
        )
779045
def encode_ipmb_msg(header, data):
    
    msg = array('B')

    msg.fromstring(header.encode())
    if data is not None:
        a = array('B')
        a.fromstring(data)
        msg.extend(a)
    msg.append(checksum(msg[3:]))
    return msg.tostring()
683228
function __serializeContent(data, options=DEFAULT_OPTIONS) {
	let type = __getType(data, options);
	let typeBuffer	= __serializeType(type, options);
	let dataBuffers = __serializeData(type, data, options);
	return [typeBuffer, ...dataBuffers];
}
693409
def compose_headers(self, req, headers=None, opt=None, as_dict=False):
        
        if headers is None:
            return list(req.header.items()) if not as_dict else req.header

        opt = opt or {}
        join_headers = opt.pop(BaseClient.join_headers, None)
        if as_dict and not join_headers:
            # pick the most efficient way for special case
            headers = dict(headers) if isinstance(headers, list) else headers
            headers.update(req.header)
            return headers

        # include Request.headers
        aggregated_headers = list(req.header.items())

        # include customized headers
        if isinstance(headers, list):
            aggregated_headers.extend(headers)
        elif isinstance(headers, dict):
            aggregated_headers.extend(headers.items())
        else:
            raise Exception('unknown type as header: {}'.format(str(type(headers))))

        if join_headers:
            joined = {}
            for h in aggregated_headers:
                key = h[0]
                if key in joined:
                    joined[key] = ','.join([joined[key], h[1]])
                else:
                    joined[key] = h[1]
            aggregated_headers = list(joined.items())

        return dict(aggregated_headers) if as_dict else aggregated_headers