コード例 #1
0
void TestDatatype::TestTaskTime()
{
    TaskTime data1;
    QVERIFY(data1.isNull());

    TaskTime data2(-10, 10);
    QVERIFY(data2.isNull());

    TaskTime data3(10, -10);
    QVERIFY(data3.isNull());

    TaskTime data4(10, 22);
    QVERIFY(!data4.isNull());
    QVERIFY(data4.start() == 10);
    QVERIFY(data4.end() == 22);
    QVERIFY(data4.total() == 12);

    TaskTime data5(22, 10);
    QVERIFY(!data5.isNull());
    QVERIFY(data5.start() == 10);
    QVERIFY(data5.end() == 22);
    QVERIFY(data5.total() == 12);

    TaskTime data6(10, 22);
    QVERIFY(!(data3 == data4));
    QVERIFY(data1 == data2);
    QVERIFY(data5 == data6);
    QVERIFY(data3 != data4);
    QVERIFY(!(data1 != data2));
    QVERIFY(!(data5 != data6));
}
コード例 #2
0
void SimpleParagraphWidget::fillListButtons()
{
    KoZoomHandler zoomHandler;
    zoomHandler.setZoom(1.2);
    zoomHandler.setDpi(72, 72);

    KoInlineTextObjectManager itom;
    KoTextRangeManager tlm;
    TextShape textShape(&itom, &tlm);
    textShape.setSize(QSizeF(300, 100));
    QTextCursor cursor (textShape.textShapeData()->document());
    foreach(const Lists::ListStyleItem &item, Lists::genericListStyleItems()) {
        QPixmap pm(48,48);

        pm.fill(Qt::transparent);
        QPainter p(&pm);

        p.translate(0, -1.5);
        p.setRenderHint(QPainter::Antialiasing);
        if(item.style != KoListStyle::None) {
            KoListStyle listStyle;
            KoListLevelProperties llp = listStyle.levelProperties(1);
            llp.setStyle(item.style);
            if (KoListStyle::isNumberingStyle(item.style)) {
                llp.setStartValue(1);
                llp.setListItemSuffix(".");
            }
            listStyle.setLevelProperties(llp);
            cursor.select(QTextCursor::Document);
            QTextCharFormat textCharFormat=cursor.blockCharFormat();
            textCharFormat.setFontPointSize(11);
            textCharFormat.setFontWeight(QFont::Normal);
            cursor.setCharFormat(textCharFormat);

            QTextBlock cursorBlock = cursor.block();
            KoTextBlockData data(cursorBlock);
            cursor.insertText("----");
            listStyle.applyStyle(cursor.block(),1);
            cursorBlock = cursor.block();
            KoTextBlockData data1(cursorBlock);
            cursor.insertText("\n----");
            cursorBlock = cursor.block();
            KoTextBlockData data2(cursorBlock);
            cursor.insertText("\n----");
            cursorBlock = cursor.block();
            KoTextBlockData data3(cursorBlock);

            KoTextDocumentLayout *lay = dynamic_cast<KoTextDocumentLayout*>(textShape.textShapeData()->document()->documentLayout());
            if(lay)
                lay->layout();

            KoShapePaintingContext paintContext; //FIXME
            textShape.paintComponent(p, zoomHandler, paintContext);
            widget.bulletListButton->addItem(pm, static_cast<int> (item.style));
        }
    }
コード例 #3
0
ファイル: ex_11.cpp プロジェクト: Leelddd/CppPrimer_5th
int main(){
	Sales_data data1;
	Sales_data data2("cpp primer5th");
	Sales_data data3("cpp primer5th", 5, 80);
	Sales_data data4(cin);
	cout << data4.isbn();
	getchar();
	getchar();
	getchar();
}
コード例 #4
0
ファイル: testattal.cpp プロジェクト: q4a/attal
void TestAttal::testGameData()
{
    GameData * data = new GameData();
    GenericBase * base = data->getNewBase( 1 );
    base->setId( 1 );
    GameData * data2 = new GameData(*data);
    GenericBase * base2 = data2->getBaseById( 1 );
    QCOMPARE( base, base2 );
    GameData data3(*data);
    GenericBase * base3 = data3.getBaseById( 1 );
    QCOMPARE( base, base3 );
}
コード例 #5
0
int __cdecl wmain()
{
    // Ignoring the return value because we want to continue running even in the
    // unlikely event that HeapSetInformation fails.
    HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

    if (SUCCEEDED(CoInitialize(NULL)))
    {
		PlotData data1(200);
		for(size_t i = 0; i < 200; ++i)
		{
			data1[i * 2] = i / 200.0f;
			data1[i * 2 + 1] = pow(i, 1.6f) / 8.0f;
		}

		PlotData data2(200);
		for(size_t i = 0; i < 200; ++i)
		{
			data2[i * 2] = i / 200.0f;
			data2[i * 2 + 1] = i;
			//data2[100 + i * 2] = 1;
			//data2[101 + i * 2] = 1;
		}

		PlotData data3(200);
		for(size_t i = 0; i < 200; ++i)
		{
			data3[i * 2] = i / 200.0f;
			data3[i * 2 + 1] = i * 2;
		}

		PlotData data4(200);
		for(size_t i = 0; i < 200; ++i)
		{
			data4[i * 2 ] = i / 200.0f; 
			data4[i * 2 + 1] = 0.125f * pow(i, 1.3f);
		}

		PlotData *data[] = { &data1, &data2, &data3, &data4, 0 };
        HRESULT hr = SaveToImageFile(data, 800, 600, 1.0f, 600.0f, 50.0f, 40.0f, 0.1f, 100.0f);
        if (FAILED(hr))
        {
            wprintf(L"Unexpected error: 0x%x", hr);
        }

        CoUninitialize();
    }

    return 0;
}
コード例 #6
0
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   UTimeDate data1(31,12,99), data2("31/12/99");

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )
   U_ASSERT( UTimeDate("31/12/1900").getJulian() == 2415385 )
   U_ASSERT( UTimeDate("01/01/1970").getJulian() == 2440588 )

   U_ASSERT( data1 == data2 )
   U_ASSERT( data1.getDayOfWeek() == 5 )           // Venerdi
   U_ASSERT( data2.getDayOfYear() == 365 )

   U_ASSERT( UTimeDate("1/3/00").getDayOfWeek() == 3 ) // Mercoledi
   U_ASSERT( UTimeDate(31,12,00).getDayOfYear() == 366 )

   UTimeDate data3(60,2000);
   UTimeDate data4("29/02/00");

   U_ASSERT( data3 == data4 )
   U_ASSERT( data3.getDayOfYear() == 60 )

   UTimeDate data5(60,1901);
   UTimeDate data6("1/3/1901");

   U_ASSERT( data5 == data6 )

   U_ASSERT( UTimeDate(17, 5, 2002).isValid() == true )  // TRUE   May 17th 2002 is valid
   U_ASSERT( UTimeDate(30, 2, 2002).isValid() == false ) // FALSE  Feb 30th does not exist
   U_ASSERT( UTimeDate(29, 2, 2004).isValid() == true )  // TRUE   2004 is a leap year

   UTimeDate data7(29, 2, 2004);

   UString x = data7.strftime("%Y-%m-%d");

   U_ASSERT( x == U_STRING_FROM_CONSTANT("2004-02-29") )

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )

   cout << "Date: " << data6.strftime("%d/%m/%y") << '\n';

   while (cin >> data6) cout << data6 << '\n';

   U_ASSERT( UTimeDate::getSecondFromTime("19030314104248Z", true, "%4u%2u%2u%2u%2u%2uZ") < u_now->tv_sec )
}
コード例 #7
0
void ComponentEventTest::testConvertValue()
{
  std::map<std::string, std::string> attributes;
  attributes["id"] = "1";
  attributes["name"] = "DataItemTest1";
  attributes["type"] = "ACCELERATION";
  attributes["category"] = "SAMPLE";

  std::string time("NOW"), value("2.0");
  
  attributes["nativeUnits"] = "REVOLUTION/MINUTE";
  DataItem data1 (attributes);
  ComponentEvent event1(data1, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f, event1.getFValue());
  CPPUNIT_ASSERT(event1.getSValue().empty());
  
  attributes["nativeUnits"] = "REVOLUTION/SECOND";
  DataItem data2 (attributes);
  ComponentEvent event2 (data2, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 60.0f, event2.getFValue());
  CPPUNIT_ASSERT(event2.getSValue().empty());
  
  attributes["nativeUnits"] = "GRAM/INCH";
  DataItem data3 (attributes);
  ComponentEvent event3 (data3, 123, time, value);
  CPPUNIT_ASSERT_EQUAL((2.0f / 1000.0f) / 25.4f, event3.getFValue());
  CPPUNIT_ASSERT(event3.getSValue().empty());
  
  attributes["nativeUnits"] = "MILLIMETER/MINUTE^3";
  DataItem data4 (attributes);
  ComponentEvent event4 (data4, 123, time, value);
  CPPUNIT_ASSERT_EQUAL((2.0f) / (60.0f * 60.0f * 60.0f), event4.getFValue());
  CPPUNIT_ASSERT(event4.getSValue().empty());
  
  attributes["nativeUnits"] = "MILLIMETER/MINUTE^3";
  attributes["nativeScale"] = "0.5";
  DataItem data5 (attributes);
  ComponentEvent event5 (data5, 123, time, value);
  CPPUNIT_ASSERT_EQUAL((2.0f) / (60.0f * 60.0f * 60.0f * 0.5f),
    event5.getFValue());
  CPPUNIT_ASSERT(event5.getSValue().empty());
}
コード例 #8
0
ファイル: wcldintr.cpp プロジェクト: ABratovic/open-watcom-v2
void test1 ( void ) {
    WCIsvDList<int_ddata>   list;
    int_ddata               data1(1);
    int_ddata               data2(2);
    int_ddata               data3(3);
    int_ddata               data4(4);
    int_ddata               data5(5);

    list.exceptions( WCExcept::check_all );
    list.append( &data2 );
    list.append( &data3 );
    list.append( &data4 );

    list.insert( &data1 );
    list.append( &data5 );
    cout << "<intrusive double list for int_ddata>\n";
    list.forAll( data_isv_prt, "" );
    data_isv_prt( list.find( 3 ), "<the fourth element>" );
    data_isv_prt( list.get( 2 ), "<the third element>" );
    data_isv_prt( list.get(), "<the first element>" );
    list.clear();
    cout.flush();
}
コード例 #9
0
ファイル: Id2DataMapTest.cpp プロジェクト: uboot/stromx
 void Id2DataMapTest::testObserver()
 {
     DataContainer data1(new UInt8());
     m_inputMap->set(1, data1);
     
     CPPUNIT_ASSERT_EQUAL((unsigned int)(1), m_observer->lastId());
     CPPUNIT_ASSERT_EQUAL(DataContainer(), m_observer->lastOldData());
     CPPUNIT_ASSERT_EQUAL(data1, m_observer->lastNewData());
     
     DataContainer data2(new UInt8());
     m_inputMap->set(0, data2);
     
     CPPUNIT_ASSERT_EQUAL((unsigned int)(0), m_observer->lastId());
     CPPUNIT_ASSERT_EQUAL(DataContainer(), m_observer->lastOldData());
     CPPUNIT_ASSERT_EQUAL(data2, m_observer->lastNewData());
     
     DataContainer data3(new UInt8());
     m_inputMap->set(0, data3);
     
     CPPUNIT_ASSERT_EQUAL((unsigned int)(0), m_observer->lastId());
     CPPUNIT_ASSERT_EQUAL(data2, m_observer->lastOldData());
     CPPUNIT_ASSERT_EQUAL(data3, m_observer->lastNewData());
 }
