当前位置: 首页>>代码示例>>C++>>正文


C++ Message类代码示例

本文整理汇总了C++中Message的典型用法代码示例。如果您正苦于以下问题:C++ Message类的具体用法?C++ Message怎么用?C++ Message使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Message类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: file

void TracerManager::output(const string &fileName)
{
    // -------------------------------------------------------------------------
    // output polygon stuffs
    polygonManager.output(fileName);
#ifdef TTS_REMAP
    // -------------------------------------------------------------------------
    NcFile file(fileName.c_str(), NcFile::Write);
    if (!file.is_valid()) {
        Message message;
        message << "Failed to open tracer output file \"";
        message << fileName << "\" for appending meshed density field!";
        REPORT_ERROR(message.str());
    }
    // -------------------------------------------------------------------------
    // output tracer densities on the polygons
    NcDim *numPolygonDim = file.get_dim("num_total_polygon");
    double q0[polygonManager.polygons.size()];
    for (int l = 0; l < tracerNames.size(); ++l) {
        char varName[30];
        sprintf(varName, "q%d", l);
        NcVar *qVar = file.add_var(varName, ncDouble, numPolygonDim);
        Polygon *polygon = polygonManager.polygons.front();
        for (int i = 0; i < polygonManager.polygons.size(); ++i) {
            q0[i] = polygon->tracers[l].getDensity();
            polygon = polygon->next;
        }
        qVar->put(q0, polygonManager.polygons.size());
    }
    // -------------------------------------------------------------------------
    // output tracer densities on the mesh
    const RLLMesh &mesh = tracerDensities[0].getMesh();
    int numLon = mesh.getNumLon()-2;
    int numLat = mesh.getNumLat();
    double lon[numLon], lat[numLat];
    for (int i = 0; i < numLon; ++i)
        lon[i] = mesh.lon(i+1)*Rad2Deg;
    for (int j = 0; j < numLat; ++j)
        lat[j] = mesh.lat(j)*Rad2Deg;
    NcDim *lonDim = file.add_dim("lon", numLon);
    NcDim *latDim = file.add_dim("lat", numLat);
    NcVar *lonVar = file.add_var("lon", ncDouble, lonDim);
    lonVar->add_att("long_name", "longitude");
    lonVar->add_att("units", "degrees_east");
    lonVar->put(lon, numLon);
    NcVar *latVar = file.add_var("lat", ncDouble, latDim);
    latVar->add_att("long_name", "latitude");
    latVar->add_att("units", "degrees_north");
    latVar->put(lat, numLat);
    NcVar *areaVar = file.add_var("area_mesh", ncDouble, latDim, lonDim);
    areaVar->add_att("long_name", "area of fixed mesh cell");
    areaVar->add_att("units", "m2");
    double area[numLat][numLon];
    for (int i = 0; i < numLon; ++i)
        for (int j = 0; j < numLat; ++j)
            area[j][i] = tracerDensities[0].getMesh(Field::Bound).area(i, j);
    areaVar->put(&area[0][0], numLat, numLon);
    double q[numLat][numLon];
    for (int l = 0; l < tracerNames.size(); ++l) {
        char varName[30];
        sprintf(varName, "q%d_mesh", l);
        NcVar *qVar = file.add_var(varName, ncDouble, latDim, lonDim);
        qVar->add_att("long_name", tracerNames[l].c_str());
        for (int i = 0; i < numLon; ++i)
            for (int j = 0; j < numLat; ++j)
                q[j][i] = tracerDensities[l].values(i+1, j, 0).getNew();
        qVar->put(&q[0][0], numLat, numLon);
    }
    // -------------------------------------------------------------------------
    file.close();
#endif
    NOTICE("TracerManager", fileName+" is generated.");
}
开发者ID:dongli,项目名称:TTS-I,代码行数:73,代码来源:TracerManager.cpp

示例2: TestNcpFrameBuffer

