Encapsulate data into a AMQP message.
178286
def prepare_message(self, message_data, delivery_mode, priority=None,
            content_type=None, content_encoding=None):
        """"""
        properties = pika.BasicProperties(priority=priority,
                                          content_type=content_type,
                                          content_encoding=content_encoding,
                                          delivery_mode=delivery_mode)
        return message_data, properties
126039
function amqpResponderNode(config) {

        RED.nodes.createNode(this, config);

        // get endpoint configuration
        this.endpoint = RED.nodes.getNode(config.endpoint);
        // get all other configuration
        this.address = config.address;

        var node = this;
        // node not yet connected
        this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });

        if (this.endpoint) {

            node.endpoint.connect(function(connection) {
                setup(connection);
            });

            /**
             * Node setup for creating receiver link for receiving the request
             * and the sender for sending reply
             *
             * @param connection    Connection instance
             */
            function setup(connection) {

                var request = undefined;
                var reply_to = undefined;
                var response = undefined;

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                node.sender = node.connection.open_sender({ target: {} });

                // build receiver options
                var receiver_options = {
                    source: {
                        address: node.address
                    }
                };
                node.receiver = node.connection.open_receiver(receiver_options);

                node.receiver.on('message', function(context) {

                    // save request and reply_to address on AMQP message received
                    request = context.message;
                    reply_to = request.reply_to;

                    // provides the request and delivery as node output
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {

                        if (reply_to) {

                            // fill the response with the provided one as input
                            response = msg.payload;
                            response.to = reply_to;

                            node.sender.send(response);
                        }
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                })

            }

        }
    }
927524
def communicate(self):
        """"""
        self._communicate_first = True
        self._process.waitForFinished()

        enco = self._get_encoding()
        if self._partial_stdout is None:
            raw_stdout = self._process.readAllStandardOutput()
            stdout = handle_qbytearray(raw_stdout, enco)
        else:
            stdout = self._partial_stdout

        raw_stderr = self._process.readAllStandardError()
        stderr = handle_qbytearray(raw_stderr, enco)
        result = [stdout.encode(enco), stderr.encode(enco)]

        if PY2:
            stderr = stderr.decode()
        result[-1] = ''

        self._result = result

        if not self._fired:
            self.sig_finished.emit(self, result[0], result[-1])

        self._fired = True

        return result
628629
def _process_info_message(self, message):
        """"""
        # Extract the output resolution from the appropriate message, if
        # it's present.
        if message['messageCode'] == 'JOB_RUNNING_RESOLUTION':
            self._resolution = message['contents']['resolutionMs']
        elif message['messageCode'] == 'FETCH_NUM_TIMESERIES':
            self._num_input_timeseries += int(message['numInputTimeSeries'])
401468
def prepare(data):
    """"""
    message = data.get("message")
    sha = data.get("sha")
    tree = data.get("tree")
    tree_sha = tree.get("sha")
    return {"message": message, "sha": sha, "tree": {"sha": tree_sha}}
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)
1165752
private function convertToAmqpLibMessage(\Interop\Amqp\AmqpMessage $amqpMessage)
    {
        $amqpLibProperties = $amqpMessage->getHeaders();
        $amqpLibProperties['application_headers'] = $amqpMessage->getProperties();

        $amqpLibMessage = new AMQPMessage($amqpMessage->getBody(), $amqpLibProperties);
        $amqpLibMessage->delivery_info = [
            'consumer_tag' => $this->consumer->getConsumerTag(),
            'delivery_tag' => $amqpMessage->getDeliveryTag(),
            'redelivered' => $amqpMessage->isRedelivered(),
            'routing_key' => $amqpMessage->getRoutingKey(),
            'channel' => $this->channel,
        ];

        return $amqpLibMessage;
    }
1004679
def _on_msg(self, msg):
        """"""
        data = msg['content']['data']

        # If the message is a call invoke, run the function and send
        # the results.
        if 'callback' in data:
            guid = data['callback']
            callback = callback_registry[guid]
            args = data['arguments']
            args = [self.deserialize(a) for a in args]
            index = data['index']

            results = callback(*args)
            return self.serialize(self._send('return', index=index, results=results))

        # The message is not a call invoke, it must be an object
        # that is a response to a Python request.
        else:
            index = data['index']
            immutable = data['immutable']
            value = data['value']
            if index in self._callbacks:
                self._callbacks[index].resolve({
                    'immutable': immutable,
                    'value': value
                })
                del self._callbacks[index]