コード例 #10
0
TVerdict CTcpClientTestUPnP13::RunTestL()
	{
	switch ( iState )
		{
		case ECreateTestServer:
			{
			iLogger.WriteFormat(_L("<i>Creating TestServer..... </i>"));
			
			iTestServer = CTestTcpServer::NewL ( *this );
			
			iState  = ECreateTestClient;
			iStatus = KRequestPending;			
			Reschedule();
			return EPass;
			}
		
		case ECreateTestClient:
			{
			iLogger.WriteFormat(_L("<i>TestServer is created..... </i>"));			
			iLogger.WriteFormat(_L("<i>Creating TestClient..... </i>"));
			
			THttpClientFlowQuery flowQuery ( TAppProtAddr ( KInetAddrLoop, KHttpDefaultPort ), Id (), EHttpClientFlow, THttpClientFlowQuery::ECreateNew, iChunkManager );
			const TUid requestedUid = { CUPnPFlowFactory::iUid };
			
			TNodeId factoryContainer = SockManGlobals::Get( )->GetPlaneFC( TCFPlayerRole ( TCFPlayerRole::EDataPlane ) );
			
			RClientInterface::OpenPostMessageClose ( NodeId (), TNodeCtxId ( KActivityNull, factoryContainer ), TCFFactory::TFindOrCreatePeer ( TCFPlayerRole::EDataPlane, requestedUid, &flowQuery ).CRef () );
			
			iState  = ESendRequestData;
			iStatus = KRequestPending;
			Reschedule();
			return EPass;
			}
		
		case ESendRequestData:
			{
			iLogger.WriteFormat(_L("<i>Client is Created</i>"));
			iLogger.WriteFormat(_L("<i>Send data..... </i>"));
			
			TPtrC8 data(KData1);
			TPtrC8 data2(KData2);
			TPtrC8 data3(KData3);
			
			iSSP->SetOption(KCHOptionLevel, KCHAbsoluteUri, _L8 ("http://127.0.0.1"));
			
			TCHMessageOption option ( 1, data.Length()+data2.Length()+data3.Length() );
			
			TPckg < TCHMessageOption > optionBuf ( option );
			
			iSSP->SetOption(KCHOptionLevel, KCHMaxLength, optionBuf);
			
			RMBufChain bodyBuf;
			bodyBuf.CreateL(KData1);
			iSSPData->Write(bodyBuf, 0, NULL);
			
			/*
			
			TCHMessageOption option2 ( 1, data2.Length() );
			TPckg < TCHMessageOption > optionBuf2 ( option2 );
			
			iSSP->SetOption(KCHOptionLevel, KCHMaxLength, optionBuf2);
			*/
			
			RMBufChain bodyBuf1;
			bodyBuf1.CreateL(KData2);
			iSSPData->Write(bodyBuf1, 0, NULL);

			/*
			
			TCHMessageOption option3 ( 1, data3.Length() );
			TPckg < TCHMessageOption > optionBuf3 ( option3 );
			
			iSSP->SetOption(KCHOptionLevel, KCHMaxLength, optionBuf3);
			*/
			
			RMBufChain bodyBuf2;
			bodyBuf2.CreateL(KData3);
			iSSPData->Write(bodyBuf2, 0, NULL);

			iState = ECleanup;
			iStatus = KRequestPending;
			Reschedule ();
			return EPass;
			}

		case ECleanup:
			{
			delete iTestServer;
			
			// cleanup tcp client flow
			delete reinterpret_cast<CHttpClientFlow*> ( iClientId.Ptr () );
			iTimer.After ( iStatus, 60000000 ); //10 secs
			iState = EComplete;
			iStatus = KRequestPending;
			Reschedule ();
			return EPass;
			}
		case EComplete:
			{
			iLogger.WriteFormat(_L("<i>TestCase: Complete..... </i>"));
			return EPass;
			}
			
		default:
			iLogger.WriteFormat(_L("<i> Failed: TestCase:..... </i>"));
			ASSERT(0);
			return EFail;
		}
	}
コード例 #11
0
ファイル: dl_jww.cpp プロジェクト: LibreCAD/LibreCAD
void DL_Jww::CreateMoji(DL_CreationInterface* creationInterface, CDataMoji& DMoji)
{
	string lName = HEX[DMoji.m_nGLayer > ArraySize(HEX)-1 ? ArraySize(HEX)-1: DMoji.m_nGLayer] + "-" +
													HEX[DMoji.m_nLayer > ArraySize(HEX)-1 ? ArraySize(HEX)-1: DMoji.m_nLayer];

	// add layer
	creationInterface->addLayer(DL_LayerData(lName,0));

	int width;
	if(DMoji.m_nPenWidth > 26)
		width = 0;
	else
		width = DMoji.m_nPenWidth;
	int color = colTable[DMoji.m_nPenColor > ArraySize(colTable)-1 ? ArraySize(colTable)-1 : DMoji.m_nPenColor];
	attrib = DL_Attributes(values[8],	  // layer
			       color,	      // color
			       width,	      // width
			       lTable[DMoji.m_nPenStyle > ArraySize(lTable)-1 ? ArraySize(lTable)-1 : DMoji.m_nPenStyle]);	  // linetype
	creationInterface->setAttributes(attrib);

	creationInterface->setExtrusion(0.0, 0.0, 1.0, 0.0 );

	DL_TextData d(
		// insertion point
		DMoji.m_start.x, DMoji.m_start.y, 0.0,
		// alignment point
		0.0, 0.0, 0.0,
		// height
		DMoji.m_dSizeY,
		// x scale
		1.0,
		// generation flags
		0,
		// h just
		0,
		// v just
		0,
		// text
		DMoji.m_string,
		// style
		string("japanese"),
		// angle
		DMoji.m_degKakudo / 180.0 * M_PI);

	creationInterface->addText(d);
#ifdef FINISHED
	QTextCodec* codec = QTextCodec::codecForName("SJIS");
	RS_TextData data3(RS_Vector(0.0, 0.0),
				10,//double height,
				10,//double width,
				RS2::VAlignMiddle,
				RS2::HAlignCenter,
				RS2::LeftToRight,
				RS2::AtLeast,
				1.0,//double lineSpacingFactor,
				RS_String(""),//const RS_String& text,
				RS_String(""),
				0.0,//double angle,
				RS2::Update);
	RS_Text*	text;
	data3.insertionPoint = RS_Vector(DMoji.m_start.x, DMoji.m_start.y);
	data3.height = DMoji.m_dSizeY;
	data3.width = DMoji.m_dSizeX;
	data3.valign = RS2::VAlignBottom;//VAlignMiddle;
	data3.halign = RS2::HAlignLeft;//HAlignCenter;
	data3.drawingDirection = RS2::LeftToRight;
	data3.lineSpacingStyle = RS2::Exact;
	data3.lineSpacingFactor = DMoji.m_dKankaku;//1.0;
	//コード変換
	size_t left = DMoji.m_string.length();
	char* sjis = (char *)DMoji.m_string.c_str();
	char buf[200];
	//memset(buf, NULL, 1000);
	char* p = buf;
	size_t bufleft = 200;
#ifdef _WINDOWS
	// エンコーディングの変換:iconvを使う場合
	iconv_t cd = iconv_open(UTF8_CES, SHIFTJIS_CES);
#ifdef	DEBUG
printf("sjis = %x, p = %x\n", sjis, p);
#endif
	size_t r = iconv(cd, (const char **)(&sjis), &left, &p, &bufleft);//const_cast<char**>
#ifdef	DEBUG
printf("sjis = %x, p = %x\n", sjis, p);
printf("sjis = %x %x %x %x, p = %x %x %x %x\n", sjis[0],sjis[1],sjis[2],sjis[3], buf[0],buf[1],buf[2],buf[3]);
printf("r = %d, left = %d, bufleft = %d\n", r, left, bufleft);
#endif
	*p = '\0';
	iconv_close(cd);
#else
//	int ires = SJIS2UTF8N(sjis,buf,bufleft);
	int nBytesOut;
	strcpy(buf,(const char *)CUnicodeF::sjis_to_euc((const unsigned char *)sjis/*, &nBytesOut*/));
//	QTextCodec* codec = QTextCodec::codecForName("eucJP");
//	data3.text = codec->toUnicode(buf);
#endif
//	data3.text = codec->toUnicode(sjis);
	data3.text = RS_String::fromUtf8(buf);
	data3.style = RS_String("japanese-euc");
	data3.angle = DMoji.m_degKakudo / 180.0 * M_PI;
#ifdef DEBUG
RS_DEBUG->setLevel(RS_Debug::D_DEBUGGING);
#endif
	data3.updateMode = RS2::Update;
	//jwDWORD m_nMojiShu;//文字種(斜体文字は20000、ボールド体は10000を加えた数値)

	text = new RS_Text(graphic, data3);
	RS2::LineType ltype = lTable[DMoji.m_nPenStyle];
	RS_Color col = colTable[DMoji.m_nPenColor];
	RS2::LineWidth lw = lWidth[DMoji.m_nPenWidth > 26 ? 0 : DMoji.m_nPenWidth];//RS2::Width12
	text->setPen(RS_Pen(col, RS2::Width08, ltype));

	//画層設定
	RS_String lName = HEX[DMoji.m_nGLayer > 0x0f ? 0: DMoji.m_nGLayer] + "-" +
		HEX[DMoji.m_nLayer > 0x0f ? 0 : DMoji.m_nLayer];
	if( graphic->findLayer(lName) == (RS_Layer*)NULL ){
#ifdef DEBUG
std::cout << lName.ascii() << std::endl;
#endif
		RS_Layer* layer = new RS_Layer(lName);
		graphic->addLayer(layer);
	}
	text->setLayer(lName);
	// add the line to the graphic
	graphic->addEntity(text);
#ifdef DEBUG
std::cout << data3.height << "  " << data3.width << std::endl;
std::cout << *text;
#endif
#endif
}
コード例 #12
0
ファイル: FirstFight.cpp プロジェクト: Tamboz/WakBox
    void OnActive(Character* character, InteractiveElementType /*type*/)
    {
        // Seuelement une instance du script ou bien ? Du coup va poser des problèmes
        // si plusieurs joueurs en même temps ? Du coup gérer la création de nouvelles instances de scripts ?
        m_char = character;

        // Envoie comme quoi l'élémentId n'est plus "usable" (différence avec le paquet de spawn 200)
        WorldPacket data(SMSG_INTERACTIVE_ELEMENT_UPDATE);

        data << quint64(20114); // Instance ElementId

        data.StartBlock<quint16>();
        {
            data << quint8(1); // BlockCount

            data << quint8(2); // blockId
            data << quint32(6); // offset

            data << quint8(2); // BlockId

            data << quint16(1); // ?
            data << quint8(1); // isVisible
            data << quint8(0); // isUsable
            data << quint8(0); // ?
            data << quint8(0); // ?
            data << quint8(0); // ?
            data << quint32(0); // ?
        }
        data.EndBlock<quint16>();

        character->GetSession()->SendPacket(data);

        // Spawn Wapin
        WorldPacket data2(SMSG_UPDATE_OBJECT);
        data2 << quint8(0);
        data2 << quint8(1);

        data2 << quint8(1);
        data2 << qint64(-1706442045669898);

        data2.StartBlock<quint16>();
        {
            data2 << quint8(7);

            // GUID
            data2 << qint64(-1706442045669898);

            // IDENTITY
            data2 << quint8(1);
            data2 << qint64(-1);

            // NAME
            data2 << quint16(0);

            // BREED
            data2 << quint16(2644);

            // POSITION
            data2 << qint32(0); // X
            data2 << qint32(-17); // Y
            data2 << qint16(0); // Z
            data2 << quint16(-1); // InstanceId
            data2 << quint8(3); // Direction

            // APPEARANCE
            data2 << quint8(1); // Show

            // PUBLIC_CHARACTERISTICS
            data2 << quint16(1); // Level
            data2 << quint16(0); // States size

            // FIGHT_PROPERTIES
            data2 << quint8(0); // hasProperties

            // FIGHT
            data2 << qint32(-1); // currentFightId
            data2 << quint8(0); // isKo
            data2 << quint8(0); // isDead
            data2 << quint8(0); // isSummoned
            data2 << quint8(0); // isFleeing
            data2 << qint8(-1); // obstacleId
            data2 << quint8(0); // hasSummon

            // EQUIPMENT_APPEARANCE
            data2 << quint8(0); // size

            // RUNNING_EFFECTS
            data2 << quint8(1); // hasInFightData
            data2 << quint16(1); // data size
            data2 << quint8(13); // data

            data2 << quint8(1); // hasOutFightData
            data2 << quint16(0); // size

            // CURRENT_MOVEMENT_PATH
            data2 << quint8(0); // hasCurrentPath

            // WORLD_PROPERTIES
            data2 << quint8(0); // hasProperties

            // GROUP
            data2 << quint64(79645873605204); // PartyId
            data2 << quint16(1); // Members size
            data2 << qint16(-1); // breedId
            data2 << qint16(-1); // Level

            // TEMPLATE
            data2 << quint16(0); // sightRadius
            data2 << quint16(0); // aggroRadius

            // COLLECT
            data2 << quint16(0);

            // OCCUPATION
            data2 << quint8(0);

            // XP
            data2 << quint64(0);

            // XP_CHARACTERISTICS
            data2 << quint16(0);
            data2 << quint16(0);
            //data2 << quint16(0);
            //data2 << quint32(0);

            // Pourquoi sniff size 110 et la on est déjà à 117 ??
        }
        data2.EndBlock<quint16>();

        character->GetSession()->SendPacket(data2);

        // Activation du script (mouvement de la fenêtre entre autre)
        // Root aussi le joueur ?
        WorldPacket data3(SMSG_SCENARIO_SCRIPT);
        data3 << quint8(0); // Event
        data3 << quint32(12603); // Function
        data3 << quint32(1611); // ScenarioId
        data3 << quint8(1); // Long size?
        data3 << qint64(-1706442045669898); // Param
        character->GetSession()->SendPacket(data3);

        // Spawn Kano
        WorldPacket data4(SMSG_UPDATE_OBJECT);
        data4 << quint8(0);
        data4 << quint8(1);

        data4 << quint8(1);
        data4 << qint64(-1706442045669878);

        data4.StartBlock<quint16>();
        {
            data4 << quint8(7);

            // GUID
            data4 << qint64(-1706442045669878);

            // IDENTITY
            data4 << quint8(1);
            data4 << qint64(-1);

            // NAME
            data4 << quint16(0);

            // BREED
            data4 << quint16(2694);

            // POSITION
            data4 << qint32(0); // X
            data4 << qint32(-21); // Y
            data4 << qint16(3); // Z
            data4 << quint16(-1); // InstanceId
            data4 << quint8(3); // Direction

            // APPEARANCE
            data4 << quint8(1); // Show

            // PUBLIC_CHARACTERISTICS
            data4 << quint16(100); // Level
            data4 << quint16(0); // States size

            // FIGHT_PROPERTIES
            data4 << quint8(0); // hasProperties

            // FIGHT
            data4 << qint32(-1); // currentFightId
            data4 << quint8(0); // isKo
            data4 << quint8(0); // isDead
            data4 << quint8(0); // isSummoned
            data4 << quint8(0); // isFleeing
            data4 << qint8(-1); // obstacleId
            data4 << quint8(0); // hasSummon

            // EQUIPMENT_APPEARANCE
            data4 << quint8(0); // size

            // RUNNING_EFFECTS should be wrong
            data4 << quint8(1); // hasInFightData
            data4 << quint16(1); // data size
            data4 << quint8(13); // data

            data4 << quint8(1); // hasOutFightData
            data4 << quint16(0); // size

            // CURRENT_MOVEMENT_PATH
            data4 << quint8(0); // hasCurrentPath

            // WORLD_PROPERTIES
            data4 << quint8(0); // hasProperties

            // GROUP
            data4 << quint64(79645873605204); // PartyId
            data4 << quint16(1); // Members size
            data4 << qint16(-1); // breedId
            data4 << qint16(-1); // Level

            // TEMPLATE
            data4 << quint16(0); // sightRadius
            data4 << quint16(0); // aggroRadius

            // COLLECT
            data4 << quint16(0);

            // OCCUPATION
            data4 << quint8(0);

            // XP
            data4 << quint64(0);

            // XP_CHARACTERISTICS
            data4 << quint16(0);
            data4 << quint16(0);
            //data4 << quint16(0);
            //data4 << quint32(0);

            // Pourquoi sniff size 110 et la on est déjà à 117 ??
        }
        data4.EndBlock<quint16>();

        character->GetSession()->SendPacket(data4);

        // Texte : "Hé toi le nouveau" etc.
        WorldPacket data5(SMSG_SCENARIO_SCRIPT);
        data5 << quint8(0); // Event
        data5 << quint32(12687); // Function
        data5 << quint32(1611); // ScenarioId
        data5 << quint8(1); // Params size?
        data5 << qint64(-1706442045669878); // Param
        character->GetSession()->SendPacket(data5);

        // Flèche sur le wapin
        WorldPacket data6(SMSG_SCENARIO_SCRIPT);
        data6 << quint8(0); // Event
        data6 << quint32(12691); // Function
        data6 << quint32(1611); // ScenarioId
        data6 << quint8(1); // Long size?
        data6 << qint64(-1706442045669898); // Param
        character->GetSession()->SendPacket(data6);

        m_spawned = true;
    }