// This function implements the NcpFrameBuffer tests
void TestNcpFrameBuffer(void)
{
    unsigned i, j;
    uint8_t buffer[kTestBufferSize];
    NcpFrameBuffer ncpBuffer(buffer, kTestBufferSize);

    Message *message;
    CallbackContext context;
    CallbackContext oldContext;
    uint8_t readBuffer[16];
    uint16_t readLen, readOffset;

    for (i = 0; i < sizeof(buffer); i++)
    {
        buffer[i] = 0;
    }

    context.mEmptyCount = 0;
    context.mNonEmptyCount = 0;

    // Set the callbacks.
    ncpBuffer.SetCallbacks(BufferDidGetEmptyCallback, BufferDidGetNonEmptyCallback, &context);

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 1: Write a frame 1 ");

    WriteTestFrame1(ncpBuffer);
    DumpBuffer("\nBuffer after frame1", buffer, kTestBufferSize);
    printf("\nFrameLen is %u", ncpBuffer.OutFrameGetLength());

    VerifyAndRemoveFrame1(ncpBuffer);

    printf("\nIterations: ");

    // Repeat this multiple times.
    for (j = 0; j < kTestIterationAttemps; j++)
    {
        printf("*");
        WriteTestFrame1(ncpBuffer);
        VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non-empty");

        VerifyAndRemoveFrame1(ncpBuffer);
        VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    }

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 2: Multiple frames write and read ");

    WriteTestFrame2(ncpBuffer);
    WriteTestFrame3(ncpBuffer);
    WriteTestFrame2(ncpBuffer);
    WriteTestFrame2(ncpBuffer);

    DumpBuffer("\nBuffer after multiple frames", buffer, kTestBufferSize);

    VerifyAndRemoveFrame2(ncpBuffer);
    VerifyAndRemoveFrame3(ncpBuffer);
    VerifyAndRemoveFrame2(ncpBuffer);
    VerifyAndRemoveFrame2(ncpBuffer);

    printf("\nIterations: ");

    // Repeat this multiple times.
    for (j = 0; j < kTestIterationAttemps; j++)
    {
        printf("*");

        WriteTestFrame2(ncpBuffer);
        WriteTestFrame3(ncpBuffer);
        WriteTestFrame2(ncpBuffer);

        VerifyAndRemoveFrame2(ncpBuffer);
        VerifyAndRemoveFrame3(ncpBuffer);

        WriteTestFrame2(ncpBuffer);
        WriteTestFrame3(ncpBuffer);

        VerifyAndRemoveFrame2(ncpBuffer);
        VerifyAndRemoveFrame2(ncpBuffer);
        VerifyAndRemoveFrame3(ncpBuffer);

        VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty.");
    }

    printf(" -- PASS\n");

    printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    printf("\nTest 3: Frame discard when buffer full and partial read restart");

    for (j = 0; j < kTestIterationAttemps; j++)
    {
        WriteTestFrame2(ncpBuffer);
        WriteTestFrame3(ncpBuffer);

        ncpBuffer.InFrameBegin();
        ncpBuffer.InFrameFeedData(sHelloText, sizeof(sHelloText));

//.........这里部分代码省略.........
开发者ID:nandojve,项目名称:openthread,代码行数:101,代码来源:test_ncp_buffer.cpp

示例3: SuccessOrExit

void Client::ProcessReceivedMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    Header responseHeader;
    Header requestHeader;
    RequestMetadata requestMetadata;
    Message *message = NULL;
    ThreadError error;

    SuccessOrExit(error = responseHeader.FromMessage(aMessage, false));
    aMessage.MoveOffset(responseHeader.GetLength());

    message = FindRelatedRequest(responseHeader, aMessageInfo, requestHeader, requestMetadata);

    if (message == NULL)
    {
        ExitNow();
    }

    switch (responseHeader.GetType())
    {
    case kCoapTypeReset:
        if (responseHeader.IsEmpty())
        {
            FinalizeCoapTransaction(*message, requestMetadata, NULL, NULL, NULL, kThreadError_Abort);
        }

        // Silently ignore non-empty reset messages (RFC 7252, p. 4.2).
        break;

    case kCoapTypeAcknowledgment:
        if (responseHeader.IsEmpty())
        {
            // Empty acknowledgment.
            if (requestMetadata.mConfirmable)
            {
                requestMetadata.mAcknowledged = true;
                requestMetadata.UpdateIn(*message);
            }

            // Remove the message if response is not expected, otherwise await response.
            if (requestMetadata.mResponseHandler == NULL)
            {
                DequeueMessage(*message);
            }
        }
        else if (responseHeader.IsResponse() && responseHeader.IsTokenEqual(requestHeader))
        {
            // Piggybacked response.
            FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, &aMessageInfo, kThreadError_None);
        }

        // Silently ignore acknowledgments carrying requests (RFC 7252, p. 4.2)
        // or with no token match (RFC 7252, p. 5.3.2)
        break;

    case kCoapTypeConfirmable:
    case kCoapTypeNonConfirmable:
        if (responseHeader.IsConfirmable())
        {
            // Send empty ACK if it is a CON message.
            SendEmptyAck(aMessageInfo.GetPeerAddr(), aMessageInfo.GetPeerPort(), responseHeader.GetMessageId());
        }

        FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, &aMessageInfo, kThreadError_None);

        break;
    }

exit:

    if (error == kThreadError_None && message == NULL)
    {
        if (responseHeader.IsConfirmable() || responseHeader.IsNonConfirmable())
        {
            // Successfully parsed a header but no matching request was found - reject the message by sending reset.
            SendReset(aMessageInfo.GetPeerAddr(), aMessageInfo.GetPeerPort(), responseHeader.GetMessageId());
        }
    }
}
开发者ID:HarryMorris,项目名称:openthread,代码行数:79,代码来源:coap_client.cpp