141842
def SendMessage(self, statement):
        """"""
        
        # The way messages are 'encapsulated' by Rekall is questionable, 99% of the
        # time it's way better to have a dictionary...shrug...
        message_type = statement[0]
        message_data = statement[1]        
        self.output.append({'type': message_type, 'data': message_data})
65978
def build_message(self, checker):
        """"""
        solution = ' (%s)' % checker.solution if self.with_solutions else ''
        return '{} {}{}'.format(checker.code,
                                checker.msg,
                                solution)
436028
def make_message(self, data):

        

        data = self.codec.loads(data)
        msg = Message(
            data.get("data"),
            *data.get("args",[]),
            **data.get("kwargs",{})
        )
        msg.meta.update(data.get("meta"))
        self.trigger("make_message", data, msg)
        return msg
216945
def display_message(pymux, variables):
    "  "
    message = variables['<message>']
    client_state = pymux.get_client_state()
    client_state.message = message
486086
def _mq_callback(self, message):
        
        try:
            raw_data = RawData.from_json(message.body)
            try:
                session = self.ss_dao.find_by_session_id(raw_data.domain_name, raw_data.session_id)

                # update the click_xxx info
                session = self.update_session_body(raw_data, session)

                epoch_current = calendar.timegm(raw_data.timestamp.replace(tzinfo=None).utctimetuple())
                epoch_start = time_helper.session_to_epoch(session.timeperiod)
                session.browsing_history.total_duration = (epoch_current - epoch_start) / 1000

                index = session.browsing_history.number_of_entries
                self.add_entry(session, index, raw_data)
                self.performance_tracker.update.increment_success()
            except LookupError:
                # insert the record
                session = SingleSession()

                # input data constraints - both session_id and user_id must be present in MQ message
                session.key = (raw_data.domain_name,
                               time_helper.datetime_to_synergy(QUALIFIER_HOURLY, raw_data.timestamp),
                               raw_data.session_id)
                session.ip = raw_data.ip
                session.total_duration = 0

                session = self.update_session_body(raw_data, session)
                self.add_entry(session, 0, raw_data)
                self.performance_tracker.insert.increment_success()

            self.ss_dao.update(session)
            self.consumer.acknowledge(message.delivery_tag)
        except AutoReconnect as e:
            self.logger.error('MongoDB connection error: {0}\nRe-queueing message & exiting the worker'.format(e))
            self.consumer.reject(message.delivery_tag)
            raise e
        except (KeyError, IndexError) as e:
            self.logger.error('Error is considered Unrecoverable: {0}\nCancelled message: {1}'.format(e, message.body))
            self.consumer.cancel(message.delivery_tag)
        except Exception as e:
            self.logger.error('Error is considered Recoverable: {0}\nRe-queueing message: {1}'.format(e, message.body))
            self.consumer.reject(message.delivery_tag)
258392
def get_message(self):
        """"""

        result = ''
        if self._data_struct is not None:
            result = self._data_struct[KEY_MESSAGE]
        return result
151115
def pub_msg(self, msg):
        """"""
        topic = msg.get('topic')
        self.pub_socket.send_multipart(
            [pickle.dumps(topic), pickle.dumps(msg)])

        for h in self._handle_funcs.get(topic, []):
            h(msg)
324349
def wrap(data):
    
    try:
        cmdid = data[0]
    except IndexError:
        log.warning('data is empty')
        return None

    try:
        message_type = CMDID_MESSAGE[cmdid]
    except KeyError:
        log.error('unknown cmdid %s', cmdid)
        return None

    try:
        message = message_type(data)
    except ValueError:
        log.error('trying to decode invalid message')
        return None

    return message
1186946
def put(self, message):
        """"""

        # First assemble the complete message string by prefixing the header.
        header = self.HEADER_FORMAT.format(len(message))
        full_message = header + message

        # Then send all bytes of the message.
        sent_count = 0
        while sent_count < len(full_message):
            try:
                msg = full_message[sent_count:]
                msg = msg.encode() if self._encode else msg
                count = self._sock.send(msg)
            except socket.error as err:
                print('error')
                return False
            if count == 0:
                return False
            sent_count += count
        return True