コード例 #13
0
int main(int argc, char** argv)
{
    try
    {
        // Parse the command line
        if (argc != 2)
        {
            std::cerr << "Usage: " << sys::Path::basename(argv[0])
                      << " <output NITF pathname prefix>\n\n";
            return 1;
        }
        const std::string outPathnamePrefix(argv[1]);
        verifySchemaEnvVariableIsSet();

        // In order to make it easier to test segmenting, let's artificially set
        // the segment size really small
        const size_t numCols = 200;

        const size_t maxSize = numCols * 50;

        six::XMLControlRegistry xmlRegistry;
        xmlRegistry.addCreator(
                six::DataType::DERIVED,
                new six::XMLControlCreatorT<
                        six::sidd::DerivedXMLControl>());

        six::Container container(six::DataType::DERIVED);

        std::vector<six::UByte*> buffers;

        // First a single segment without a legend
        types::RowCol<size_t> dims1(40, numCols);
        std::auto_ptr<six::Data> data1(mockupDerivedData(dims1));

        const mem::ScopedArray<sys::ubyte> buffer1(new sys::ubyte[dims1.normL1()]);
        std::fill_n(buffer1.get(), dims1.normL1(), 20);

        container.addData(data1);
        buffers.push_back(buffer1.get());

        // Now a single segment with a mono legend
        types::RowCol<size_t> dims2(40, numCols);
        std::auto_ptr<six::Data> data2(mockupDerivedData(dims2));

        const types::RowCol<size_t> legendDims(50, 50);
        std::auto_ptr<six::Legend> monoLegend(new six::Legend());
        monoLegend->mType = six::PixelType::MONO8I;
        monoLegend->mLocation.row = 10;
        monoLegend->mLocation.col = 10;
        monoLegend->setDims(legendDims);

        const mem::ScopedArray<sys::ubyte> buffer2(new sys::ubyte[dims2.normL1()]);
        std::fill_n(buffer2.get(), dims2.normL1(), 100);

        container.addData(data2, monoLegend);
        buffers.push_back(buffer2.get());

        // Now a multi-segment without a legend
        types::RowCol<size_t> dims3(150, numCols);
        std::auto_ptr<six::Data> data3(mockupDerivedData(dims3));

        const mem::ScopedArray<sys::ubyte> buffer3(new sys::ubyte[dims3.normL1()]);
        std::fill_n(buffer3.get(), dims3.normL1(), 60);

        container.addData(data3);
        buffers.push_back(buffer3.get());

        // Now a multi-segment with an RGB legend
        types::RowCol<size_t> dims4(155, numCols);
        std::auto_ptr<six::Data> data4(mockupDerivedData(dims4));

        std::auto_ptr<six::Legend> rgbLegend(new six::Legend());
        rgbLegend->mType = six::PixelType::RGB8LU;
        rgbLegend->mLocation.row = 10;
        rgbLegend->mLocation.col = 10;
        rgbLegend->setDims(legendDims);
        rgbLegend->mLUT.reset(new six::LUT(256, 3));
        for (size_t ii = 0, idx = 0;
             ii < rgbLegend->mLUT->numEntries;
             ++ii, idx += 3)
        {
            rgbLegend->mLUT->table[idx] = ii;
            rgbLegend->mLUT->table[idx + 1] = ii;
            rgbLegend->mLUT->table[idx + 2] = ii;
        }

        const mem::ScopedArray<sys::ubyte> buffer4(new sys::ubyte[dims4.normL1()]);
        std::fill_n(buffer4.get(), dims4.normL1(), 200);

        container.addData(data4, rgbLegend);
        buffers.push_back(buffer4.get());

        // Write it out
        {
            six::NITFWriteControl writer;

            writer.getOptions().setParameter(
                    six::NITFWriteControl::OPT_MAX_PRODUCT_SIZE,
                    str::toString(maxSize));

            writer.setXMLControlRegistry(&xmlRegistry);
            writer.initialize(&container);

            writer.save(buffers, outPathnamePrefix + "_unblocked.nitf");
        }

        // Write it out with blocking
        {
            six::NITFWriteControl writer;

            writer.getOptions().setParameter(
                    six::NITFWriteControl::OPT_MAX_PRODUCT_SIZE,
                    str::toString(maxSize));

            const std::string blockSize("1024");
            writer.getOptions().setParameter(
                    six::NITFWriteControl::OPT_NUM_ROWS_PER_BLOCK,
                    blockSize);

            writer.getOptions().setParameter(
                    six::NITFWriteControl::OPT_NUM_COLS_PER_BLOCK,
                    blockSize);

            writer.setXMLControlRegistry(&xmlRegistry);
            writer.initialize(&container);

            writer.save(buffers, outPathnamePrefix + "_blocked.nitf");
        }

        return 0;
    }
    catch (const except::Exception& e)
    {
        std::cerr << "Caught exception: " << e.getMessage() << std::endl;
        return 1;
    }
    catch (const std::exception& e)
    {
        std::cerr << "Caught exception: " << e.what() << std::endl;
        return 1;
    }
    catch (...)
    {
        std::cerr << "Unknown exception\n";
        return 1;
    }
}
コード例 #14
0
void CCommandParser::RunL()
    {
    RDebug::Print(_L("CCommandParser::RunL report: %X"),iState);
    switch(iState)
        {
        case TControllerDataTypes::EWiiMoteReportButton:
            {
            TUint16 btn(0);
            btn = iDataPtr[2];
            btn = iDataPtr[2] << 8;
            btn |= iDataPtr[3];
            HandleButtonReport(btn);            
            }break;

        case TControllerDataTypes::EWiiMoteReportButtonAcc:
            {
            TUint16 btn(0);
            TUint16 accX(0);
            TUint16 accY(0);
            TUint16 accZ(0);
            btn = iDataPtr[2];
            btn = btn << 8;
            btn |= iDataPtr[3];
            HandleButtonReport(btn);
            
            accX = iDataPtr[4];
            accY = iDataPtr[5];
            accZ = iDataPtr[6];
            
            TUint8 lsb1(0);
            TUint8 lsb2(0);
            TUint8 lsb3(0);
            TUint8 lsb4(0);
            
            lsb1 = iDataPtr[2] & 0x40;
            lsb2 = iDataPtr[2] & 0x20;
            lsb3 = iDataPtr[3] & 0x40;
            lsb4 = iDataPtr[3] & 0x20;
            RDebug::Print(_L("XLRLSB: %X , %d - XLRLSB: %X , %d"),lsb1,lsb1,lsb2,lsb2);
            RDebug::Print(_L("XLRLSB: %X , %d - XLRLSB: %X , %d"),lsb3,lsb3,lsb4,lsb4);
            RDebug::Print(_L("AccX: %X , %d - AccY: %X , %d - AccZ: %X , %d"),accX,accX,accY,accY,accZ,accZ);
            
            HandleAccReport(accX,accY,accZ);
            }break;
            
        case TControllerDataTypes::EWiiMoteReportControlStatus:
            {
            TUint8 data(0);
            data = iDataPtr[7];
            
            TRemoteInfo info;
            info = iObserver.RemoteInfo();
            info.iCommand = (TControllerDataTypes::TWiiMoteCommands)iState;
            TReal32 d(data);
            TReal32 b(TControllerDataTypes::EWiiMoteControlStatusBattery);
            TInt16 bat=0;
            TReal calc( (d/b)*100);
            Math::Int(bat,calc);
            info.iBattery = bat;
            iObserver.UpdateRemoteInfo(info);
            }break;
            
        case TControllerDataTypes::EWiiMoteReportWrite:
            {
            TUint8 data1(0);
            TUint8 data2(0);
            TUint8 data3(0);
            TUint8 data4(0);
            data1 = iDataPtr[0];
            data2 = iDataPtr[1];
            data3 = iDataPtr[2];
            data4 = iDataPtr[3];

            TRemoteInfo info;
            info = iObserver.RemoteInfo();
            info.iCommand = (TControllerDataTypes::TWiiMoteCommands)data3;
            switch(data3)
                {
                case TControllerDataTypes::EWiiMoteCommandAudioEnable:
                case TControllerDataTypes::EWiiMoteCommandAudioMute:
                    {
                    if(data1 || data2 || data4)
                        {
                        info.iWiiSpeakerEnabled = TControllerDataTypes::EWiiSpeakerError;
                        }
                    }break;
                }            
            iObserver.UpdateRemoteInfo(info);
            }break;
        default:
            break;
        }
    }