示例4: switch

void *SearchDialog::processEvent(Event *e)
{
    switch (e->type()){
    case EventClientsChanged:
    case EventClientChanged:
        fillClients();
        break;
    case EventCommandExec:{
            if (m_result != m_currentResult)
                return NULL;
            CommandDef *cmd = (CommandDef*)(e->param());
            if (cmd->menu_id == MenuSearchGroups){
                Group *grp = getContacts()->group(cmd->id - CmdContactGroup);
                if (grp){
                    Contact *contact = NULL;
                    if ((QWidget*)(cmd->param) == m_search->btnSearch){
                        if (m_current){
                            connect(this, SIGNAL(createContact(unsigned,Contact*&)), m_current, SLOT(createContact(unsigned,Contact*&)));
                            emit createContact(CONTACT_TEMP, contact);
                            disconnect(this, SIGNAL(createContact(unsigned,Contact*&)), m_current, SLOT(createContact(unsigned,Contact*&)));
                        }
                    }else{
                        contact = createContact(CONTACT_TEMP);
                    }
                    if (contact){
                        if ((contact->getFlags() & CONTACT_TEMP) == 0){
                            QString err = i18n("%1 already in contact list") .arg(contact->getName());
                            if ((QWidget*)(cmd->param) == m_search->btnAdd){
                                BalloonMsg::message(err, m_search->btnAdd);
                            }else if ((QWidget*)(cmd->param) == m_search->btnSearch){
                                BalloonMsg::message(err, m_search->btnSearch);
                            }else{
                                BalloonMsg::message(err, m_result);
                            }
                            return e->param();
                        }
                        contact->setFlags(contact->getFlags() & ~CONTACT_TEMP);
                        contact->setGroup(grp->id());
                        Event e(EventContactChanged, contact);
                        e.process();
                    }
                }
                return e->param();
            }
            if (cmd->id == CmdSearchInfo){
                Contact *contact = createContact(CONTACT_TEMP);
                if (contact == NULL)
                    return e->param();
                Command cmd;
                cmd->id		 = CmdInfo;
                cmd->menu_id = MenuContact;
                cmd->param   = (void*)(contact->id());
                CorePlugin::m_plugin->showInfo(cmd);
                return e->param();
            }
            if (cmd->id == CmdSearchMsg){
                Contact *contact = createContact(CONTACT_TEMP);
                if (contact == NULL)
                    return e->param();
                Message *m = new Message(MessageGeneric);
                m->setContact(contact->id());
                Event e(EventOpenMessage, &m);
                e.process();
                delete m;
            }
            break;
        }
开发者ID:,项目名称:,代码行数:67,代码来源:

示例5: configureCorrections

void DSPEngine::configureCorrections(bool dcOffsetCorrection, bool iqImbalanceCorrection)
{
	Message* cmd = DSPConfigureCorrection::create(dcOffsetCorrection, iqImbalanceCorrection);
	cmd->submit(&m_messageQueue);
}
开发者ID:zoutepopcorn,项目名称:rtl-sdrangelove,代码行数:5,代码来源:dspengine.cpp

示例6: newRunQuery

    /**
     * This is called by db/ops/query.cpp.  This is the entry point for answering a query.
     */
    string newRunQuery(Message& m, QueryMessage& q, CurOp& curop, Message &result) {
        // This is a read lock.
        Client::ReadContext ctx(q.ns, dbpath);

        // Parse, canonicalize, plan, transcribe, and get a runner.
        Runner* rawRunner;
        Status status = getRunner(q, &rawRunner);
        if (!status.isOK()) {
            uasserted(17007, "Couldn't process query " + q.query.toString()
                         + " why: " + status.reason());
        }
        verify(NULL != rawRunner);
        auto_ptr<Runner> runner(rawRunner);

        // We freak out later if this changes before we're done with the query.
        const ChunkVersion shardingVersionAtStart = shardingState.getVersion(q.ns);

        // We use this a lot below.
        const ParsedQuery& pq = runner->getQuery().getParsed();

        // TODO: Document why we do this.
        replVerifyReadsOk(&pq);

        // If this exists, the collection is sharded.
        // If it doesn't exist, we can assume we're not sharded.
        // If we're sharded, we might encounter data that is not consistent with our sharding state.
        // We must ignore this data.
        CollectionMetadataPtr collMetadata;
        if (!shardingState.needCollectionMetadata(pq.ns())) {
            collMetadata = CollectionMetadataPtr();
        }
        else {
            collMetadata = shardingState.getCollectionMetadata(pq.ns());
        }

        // Run the query.
        BufBuilder bb(32768);
        bb.skip(sizeof(QueryResult));

        // How many results have we obtained from the runner?
        int numResults = 0;

        // If we're replaying the oplog, we save the last time that we read.
        OpTime slaveReadTill;

        // Do we save the Runner in a ClientCursor for getMore calls later?
        bool saveClientCursor = false;

        BSONObj obj;
        // TODO: Differentiate EOF from error.
        while (runner->getNext(&obj)) {
            // If we're sharded make sure that we don't return any data that hasn't been migrated
            // off of our shared yet.
            if (collMetadata) {
                // This information can change if we yield and as such we must make sure to re-fetch
                // it if we yield.
                KeyPattern kp(collMetadata->getKeyPattern());
                // This performs excessive BSONObj creation but that's OK for now.
                if (!collMetadata->keyBelongsToMe(kp.extractSingleKey(obj))) { continue; }
            }

            // Add result to output buffer.
            bb.appendBuf((void*)obj.objdata(), obj.objsize());

            // Count the result.
            ++numResults;

            // Possibly note slave's position in the oplog.
            if (pq.hasOption(QueryOption_OplogReplay)) {
                BSONElement e = obj["ts"];
                if (Date == e.type() || Timestamp == e.type()) {
                    slaveReadTill = e._opTime();
                }
            }

            // TODO: only one type of 2d search doesn't support this.  We need a way to pull it out
            // of CanonicalQuery. :(
            const bool supportsGetMore = true;
            const bool isExplain = pq.isExplain();
            if (isExplain && pq.enoughForExplain(numResults)) {
                break;
            }
            else if (!supportsGetMore && (pq.enough(numResults)
                                          || bb.len() >= MaxBytesToReturnToClientAtOnce)) {
                break;
            }
            else if (pq.enoughForFirstBatch(numResults, bb.len())) {
                // If only one result requested assume it's a findOne() and don't save the cursor.
                if (pq.wantMore() && 1 != pq.getNumToReturn()) {
                    saveClientCursor = true;
                }
                break;
            }
        }

        // TODO: Stage creation can set tailable depending on what's in the parsed query.  We have
        // the full parsed query available during planning...set it there.
//.........这里部分代码省略.........
开发者ID:acruikshank,项目名称:mongo,代码行数:101,代码来源:new_find.cpp

示例7: logError

void BusHandler::receiveCompleted()
{
	unsigned char srcAddress = m_command[0], dstAddress = m_command[1];
	if (srcAddress == dstAddress) {
		logError(lf_bus, "invalid self-addressed message from %2.2x", srcAddress);
		return;
	}
	addSeenAddress(srcAddress);
	addSeenAddress(dstAddress);

	bool master = isMaster(dstAddress);
	if (dstAddress == BROADCAST) {
		logInfo(lf_update, "update BC cmd: %s", m_command.getDataStr().c_str());
		if (m_command.size()>=5+9 && m_command[2]==0x07 && m_command[3]==0x04) {
			unsigned char slaveAddress = (unsigned char)((srcAddress+5)&0xff);
			addSeenAddress(slaveAddress);
			Message* message = m_messages->getScanMessage(slaveAddress);
			if (message && (message->getLastUpdateTime()==0 || message->getLastSlaveData().size()<10)) {
				// e.g. 10fe07040a b5564149303001248901
				m_seenAddresses[slaveAddress] |= SCAN_INIT;
				SymbolString idData;
				istringstream input;
				result_t result = message->prepareMaster(m_ownMasterAddress, idData, input);
				if (result==RESULT_OK) {
					idData.clear();
					idData.push_back(9);
					for (size_t i = 5; i <= 5+9; i++) {
						idData.push_back(m_command[i]);
					}
					result = message->storeLastData(pt_slaveData, idData, 0);
				}
				if (result==RESULT_OK) {
					m_seenAddresses[slaveAddress] |= SCAN_DONE;
				}
				logNotice(lf_update, "store BC ident: %s", getResultCode(result));
			}
		}
	} else if (master) {
		logInfo(lf_update, "update MM cmd: %s", m_command.getDataStr().c_str());
	} else {
		logInfo(lf_update, "update MS cmd: %s / %s", m_command.getDataStr().c_str(), m_response.getDataStr().c_str());
	}
	Message* message = m_messages->find(m_command);
	if (m_grabMessages) {
		unsigned long long key;
		if (message) {
			key = message->getKey();
		} else {
			key = Message::createKey(m_command, 4); // up to 4 DD bytes
		}
		m_grabbedMessages[key].setLastData(m_command, m_response);
	}
	if (message == NULL) {
		if (dstAddress == BROADCAST) {
			logNotice(lf_update, "unknown BC cmd: %s", m_command.getDataStr().c_str());
		} else if (master) {
			logNotice(lf_update, "unknown MM cmd: %s", m_command.getDataStr().c_str());
		} else {
			logNotice(lf_update, "unknown MS cmd: %s / %s", m_command.getDataStr().c_str(), m_response.getDataStr().c_str());
		}
	} else {
		m_messages->invalidateCache(message);
		string circuit = message->getCircuit();
		string name = message->getName();
		result_t result = message->storeLastData(m_command, m_response);
		ostringstream output;
		if (result==RESULT_OK) {
			result = message->decodeLastData(output);
		}
		if (result < RESULT_OK) {
			logError(lf_update, "unable to parse %s %s from %s / %s: %s", circuit.c_str(), name.c_str(), m_command.getDataStr().c_str(), m_response.getDataStr().c_str(), getResultCode(result));
		} else {
			string data = output.str();
			if (m_answer && dstAddress == (master ? m_ownMasterAddress : m_ownSlaveAddress)) {
				logNotice(lf_update, "self-update %s %s QQ=%2.2x: %s", circuit.c_str(), name.c_str(), srcAddress, data.c_str()); // TODO store in database of internal variables
			} else if (message->getDstAddress() == SYN) { // any destination
				if (message->getSrcAddress() == SYN) { // any destination and any source
					logNotice(lf_update, "update %s %s QQ=%2.2x ZZ=%2.2x: %s", circuit.c_str(), name.c_str(), srcAddress, dstAddress, data.c_str());
				} else {
					logNotice(lf_update, "update %s %s ZZ=%2.2x: %s", circuit.c_str(), name.c_str(), dstAddress, data.c_str());
				}
			} else if (message->getSrcAddress() == SYN) { // any source
				logNotice(lf_update, "update %s %s QQ=%2.2x: %s", circuit.c_str(), name.c_str(), srcAddress, data.c_str());
			} else {
				logNotice(lf_update, "update %s %s: %s", circuit.c_str(), name.c_str(), data.c_str());
			}
		}
	}
}
开发者ID:john30,项目名称:ebusd,代码行数:89,代码来源:bushandler.cpp

示例8: QCOMPARE

void MessageTest::send()
{
  QCOMPARE(m_conn.messageCount(), 0);

  // Invalid message, no connection set
  Message invalidMessage;
  QCOMPARE(invalidMessage.send(), false);
  QCOMPARE(m_conn.messageCount(), 0);

  // Invalid message, no connection set
  invalidMessage.setConnection(&m_conn);
  QCOMPARE(invalidMessage.send(), false);
  QCOMPARE(m_conn.messageCount(), 0);

  // Valid message, no connection set
  Message request(Message::Request);
  request.setMethod("testMethod");
  QCOMPARE(request.send(), false);
  QCOMPARE(m_conn.messageCount(), 0);

  // Test id generation for requests
  request.setConnection(&m_conn);
  QVERIFY(request.id().isNull());
  QCOMPARE(request.send(), true);
  QVERIFY(!request.id().isNull());
  QCOMPARE(m_conn.messageCount(), 1);

  // Id should match the message received by the connection:
  Message connMessage = m_conn.popMessage();
  MoleQueue::MessageIdType requestId = request.id();
  QCOMPARE(requestId, connMessage.id());

  // Resending the request should assign a different id.
  QCOMPARE(request.send(), true);
  QVERIFY(!request.id().isNull());
  QCOMPARE(m_conn.messageCount(), 1);

  // The new id should not match the old one:
  connMessage = m_conn.popMessage();
  QVERIFY(requestId != connMessage.id());

  // Sending any other type of message should not modify the ids.
  MoleQueue::MessageIdType testId(QLatin1String("testId"));

  // Notifications
  // (no id testing -- ids are not used.)
  Message notification(Message::Notification, &m_conn);
  notification.setMethod("testMethod");
  QCOMPARE(notification.send(), true);
  QCOMPARE(m_conn.messageCount(), 1);
  m_conn.popMessage();

  // Response
  Message response(Message::Response, &m_conn);
  response.setId(testId);
  response.setMethod("testMethod");
  QCOMPARE(response.send(), true);
  QCOMPARE(m_conn.messageCount(), 1);
  QCOMPARE(m_conn.popMessage().id(), testId);

  // Error
  Message error(Message::Error, &m_conn);
  error.setId(testId);
  error.setErrorCode(2);
  error.setErrorMessage("Test error");
  QCOMPARE(error.send(), true);
  QCOMPARE(m_conn.messageCount(), 1);
  QCOMPARE(m_conn.popMessage().id(), testId);
}
开发者ID:OpenChemistry,项目名称:molequeue,代码行数:69,代码来源:messagetest.cpp

示例9: if

void
SelectionTable::Receive
	(
	JBroadcaster* 	sender, 
	const Message& 	message
	)
{
	// Here we check to see what messages we have received.

	// We first check if the sender is our data array
	if (sender == itsData)
		{
		// Our data array sent us a message

		// Was data inserted?
		if (message.Is(JOrderedSetT::kElementsInserted))
			{
			// cast the message to an ElementsInserted object
			const JOrderedSetT::ElementsInserted* info = 
				dynamic_cast<const JOrderedSetT::ElementsInserted*>(&message);
			assert(info != NULL);

			// For each element inserted, we insert a row
			InsertRows(info->GetFirstIndex(), info->GetCount(), kDefRowHeight);
			}

		// Was data removed?
		else if (message.Is(JOrderedSetT::kElementsRemoved))
			{
			// cast the message to an ElementsRemoved object
			const JOrderedSetT::ElementsRemoved* info = 
				dynamic_cast<const JOrderedSetT::ElementsRemoved*>(&message);
			assert(info != NULL);

			// Remove corresponding table rows.
			for (JSize i = info->GetLastIndex(); i >= info->GetFirstIndex() ; i--)
				{
				RemoveNextRows(info->GetFirstIndex(), info->GetCount());
				}
			}

		// Was an element changed?
		else if (message.Is(JOrderedSetT::kElementChanged))
			{
			// cast the message to an ElementsRemoved object
			const JOrderedSetT::ElementChanged* info = 
				dynamic_cast<const JOrderedSetT::ElementChanged*>(&message);
			assert(info != NULL);

			// The element changed, so redraw it.
			// (This would not be necessary if we were using a
			//  class derived from JTableData.)
			TableRefreshRow(info->GetFirstIndex());
			}
		}

	// Did the Table menu send a message?
	else if (sender == itsTableMenu)
		{
		// Does the menu need an update?
		if (message.Is(JXMenu::kNeedsUpdate))
			{
			UpdateTableMenu();
			}

		// Has a menu item been selected?
		else if (message.Is(JXMenu::kItemSelected))
			{
			// cast the message to an ItemSelecte object.
			// This will tell us which item was selected.
			const JXMenu::ItemSelected* info = 
				dynamic_cast<const JXMenu::ItemSelected*>(&message);
			assert(info != NULL);

			// Pass the selected menu item to our menu handler function.
			HandleTableMenu(info->GetIndex());
			}
		}

	// pass the message to our base class
	else
		{
		JXTable::Receive(sender, message);
		}
}
开发者ID:raorn,项目名称:jx_application_framework,代码行数:85,代码来源:SelectionTable.cpp

示例10: QLatin1String

void MessageTest::toJson()
{
  // Misc objects used in testing:
  QJsonObject testObject;
  testObject.insert("test", QLatin1String("value"));

  QJsonArray testArray;
  testArray.append(QString("Test"));

  QJsonArray testCompositeArray;
  testCompositeArray.append(MoleQueue::idTypeToJson(MoleQueue::InvalidId));
  testCompositeArray.append(testObject);
  testCompositeArray.append(testArray);
  testCompositeArray.append(true);
  testCompositeArray.append(5);
  testCompositeArray.append(5.36893473232); // This will be truncated to %.5f!
  testCompositeArray.append(QString("Abrakadabra"));

  // Test that the idtypeutils is working as expected.
  QVERIFY(testCompositeArray.first().isNull());
  QCOMPARE(MoleQueue::toIdType(testCompositeArray.first()),
           MoleQueue::InvalidId);

  // Invalid message
  Message invalid;
  QCOMPARE(QString(invalid.toJson()),
           QString(ReferenceString("message-ref/invalidJson.json")));

  // Request -- no params
  Message request(Message::Request);
  request.setMethod("testMethod");
  request.setId(MoleQueue::MessageIdType(1));
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-noParams.json")));

  // Request -- object params
  request.setParams(testObject);
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-objectParams.json")));

  // Request -- array params
  request.setParams(testArray);
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-arrayParams.json")));

  // Notification -- no params
  Message notification(Message::Notification);
  notification.setMethod("poke");
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-noParams.json")));

  // Notification -- object params
  notification.setParams(testObject);
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-objectParams.json")));

  // Notification -- array params
  notification.setParams(testArray);
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-arrayParams.json")));

  // Response
  Message response(Message::Response);
  response.setId(MoleQueue::MessageIdType(42));
  response.setMethod("Won't be in JSON string for response.");
  response.setResult(testCompositeArray);
  QCOMPARE(QString(response.toJson()),
           QString(ReferenceString("message-ref/responseJson.json")));

  // Error -- no data
  Message error(Message::Error);
  error.setId(MoleQueue::MessageIdType(13));
  error.setMethod("Won't be in JSON string for error.");
  error.setErrorCode(666);
  error.setErrorMessage("Server is possessed.");
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-noData.json")));

  // Error -- primitive data
  error.setErrorData(55);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-primData.json")));

  // Error -- object data
  error.setErrorData(testObject);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-objectData.json")));

  // Error -- array data
  error.setErrorData(testArray);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-arrayData.json")));
}
开发者ID:OpenChemistry,项目名称:molequeue,代码行数:93,代码来源:messagetest.cpp

示例11: answer_to_changeroot

void Node::answer_to_changeroot(Message& msg)
{
    int sender_index = msg.get_sender_ID();
    fp.write("Recv: Changeroot from host" + to<>(sender_index) + " on (" + to<>(sender_index) + "-" + to<>(index));
    changeroot();
}
开发者ID:Lenti05,项目名称:Simple_GHS,代码行数:6,代码来源:Node.cpp

示例12: sendPublish

quint16 ClientPrivate::sendPublish(Message &msg)
{
    quint8 header = PUBLISH;
    header = SETRETAIN(header, msg.retain() ? 1 : 0);
    header = SETQOS(header, msg.qos());
    header = SETDUP(header, msg.dup() ? 1 : 0);
    Frame frame(header);
    frame.writeString(msg.topic());
    if(msg.qos() > MQTT_QOS0) {
        if(msg.id() == 0) {
            msg.setId(gmid++);
        }
        frame.writeInt(msg.id());
    }
    if(!msg.payload().isEmpty()) {
        frame.writeRawData(msg.payload());
    }
    network->sendFrame(frame);
    return msg.id();
}
开发者ID:ehntoo,项目名称:qmqtt,代码行数:20,代码来源:qmqtt_client_p.cpp

示例13: ncError

void TracerManager::registerTracer(const string &fileName,
                                   const MeshManager &meshManager)
{
    // -------------------------------------------------------------------------
    // parse and read file
    NcError ncError(NcError::silent_nonfatal);

    NcFile file(fileName.c_str(), NcFile::ReadOnly);
    if (!file.is_valid()) {
        Message message;
        message << "Failed to open tracer file \"" << fileName << "\"!";
        REPORT_ERROR(message.str());
    }

    if (file.get_att("name") == NULL) {
        Message message;
        message << "There is no \"name\" attribute in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    tracerNames.push_back(file.get_att("name")->as_string(0));

    if (file.get_att("name") == NULL) {
        Message message;
        message << "There is no \"name\" attribute in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    tracerNames.push_back(file.get_att("name")->as_string(0));

    int numPolygon = static_cast<int>(file.get_dim("num_total_polygon")->size());
    if (numPolygon != polygonManager.polygons.size()) {
        Message message;
        message << "Polygon numbers (" << numPolygon << " != ";
        message << polygonManager.polygons.size();
        message << ") are not consistent in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    double mass[numPolygon];
    if (file.get_var("mass") == NULL) {
        Message message;
        message << "There is no \"mass\" variable in tracer file \"";
        message << fileName << "\"!";
        REPORT_ERROR(message.str());
    }
    file.get_var("mass")->get(mass);
    // -------------------------------------------------------------------------
    // initialize tracer density on the mesh
    tracerDensities.push_back(Field());
    if (meshManager.hasLayers())
        tracerDensities.back().init(meshManager.getMesh(PointCounter::Center),
                                    meshManager.getMesh(PointCounter::Bound),
                                    meshManager.getLayers(Layers::Full));
    else
        tracerDensities.back().init(meshManager.getMesh(PointCounter::Center),
                                    meshManager.getMesh(PointCounter::Bound));
    // -------------------------------------------------------------------------
    // set up tracer variables in polygons
    int tracerId = static_cast<int>(tracerNames.size()-1);
    Polygon *polygon = polygonManager.polygons.front();
    for (int i = 0; i < polygonManager.polygons.size(); ++i) {
        polygon->tracers.push_back(Tracer());
        polygon->tracers[tracerId].setMass(mass[i]);
        polygon = polygon->next;
    }
}
开发者ID:dongli,项目名称:TTS-I,代码行数:67,代码来源:TracerManager.cpp

示例14: theVect

int
ActorSubdomain::run(void)
{
    static Vector theVect(4);
	static Vector theVect1(1);
    bool exitYet = false;
    int res = 0;

    while (exitYet == false) {
      int action;
      res = this->recvID(msgData);
      if (res != 0) {
	opserr << "ActorSubdomain::run - error receiving msgData\n";
	exitYet = true;
        action = ShadowActorSubdomain_DIE;
      } else {
	action = msgData(0);
      }

      bool change;
      int theType, theOtherType, tag, dbTag, loadPatternTag;
      int startTag, endTag, axisDirn, numSP, i, numMode, dof;
      Element *theEle;
      Node *theNod;
      SP_Constraint *theSP;
      MP_Constraint *theMP;
      LoadPattern *theLoadPattern;
      NodalLoad *theNodalLoad;
      ElementalLoad *theElementalLoad;
      DomainDecompositionAnalysis *theDDAnalysis;
      const Matrix *theMatrix;
      const Vector *theVector;
      Matrix *theM;
      Vector *theV;
      ID     *theI, *theNodeTags, *theEleTags;
      PartitionedModelBuilder *theBuilder;
      IncrementalIntegrator *theIntegrator;
      EquiSolnAlgo *theAlgorithm;
      LinearSOE *theSOE;
      EigenSOE *theEigenSOE;
      ConvergenceTest *theTest;
      Recorder *theRecorder;
      bool res, generalized, findSmallest;
      double doubleRes;
      int intRes;
      NodeResponseType nodeResponseType;
      Parameter *theParameter;
      int argc;
      char **argv;
      char *allResponseArgs;
      char *currentLoc;
      int argLength, msgLength;
      Message theMessage;

      const ID *theID;
      
      //     opserr << "ActorSubdomain ACTION: " << action << endln;

      switch (action) {
	  case ShadowActorSubdomain_setTag:
	    tag = msgData(1); // subdomain tag
	    this->setTag(tag);
	    this->Actor::setCommitTag(tag);
	    break;

	  case ShadowActorSubdomain_analysisStep:
	    this->recvVector(theVect);
	    this->analysisStep(theVect(0));
	    break;

	  case ShadowActorSubdomain_eigenAnalysis:
	    numMode = msgData(1);
	    if (msgData(2) == 0)
	      generalized = true;
	    else
	      generalized = false;
	    if (msgData(3) == 0)
	      findSmallest = true;
	    else
	      findSmallest = false;
		
	    this->eigenAnalysis(numMode, generalized, findSmallest);
	    break;
	    /*
	  case ShadowActorSubdomain_buildSubdomain:
	    theType = msgData(1);
	    tag = msgData(3); // subdomain tag
	    this->setTag(tag);
	    tag = msgData(2); // numSubdomains
	    theBuilder = theBroker->getPtrNewPartitionedModelBuilder(*this, 
								     theType);
	    this->recvObject(*theBuilder);
	    this->buildSubdomain(tag, *theBuilder);

	    break;
	    */
	case ShadowActorSubdomain_getRemoteData:
	    theID = &(this->getExternalNodes());
	    msgData(0) = theID->Size();
	    msgData(1) = this->getNumDOF();
//.........这里部分代码省略.........
开发者ID:DBorello,项目名称:OpenSees,代码行数:101,代码来源:ActorSubdomain.cpp

示例15: Q_UNUSED

void Firewall::filterIncomingMessage(Chat chat, Contact sender, QString &message, time_t time, bool &ignore)
{
    Q_UNUSED(time)

    Account account = chat.chatAccount();

    Protocol *protocol = account.protocolHandler();
    if (!protocol)
        return;

// emotikony s± sprawdzane nawet przy ³±czeniu
    const int min_interval_notify = 2000;

    if (CheckFloodingEmoticons)
    {
        if ((!EmoticonsAllowKnown || sender.ownerBuddy().isAnonymous()) && checkEmoticons(message))
        {
            ignore = true;
            if (LastNotify.elapsed() > min_interval_notify)
            {
                FirewallNotification::notify(chat, sender, tr("flooding DoS attack with emoticons!"));

                writeLog(sender, message);

                LastNotify.restart();
            }
            kdebugf2();
            return;
        }
    }

// atak floodem
    if (checkFlood())
    {
        ignore = true;
        if (LastNotify.elapsed() > min_interval_notify)
        {
            FirewallNotification::notify(chat, sender, tr("flooding DoS attack!"));

            writeLog(sender, message);

            LastNotify.restart();
        }
        kdebugf2();
        return;
    }

// ochrona przed anonimami
    if (checkChat(chat, sender, message, ignore))
        ignore = true;

// ochrona przed konferencjami
    if (checkConference(chat))
        ignore = true;

// wiadomosc zatrzymana. zapisz do loga i wyswietl dymek
    if (ignore)
    {
        if (message.length() > 50)
            FirewallNotification::notify(chat, sender, message.left(50).append("..."));
        else
            FirewallNotification::notify(chat, sender, message);

        writeLog(sender, message);

        if (WriteInHistory)
        {
            if (History::instance()->currentStorage())
            {
                Message msg = Message::create();
                msg.setContent(message);
                msg.setType(Message::TypeReceived);
                msg.setReceiveDate(QDateTime::currentDateTime());
                msg.setSendDate(QDateTime::fromTime_t(time));
                History::instance()->currentStorage()->appendMessage(msg);
            }
        }
    }

    kdebugf2();
}
开发者ID:partition,项目名称:kadu,代码行数:81,代码来源:firewall.cpp


注:本文中的Message类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。