Build :class:`hbmqtt.mqtt.publish.PublishPacket` from attributes

        :param dup: force dup flag
        :return: :class:`hbmqtt.mqtt.publish.PublishPacket` built from ApplicationMessage instance attributes
509359
def build_publish_packet(self, dup=False):
        
        return PublishPacket.build(self.topic, self.data, self.packet_id, dup, self.qos, self.retain)
651538
private void publish2Subscribers(String topic, AbstractMessage.QOSType qos, ByteBuffer origMessage, boolean retain, Integer messageID) {
        Log.trace("publish2Subscribers republishing to existing subscribers that matches the topic {}", topic);
        if (Log.DEBUG) {
            Log.trace("content <{}>", DebugUtils.payload2Str(origMessage));
            Log.trace("subscription tree {}", subscriptions.dumpTree());
        }
        for (final Subscription sub : subscriptions.matches(topic)) {
            if(m_clientIDs.get(sub.getClientId()) == null) {
                subscriptions.removeSubscription(topic, sub.getClientId());
                continue;
            }
            if (qos.ordinal() > sub.getRequestedQos().ordinal()) {
                qos = sub.getRequestedQos();
            }

            ByteBuffer message = origMessage.duplicate();

            if (qos == AbstractMessage.QOSType.MOST_ONE && sub.isActive()) {
                //QoS 0
                sendPublish(sub.getClientId(), topic, qos, message, false);
            } else {
                //QoS 1 or 2
                //if the target subscription is not clean session and is not connected => store it
                if (!sub.isCleanSession() && !sub.isActive()) {
                    //clone the event with matching clientID
                    PublishEvent newPublishEvt = new PublishEvent(topic, qos, message, retain, sub.getClientId(), messageID);
                    m_storageService.storePublishForFuture(newPublishEvt);
                } else  {
                    //if QoS 2 then store it in temp memory
                    if (qos ==AbstractMessage.QOSType.EXACTLY_ONCE) {
                        String publishKey = String.format("%s%d", sub.getClientId(), messageID);
                        PublishEvent newPublishEvt = new PublishEvent(topic, qos, message, retain, sub.getClientId(), messageID);
                        m_storageService.addInFlight(newPublishEvt, publishKey);
                    }
                    //publish
                    if (sub.isActive()) {
                        sendPublish(sub.getClientId(), topic, qos, message, false);
                    }
                }
            }
        }
    }
645542
def copy(self):
        '''
        
        '''
        dup = super(Conditional, self).copy()
        condition = self._condition.copy()
        condition.invalidate(self)
        dup._condition = condition
        return dup
335137
def send(self, msg):
        
        with self._pub_lock:
            self.publish.send_string(msg)
        return self
1162298
def buildProtocol(self, addr):
        
        self.resetDelay()  # reset reconnection backoff state
        clargs = self.client_args.copy()

        # optionally configure antennas from self.antenna_dict, which looks
        # like {'10.0.0.1:5084': {'1': 'ant1', '2': 'ant2'}}
        hostport = '{}:{}'.format(addr.host, addr.port)
        logger.debug('Building protocol for %s', hostport)
        if hostport in self.antenna_dict:
            clargs['antennas'] = [
                int(x) for x in self.antenna_dict[hostport].keys()]
        elif addr.host in self.antenna_dict:
            clargs['antennas'] = [
                int(x) for x in self.antenna_dict[addr.host].keys()]
        logger.debug('Antennas in buildProtocol: %s', clargs.get('antennas'))

        logger.debug('%s start_inventory: %s', hostport,
                     clargs.get('start_inventory'))
        if self.start_first and not self.protocols:
            # this is the first protocol, so let's start it inventorying
            clargs['start_inventory'] = True
        proto = LLRPClient(factory=self, **clargs)

        # register state-change callbacks with new client
        for state, cbs in self._state_callbacks.items():
            for cb in cbs:
                proto.addStateCallback(state, cb)

        # register message callbacks with new client
        for msg_type, cbs in self._message_callbacks.items():
            for cb in cbs:
                proto.addMessageCallback(msg_type, cb)

        return proto