コード例 #15
0
BOOST_FIXTURE_TEST_CASE(GeneralSigningInterface, IdentityManagementFixture)
{
  Name id("/id");
  Name certName = m_keyChain.createIdentity(id);
  shared_ptr<v1::IdentityCertificate> idCert = m_keyChain.getCertificate(certName);
  Name keyName = idCert->getPublicKeyName();
  m_keyChain.setDefaultIdentity(id);

  Name id2("/id2");
  Name cert2Name = m_keyChain.createIdentity(id2);
  shared_ptr<v1::IdentityCertificate> id2Cert = m_keyChain.getCertificate(cert2Name);

  // SigningInfo is set to default
  Data data1("/data1");
  m_keyChain.sign(data1);
  BOOST_CHECK(Validator::verifySignature(data1, idCert->getPublicKeyInfo()));
  BOOST_CHECK_EQUAL(data1.getSignature().getKeyLocator().getName(), certName.getPrefix(-1));

  Interest interest1("/interest1");
  m_keyChain.sign(interest1);
  BOOST_CHECK(Validator::verifySignature(interest1, idCert->getPublicKeyInfo()));
  SignatureInfo sigInfo1(interest1.getName()[-2].blockFromValue());
  BOOST_CHECK_EQUAL(sigInfo1.getKeyLocator().getName(), certName.getPrefix(-1));

  // SigningInfo is set to Identity
  Data data2("/data2");
  m_keyChain.sign(data2, SigningInfo(SigningInfo::SIGNER_TYPE_ID, id2));
  BOOST_CHECK(Validator::verifySignature(data2, id2Cert->getPublicKeyInfo()));
  BOOST_CHECK_EQUAL(data2.getSignature().getKeyLocator().getName(), cert2Name.getPrefix(-1));

  Interest interest2("/interest2");
  m_keyChain.sign(interest2, SigningInfo(SigningInfo::SIGNER_TYPE_ID, id2));
  BOOST_CHECK(Validator::verifySignature(interest2, id2Cert->getPublicKeyInfo()));
  SignatureInfo sigInfo2(interest2.getName()[-2].blockFromValue());
  BOOST_CHECK_EQUAL(sigInfo2.getKeyLocator().getName(), cert2Name.getPrefix(-1));

  // SigningInfo is set to Key
  Data data3("/data3");
  m_keyChain.sign(data3, SigningInfo(SigningInfo::SIGNER_TYPE_KEY, keyName));
  BOOST_CHECK(Validator::verifySignature(data3, idCert->getPublicKeyInfo()));
  BOOST_CHECK_EQUAL(data3.getSignature().getKeyLocator().getName(), certName.getPrefix(-1));

  Interest interest3("/interest3");
  m_keyChain.sign(interest3);
  BOOST_CHECK(Validator::verifySignature(interest3, idCert->getPublicKeyInfo()));
  SignatureInfo sigInfo3(interest1.getName()[-2].blockFromValue());
  BOOST_CHECK_EQUAL(sigInfo3.getKeyLocator().getName(), certName.getPrefix(-1));

  // SigningInfo is set to Cert
  Data data4("/data4");
  m_keyChain.sign(data4, SigningInfo(SigningInfo::SIGNER_TYPE_CERT, certName));
  BOOST_CHECK(Validator::verifySignature(data4, idCert->getPublicKeyInfo()));
  BOOST_CHECK_EQUAL(data4.getSignature().getKeyLocator().getName(), certName.getPrefix(-1));

  Interest interest4("/interest4");
  m_keyChain.sign(interest4, SigningInfo(SigningInfo::SIGNER_TYPE_CERT, certName));
  BOOST_CHECK(Validator::verifySignature(interest4, idCert->getPublicKeyInfo()));
  SignatureInfo sigInfo4(interest4.getName()[-2].blockFromValue());
  BOOST_CHECK_EQUAL(sigInfo4.getKeyLocator().getName(), certName.getPrefix(-1));


  // SigningInfo is set to DigestSha256
  Data data5("/data5");
  m_keyChain.sign(data5, SigningInfo(SigningInfo::SIGNER_TYPE_SHA256));
  BOOST_CHECK(Validator::verifySignature(data5, DigestSha256(data5.getSignature())));

  Interest interest5("/interest4");
  m_keyChain.sign(interest5, SigningInfo(SigningInfo::SIGNER_TYPE_SHA256));
  BOOST_CHECK(Validator::verifySignature(interest5,
                                         DigestSha256(Signature(interest5.getName()[-2].blockFromValue(),
                                                                interest5.getName()[-1].blockFromValue()))));
}
コード例 #16
0
ファイル: test_date.cpp プロジェクト: anguyenhuy/ULib
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   UTimeDate data1(31,12,99), data2("31/12/99");

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )
   U_ASSERT( UTimeDate("31/12/1900").getJulian() == 2415385 )
   U_ASSERT( UTimeDate("01/01/1970").getJulian() == 2440588 )

   U_ASSERT( data1 == data2 )
   U_ASSERT( data1.getDayOfWeek() == 5 ) // Venerdi
   U_ASSERT( data2.getDayOfYear() == 365 )

   U_ASSERT( UTimeDate("1/3/00").getDayOfWeek() == 3 ) // Mercoledi
   U_ASSERT( UTimeDate(31,12,0).getDayOfYear() == 366 )

   UTimeDate data3(60,2000);
   UTimeDate data4("29/02/00");

   U_ASSERT( data3 == data4 )
   U_ASSERT( data3.getDayOfYear() == 60 )

   UTimeDate data5(60,1901);
   UTimeDate data6("1/3/1901");

   U_ASSERT( data5 == data6 )

   U_ASSERT( UTimeDate(17, 5, 2002).isValid() == true )  // TRUE   May 17th 2002 is valid
   U_ASSERT( UTimeDate(30, 2, 2002).isValid() == false ) // FALSE  Feb 30th does not exist
   U_ASSERT( UTimeDate(29, 2, 2004).isValid() == true )  // TRUE   2004 is a leap year

   UTimeDate data7(29, 2, 2004);

   UString x = data7.strftime("%Y-%m-%d");

   U_ASSERT( x == U_STRING_FROM_CONSTANT("2004-02-29") )

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )

   cout << "Date: " << data6.strftime("%d/%m/%y") << '\n';

   while (cin >> data6) cout << data6 << '\n';

   U_ASSERT( UTimeDate::getSecondFromTime("19030314104248Z", true, "%4u%2u%2u%2u%2u%2uZ") < u_now->tv_sec )

   /*
   typedef struct static_date {
      struct timeval _timeval;      // => u_now
      char lock1[1];
      char date1[17+1];             // 18/06/12 18:45:56
      char lock2[1];
      char date2[26+1];             // 04/Jun/2012:18:18:37 +0200
      char lock3[1];
      char date3[6+29+2+12+2+19+1]; // Date: Wed, 20 Jun 2012 11:43:17 GMT\r\nServer: ULib\r\nConnection: close\r\n
   } static_date;
   */

   ULog::static_date log_data;

   (void) u_strftime2(log_data.date1, 17,               "%d/%m/%y %T",    u_now->tv_sec + u_now_adjust);
   (void) u_strftime2(log_data.date2, 26,               "%d/%b/%Y:%T %z", u_now->tv_sec + u_now_adjust);
   (void) u_strftime2(log_data.date3, 6+29+2+12+2+17+2, "Date: %a, %d %b %Y %T GMT\r\nServer: ULib\r\nConnection: close\r\n", u_now->tv_sec);

   U_INTERNAL_DUMP("date1 = %.17S date2 = %.26S date3+6 = %.29S", log_data.date1, log_data.date2, log_data.date3+6)

   /*
   for (int i = 0; i < 360; ++i)
      {
      u_now->tv_sec++;

      UTimeDate::updateTime(log_data.date1   + 12);
      UTimeDate::updateTime(log_data.date2   + 15);
      UTimeDate::updateTime(log_data.date3+6 + 20);

      cout.write(log_data.date1, 17);
      cout.write(" - ", 3);
      cout.write(log_data.date2, 26);
      cout.write(" - ", 3);
      cout.write(log_data.date3+6, 29);
      cout.put('\n');
      }
   */
}
コード例 #17
0
ファイル: udp.cpp プロジェクト: PhilipsIII/NFD
BOOST_FIXTURE_TEST_CASE(EndToEnd6, EndToEndFixture)
{
  UdpFactory factory;

  factory.createChannel("::1", "20071");

  factory.createFace(FaceUri("udp://[::1]:20070"),
                     bind(&EndToEndFixture::channel2_onFaceCreated, this, _1),
                     bind(&EndToEndFixture::channel2_onConnectFailed, this, _1));


  BOOST_CHECK_MESSAGE(limitedIo.run(1, time::seconds(1)) == LimitedIo::EXCEED_OPS,
                      "UdpChannel error: cannot connect or cannot accept connection");

  BOOST_REQUIRE(static_cast<bool>(face2));
  BOOST_CHECK_EQUAL(face2->getRemoteUri().toString(), "udp6://[::1]:20070");
  BOOST_CHECK_EQUAL(face2->getLocalUri().toString(), "udp6://[::1]:20071");
  BOOST_CHECK_EQUAL(face2->isLocal(), false);
  // face1 is not created yet

  shared_ptr<UdpChannel> channel1 = factory.createChannel("::1", "20070");
  channel1->listen(bind(&EndToEndFixture::channel1_onFaceCreated,   this, _1),
                   bind(&EndToEndFixture::channel1_onConnectFailed, this, _1));

  Interest interest1("ndn:/TpnzGvW9R");
  Data     data1    ("ndn:/KfczhUqVix");
  data1.setContent(0, 0);
  Interest interest2("ndn:/QWiIMfj5sL");
  Data     data2    ("ndn:/XNBV796f");
  data2.setContent(0, 0);
  Interest interest3("ndn:/QWiIhjgkj5sL");
  Data     data3    ("ndn:/XNBV794f");
  data3.setContent(0, 0);


  ndn::SignatureSha256WithRsa fakeSignature;
  fakeSignature.setValue(ndn::dataBlock(tlv::SignatureValue,
                                        reinterpret_cast<const uint8_t*>(0),
                                        0));

  // set fake signature on data1 and data2
  data1.setSignature(fakeSignature);
  data2.setSignature(fakeSignature);
  data3.setSignature(fakeSignature);

  face2->sendInterest(interest2);
  face2->sendData    (data2    );

  BOOST_CHECK_MESSAGE(limitedIo.run(3,//2 send + 1 listen return
                      time::seconds(1)) == LimitedIo::EXCEED_OPS,
                      "UdpChannel error: cannot send or receive Interest/Data packets");

  BOOST_REQUIRE(static_cast<bool>(face1));
  BOOST_CHECK_EQUAL(face1->getRemoteUri().toString(), "udp6://[::1]:20071");
  BOOST_CHECK_EQUAL(face1->getLocalUri().toString(), "udp6://[::1]:20070");
  BOOST_CHECK_EQUAL(face1->isLocal(), false);

  face1->sendInterest(interest1);
  face1->sendData    (data1    );

  BOOST_CHECK_MESSAGE(limitedIo.run(2, time::seconds(1)) == LimitedIo::EXCEED_OPS,
                      "UdpChannel error: cannot send or receive Interest/Data packets");


  BOOST_REQUIRE_EQUAL(face1_receivedInterests.size(), 1);
  BOOST_REQUIRE_EQUAL(face1_receivedDatas    .size(), 1);
  BOOST_REQUIRE_EQUAL(face2_receivedInterests.size(), 1);
  BOOST_REQUIRE_EQUAL(face2_receivedDatas    .size(), 1);

  BOOST_CHECK_EQUAL(face1_receivedInterests[0].getName(), interest2.getName());
  BOOST_CHECK_EQUAL(face1_receivedDatas    [0].getName(), data2.getName());
  BOOST_CHECK_EQUAL(face2_receivedInterests[0].getName(), interest1.getName());
  BOOST_CHECK_EQUAL(face2_receivedDatas    [0].getName(), data1.getName());



  //checking if the connection accepting mechanism works properly.

  face2->sendData    (data3    );
  face2->sendInterest(interest3);

  BOOST_CHECK_MESSAGE(limitedIo.run(2, time::seconds(1)) == LimitedIo::EXCEED_OPS,
                      "UdpChannel error: cannot send or receive Interest/Data packets");

  BOOST_REQUIRE_EQUAL(face1_receivedInterests.size(), 2);
  BOOST_REQUIRE_EQUAL(face1_receivedDatas    .size(), 2);

  BOOST_CHECK_EQUAL(face1_receivedInterests[1].getName(), interest3.getName());
  BOOST_CHECK_EQUAL(face1_receivedDatas    [1].getName(), data3.getName());
}
コード例 #18
0
void ComponentEventTest::testConvertSimpleUnits()
{
  std::map<std::string, std::string> attributes;
  attributes["id"] = "1";
  attributes["name"] = "DataItemTest1";
  attributes["type"] = "ACCELERATION";
  attributes["category"] = "SAMPLE";
  
  std::string time("NOW"), value("2.0");
  attributes["nativeUnits"] = "INCH";
  DataItem data1 (attributes);
  ComponentEvent event1 (data1, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 25.4f, event1.getFValue());
  CPPUNIT_ASSERT(event1.getSValue().empty());
  
  attributes["nativeUnits"] = "FOOT";
  DataItem data2 (attributes);
  ComponentEvent event2 (data2, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 304.8f, event2.getFValue());
  CPPUNIT_ASSERT(event2.getSValue().empty());
  
  attributes["nativeUnits"] = "CENTIMETER";
  DataItem data3 (attributes);
  ComponentEvent event3 (data3, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 10.0f, event3.getFValue());
  CPPUNIT_ASSERT(event3.getSValue().empty());
  
  attributes["nativeUnits"] = "DECIMETER";
  DataItem data4 (attributes);
  ComponentEvent event4 (data4, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 100.0f, event4.getFValue());
  CPPUNIT_ASSERT(event4.getSValue().empty());
  
  attributes["nativeUnits"] = "METER";
  DataItem data5 (attributes);
  ComponentEvent event5 (data5, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 1000.0f, event5.getFValue());
  CPPUNIT_ASSERT(event5.getSValue().empty());
  
  attributes["nativeUnits"] = "FAHRENHEIT";
  DataItem data6 (attributes);
  ComponentEvent event6 (data6, 123, "NOW", "2.0");
  CPPUNIT_ASSERT_EQUAL((2.0f - 32.0f) * (5.0f / 9.0f), event6.getFValue());
  CPPUNIT_ASSERT(event6.getSValue().empty());
  
  attributes["nativeUnits"] = "POUND";
  DataItem data7 (attributes);
  ComponentEvent event7 (data7, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 0.45359237f, event7.getFValue());
  CPPUNIT_ASSERT(event7.getSValue().empty());
  
  attributes["nativeUnits"] = "GRAM";
  DataItem data8 (attributes);
  ComponentEvent event8 (data8, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f / 1000.0f, event8.getFValue());
  CPPUNIT_ASSERT(event8.getSValue().empty());
  
  attributes["nativeUnits"] = "RADIAN";
  DataItem data9 (attributes);
  ComponentEvent event9 (data9, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 57.2957795f, event9.getFValue());
  CPPUNIT_ASSERT(event9.getSValue().empty());
  
  attributes["nativeUnits"] = "MINUTE";
  DataItem data10 (attributes);
  ComponentEvent event10 (data10, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 60.0f, event10.getFValue());
  CPPUNIT_ASSERT(event10.getSValue().empty());
  
  attributes["nativeUnits"] = "HOUR";
  DataItem data11 (attributes);
  ComponentEvent event11 (data11, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f * 3600.0f, event11.getFValue());
  CPPUNIT_ASSERT(event11.getSValue().empty());
  
  attributes["nativeUnits"] = "MILLIMETER";
  DataItem data12 (attributes);
  ComponentEvent event12 (data12, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f, event12.getFValue());
  CPPUNIT_ASSERT(event12.getSValue().empty());
  
  attributes["nativeUnits"] = "PERCENT";
  DataItem data13 (attributes);
  ComponentEvent event13 (data13, 123, time, value);
  CPPUNIT_ASSERT_EQUAL(2.0f, event13.getFValue());
  CPPUNIT_ASSERT(event13.getSValue().empty());
}
コード例 #19
0
void CUT_PBASE_T_USBDI_0498::TransferCompleteL(TInt aTransferId,TInt aCompletionCode)
	{
	OstTraceFunctionEntryExt( CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_ENTRY, this );
	Cancel();
	
	TInt err(KErrNone);
	TBuf<256> msg;
	OstTraceExt3(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL, "Transfer completed (id=%d), aCompletionCode = %d, test step = %d",aTransferId, aCompletionCode, iCaseStep);


	switch(iCaseStep)
		{
		case ETransfer:
			if(aCompletionCode != KErrNone)
				{
				iIfc1OutTransfer[0]->Cancel();
				iIfc1OutTransfer[1]->Cancel();
				iIfc2OutTransfer[0]->Cancel();
				iIfc2OutTransfer[1]->Cancel();
				iIfc1InTransfer[0]->Cancel();
				iIfc1InTransfer[1]->Cancel();
				iIfc2InTransfer[0]->Cancel();
				iIfc2InTransfer[1]->Cancel();
				err = KErrCorrupt;
				msg.Format(_L("<Error %d> The transfer completed with an error."), aCompletionCode);
				break; //switch(iCaseStep)
				}
	
			switch(aTransferId)
				{
				case KIfc1BulkTransferOutId1:
				case KIfc1BulkTransferOutId2:
				case KIfc2BulkTransferOutId1:
				case KIfc2BulkTransferOutId2:
					iTransferComplete |= aTransferId;
					OstTraceExt2(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP01, "Transfer OUT %d completed (Transfer Completion Aggregation Mask 0x%x)", aTransferId, iTransferComplete);
					break; //switch(aTransferId)

				case KIfc1BulkTransferInId1:
				case KIfc1BulkTransferInId2:
				case KIfc2BulkTransferInId1:
				case KIfc2BulkTransferInId2:
					iTransferComplete |= aTransferId;
					OstTraceExt2(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP02, "Transfer OUT %d completed (Transfer Completion Aggregation Mask 0x%x)", aTransferId, iTransferComplete);
					break; //switch(aTransferId)

				default:
					iTransferComplete = 0; //reset
					err = KUnexpectedTransferID;
					msg.Format(_L("<Error %d> Unexpected transfer ID, GOT %d, (wanted one of:- %d, %d, %d, %d, %d, %d, %d, or%d)"),
							       err, aTransferId,
							       KIfc1BulkTransferInId1, 
							       KIfc1BulkTransferInId2, 
							       KIfc2BulkTransferInId1, 
							       KIfc2BulkTransferInId2, 
							       KIfc1BulkTransferOutId1, 
							       KIfc1BulkTransferOutId2, 
							       KIfc2BulkTransferOutId1, 
							       KIfc2BulkTransferOutId2
							       );
					break; //switch(aTransferId)
				}
			
			// Transfer Out Response
			if(err==KErrNone && iTimeElapsed[0] == 0 && (iTransferComplete & KIfc1BulkTransferOutIdMask) == KIfc1BulkTransferOutIdMask) 
				//Record time elapsed for Interface 1 if not yet recorded.
				{
				RecordTime(0);
				}
			if(err==KErrNone && iTimeElapsed[1] == 0 && (iTransferComplete & KIfc2BulkTransferOutIdMask) == KIfc2BulkTransferOutIdMask)
				//Record time elapsed for Interface 2 if not yet recorded.
				{
				RecordTime(1);
				}
			if(err==KErrNone && (iTransferComplete & KBulkTransferOutIdMask) == KBulkTransferOutIdMask)
				{
				OstTrace1(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP03, "All OUT Transfers Completed Successfully: Transfer Completion Aggregation Mask 0x%x", iTransferComplete);
				//Leave validation to the point at which all transfers have completed.
				}
	
			// Transfer In Response
			if(err==KErrNone && iTimeElapsed[2] == 0 && (iTransferComplete & KIfc1BulkTransferInIdMask) == KIfc1BulkTransferInIdMask)
				//Record time elapsed for Interface 1 if not yet recorded.
				{
				RecordTime(2);
				}
			if(err==KErrNone && iTimeElapsed[3] == 0 && (iTransferComplete & KIfc2BulkTransferInIdMask) == KIfc2BulkTransferInIdMask) 
				//Record time elapsed for Interface 2 if not yet recorded.
				{
				RecordTime(3);
				}
			if(err==KErrNone && (iTransferComplete & KBulkTransferInIdMask) == KBulkTransferInIdMask)
				{
				// ok, compare data rcvd now
				OstTrace1(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP04, "All IN Transfers Completed Successfully: Transfer Completion Aggregation Mask 0x%x", iTransferComplete);
	
				TPtrC8 data1(iIfc1InTransfer[0]->DataPolled());	
				TPtrC8 data2(iIfc1InTransfer[1]->DataPolled());		
				TPtrC8 data3(iIfc2InTransfer[0]->DataPolled());		
				TPtrC8 data4(iIfc2InTransfer[1]->DataPolled());		
				//Validate first transfer on Interface 1 for number of bytes originally written.
				if(ValidateData(data1, KLiteralFrench4(), KHostNumWriteBytes1) == EFalse)
					{
					OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP05, "Validation failure 1st transfer, Interface 1");
					err = KErrCompletion; //indicates data validation failure
					break; //switch(iCaseStep)
					}

				//Validate second transfer on Interface 1 for number of bytes originally written.
				if(ValidateData(data2, KLiteralFrench4(), KHostNumWriteBytes1, KHostNumWriteBytes2) == EFalse)
					{
					OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP06, "Validation failure 2nd transfer, Interface 1");
					err = KErrCompletion; //indicates data validation failure
					break; //switch(iCaseStep)
					}
				
				//Validate first transfer on Interface 2 for number of bytes originally written.
				if(ValidateData(data3, KLiteralEnglish2(), KHostNumWriteBytes1) == EFalse)
					{
					OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP07, "Validation failure 1st transfer, Interface 2");
					err = KErrCompletion; //indicates data validation failure
					break; //switch(iCaseStep)
					}
				
				//Validate second transfer on Interface 2 for number of bytes originally written.
				if(ValidateData(data4, KLiteralEnglish2(), KHostNumWriteBytes1, KHostNumWriteBytes2) == EFalse)
					{
					OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP08, "Validation failure 2nd transfer, Interface 2");
					err = KErrCompletion; //indicates data validation failure
					break; //switch(iCaseStep)
					}
				
				// Comparison is a match
				OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP09, "Comparison for IN transfer is a match");
				}
			break; //switch(iCaseStep)

		default:
			err = KUndefinedStep;
			msg.Format(_L("<Error %d> Undefined case step %d reached"),KUndefinedStep, iCaseStep);
			break; //switch(iCaseStep)
		}

	if(err == KErrNone && iTransferComplete == KBulkTransferIdMask)
	/*
	Transfers all complete - now ask device to validate first interface's transfer OUT
	*/
		{
		OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP10, "Checking all times against each other");
		err = CheckTimes(0, 1, KMaxTimeDiffPercentage);
		err = err?err:CheckTimes(0, 2, KMaxTimeDiffPercentage);
		err = err?err:CheckTimes(0, 3, KMaxTimeDiffPercentage);
		err = err?err:CheckTimes(1, 2, KMaxTimeDiffPercentage);
		err = err?err:CheckTimes(1, 3, KMaxTimeDiffPercentage);
		err = err?err:CheckTimes(2, 3, KMaxTimeDiffPercentage);
		ResetTimes(0);
		ResetTimes(1);
		ResetTimes(2);
		ResetTimes(3);
		
		if(err==KErrNone)
			{
			OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP11, "Asking client for 'Validate' data written on interface 1");
			iCaseStep = ERequestDeviceValidateIFC1;
			TEndpointStringValidationRequest request(1,1,KLiteralFrench4(),KDeviceNumReadBytes);
			iControlEp0->SendRequest(request,this);
			}
		}

	if(err == KErrCompletion)
		//indicates data validation failure
		{
		msg.Format(_L("<Error %d> Bulk transfer IN data received does not match Bulk Transfer OUT data"), err);
		}

	if(err == KErrTooBig)
		//indicates timing validation failure
		{
		msg.Format(_L("<Error %d> Timer comparison showed too great a difference in transfer times between the two interfaces"), err);
		}
	
	if(err!=KErrNone)
		{	
		OstTrace0(TRACE_NORMAL, CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_DUP12, msg);
		iCaseStep = EFailed;
		TTestCaseFailed request(err,msg);
		return iControlEp0->SendRequest(request,this);
		}	
	OstTraceFunctionExit1( CUT_PBASE_T_USBDI_0498_TRANSFERCOMPLETEL_EXIT, this );
	}