1226745
def restore_publish(self, config, components, recreate=False):
        
        if "all" in components:
            components = []

        try:
            self.load()
            publish = True
        except NoSuchPublish:
            publish = False

        new_publish_snapshots = []
        to_publish = []
        created_snapshots = []

        for saved_component in config.get('components', []):
            component_name = saved_component.get('component')

            if not component_name:
                raise Exception("Corrupted file")

            if components and component_name not in components:
                continue

            saved_packages = []
            if not saved_component.get('packages'):
                raise Exception("Component %s is empty" % component_name)

            for package in saved_component.get('packages'):
                package_ref = '{} {} {} {}'.format(package.get('arch'), package.get('package'), package.get('version'), package.get('ref'))
                saved_packages.append(package_ref)

            to_publish.append(component_name)

            timestamp = time.strftime("%Y%m%d%H%M%S")
            snapshot_name = '{}-{}-{}'.format("restored", timestamp, saved_component.get('snapshot'))
            lg.debug("Creating snapshot %s for component %s of packages: %s"
                     % (snapshot_name, component_name, saved_packages))

            try:
                self.client.do_post(
                    '/snapshots',
                    data={
                        'Name': snapshot_name,
                        'SourceSnapshots': [],
                        'Description': saved_component.get('description'),
                        'PackageRefs': saved_packages,
                    }
                )
                created_snapshots.append(snapshot_name)
            except AptlyException as e:
                if e.res.status_code == 404:
                    # delete all the previously created
                    # snapshots because the file is corrupted
                    self._remove_snapshots(created_snapshots)
                    raise Exception("Source snapshot or packages don't exist")
                else:
                    raise

            new_publish_snapshots.append({
                'Component': component_name,
                'Name': snapshot_name
            })

        if components:
            self.publish_snapshots = [x for x in self.publish_snapshots if x['Component'] not in components and x['Component'] not in to_publish]
            check_components = [x for x in new_publish_snapshots if x['Component'] in components]
            if len(check_components) != len(components):
                self._remove_snapshots(created_snapshots)
                raise Exception("Not possible to find all the components required in the backup file")

        self.publish_snapshots += new_publish_snapshots
        self.do_publish(recreate=recreate, merge_snapshots=False)
1211664
def CreateReply(self, **attributes):
        
        return CoAPacket(CoAACK, self.id,
            self.secret, self.authenticator, dict=self.dict,
            **attributes)
756464
def get_duplicated_model(class_inst, new_class_name):
    
    # Ref: http://www.cnblogs.com/Jerryshome/archive/2012/12/21/2827492.html
    # get caller stack frame
    # caller_frame = inspect.currentframe()
    caller_frame_record = inspect.stack()[1]

    # parse module name
    module = inspect.getmodule(caller_frame_record[0])
    return ModelDuplicator(module.__name__).get_duplicated_model(class_inst, new_class_name)
773490
def create(self, msgtype, *args, **kwargs):
        ''' 

        '''
        if msgtype not in self._messages:
            raise ProtocolError("Unknown message type %r for protocol version %s" % (msgtype, self._version))
        return self._messages[msgtype].create(*args, **kwargs)
888083
function (client, backlog, channel, message) {
    if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return;
    message = new mqtt_lib.Message(message);
    message.destinationName = channel;
    client.send(message);
}
143952
def fromimportupdate(cls, bundle, import_reg):
        # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
        
        exc = import_reg.get_exception()
        if exc:
            return RemoteServiceAdminEvent(
                RemoteServiceAdminEvent.IMPORT_ERROR,
                bundle,
                import_reg.get_import_container_id(),
                import_reg.get_remoteservice_id(),
                None,
                None,
                exc,
                import_reg.get_description(),
            )

        return RemoteServiceAdminEvent(
            RemoteServiceAdminEvent.IMPORT_UPDATE,
            bundle,
            import_reg.get_import_container_id(),
            import_reg.get_remoteservice_id(),
            import_reg.get_import_reference(),
            None,
            None,
            import_reg.get_description(),
        )
92446
def _republish_dropped_message(self, reason):
        
        self.logger.debug('Republishing due to ProcessingException')
        properties = dict(self._message.properties) or {}
        if 'headers' not in properties or not properties['headers']:
            properties['headers'] = {}
        properties['headers']['X-Dropped-By'] = self.name
        properties['headers']['X-Dropped-Reason'] = reason
        properties['headers']['X-Dropped-Timestamp'] = \
            datetime.datetime.utcnow().isoformat()
        properties['headers']['X-Original-Exchange'] = self._message.exchange

        self._message.channel.basic_publish(
            self._drop_exchange, self._message.routing_key, self._message.body,
            pika.BasicProperties(**properties))
54370
def clone(self, **kw):
        """"""
        names = 'project_name version py_version platform location precedence'
        for attr in names.split():
            kw.setdefault(attr, getattr(self, attr, None))
        kw.setdefault('metadata', self._provider)
        return self.__class__(**kw)
788812
def clone(self, opts):
        '''
        
        '''
        topt = self.opts.copy()
        topt.update(opts)
        return self.__class__(self.modl, self.name, self.info, topt)
586807
function BlockTxnPacket(response, witness) {
  if (!(this instanceof BlockTxnPacket))
    return new BlockTxnPacket(response, witness);

  Packet.call(this);

  this.response = response || new bip152.TXResponse();
  this.witness = witness || false;
}
1328403
def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
    '''
    '''
    pub = jps.Publisher(topic_name, host=host, pub_port=pub_port)
    time.sleep(0.1)
    if repeat_rate is None:
        pub.publish(json_msg)
    else:
        try:
            while True:
                pub.publish(json_msg)
                time.sleep(1.0 / repeat_rate)
        except KeyboardInterrupt:
            pass
1061073
function() {
    var dup = this._dup();
    dup = dup.transform(dup._modelTransform);
    dup._model = dup._priorModel;
    dup._priorModel = undefined;
    return dup;
  }