コード例 #20
0
ファイル: roo_fitWH.C プロジェクト: bluejelibaby/AnalysisV2
void roo_fitWH()
{
  TString poscharge = "Plus";
  TString negcharge = "Minus";

  std::vector<TString> charge(2);
  charge.at(0) = poscharge;
  charge.at(1) = negcharge;

  TString canvas_name_plus = "muon_MC_WHelicityFramePlots_PlusICVar";
  TCanvas *c0 = new TCanvas(canvas_name_plus,"",450,400);
  TString canvas_name_minus = "muon_MC_WHelicityFramePlots_MinusICVar";
  TCanvas *c1 = new TCanvas(canvas_name_minus,"",450,400);
 
  // Run both for + and - charges
  for(unsigned int j=0; j<charge.size(); j++) {
   
    //  if (j==1) break; // do only + charge fit
    if (realData) { sfactor=36; }

      // Nominal values are taken from a fit to the MC W data (scaled to 100pb-1)
    RooRealVar *fLnom, *fRnom, *f0nom;
    if (j==0) { 
      fLnom=new RooRealVar("fL_nom","fLnom",0.556);
      fRnom=new RooRealVar("fR_nom","fRnom",0.234);
      f0nom=new RooRealVar("f0_nom","f0nom",0.210);
    } else {
      fLnom=new RooRealVar("fL_nom","fLnom",0.523);
      fRnom=new RooRealVar("fR_nom","fRnom",0.265);
      f0nom=new RooRealVar("f0_nom","f0nom",0.212);
    }

    TString Hist1 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j) + "_LH";
    TString Hist2 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j) + "_RH";
    TString Hist3 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j) + "_LO";
    TString Hist_data1 = "RECO_PolPlots_50toinf/RECO_ICVarPF"+ charge.at(j);
    
    TH1D *mc1 = (TH1D*)sigfile->Get(Hist1);
    TH1D *mc2 = (TH1D*)sigfile->Get(Hist2);
    TH1D *mc3 = (TH1D*)sigfile->Get(Hist3);
    
    TH1D *sighist = (TH1D*)sigfile->Get(Hist_data1); // W signal histogram
    TH1D *bkghist=(TH1D*)bkgfile->Get(Hist_data1); // Bkg histogram
    TH1D *hdata=(TH1D*)datafile->Get(Hist_data1); // Real data histogram

    // //we are only fitting for fL and fR
    // double accFactor1 = refTempHist1->Integral() / mc1->Integral();
    // double accFactor2 = refTempHist2->Integral() / mc2->Integral();
    // double accFactor3 = refTempHist3->Integral() / mc3->Integral();
    // double normFactor = (mc1->Integral() + mc2->Integral() + mc3->Integral()) / (refTempHist1->Integral() + refTempHist2->Integral() + refTempHist3->Integral());
    
    mc1->Rebin(rbin); mc2->Rebin(rbin); mc3->Rebin(rbin);
    sighist->Rebin(rbin); bkghist->Rebin(rbin); hdata->Rebin(rbin);

      // Scale to sfactor/pb if MC
    //if (!realData) {
    if (toyMC) sfactor=400;
    sighist->Scale(sfactor); bkghist->Scale(sfactor);
      // }
      //datahist->Scale(invWeightW);//to get MC errors - otherwise comment out

    Double_t nbkg=0;

    TH1D *datahist;
    if (realData) { datahist=hdata;
    } else {
      datahist=(TH1D*)sighist->Clone();
      if (addbkg) {datahist->Add(bkghist); }
    }
    if (addbkg) { 
      //nbkg=bkghist->Integral();
      nbkg=bkghist->Integral(bkghist->FindBin(xmin+quanta),bkghist->FindBin(xmax-quanta));
    }

    //Double_t istat=datahist->Integral();
    //Double_t f_sig=(sighist->Integral())/istat; // signal fraction
    Double_t istat=datahist->Integral(datahist->FindBin(xmin+quanta),datahist->FindBin(xmax-quanta));
    Double_t f_sig=(sighist->Integral(sighist->FindBin(xmin+quanta),sighist->FindBin(xmax-quanta)))/istat;
    Double_t f_bkg=nbkg/istat; // bkg fraction


      // Start RooFit session
    RooRealVar x("x","LP",xmin,xmax);
      // Import binned Data
    RooDataHist data1("data1","dataset with WHICVarPlus",x,mc1);
    RooDataHist data2("data2","dataset with WHICVarPlus",x,mc2);
    RooDataHist data3("data3","dataset with WHICVarPlus",x,mc3);
  
    RooDataHist test("data","dataset with WHICVarPlus",x,datahist);
    RooDataHist data_bkg("data4","dataset with ICVar",x,bkghist);

    // Relative fractions - allow them to float to negative values too if needs be
    //   if (fitMode==0) {
    RooRealVar f1("fL","fL fraction",fLnom->getVal(),0.,1.);
    RooRealVar f2("fR","fR fraction", fRnom->getVal(),0.,1.);
    RooFormulaVar f3("f0","1-fL-fR",RooArgList(f1,f2));
    if (fitMode) {
      f1.setVal((fLnom->getVal()-fRnom->getVal())); f1.setRange(-1.,1.); 
      f1.setPlotLabel("f_{L}-f_{R}"); 
      f2.setVal(f0nom->getVal()); 
      f2.setPlotLabel("f_{0}");
    } 
    // } else {
    //   RooRealVar f1("fL","fL fraction",(fLnom->getVal()-fRnom->getVal()),-1.,1.);
    //   RooRealVar f2("fR","fR fraction", (fLnom->getVal()+fRnom->getVal()),-1.,1.);
    //   RooFormulaVar f3("f0","1-fL-fR",RooArgList(f1,f2));
    // }
    RooRealVar fsub("fsub","fsub par",(fLnom->getVal()-fRnom->getVal()),-1.,1.);
    RooRealVar fsum("fsum","fsum par",(fLnom->getVal()+fRnom->getVal()), -1.,1.);
    
    // Background template
    RooHistPdf *bkg = new RooHistPdf("bkg","bkg",x,data_bkg);
    // Bkg fraction
    RooRealVar fbkg("f_{bkg}","f_bkg fraction",f_bkg);

      // Templates 
    RooHistPdf h1("h1","h1",x,data1); // left-handed template histogram
    RooHistPdf h2("h2","h2",x,data2); // right-handed template histo
    RooHistPdf h3("h3","h3",x,data3); // longitudinal template histo

      // Construct model PDF
    RooAbsPdf *sig, *model;

    if (charge.at(j) == "Plus") { // plus charge PDFs
      if (addParameter) { sig = new RooWPlusExtended("sigmodel","model",x,f1,f2,fsub);
      } else { sig = new RooWPlus("sigmodel","model",x,f1,f2); } 
    } else if (charge.at(j) == "Minus") { // minus charge PDFs
      if (addParameter) { sig = new RooWMinusExtended("sigmodel","model",x,f1,f2,fsub);
      } else { sig = new RooWMinus("sigmodel","model",x,f1,f2); } 
    }
    
    if (addbkg) {
      model = new RooAddPdf("model","model",RooArgList(*bkg,*sig),fbkg);
    } else { model = sig; }
    
    // Set the Fit Range
    x.setRange("fitrange",-0.0,1.3);
    // Construct likelihood ( + penalty term)
    RooNLLVar nll("nll","nll",*model,test,Range("fitrange"));
    RooRealVar pen("pen","penalty term",(0.5*1./(0.01*0.01)));
    RooFormulaVar nllPen("nllPen","nll+pen*fsub^2",RooArgList(nll,pen,fsub));
    
      // Fitting
    RooMinuit *m;
    if (!addParameter) { m = new RooMinuit(nll); }
    else {  m = new RooMinuit(nllPen);}

    if (!toyMC) {
      m->migrad(); m->hesse();
    }
    RooFitResult *res1 = m->save();
    
    // Re-diced data 
    // Int_t nevt=static_cast<int>(istat);
    // RooDataSet *gtest = model->generate(x,nevt);
    
    // Fitting
    //   RooFitResult * res1 = model.fitTo(test,Minos(kFALSE), Save());
    //       res1->Print();
   
    if(makePlots) {
   



      // Temp PDF for plotting purposes
      // RooAddPdf temp("temp","component 1",RooArgList(*h1,*h2,*h3),RooArgList(*f1,*f2)) ;
      // Plotting
      gROOT->SetStyle("Plain");  
      gStyle->SetOptFit(0);
      gStyle->SetOptTitle(0);
      gStyle->SetOptStat(0);      //gStyle->SetCanvasDefH(600); //Height of canvas
      //gStyle->SetCanvasDefW(600); //Width of canvas   
      if(charge.at(j) == "Plus") { c0->cd();
	//c0->Divide(2,1);c0->cd(1);
      }
      if(charge.at(j) == "Minus") { c1->cd();
	//c1->Divide(2,1);c1->cd(1);
      }
      //RooPlot* frame = new RooPlot(0.0,1.3,0,800);
      RooPlot* frame = x.frame();


      test.plotOn(frame,Name("data")); 
      model->plotOn(frame,Name("model")); 
      // model->paramOn(frame);//, Format("NELU", AutoPrecision(2)), Layout(0.1,0.5,0.9));
        
      //  h1.plotOn(frame);
      //     h2.plotOn(frame);
      //    h3.plotOn(frame);

       //  model->plotOn(frame, Components(h1),LineColor(kRed),LineStyle(kDashed));
       //     temp->plotOn(frame, Components(h2),LineColor(kGreen),LineStyle(kDashed));
      //  temp->plotOn(frame, Components(h3),LineColor(kYellow),LineStyle(kDashed));
      if (addbkg) {
	//  model->plotOn(frame, Components(h1),FillColor(5),DrawOption("F"));
     	//model->plotOn(frame,Components(*bkg),FillColor(5),DrawOption(""));
      } 

   
  hdata->GetYaxis()->SetTitle("Events / 0.1");
  if(charge.at(j) == "Plus") {  hdata->GetXaxis()->SetTitle("#it{L_{P}}(#mu^{+})");}
  if(charge.at(j) == "Minus") {hdata->GetXaxis()->SetTitle("#it{L_{P}}(#mu^{-})");}
      hdata->GetXaxis()->SetTitleSize(0.06);
      hdata->GetXaxis()->SetTitleOffset(1.);
      hdata->GetYaxis()->SetTitleSize(0.06);
      hdata->GetYaxis()->SetTitleOffset(1.2);
      hdata->GetXaxis()->SetLabelSize(0.055);
      hdata->GetYaxis()->SetLabelSize(0.055);
      hdata->GetXaxis()->SetRangeUser(0.0,1.29);
      hdata->GetYaxis()->SetRangeUser(0.0,600);
      hdata->SetMarkerStyle(20);

      //  mc1->Draw("same");
      // Goodness-of-fit
      Double_t chi2= frame->chiSquare("model","data",3);
      Double_t nllmin=res1->minNll();
      cout << "" << endl;
      cout << "Printing out the goodness-of-fit measure:" << endl;
      cout << "chi2 = " << chi2 << "\t" << "min NLL = " << nllmin << endl;
      res1->Print();

      //   TCanvas* testt  = new TCanvas ("testt","hj");
      cout <<"intetral: "<<   hdata->Integral()<<endl;
      hdata->GetXaxis()->SetRangeUser(0.0,1.29);
      cout <<   hdata->Integral()<<endl;
      
      hdata->Draw("");
      //  frame->Draw("same");
      mc1->GetXaxis()->SetRangeUser(0.0,1.29);
      float f_l_a =  mc1->Integral();
      mc2->GetXaxis()->SetRangeUser(0.0,1.29);
      float f_r_a =  mc2->Integral();
      mc3->GetXaxis()->SetRangeUser(0.0,1.29);
      float f_0_a =  mc3->Integral();

      float allData =  hdata->Integral();
      float EWKBkg = allData*(f_bkg);
      float WData = allData*(1-f_bkg);

      float f_l = 0.5*(1-f2.getVal()+f1.getVal());
      float f_r = 0.5*(1-f2.getVal()-f1.getVal());
      float f_0 = f2.getVal();
      cout << "f_l: "<< f_l<< ",f_r: "<< f_r<< ", f_0: "<< f_0<< " 1= "<< f_l+f_r+f_0<< endl;
      float allW = f_l*f_l_a+f_r*f_r_a+f_0*f_0_a;

      //hdata->Draw("");
      //    bkghist->GetXaxis()->SetRangeUser(0.0,1.3);
      bkghist->Scale(EWKBkg/bkghist->Integral());
      bkghist->Draw("samehist");
      bkghist->SetLineColor(kYellow);
      bkghist->SetFillColor(kYellow);

      mc1->Scale(f_l*WData/allW);
      mc2->Scale(f_r*WData/allW);
      mc3->Scale(f_0*WData/allW);
      mc1->SetLineColor(kRed);
      mc2->SetLineColor(kGreen);
      mc3->SetLineColor(kBlue);
      mc1->SetLineWidth(3);
      mc2->SetLineWidth(3);
      mc3->SetLineWidth(3);
      mc1->SetLineStyle(2);
      mc2->SetLineStyle(3);
      mc3->SetLineStyle(4);
      mc1->Draw("samehist");
      mc2->Draw("samehist");
      mc3->Draw("samehist");

      TH1D* allHists = (TH1D*)mc1->Clone();
      allHists->Add(mc2,1);
      allHists->Add(mc3,1);
      allHists->Add(bkghist,1);
      allHists->SetLineWidth(3);
      //   frame->SetOptFit(0);

        frame->Draw("same");
      //   allHists->Draw("same");
	TLegend* aleg;
	//if(charge.at(j) == "Minus") aleg = new TLegend(0.2,0.69,0.6,0.9,"");
	//  if(charge.at(j) == "Plus") 
	//aleg =  new TLegend(0.5,0.6,0.7,0.9,"");//new TLegend(0.8,0.69,0.95,0.9,"");
      aleg = new TLegend(0.2017937,0.7419355,0.4775785,0.9193548,NULL,"brNDC");
      aleg->SetNColumns(2);
      aleg->SetFillColor(0);
      aleg->SetLineColor(0);
      aleg->AddEntry(mc1,"f_{L}","lf");
      aleg->AddEntry(mc2,"f_{R}","lf");
      aleg->AddEntry(mc3,"f_{0}","lf");
      aleg->AddEntry(bkghist,"EWK","lf");
      TH1* dummyhist = new TH1F("", "", 1, 0, 1);
      dummyhist->SetLineColor(kBlue);
      dummyhist->SetLineWidth(3);
      aleg->AddEntry(dummyhist, "fit result", "lf");
      aleg->AddEntry(hdata, "data","P");

      aleg->Draw("same");

      //TLatex* preliminary; 

      //TLatex* text;
      //if(false) {
	//text = new TLatex(0.35,480,"#splitline{f_{L}-f_{R}=0.240#pm0.036(stat.)#pm0.031(syst.)}{f_{0}=0.183#pm0.087(stat.)#pm0.123(syst.)}");
	//preliminary = new TLatex(0.35,550,"CMS preliminary: #it{L} = 36pb^{-1}@ 7 TeV");
      //}

      //if(true){
	//text = new TLatex(0.05,480,"#splitline{f_{L}-f_{R}=0.310#pm0.036(stat.)#pm0.017(syst.)}{f_{0}=0.171#pm0.085(stat.)#pm0.099(syst.)}");
	//preliminary = new TLatex(0.05,550,"#splitline{CMS, #sqrt{s} = 7 TeV,}{#it{L_{int}} = 36 pb^{-1}}");}
      //preliminary->SetTextSize(0.043);
      //preliminary->Draw("same");
      
      //text->SetTextSize(0.043);
      //  text->Draw("same");
      /*
	// Draw Minuit contours
      if(charge.at(j) == "Plus") { c0->cd(2);
      } else { c1->cd(2); }

	// RooPlot *rcont=m->contour(f1,f2,1,2);
	// rcont->Draw();
      RooPlot *rcontour=new RooPlot(f1,f2);
      res1->plotOn(rcontour,f1,f2,"ME123VHB");
      rcontour->Draw();
      if (fitMode) {
	rcontour->GetXaxis()->SetTitle("f_{L}-f_{R}");
	rcontour->GetYaxis()->SetTitle("f_{0}");
      } else {
	rcontour->GetXaxis()->SetTitle("f_{L}");
	rcontour->GetYaxis()->SetTitle("f_{R}");
      }
      */

    }

    TLatex * text = new TLatex(0.7451931,500.8655,"#splitline{CMS,  #sqrt{s} = 7 TeV}{L_{ int} = 36 pb^{-1}}");
    text->SetTextSize(0.043);
    text->SetLineWidth(2);
    text->Draw("same");

     
    const TMatrixDSym& cor = res1->correlationMatrix();
    const TMatrixDSym& cov = res1->covarianceMatrix();
    
    //Print correlation, covariance matrix
    cout << "correlation matrix" << endl; cor.Print();
    cout << "covariance matrix" << endl; cov.Print();
  
    cout << f1 << endl; cout << f2 << endl;
    if (!fitMode) {
      cout << "f0 = " << f3 << " +/- " << f3.getPropagatedError(*res1) << endl;
    }
  }
     
  if(makePlots) {
    c0->Print(canvas_name_plus+".pdf");
    c1->Print(canvas_name_minus+".pdf");
  }

  if (toyMC) {

    // MC STudies
  Int_t nevt=istat;
  Int_t nEXP=100;

  RooMCStudy mgr(*model,*model,x,"","mhrv");
  mgr.generateAndFit(nEXP,nevt,kTRUE);
  
  TCanvas *cp0 = new TCanvas("c0","",1200,400);
  cp0->Divide(3,1);
  cp0->cd(1);
  RooPlot *p1=mgr.plotParam(f1); p1->Draw(); 
  if (fitMode) p1->SetTitle(";f_{L}-f_{R};number of toys");
  cp0->cd(2);
  RooPlot *p2 = mgr.plotError(f1); p2->Draw();
  if (fitMode) p2->SetTitle(";#delta (f_{L}-f_{R});number of toys");
  cp0->cd(3);
  // f1 pull
  RooPlot* m1pframe = mgr.plotPull(f1,-3.,3.,30,kTRUE);
  m1pframe->Draw();
  if (fitMode) {
    m1pframe->SetTitle(";f_{L}-f_{R};number of toys");
  }

  TCanvas *cp02 = new TCanvas("c1","",1200,400);
  cp02->Divide(3,1);
  cp02->cd(1);
  RooPlot *p3=mgr.plotParam(f2); p3->Draw();
  if (fitMode) p3->SetTitle(";f_{0};number of toys");
  cp02->cd(2);
  RooPlot *p4=mgr.plotError(f2); p4->Draw();
  if (fitMode) p4->SetTitle(";#delta f_{0}; number of toys");
  cp02->cd(3);
  // f2 pull
  RooPlot* m2pframe = mgr.plotPull(f2,-3.,3.,30,kTRUE);
  m2pframe->Draw();
  if (fitMode) {
    m2pframe->SetTitle(";f_{0};number of toys");
  }

  TCanvas *cnll = new TCanvas("cnll","");
  RooPlot* nllframe = mgr.plotNLL();
  // nllframe->Draw();


  }

  return;
}
コード例 #21
0
ファイル: thScan.cpp プロジェクト: amartelli/IMCP_BTFAnalysis
int main (int argc, char** argv)
{  
    // get run number
    std::string inputName = std::string(argv[1]);
    char split_char = '/';
    std::vector<std::string> tokens;
    std::istringstream split(inputName);
    for(std::string each; getline(split, each, split_char); 
        tokens.push_back(each));
    
    split_char = '_';
    std::vector<std::string> tokens_name;
    std::istringstream split_name(tokens.at(1));
    for(std::string each; getline(split_name, each, split_char); 
        tokens_name.push_back(each));

    const int Ch_ref1 = atoi((tokens_name.at(1)).c_str());
    const int Ch_ref2 = atoi((tokens_name.at(3)).c_str());
    const int Ch_1 = atoi((tokens_name.at(5)).c_str());
    const int Ch_2 = atoi((tokens_name.at(7)).c_str());
    const int Ch_3 = atoi((tokens_name.at(9)).c_str());

    std::vector<std::string> nameMCP;
    nameMCP.push_back("MiB1");
    nameMCP.push_back("MiB2");
    nameMCP.push_back("ScB");
    nameMCP.push_back("Planacon");
    nameMCP.push_back("MiB3");
    nameMCP.push_back("Roma2");
    if(tokens_name.at(0) == "Scan3") nameMCP.at(1) = "Roma1";

    std::vector<std::string> pcMCP;                                     
    for(unsigned int ii=0; ii<nameMCP.size(); ++ii) pcMCP.push_back("");
    pcMCP.at(Ch_ref1) = tokens_name.at(2);
    pcMCP.at(Ch_ref2) = tokens_name.at(4);
    pcMCP.at(Ch_1) = tokens_name.at(6);
    pcMCP.at(Ch_2) = tokens_name.at(8);
    pcMCP.at(Ch_3) = tokens_name.at(10);

    //---treshold setup Scan-dependent 
    init();
    const int iScanTh = atoi(argv[2])-1;
    float Ch_th[6]={0,0,0,0,0,0};
    Ch_th[Ch_ref1] = _th[iScanTh][Ch_ref1];
    Ch_th[Ch_ref2] = _th[iScanTh][Ch_ref2];
    Ch_th[Ch_1] = _th[iScanTh][Ch_1];
    Ch_th[Ch_2] = _th[iScanTh][Ch_2];
    Ch_th[Ch_3] = _th[iScanTh][Ch_3];


    TFile* out = TFile::Open((tokens_name.at(0)+"_outHistos.root").c_str(),"recreate");  
    out->cd();
    
    //Output dat
    std::ofstream data1(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_1)+"_pc_"+pcMCP.at(Ch_1)+".dat").data());
    std::ofstream data2(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_2)+"_pc_"+pcMCP.at(Ch_2)+".dat").data());
    std::ofstream data3(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_3)+"_pc_"+pcMCP.at(Ch_3)+".dat").data());

    int nFiles = 1, iRun = 0, goodEvt = 0;
    int iScan = 0;
    
    //---usefull histos
    TH1F* chHistoBase_All[9];
    TH1F* chHistoSignal_All[9];
    TH1F* timeDiffHisto[9];
    TH1F* timeDiffHisto_Double = new TH1F("timeDiffHisto_Double", "timeDiffHisto_Double",5000,-10,10);
    //---histos initialization
    for(int iCh=0; iCh<6; ++iCh)
      {
	char h1[30], h2[30], h3[30];
	sprintf(h1, "histoBase_All_Ch%d", iCh);
	sprintf(h2, "histoSignal_All_Ch%d", iCh);
	sprintf(h3, "histoTime_Ch%d", iCh);
	chHistoBase_All[iCh] = new TH1F(h1,h1,30000,-30000,1000);
	chHistoSignal_All[iCh] = new TH1F(h2, h2,30000,-30000,1000);
	timeDiffHisto[iCh] = new TH1F(h3, h3,1024,0,1024);
      } 

    
    //---do runs loop
    ifstream log (argv[1], ios::in);
    while(log >> nFiles)
    {
      ++iScan;
      vector<float> digiCh[9];
      float timeCF[9];
      float baseline[9];
      float intSignal[9],  intBase[9];
      int count[5]={0,0,0,0,0}, spare[5]={0,0,0,0,0}, spare2[5]={0,0,0,0,0};
      int tot_tr1 = 0, tot_tr0 = 0, trig = 0;
      int HV1=0, HV2=0, HV3=0;
      
      TH1F* chHistoWF_Ch[9];
      TH1F* chHistoBase_Ch[9];
      TH1F* chHistoSignal_Ch[9];
      TH1F* timeDiffHisto_Triple_Ch1 = new TH1F(Form("timeDiffHisto_Triple_Ch1_Scan%d",iScan), "", 5000,-100,100);
      TH1F* timeDiffHisto_Triple_Ch2 = new TH1F(Form("timeDiffHisto_Triple_Ch2_Scan%d",iScan), "", 5000,-100,100);
      TH1F* timeDiffHisto_Triple_Ch3 = new TH1F(Form("timeDiffHisto_Triple_Ch3_Scan%d",iScan), "", 5000,-100,100);
      
      char ha[10];
      for (int iiw=0;iiw<9;++iiw){
	sprintf (ha,"histoWF_Ch%d_Scan_%d",iiw, iScan);
	chHistoWF_Ch[iiw] = new TH1F( ha, "", 1024,0.,1024);
	chHistoWF_Ch[iiw]->SetXTitle("Waveform");
	
	sprintf (ha,"histoBase_Ch%d_Scan_%d",iiw, iScan);
	chHistoBase_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000);
	chHistoBase_Ch[iiw] -> SetXTitle ("Integral BaseLine Ch(ADC)");
	
	sprintf (ha,"histoSignal_Ch%d_Scan_%d",iiw, iScan);
	chHistoSignal_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000);
	chHistoSignal_Ch[iiw] -> SetXTitle ("Integral Signal Ch(ADC)");
      }
      
      //---data chain
      TChain* chain = new TChain("eventRawData");
      InitTree(chain);
      for(int iFiles=0; iFiles<nFiles; iFiles++){
	log >> iRun;
	char iRun_str[30];
	sprintf(iRun_str, "../Analysis_TB/DATA/run_IMCP_%d_*.root", iRun);
	chain->Add(iRun_str);
	cout << "Reading:  ../Analysis_TB/DATA/run_IMCP_" << iRun << endl;
      }
      log >> HV1 >> HV2 >> HV3;
      
      for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++) {
	
	//---always clear the std::vector !!!
	for(int iCh=0; iCh<9; iCh++) digiCh[iCh].clear();
	
	//---Read the entry
	chain->GetEntry(iEntry);
	
	//---DAQ bug workaround
	if(iRun < 145) goodEvt = 10;
	else goodEvt = 1;
	
	if(evtNumber % goodEvt == 0){
	  //---Read SciFront ADC value and set the e- multiplicity 
	  //---(default = 1)
	  trig = 1;
	  for(int iCh=0; iCh<nAdcChannels; iCh++)
	    {
	      if(adcData[iCh] > 1500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=2;
	      if(adcData[iCh] < 500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=0;
	    }
	  if(trig > 1) continue; 
	  
	  //---Read digitizer samples
	  for(int iSample=0; iSample<nDigiSamples; iSample++){
	    if(digiChannel[iSample] == 3){
	      digiCh[digiChannel[iSample]].push_back(-digiSampleValue[iSample]);
	      chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, -digiSampleValue[iSample]);
	    }
	    else{
	      digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]);
	      chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, digiSampleValue[iSample]);
	    }
	    
	  }
	  for(int iCh=0; iCh<6; iCh++){
	    //	    baseline[iCh] = SubtractBaseline(5, 25, &digiCh[iCh]);
	    baseline[iCh] = SubtractBaseline(26, 46, &digiCh[iCh]);
	    intBase[iCh] = ComputeIntegral(26, 46, &digiCh[iCh]);
	    if(trig == 0) {
	      chHistoBase_All[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh]));
	      chHistoBase_Ch[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh]));
	      // 		    chHistoBase_All[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh]));
	      // 		    chHistoBase_Ch[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh]));
	    }
	    timeCF[iCh]=TimeConstFrac(30, 500, &digiCh[iCh], 0.5);
	    //		  timeDiffHisto[iCh]->Fill(timeCF[iCh]*0.2-timeCF[0]*0.2); 
	    timeDiffHisto[iCh]->Fill(timeCF[iCh]); 
	    
	    int t1 = (int)(timeCF[iCh]/0.2) - 3;
	    int t2 = (int)(timeCF[iCh]/0.2) + 17;
	    //---Fill the signal integral histo only if the e- multiplicity is 1
	    if(t1 > 30 && t1 < 1024 && t2 > 30 && t2 < 1024 && trig == 1)
	      {
		chHistoSignal_All[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh]));
		chHistoSignal_Ch[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh]));
		intSignal[iCh] = ComputeIntegral(t1, t2, &digiCh[iCh]);
	      }
	    else intSignal[iCh] = ComputeIntegral(50, 70, &digiCh[iCh]);
	  }// loop over Ch
	  //---Multiplicity == 1 --> compute efficency, fake rate and timing                                                                          
	  if(intSignal[Ch_ref1] < Ch_th[Ch_ref1] && intSignal[Ch_ref2] < Ch_th[Ch_ref2] && trig == 1){
	    ++tot_tr1;
	    float tDiff = (timeCF[Ch_ref1] - timeCF[Ch_ref2]);
	    float tMean = (timeCF[Ch_ref1] + timeCF[Ch_ref2])*0.5;
	    timeDiffHisto_Double->Fill(tDiff);
	    timeDiffHisto_Triple_Ch1->Fill(tMean - timeCF[Ch_1]);
	    timeDiffHisto_Triple_Ch2->Fill(tMean - timeCF[Ch_2]);
	    timeDiffHisto_Triple_Ch3->Fill(tMean - timeCF[Ch_3]);
	    
	    if(intSignal[Ch_1] < Ch_th[Ch_1]) ++count[1];
	    if(intSignal[Ch_2] < Ch_th[Ch_2]) ++count[2];
	    if(intSignal[Ch_3] < Ch_th[Ch_3]) ++count[3];
	    
	    if(intBase[Ch_1] < Ch_th[Ch_1])  ++spare[1];
	    if(intBase[Ch_2] < Ch_th[Ch_2])  ++spare[2];
	    if(intBase[Ch_3] < Ch_th[Ch_3])  ++spare[3];
	  }
	}// good Event
      }// loop over entries
    
      std::cout << "HV1 = " << HV1 << " HV2 = " << HV2 << " HV3 = " << HV3 << std::endl;
      double eff1 = ((double)count[1]-(double)spare[1])/(double)tot_tr1;
      double eff2 = ((double)count[2]-(double)spare[2])/(double)tot_tr1;
      double eff3 = ((double)count[3]-(double)spare[3])/(double)tot_tr1;
    
      double eff1Err = TMath::Sqrt((eff1*(1-eff1))/tot_tr1);
      double eff2Err = TMath::Sqrt((eff2*(1-eff2))/tot_tr1);
      double eff3Err = TMath::Sqrt((eff3*(1-eff3))/tot_tr1);

      std::cout << "Ch_1 eff = " << eff1 << " +/- " << eff1Err << std::endl;
      std::cout << "Ch_2 eff = " << eff2 << " +/- " << eff2Err << std::endl;
      std::cout << "Ch_3 eff = " << eff3 << " +/- " << eff3Err << std::endl;
     
      /*
	data1 << HV1 << " " <<  eff1 << " " << 0 << " " << eff1Err << std::endl;
	data1 << HV2 << " " <<  eff2 << " " << 0 << " " << eff2Err << std::endl;
	data1 << HV3 << " " <<  eff3 << " " << 0 << " " << eff3Err << std::endl;
      */
  
      for(int iw=0; iw<6; ++iw){
	if(iw == 2) continue;
	chHistoBase_Ch[iw]->Write();
	chHistoSignal_Ch[iw]->Write();
	chHistoWF_Ch[iw]->Write();
      }
      timeDiffHisto_Triple_Ch1->Write();
      timeDiffHisto_Triple_Ch2->Write();
      timeDiffHisto_Triple_Ch3->Write();
      chain->Delete();
    }

    for(int iw=0; iw<6; ++iw){
      if(iw == 2) continue;
      chHistoBase_All[iw]->Write();
      chHistoSignal_All[iw]->Write();
      timeDiffHisto[iw]->Write();
    }

    data1.close();
    data2.close();
    data3.close();

    timeDiffHisto_Double->Write();
    out->Close();
    return 0;
}
コード例 #22
0
ファイル: Vehicle.cpp プロジェクト: sc0rpio0o/diamondcore
void Vehicle::AddPassenger(Unit *unit, int8 seatId, bool force)
{
    SeatMap::iterator seat;
    seat = m_Seats.find(seatId);

    // this should never happen
    if(seat == m_Seats.end())
        return;

    unit->SetVehicleGUID(GetGUID());

    seat->second.passenger = unit;
    if(unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->isVehicle())
    {
        if(((Vehicle*)unit)->GetEmptySeatsCount(true) == 0)
            seat->second.flags = SEAT_VEHICLE_FULL;
        else
            seat->second.flags = SEAT_VEHICLE_FREE;
    }
    else
    {
        seat->second.flags = SEAT_FULL;
    }

    if(unit->GetTypeId() == TYPEID_PLAYER)
    {
        WorldPacket data0(SMSG_FORCE_MOVE_ROOT, 10);
        data0 << unit->GetPackGUID();
        data0 << (uint32)((seat->second.vs_flags & SF_CAN_CAST) ? 2 : 0);
        unit->SendMessageToSet(&data0,true);
    }

    if(seat->second.vs_flags & SF_MAIN_RIDER)
    {
        if(!(GetVehicleFlags() & VF_MOVEMENT))
        {
            GetMotionMaster()->Clear(false);
            GetMotionMaster()->MoveIdle();
            SetCharmerGUID(unit->GetGUID());
            unit->SetUInt64Value(UNIT_FIELD_CHARM, GetGUID());
            if(unit->GetTypeId() == TYPEID_PLAYER)
            {
				((Player*)unit)->SetMover(this);
                ((Player*)unit)->SetMoverInQueve(this);
                ((Player*)unit)->SetClientControl(this, 1);
            }
            if(canFly() || HasAuraType(SPELL_AURA_FLY) || HasAuraType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED))
            {
                WorldPacket data3(SMSG_MOVE_SET_CAN_FLY, 12);
                data3<< GetPackGUID();
                data3 << (uint32)(0);
                SendMessageToSet(&data3,false);
            }
        }

        SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(GetEntry());
        for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
        {
            if (unit->GetTypeId() == TYPEID_UNIT || itr->second.IsFitToRequirements((Player*)unit))
            {
                Unit *caster = (itr->second.castFlags & 0x1) ? unit : this;
                Unit *target = (itr->second.castFlags & 0x2) ? unit : this;

                caster->CastSpell(target, itr->second.spellId, true);
            }
        }
        if(unit->GetTypeId() == TYPEID_PLAYER)
        {
            // it should be added only on rider enter?
            if(((Player*)unit)->GetGroup())
                ((Player*)unit)->SetGroupUpdateFlag(GROUP_UPDATE_VEHICLE);

            ((Player*)unit)->GetCamera().SetView(this);

            BuildVehicleActionBar((Player*)unit);
        }

        if(!(GetVehicleFlags() & VF_FACTION))
            setFaction(unit->getFaction());

        if(GetVehicleFlags() & VF_CANT_MOVE)
        {
            WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
            data2<< GetPackGUID();
            data2 << (uint32)(2);
            SendMessageToSet(&data2,false);
        }

        if(GetVehicleFlags() & VF_NON_SELECTABLE)
            SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
    }
    if(seat->second.vs_flags & SF_UNATTACKABLE)
        unit->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);

    EmptySeatsCountChanged();
}
コード例 #23
0
ファイル: _test_lpdu.cpp プロジェクト: rickfoosusa/dnp
void TestLpdu::testBuildLpdu()
{

  /* application layer data for r1 */
  uint8_t a1[] = { 0xcd, 0xcc, 0x01, 0x3c, 0x02, 0x06, 0x3c, 0x03,
                         0x06, 0x3c, 0x04, 0x06 };

  /* application layer data for r2 */
  uint8_t a2[] = { 0xc1, 0xe3, 0x81, 0x96, 0x00, 0x02, 0x01, 0x28,
                         0x01, 0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0x28,
                         0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x01, 0x28,
                         0x01, 0x00, 0x02, 0x00, 0x01, 0x02, 0x01, 0x28,
                         0x01, 0x00, 0x03, 0x00, 0x01, 0x20, 0x02, 0x28,
                         0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20,
                         0x02, 0x28, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00,
                         0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x03, 0x00,
                         0x00, 0x1e, 0x02, 0x01, 0x00, 0x00, 0x01, 0x00,
                         0x01, 0x00, 0x00, 0x01, 0x00, 0x00 };

  /* these are known good DNP LPDUs */
  uint8_t r0[] = { 0x05, 0x64, 0x05, 0xc0, 0x02, 0x00, 0x01, 0x00,
                         0x9e, 0x59 }; /* header only */

  uint8_t r1[] = { 0x05, 0x64, 0x11, 0xc4, 0x15, 0x00, 0x17, 0x00,
                         0x63, 0x62, 0xcd, 0xcc, 0x01, 0x3c, 0x02, 0x06,
                         0x3c, 0x03, 0x06, 0x3c, 0x04, 0x06, 0x08, 0x9e };
    
  uint8_t r2[] = { 0x05, 0x64, 0x53, 0x73, 0x00, 0x04, 0x01, 0x00,
                         0x03, 0xfc, 0xc1, 0xe3, 0x81, 0x96, 0x00, 0x02,
                         0x01, 0x28, 0x01, 0x00, 0x00, 0x00, 0x01, 0x02,
                         0x01, 0x28, 0x05, 0x24, 0x01, 0x00, 0x01, 0x00,
                         0x01, 0x02, 0x01, 0x28, 0x01, 0x00, 0x02, 0x00,
                         0x01, 0x02, 0x01, 0x28, 0xb4, 0x77, 0x01, 0x00,
                         0x03, 0x00, 0x01, 0x20, 0x02, 0x28, 0x01, 0x00,
                         0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0xa5, 0x25,
                         0x02, 0x28, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00,
                         0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x03, 0x00,
                         0x2f, 0xac, 0x00, 0x1e, 0x02, 0x01, 0x00, 0x00,
                         0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00,
                         0x16, 0xed };


  uint8_t twoLpdus[] = { 0x05, 0x64, 0x08, 0xc4, 0x02, 0x00, 0x2d, 0x00,
                         0xa4, 0x1c, 0xc0, 0xcd, 0x00, 0x23, 0x65, 0x05,
                         0x64, 0x0b, 0xc4, 0x02, 0x00, 0x2d, 0x00, 0xf4,
                         0x8f, 0xc0, 0xce, 0x01, 0x3c, 0x02, 0x06, 0x09,
                         0x7f };

  /* header only - no application data */
  uint8_t r3[] = { 0x05, 0x64, 0x05, 0xc0, 0x01, 0x00, 0x00, 0x04,
                         0xe9, 0x21 };

  /* header only - no application data */
  uint8_t r4[] = { 0x05, 0x64, 0x05, 0x00, 0x00, 0x04, 0x01, 0x00,
                         0x19, 0xa6 };

  uint8_t r5[] = { 0x05, 0x64, 0x0a, 0x44, 0x01, 0x00, 0x02, 0x00,
                   0xfa, 0x4a, 0xc1, 0xe1, 0x81, 0x10, 0x00, 0x6d,
                   0xd5 };

  /* known bad lpdu data */
  uint8_t r10[] ={ 108, 68, 3, 0, 17, 8, 127, 38, 193, 201 };
  uint8_t r11[] ={ 129, 144, 0, 20, 6, 0, 0, 8, 16, 0 };
  uint8_t r12[] ={ 0, 0, 16, 0, 48, 78, 16, 0, 7, 0 };
  uint8_t r13[] ={ 0, 0, 7, 0, 7, 0, 17, 0, 30, 4 };
  uint8_t r14[] ={ 0, 0, 156, 186, 34, 120, 0, 120, 0, 120 };
  uint8_t r15[] ={ 0, 120, 0, 48, 81, 66, 81, 69, 81, 61 };
  uint8_t r16[] ={ 76, 53, 81, 4, 0, 5, 0, 4, 0, 4 };
  uint8_t r20[] ={ 81, 48, 81, 48, 223, 36, 81, 4, 0, 5 };

  enum StatIndex { RX_START_OCTETS = 0,
                   RX_LPDUS,
                   LOST_BYTES,
                   CRC_ERRORS,
                   NUM_STATS };

  Stats::Element statElements[] =
  {
      { RX_START_OCTETS,       "Rx Start Octets",         Stats::NORMAL,0,0},
      { RX_LPDUS,              "Rx Lpdus",                Stats::NORMAL,0,0},
      { LOST_BYTES,            "Lost Bytes",            Stats::ABNORMAL,0,0},
      { CRC_ERRORS,            "CRC Errors",            Stats::ABNORMAL,0,0},
  };

  Stats stats;
  char name[Stats::MAX_USER_NAME_LEN];
  int debugLevel = -1;
  DummyDb db;

  assert(sizeof(statElements)/sizeof(Stats::Element) == NUM_STATS);
  snprintf(name, Stats::MAX_USER_NAME_LEN, "DL TEST");
  stats = Stats( name, 1, &debugLevel, statElements, NUM_STATS, &db);

  Lpdu lpdu = Lpdu( &stats);

  unsigned int i;
  bool lpduFound;

  lpdu.build( 1, 1, 0, 0, 0, 2, 1);
  lpduToArrayCmp( lpdu, r0);

  lpdu.build( 1, 1, 0, 0, 4, 21, 23, TO_BYTES(a1));
  lpduToArrayCmp( lpdu, r1);

  lpdu.build( 0, 1, 1, 1, 3, 1024, 1, TO_BYTES(a2));
  lpduToArrayCmp( lpdu, r2);

  lpdu.reset();
  /* test building from incoming bytes */
  Bytes data1( r5, r5 + 10);
  lpduFound = lpdu.buildFromBytes( data1);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 10);

  Bytes data2( &r5[10], &r5[10] + sizeof(r5) - 10);
  lpduFound = lpdu.buildFromBytes( data2);
  QVERIFY( lpduFound == true);
  QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS)    == 1);
  QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES)         == 0);
  QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS)         == 0);

  Bytes data3(TO_BYTES(r3));
  lpduFound = lpdu.buildFromBytes( data3);
  QVERIFY( lpduFound == true);

  Bytes data4(TO_BYTES(r4));
  lpduFound = lpdu.buildFromBytes( data4);
  QVERIFY( lpduFound == true);

  /* create 4x a good lpdu */
  Bytes data5(TO_BYTES(r1));
  Bytes data6(data5);
  data6.insert(data6.end(), data5.begin(), data5.end());
  data6.insert(data6.end(), data5.begin(), data5.end());
  data6.insert(data6.end(), data5.begin(), data5.end());

  /* ensure we receive 4 good ones */
  for (i=0; i<4; i++)
  {
    lpdu.reset();
    lpduFound = lpdu.buildFromBytes( data6);
    QVERIFY( lpduFound == true);
    QVERIFY (data6.size() == (sizeof(r1)*(3-i)));
    QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS) == (2+i));
    QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES)      == 0);
    QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS)      == 0);
  }
 
  /* header only lpdu */
  lpdu.reset();
  Bytes data7(TO_BYTES(r0));
  lpduFound = lpdu.buildFromBytes( data7);
  QVERIFY( lpduFound == true);
  QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS)   == 6);
  QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES)        == 0);
  QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS)        == 0);

  /* building of two lpdus coming in across two simulated reads */
  /* with the break on the last byte of the last CRC            */
  lpdu.reset();
  Bytes data8(TO_BYTES(twoLpdus));
  Bytes data9;
  data9.push_back(data8.back());
  data8.pop_back();

  lpduFound = lpdu.buildFromBytes( data8);
  QVERIFY( lpduFound == true);
  QVERIFY (lpdu.ab.size() == 15);  /* manually counted */
  QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS)   == 7);
  QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES)        == 0);
  QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS)        == 0);
  QVERIFY( data8.size() == 17);

  lpdu.reset(); 

  lpduFound = lpdu.buildFromBytes( data8);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 17);
  QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS)   == 8);
  QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES)        == 0);
  QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS)        == 0);

  lpduFound = lpdu.buildFromBytes( data9);
  QVERIFY( lpduFound == true);
  QVERIFY (lpdu.getStat(Lpdu::RX_START_OCTETS)   == 8);
  QVERIFY (lpdu.getStat(Lpdu::LOST_BYTES)        == 0);
  QVERIFY (lpdu.getStat(Lpdu::CRC_ERRORS)        == 0);

  lpdu.reset();

  /* test known bad cases */
  Bytes data10(TO_BYTES(r10));
  lpduFound = lpdu.buildFromBytes( data10);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data11(TO_BYTES(r11));
  lpduFound = lpdu.buildFromBytes( data11);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data12(TO_BYTES(r12));
  lpduFound = lpdu.buildFromBytes( data12);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data13(TO_BYTES(r13));
  lpduFound = lpdu.buildFromBytes( data13);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data14(TO_BYTES(r14));
  lpduFound = lpdu.buildFromBytes( data14);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data15(TO_BYTES(r15));
  lpduFound = lpdu.buildFromBytes( data15);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data16(TO_BYTES(r16));
  lpduFound = lpdu.buildFromBytes( data16);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);

  lpdu.reset();
  Bytes data20(TO_BYTES(r20));
  lpduFound = lpdu.buildFromBytes( data20);
  QVERIFY( lpduFound == false);
  QVERIFY (lpdu.ab.size() == 0);
}