Exemple #1
0
TEST (json, fetch_object)
{
	std::string string1 ("{ \"thing\": \"junktest\" }");
	std::stringstream stream1 (string1);
	json_upgrade_test object1;
	auto error1 (rai::fetch_object (object1, stream1));
	ASSERT_FALSE (error1);
	ASSERT_EQ ("changed", object1.text);
	boost::property_tree::ptree tree1;
	stream1.seekg (0);
	boost::property_tree::read_json (stream1, tree1);
	ASSERT_EQ ("changed", tree1.get <std::string> ("thing"));
	std::string string2 ("{ \"thing\": \"junktest2\" }");
	std::stringstream stream2 (string2);
	json_upgrade_test object2;
	auto error2 (rai::fetch_object (object2, stream2));
	ASSERT_FALSE (error2);
	ASSERT_EQ ("junktest2", object2.text);
	ASSERT_EQ ("{ \"thing\": \"junktest2\" }", string2);
	std::string string3 ("{ \"thing\": \"error\" }");
	std::stringstream stream3 (string3);
	json_upgrade_test object3;
	auto error3 (rai::fetch_object (object3, stream3));
	ASSERT_TRUE (error3);
	std::fstream stream4;
	rai::open_or_create (stream4, rai::unique_path().string());
	json_upgrade_test object4;
	auto error4 (rai::fetch_object (object4, stream4));
	ASSERT_FALSE (error4);
	ASSERT_EQ ("created", object4.text);
	boost::property_tree::ptree tree2;
	stream4.seekg (0);
	boost::property_tree::read_json (stream4, tree2);
	ASSERT_EQ ("created", tree2.get <std::string> ("thing"));
}
Exemple #2
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    printf("Please Input Process Num :\n");
    int Pnumber;
    QTextStream stream(stdin);
    stream >> Pnumber;

    printf("Please Input fileBase Num  :\n");
    int fileBaseNum;
    QTextStream stream1(stdin);
    stream1 >> fileBaseNum;

    printf("Please Input fileSize (kB) :\n");
    int fileSize;
    QTextStream stream2(stdin);
    stream2 >> fileSize;

    readConfig read;

    QString program = read.map["writeFileEXE"] ;

    QTime timer;
    timer.start();

    CreateProcess Cprocess(Pnumber, fileBaseNum, program, fileSize, timer);
    Cprocess.clear_pro();

    return 0;
}
Exemple #3
0
QMimeData* KexiFieldListModel::mimeData(const QModelIndexList& indexes) const
{
    if (!d->schema) {
        return new QMimeData();
    }

    QString sourceMimeType;
    QString sourceName;
    QStringList fields;

    QMimeData *mimedata = new QMimeData();
    QByteArray fielddata;
    QDataStream stream1(&fielddata, QIODevice::WriteOnly);

    if (d->schema->table()) {
        sourceMimeType = "kexi/table";
    } else if (d->schema->query()) {
        sourceMimeType = "kexi/query";
    }

    sourceName = d->schema->name();

    foreach (const QModelIndex &idx, indexes) {
        fields << data(idx, Qt::DisplayRole).toString();
    }
Exemple #4
0
void Ventana_Principal::AnalisisJSON()
{
    Pestana *actual = (Pestana*)ui->tabWidget->currentWidget();

    if(actual != NULL){
        QFile file("temp.txt"); //SE CREA UN ARCHIVO TEMPORAL PARA COMPILARLO
        if ( file.open( file.WriteOnly ) ) { //BUFFER PARA EL TEXTO QUE SE DESEA COMPILAR
            QTextStream stream1( &file );
            stream1 << actual->enviar_texto();
        }

        const char* x = "temp.txt";
        FILE* input = fopen(x, "r" );

        errores_json->ven()->clear();
        SetVentanita_json(errores_json->ven());
        setFila();
        setColumna();
        setEdit(actual->textedit());
        yyrestart(input);//SE PASA LA CADENA DE ENTRADA A FLEX
        yyparse();//SE INICIA LA COMPILACION

        ArbolJ *nuevo = setArbolito();
        if(nuevo != NULL && correctojson() != 1){
            //nuevo->Dibujar();
        }
    }
}
void tst_QContactRelationship::datastream()
{
    QSKIP("Datastream is not currently supported when using the QContactIdMock class");
    //After QContactId introduction, the QCOMPARE at then end this case will fail, since
    //relationshipOut will contain contacts with "null" QContactIds, whereas
    //relationshipIn will contain contacts with QContactIds referring to
    //manager "a", which is an invalid one.

    QByteArray buffer;
    QDataStream stream1(&buffer, QIODevice::WriteOnly);
    QContactRelationship relationshipIn;
    QContact contact1;
    contact1.setId(QContactIdMock::createId("a", 1));
    relationshipIn.setFirst(contact1);
    QContact contact2;
    contact2.setId(QContactIdMock::createId("a", 2));
    relationshipIn.setSecond(contact2);
    relationshipIn.setRelationshipType(QContactRelationship::HasMember());
    stream1 << relationshipIn;

    QVERIFY(buffer.size() > 0);

    QDataStream stream2(buffer);
    QContactRelationship relationshipOut;
    stream2 >> relationshipOut;
    QCOMPARE(relationshipOut, relationshipIn);
}
int main() {
	//get camera stream
	VideoCapture stream1(countCameras());   //id of video device
	if (!stream1.isOpened()) {
		cout << "cannot open camera";
	}

	//load up face detection
	String face_cascade_name = "haarcascade_frontalface_alt.xml";
	if(!face_cascade.load(face_cascade_name)){
		cout << "Could not find face cascade file: " + face_cascade_name + "\n";
		return -1;
	}
	//load lookup tables
	calcGradientLookup();

	//loop forever
	while (true) {
		Mat cameraFrame;
		stream1.read(cameraFrame);

		getGazePosition(cameraFrame);

		if (waitKey(30) >= 0)
		break;
	}
	return 0;
}
Exemple #7
0
/**
Opens the exported file and compares it with expected vCard file passed as argument.
*/
void CCntPBAPSupport::CompareFilesL(RReadStream& aCompareStream)
	{
	RFile exportedFile;	
	TInt err = exportedFile.Open(iFsSession, KTempExportFile(), EFileRead);
	if (err != KErrNone)
		{
		ReportFileErrorL(err, KTempExportFile());	
		}
	CleanupClosePushL(exportedFile);
	RFileReadStream stream1(exportedFile);
	CleanupClosePushL(stream1);

	TBuf8<0x80> bufO,bufC;
	
	TInt line = 1;
	do {
		TRAP(err, stream1.ReadL(bufO, TChar(0xa)));
		if (err == KErrNone || err == KErrEof)
			{
			TRAP(err, aCompareStream.ReadL(bufC, TChar(0xa)));	
			}
		if (err != KErrNone && err != KErrEof)
			{
			User::Leave(err);	
			}
		test(CompareLines(bufO, bufC));
		++line;
		} while (err != KErrEof);
	CleanupStack::PopAndDestroy(2,&exportedFile);
	}
Exemple #8
0
// Test asynchronous HTTP with an error status returned by the server.
void read_stream_asynchronous_http_not_found_test()
{
  http_server server;
  std::string port = boost::lexical_cast<std::string>(server.port());

  std::string request =
    "GET / HTTP/1.0\r\n"
    "Host: localhost:" + port + "\r\n"
    "Accept: */*\r\n"
    "Connection: close\r\n\r\n";
  std::string response =
    "HTTP/1.0 404 Not Found\r\n"
    "Content-Length: 9\r\n"
    "Content-Type: text/plain\r\n\r\n";
  std::string content = "Not Found";

  server.start(request, 0, response, 0, content);

  boost::asio::io_service io_service;
  urdl::read_stream stream1(io_service);

  boost::system::error_code ec;
  std::size_t bytes_transferred = 0;
  handler h = { ec, bytes_transferred };

  stream1.async_open("http://localhost:" + port + "/", h);
  io_service.run();

  bool request_matched = server.stop();

  BOOST_CHECK(request_matched);
  BOOST_CHECK(ec == urdl::http::errc::not_found);
}
Exemple #9
0
void DigManager::shortDigAnswer(const QStringList hostname, QByteArray bufferData, QByteArray bufferError)
{
    Q_UNUSED(hostname);

    /*
     * TODO: remove this check with QT5 QStandardPaths::findExecutable.
     *
     */
    if (!bufferData.size() && bufferError.size()) {
        qWarning() << "Error: Dig is not installed.";
        return;
    }

    QString buff1(bufferData);
    QTextStream stream1(&buff1);
    QString line;

    m_elemObjUtil->setHostName(m_hostNameLocal);

    while (!stream1.atEnd()) {
        line = stream1.readLine();
        m_elemObjUtil->setInfoLookup(line);
    }

    // clear thread
    bufferData.clear();
    bufferError.clear();
}
/** Compares two files, excluding the REV property, as it doesn't remain the same always
@param	aExpectedFile The expected vcf file
@param	aFile This is the vcf file produced, and will be compared against aExpectedFile
*/
TBool CTestCompareCntFiles::CompareWholeFileL(const TDesC& aExpectedFile, const TDesC& aFile)
	{
	User::LeaveIfError(iFsSession.Connect());
	CleanupClosePushL(iFsSession);
	
	RFile fileExpected;
	RFile fileOutput;
	CleanupClosePushL(fileExpected);
	CleanupClosePushL(fileOutput);
	
	TInt err;
	err = fileExpected.Open(iFsSession, aExpectedFile, EFileRead);

	if (err != KErrNone)
		{
		User::Leave(err);
		}

	err = fileOutput.Open(iFsSession, aFile, EFileWrite);
	if (err != KErrNone)
		{
		User::Leave(err);
		}

	RFileReadStream stream1(fileExpected);
	RFileReadStream stream2(fileOutput);
	CleanupClosePushL(stream1);
	CleanupClosePushL(stream2);
	TBuf8<0x80> bufO,bufC;
	TBool flag = ETrue;
	TInt line = 1;
	do
		{
		TRAP(err, stream1.ReadL(bufO, KLinefeedChar));
		if (err == KErrNone || err == KErrEof)
			TRAP(err, stream2.ReadL(bufC, KLinefeedChar));
		if (err != KErrNone && err != KErrEof)
			User::Leave(err);
		if (CompareLine(bufO, bufC) == EFalse)
			{
			flag = EFalse;
			break;
			}
		++line;
		}
	while (err != KErrEof);

	CleanupStack::PopAndDestroy(4, &fileExpected);
	CleanupStack::PopAndDestroy(&iFsSession);
    iFsSession.Close();
	
	if(flag)
		{
		return ETrue;		
		}
	else
		{
		return EFalse;
		}		
	}
Exemple #11
0
// Test synchronous HTTP.
void read_stream_synchronous_http_test()
{
  http_server server;
  std::string port = boost::lexical_cast<std::string>(server.port());

  std::string request =
    "GET / HTTP/1.0\r\n"
    "Host: localhost:" + port + "\r\n"
    "Accept: */*\r\n"
    "Connection: close\r\n\r\n";
  std::string response =
    "HTTP/1.0 200 OK\r\n"
    "Content-Length: 13\r\n"
    "Content-Type: text/plain\r\n\r\n";
  std::string content = "Hello, World!";

  server.start(request, 0, response, 0, content);

  boost::asio::io_service io_service;
  urdl::read_stream stream1(io_service);

  stream1.open("http://localhost:" + port + "/");

  std::string returned_content(stream1.content_length(), 0);
  boost::asio::read(stream1, boost::asio::buffer(
        &returned_content[0], returned_content.size()));

  bool request_matched = server.stop();

  BOOST_CHECK(request_matched);
  BOOST_CHECK(stream1.content_type() == "text/plain");
  BOOST_CHECK(stream1.content_length() == 13);
  BOOST_CHECK(returned_content == content);
}
Exemple #12
0
details::details(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::details)
{
    ui->setupUi(this);
    this->setWindowTitle("TICKET CONFIRMED!!!");
    QString filename="D:\\qt\\irctc3\\p-detail.txt";
    QFile file(filename);
    if(!file.exists()){
        qDebug() << "NO exist "<<filename;
    }else{
        qDebug() << filename<<" exits...";
    }
    QString line;
    QString name,age,gender;
    int i=0;
    ui->label->setText(ui->label->text()+"\nS.No.\tName\tAge\tGender\n");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
    QTextStream stream(&file);
    while (!stream.atEnd()){
         line = stream.readLine();

           name = line.split(" ").at(0);
           age = line.split(" ").at(1);
           gender=line.split(" ").at(2);
            i++;
            ui->label->setText(ui->label->text()+"\n"+QString::number(i)+"\t"+name+"\t"+age+"\t"+gender);
        }
    }

    file.close();

    QString src,dst,date,arr_time,fare,avail,train_no,train_name,day;
   QString filename1="D:\\qt\\irctc3\\select.txt";
   QFile file1(filename1);
   if(!file1.exists()){
       qDebug() << "NO exist "<<filename1;
   }else{
       qDebug() << filename1<<" exits...";
   }
   QString line1;
   if (file1.open(QIODevice::ReadOnly | QIODevice::Text)){
   QTextStream stream1(&file1);
   while (!stream1.atEnd()){
        line1 = stream1.readLine();

          train_no= line1.split(" ").at(0);
          train_name= line1.split(" ").at(1);
          arr_time= line1.split(" ").at(2);
          avail= line1.split(" ").at(3);
          fare= line1.split(" ").at(4);
       }
   }
   file1.close();

   int f=fare.toInt();
   f=(i)*f;
   ui->label->setText(ui->label->text()+"\n\nFare Details:\nTicket Fare: "+QString ::number(f)+"\nService Charge: 22.90\ntotal Fare: "+QString :: number(f+22.9) );
}
Exemple #13
0
void ImageWidget::readImageInfo()
{
     int nn = socket->bytesAvailable();
     if(bytesReceived <= 0)
     {
         if(socket->bytesAvailable() > 0)
         {
            info = new ImageInfo();
            bytesReceived = socket->bytesAvailable();
            QByteArray tt = socket->readAll();

            QByteArray bt = tt.left(8);
            QDataStream stream1(bt);
            qint64 infosize;
            stream1 >>infosize;
            tt.remove(0,8);

            QByteArray ct = tt.left(8);
            QDataStream stream2(ct);
            stream2 >>totalBytes;
            tt.remove(0,8);

            QByteArray infoData = tt.left((int)infosize);
            tt.remove(0,(int)infosize);

            QString readData = QString::fromUtf8(infoData);
            QStringList ColumnList  = readData.split(":");
            info->id = ColumnList.at(0);
            info->title = ColumnList.at(1);
            info->size = ColumnList.at(2);
            info->path = ColumnList.at(3);
            info->bm = tt;

            if(bytesReceived == totalBytes)
            {
               socket->disconnectFromHost();
               imageInfoList.append(*info);
               insertTableRow(*info);
               currentNum++;
               if(currentNum < imageCount)
               {
                   ui->progressBar->setValue(currentNum);
                   GetImageInfo(currentNum);
               }else{
                   disconnect(socket,SIGNAL(readyRead()),this,SLOT(readImageInfo()));
                   connect(playlist,SIGNAL(clicked(QModelIndex)),this,SLOT(ImageChange(QModelIndex)));
                   connect(playlist, SIGNAL(cellChanged(int,int)), this, SLOT(CheckBoxChanged(int, int)));
                   ui->progressBar->hide();
               }
            }
         }
void tst_QContactDetail::datastream()
{
    QByteArray buffer;
    QDataStream stream1(&buffer, QIODevice::WriteOnly);
    QContactDetail detailIn("definition");
    detailIn.setValue("key1", "value1");
    detailIn.setValue("key2", "value2");
    stream1 << detailIn;

    QVERIFY(buffer.size() > 0);

    QDataStream stream2(buffer);
    QContactDetail detailOut;
    stream2 >> detailOut;
    QCOMPARE(detailOut, detailIn);
}
Exemple #15
0
TEST (message, confirm_ack_serialization)
{
	rai::keypair key1;
	auto vote (std::make_shared<rai::vote> (key1.pub, key1.prv, 0, std::unique_ptr<rai::block> (new rai::send_block (0, 1, 2, key1.prv, 4, 5))));
	rai::confirm_ack con1 (vote);
	std::vector<uint8_t> bytes;
	{
		rai::vectorstream stream1 (bytes);
		con1.serialize (stream1);
	}
	rai::bufferstream stream2 (bytes.data (), bytes.size ());
	bool error;
	rai::message_header header (error, stream2);
	rai::confirm_ack con2 (error, stream2, header);
	ASSERT_FALSE (error);
	ASSERT_EQ (con1, con2);
}
Exemple #16
0
void CCntPBAPSupport::CompareExportsL(const TDesC8& aExpected)
    {
    
	RFile exportedFile;	
	TInt err = exportedFile.Open(iFsSession, KTempExportFile(), EFileRead);
	if (err != KErrNone)
		{
		ReportFileErrorL(err, KTempExportFile());	
		}
	CleanupClosePushL(exportedFile);
	RFileReadStream stream1(exportedFile);
	CleanupClosePushL(stream1);

	TBuf8<0x80> bufO;
	
	TInt line = 1;
	do {
		TRAP(err, stream1.ReadL(bufO, TChar(0xa)));
		if (err != KErrNone && err != KErrEof)
			{
			User::Leave(err);	
			}
        			
    	_LIT8(KPropREV,"REV:");
    	_LIT8(KPropUID,"UID:");
		TBufC8<4> first4char(bufO.Left(4));
		if(!first4char.Compare(KPropREV()) || !first4char.Compare(KPropUID()))
		    {
		    continue;
		    }
		
        if (KErrNotFound == aExpected.Find(bufO))
        	{
        	TBuf<256> info;
            info.Copy(bufO);
            TRefByValue<const TDesC> format(info);
            test.Printf(format);
            test (EFalse);
        	}
		++line;
		} while (err != KErrEof);
	CleanupStack::PopAndDestroy(2,&exportedFile);
    }
Exemple #17
0
void CAgentTest::CompareFilesL(const TDesC& aOutputFile,const TDesC& aCompareFile)
	{
	RFs fsSession;
	User::LeaveIfError(fsSession.Connect());
	RFile file1,file2;
	TInt err=file1.Open(fsSession, aOutputFile, EFileRead);
	if (err!=KErrNone)
		{
		User::Leave(err);	
		}
	
	CleanupClosePushL(file1);
	err=file2.Open(fsSession, aCompareFile, EFileRead);
	
	if (err!=KErrNone)
		{
		User::Leave(err);	
		}

	
	CleanupClosePushL(file2);
	RFileReadStream stream1(file1);
	RFileReadStream stream2(file2);
	CleanupClosePushL(stream1);
	CleanupClosePushL(stream2);
	TBuf8<0x80> bufO,bufC;
	TInt line=1;
	do {
		TRAP(err,stream1.ReadL(bufO,TChar(0xa)));
		if (err==KErrNone || err==KErrEof)
		{
		TRAP(err,stream2.ReadL(bufC,TChar(0xa)));	
		}
		if (err!=KErrNone && err!=KErrEof)
		{
		User::Leave(err);	
		}
		
		CompareLines(bufO, bufC);
		++line;
		} while (err!=KErrEof);
	CleanupStack::PopAndDestroy(4,&file1);
	}
Exemple #18
0
void Ventana_Principal::AnalisisJSLT()
{
    Pestana *actual = (Pestana*)ui->tabWidget->currentWidget();

    if(actual != NULL){
        QFile file("temp2.txt"); //SE CREA UN ARCHIVO TEMPORAL PARA COMPILARLO
        if ( file.open( file.WriteOnly ) ) { //BUFFER PARA EL TEXTO QUE SE DESEA COMPILAR
            QTextStream stream1( &file );
            stream1 << actual->enviar_texto();
        }

        //INICIO DE AUTOCOMPLETADO

        completer->setModel(modelFromFile("/home/jerduar/COMPI2/palabras.txt"));
        completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
        completer->setCaseSensitivity(Qt::CaseInsensitive);
        completer->setWrapAround(false);
        actual->setCompleter(completer);


        const char* x = "temp2.txt";
        FILE* input = fopen(x, "r" );
        this->errores->ven()->clear();
        SetVentana(this->errores->ven());
        SetVentanita(this->errores->ven());
        jjsetFila();
        jjsetColumna();
        setEdit_jslt(actual->textedit());
        jjrestart(input);//SE PASA LA CADENA DE ENTRADA A FLEX
        jjparse();//SE INICIA LA COMPILACION


        ArbolAST *nuevo;
        nuevo = setArbol();
        if(nuevo != NULL){
            //nuevo->Dibujar();
        }else{
            //QMessageBox::information(this,"ÁRBOL","El árbol es nulo");
        }
    }
}
Exemple #19
0
int main()
{
    typedef std::vector< copy_ptr<process_data> >::iterator iterator;
    assert(spawn_status::last_value == GEPD::ExitStatus::min);

    int const timeout = -1; // milliseconds
    realloc_ptr<unsigned char> erlang_buffer(32768, 4194304); // 4MB
    realloc_ptr<unsigned char> stream1(1, 16384);
    realloc_ptr<unsigned char> stream2(1, 16384);
    int status;
    if ((status = GEPD::init()))
        return status;
    int count;
    while ((status = GEPD::wait(count, timeout, erlang_buffer,
                                stream1, stream2)) == GEPD::ExitStatus::ready)
    {
        iterator itr = processes.begin();
        while (itr != processes.end() && count > 0)
        {
            if ((status = (*itr)->check(count, erlang_buffer)))
            {
                if (status != GEPD::ExitStatus::error_HUP)
                    return status;
                if ((status = (*itr)->flush(count, erlang_buffer)))
                    return status;
                iterator const dead = itr;
                (*dead)->close();
                for (++itr; itr != processes.end(); ++itr)
                    (*itr)->shift();
                itr = processes.erase(dead);
            }
            else
            {
                ++itr;
            }
        }
    }
    return status;
}
void tst_QContactRelationship::datastream()
{
    QByteArray buffer;
    QDataStream stream1(&buffer, QIODevice::WriteOnly);
    QContactRelationship relationshipIn;
    QContactId id1;
    id1.setManagerUri("a");
    id1.setLocalId(1);
    relationshipIn.setFirst(id1);
    QContactId id2;
    id2.setManagerUri("b");
    id2.setLocalId(2);
    relationshipIn.setSecond(id2);
    relationshipIn.setRelationshipType(QContactRelationship::HasMember);
    stream1 << relationshipIn;

    QVERIFY(buffer.size() > 0);

    QDataStream stream2(buffer);
    QContactRelationship relationshipOut;
    stream2 >> relationshipOut;
    QCOMPARE(relationshipOut, relationshipIn);
}
Trampoline AmbTest(Search &s)
{
	CapturedVar<int> n, m;
	CapturedCont c1, c2, c3;
	UncountedCont c1_u = c1, c2_u = c2, c3_u = c3;
	combine_refs(c1, c2, c3);

	//note it can't safely use Search inside of functions that return a value
	*c1 = [=](Search &s) { return stream1(s, n, trampoline(c2_u, s)); };
	*c2 = [=](Search &s) { return stream2(s, m, trampoline(c3_u, s)); };
	*c3 = [=](Search &s)
	{
		if (*n != *m) return s.fail();
		else {
			s.results.insert_or_assign("n", *n);
			s.results.insert_or_assign("m", *m);
			return end_search;
		}
	};
	cout << c1.get()->use_count() << endl;
	cout << c2.get()->use_count() << endl;
	cout << c3.get()->use_count() << endl;
	return trampoline(c1, s);
}
void tst_QOrganizerCollection::datastream()
{
    // collection datastreaming
    QByteArray buffer;
    QOrganizerCollection collectionIn;
    collectionIn.setMetaData("key", "value");
    QOrganizerCollection collectionOut;
    QOrganizerCollectionId originalId;

    // first, stream an item with a complete id
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        QOrganizerManager om("memory");
        QVERIFY(om.saveCollection(&collectionIn)); // fill in its ID
        originalId = collectionIn.id();
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
    }

    // second, stream an item with an id with the mgr uri set, local id null
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        collectionIn.setId(QOrganizerCollectionId());
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
    }

    /* TODO: Review tests
    // third, stream an item with an id with the mgr uri null, local id set
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        QOrganizerCollectionId modifiedId = originalId;
        modifiedId.setManagerUri(QString()); // this will clear the local id!
        modifiedId.setId(originalId.localId()); // so reset it and make sure nothing bad happens.
        collectionIn.setId(modifiedId);
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QVERIFY(collectionOut.metaData() == collectionIn.metaData());
        QVERIFY(collectionOut.id() != collectionIn.id()); // no manager uri of input :. won't be serialized.
    }*/

    // fourth, stream an item with a null id
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        collectionIn.setId(QOrganizerCollectionId());
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QVERIFY(collectionOut.metaData() == collectionIn.metaData());
        QVERIFY(collectionOut.id() == collectionIn.id()); // should both be null ids.
    }

    // id datastreaming
    buffer.clear();
    QOrganizerCollectionId inputId;
    QOrganizerCollectionId outputId;

    // first, stream the whole id (mgr uri set, local id set)
    {
        inputId = originalId;
        QString serializedId = inputId.toString();
        outputId = QOrganizerCollectionId::fromString(serializedId);
        QCOMPARE(inputId, outputId);

        inputId = originalId;
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    /* TODO: review test
    // second, stream a partial id (mgr uri null, local id set)
    {
        inputId.setManagerUri(QString());
        inputId.setId(originalId.localId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;

        // because the manager uri is null, we cannot stream it in.
        QVERIFY(outputId.isNull());
        QVERIFY(!inputId.isNull());
    }

    // third, stream a partial id (mgr uri set, local id null).
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setId(QOrganizerCollectionId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }*/

    // fourth, stream a null id
    {
        inputId = QOrganizerCollectionId();
        QString serializedId = inputId.toString();
        outputId = QOrganizerCollectionId::fromString(serializedId);
        QCOMPARE(inputId, outputId);

        inputId = QOrganizerCollectionId();
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    /* TODO: review test
    // fifth, stream an id after changing it's manager uri.
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setId(originalId.localId());
        inputId.setManagerUri("test manager uri"); // should clear the local id.
        QVERIFY(inputId.localId() == QOrganizerCollectionId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    // sixth, stream an id after changing it's manager uri and resetting the local id.
    // this should cause great problems, because the manager doesn't exist so it shouldn't
    // be able to deserialize.  Make sure it's handled gracefully.
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setManagerUri("test manager uri"); // should clear the local id.
        inputId.setId(originalId.localId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QVERIFY(outputId.isNull());
    } */
}
Exemple #23
0
DEF_TEST(FILEStreamWithOffset, r) {
    if (GetResourcePath().isEmpty()) {
        return;
    }

    SkString filename = GetResourcePath("images/baby_tux.png");
    SkFILEStream stream1(filename.c_str());
    if (!stream1.isValid()) {
        ERRORF(r, "Could not create SkFILEStream from %s", filename.c_str());
        return;
    }
    REPORTER_ASSERT(r, stream1.hasLength());
    REPORTER_ASSERT(r, stream1.hasPosition());

    // Seek halfway through the file. The second SkFILEStream will be created
    // with the same filename and offset and therefore will treat that offset as
    // the beginning.
    const size_t size = stream1.getLength();
    const size_t middle = size / 2;
    if (!stream1.seek(middle)) {
        ERRORF(r, "Could not seek SkFILEStream to %lu out of %lu", middle, size);
        return;
    }
    REPORTER_ASSERT(r, stream1.getPosition() == middle);

    FILE* file = sk_fopen(filename.c_str(), kRead_SkFILE_Flag);
    if (!file) {
        ERRORF(r, "Could not open %s as a FILE", filename.c_str());
        return;
    }

    if (fseek(file, (long) middle, SEEK_SET) != 0) {
        ERRORF(r, "Could not fseek FILE to %lu out of %lu", middle, size);
        return;
    }
    SkFILEStream stream2(file);

    const size_t remaining = size - middle;
    SkAutoTMalloc<uint8_t> expected(remaining);
    REPORTER_ASSERT(r, stream1.read(expected.get(), remaining) == remaining);

    auto test_full_read = [&r, &expected, remaining](SkStream* stream) {
        SkAutoTMalloc<uint8_t> actual(remaining);
        REPORTER_ASSERT(r, stream->read(actual.get(), remaining) == remaining);
        REPORTER_ASSERT(r, !memcmp(expected.get(), actual.get(), remaining));

        REPORTER_ASSERT(r, stream->getPosition() == stream->getLength());
        REPORTER_ASSERT(r, stream->isAtEnd());
    };

    auto test_rewind = [&r, &expected, remaining](SkStream* stream) {
        // Rewind goes back to original offset.
        REPORTER_ASSERT(r, stream->rewind());
        REPORTER_ASSERT(r, stream->getPosition() == 0);
        SkAutoTMalloc<uint8_t> actual(remaining);
        REPORTER_ASSERT(r, stream->read(actual.get(), remaining) == remaining);
        REPORTER_ASSERT(r, !memcmp(expected.get(), actual.get(), remaining));
    };

    auto test_move = [&r, &expected, size, remaining](SkStream* stream) {
        // Cannot move to before the original offset.
        REPORTER_ASSERT(r, stream->move(- (long) size));
        REPORTER_ASSERT(r, stream->getPosition() == 0);

        REPORTER_ASSERT(r, stream->move(std::numeric_limits<long>::min()));
        REPORTER_ASSERT(r, stream->getPosition() == 0);

        SkAutoTMalloc<uint8_t> actual(remaining);
        REPORTER_ASSERT(r, stream->read(actual.get(), remaining) == remaining);
        REPORTER_ASSERT(r, !memcmp(expected.get(), actual.get(), remaining));

        REPORTER_ASSERT(r, stream->isAtEnd());
        REPORTER_ASSERT(r, stream->getPosition() == remaining);

        // Cannot move beyond the end.
        REPORTER_ASSERT(r, stream->move(1));
        REPORTER_ASSERT(r, stream->isAtEnd());
        REPORTER_ASSERT(r, stream->getPosition() == remaining);
    };

    auto test_seek = [&r, &expected, middle, remaining](SkStream* stream) {
        // Seek to an arbitrary position.
        const size_t arbitrary = middle / 2;
        REPORTER_ASSERT(r, stream->seek(arbitrary));
        REPORTER_ASSERT(r, stream->getPosition() == arbitrary);
        const size_t miniRemaining = remaining - arbitrary;
        SkAutoTMalloc<uint8_t> actual(miniRemaining);
        REPORTER_ASSERT(r, stream->read(actual.get(), miniRemaining) == miniRemaining);
        REPORTER_ASSERT(r, !memcmp(expected.get() + arbitrary, actual.get(), miniRemaining));
    };

    auto test_seek_beginning = [&r, &expected, remaining](SkStream* stream) {
        // Seek to the beginning.
        REPORTER_ASSERT(r, stream->seek(0));
        REPORTER_ASSERT(r, stream->getPosition() == 0);
        SkAutoTMalloc<uint8_t> actual(remaining);
        REPORTER_ASSERT(r, stream->read(actual.get(), remaining) == remaining);
        REPORTER_ASSERT(r, !memcmp(expected.get(), actual.get(), remaining));
    };

    auto test_seek_end = [&r, remaining](SkStream* stream) {
        // Cannot seek past the end.
        REPORTER_ASSERT(r, stream->isAtEnd());

        REPORTER_ASSERT(r, stream->seek(remaining + 1));
        REPORTER_ASSERT(r, stream->isAtEnd());
        REPORTER_ASSERT(r, stream->getPosition() == remaining);

        const size_t middle = remaining / 2;
        REPORTER_ASSERT(r, stream->seek(middle));
        REPORTER_ASSERT(r, !stream->isAtEnd());
        REPORTER_ASSERT(r, stream->getPosition() == middle);

        REPORTER_ASSERT(r, stream->seek(remaining * 2));
        REPORTER_ASSERT(r, stream->isAtEnd());
        REPORTER_ASSERT(r, stream->getPosition() == remaining);

        REPORTER_ASSERT(r, stream->seek(std::numeric_limits<long>::max()));
        REPORTER_ASSERT(r, stream->isAtEnd());
        REPORTER_ASSERT(r, stream->getPosition() == remaining);
    };


    std::function<void (SkStream* stream, bool recurse)> test_all;
    test_all = [&](SkStream* stream, bool recurse) {
        REPORTER_ASSERT(r, stream->getLength() == remaining);
        REPORTER_ASSERT(r, stream->getPosition() == 0);

        test_full_read(stream);
        test_rewind(stream);
        test_move(stream);
        test_seek(stream);
        test_seek_beginning(stream);
        test_seek_end(stream);

        if (recurse) {
            // Duplicate shares the original offset.
            auto duplicate = stream->duplicate();
            if (!duplicate) {
                ERRORF(r, "Failed to duplicate the stream!");
            } else {
                test_all(duplicate.get(), false);
            }

            // Fork shares the original offset, too.
            auto fork = stream->fork();
            if (!fork) {
                ERRORF(r, "Failed to fork the stream!");
            } else {
                REPORTER_ASSERT(r, fork->isAtEnd());
                REPORTER_ASSERT(r, fork->getLength() == remaining);
                REPORTER_ASSERT(r, fork->rewind());

                test_all(fork.get(), false);
            }
        }
    };

    test_all(&stream2, true);
}
void tst_QOrganizerItemDetailDefinition::testStreaming()
{
    QMap<QString, QOrganizerItemDetailFieldDefinition> allFields;

    QVariantList allowedStrings;
    allowedStrings << QString("First") << QString("Second");

    // generate some field definitions
    QOrganizerItemDetailFieldDefinition dfd;
    dfd.setDataType(QVariant::String);
    dfd.setAllowableValues(allowedStrings);
    allFields.insert("TestFieldDefinition", dfd);

    dfd.setDataType(QVariant::Int);
    dfd.setAllowableValues(QVariantList());
    allFields.insert("TestCount", dfd);

    // now create our detail definition
    QOrganizerItemDetailDefinition dd;
    dd.setName("TestDefinitionName");
    dd.setUnique(true);
    dd.setFields(allFields);

    // testing streaming of field definition, with no allowable values set
    {
        QByteArray buffer;
        QOrganizerItemDetailFieldDefinition fieldDefIn = allFields.value("TestCount");
        QOrganizerItemDetailFieldDefinition fieldDefOut;
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << fieldDefIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> fieldDefOut;
        QVERIFY(fieldDefIn == fieldDefOut);
    }

    // testing streaming of field definition, with specific allowable values set
    {
        QByteArray buffer;
        QOrganizerItemDetailFieldDefinition fieldDefIn = allFields.value("TestFieldDefinition");
        QOrganizerItemDetailFieldDefinition fieldDefOut;
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << fieldDefIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> fieldDefOut;
        QVERIFY(fieldDefIn == fieldDefOut);
    }

    // testing streaming of detail definition
    {
        QByteArray buffer;
        QOrganizerItemDetailDefinition defIn = dd;
        QOrganizerItemDetailDefinition defOut;
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << defIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> defOut;
        QVERIFY(defIn == defOut);
    }

    // now try inserting and removing a field, streaming again, and testing.
    {
        // remove the field
        QByteArray buffer;
        QOrganizerItemDetailDefinition defIn = dd;
        defIn.removeField("TestCount");
        QVERIFY(defIn != dd);
        QOrganizerItemDetailDefinition defOut;
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << defIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> defOut;
        QVERIFY(defIn == defOut);
    }

    {
        // re-add the field.
        QByteArray buffer;
        QOrganizerItemDetailDefinition defIn = dd;
        defIn.removeField("TestCount"); // remove and reinsert the field
        QVERIFY(defIn != dd);
        defIn.insertField("TestCount", dfd);
        QVERIFY(defIn == dd);
        QOrganizerItemDetailDefinition defOut;
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << defIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> defOut;
        QVERIFY(defIn == defOut);
        QVERIFY(defOut == dd); // should be equal to the original.
    }
}
bool CGloryAndTitleServer::Init()
{
	//加载荣耀基本数据
	dwt::ifstream stream("Data\\荣耀和称号\\GloryTable.txt");
	if (!stream.is_open())
		return false;

	char buffer[2048];
	SGloryBaseData *pData = 0;

	while (!stream.eof())
	{
		stream.getline(buffer, sizeof(buffer));
		if (0 == buffer[0] || '//' == (*(LPWORD)buffer))
			continue;

		std::strstream linebuf(buffer, (std::streamsize)strlen(buffer));
		pData = new SGloryBaseData;

		DWORD temp = 0;
		pData->m_GloryID= ((linebuf >> temp), temp); temp = 0;
		linebuf >> pData->m_GloryName;
		pData->m_GloryType = ((linebuf >> temp), temp); temp = 0;
		for (int i = 0; i < GLORY_AMAX; i++)
			linebuf >> pData->m_AwardFactor[i];
		for (int i = 0; i < GLORY_CMAX; i++)
			linebuf >> pData->m_GetConditionFactor[i]; 
		pData->m_GloryConditionIndex = ((linebuf >> temp), temp); temp = 0;
		linebuf >> pData->m_ConditionDetail;
		pData->m_GloryIcon = ((linebuf >> temp), temp); temp = 0;


		m_GloryBaseData.insert(make_pair(pData->m_GloryID, pData));
	}

	//加载称号基本数据
	dwt::ifstream stream1("Data\\荣耀和称号\\TitleTable.txt");
	if (!stream1.is_open())
		return false;

	char buffer1[2048];
	STitleBaseData *pData1 = 0;

	while (!stream1.eof())
	{
		stream1.getline(buffer1, sizeof(buffer1));
		if (0 == buffer1[0] || '//' == (*(LPWORD)buffer1))
			continue;

		std::strstream linebuf1(buffer1, (std::streamsize)strlen(buffer1));
		pData1 = new STitleBaseData;

		DWORD temp = 0; 
		pData1->m_TitleID = ((linebuf1 >> temp), temp); temp = 0;
		linebuf1 >> pData1->m_TitleName;
		for (int i = 0; i < TITLE_AMAX; i++)
			linebuf1 >> pData1->m_AddFactor[i];
		for (int i = 0; i < TITLE_CMAX; i++)
			linebuf1 >> pData1->m_ConsumeFactor[i];
		pData1->m_ConsumeItemID = ((linebuf1 >> temp), temp); temp = 0; 
		pData1->m_TitleIcon = ((linebuf1 >> temp), temp); temp = 0;
		linebuf1 >> pData1->m_TitleDescript;
		m_TitleBaseData.insert(make_pair(pData1->m_TitleID, pData1));
	}
	return true;
}
Exemple #26
0
// Ensure all functions compile correctly.
void read_stream_compile_test()
{
  try
  {
    boost::asio::io_service io_service;
    boost::system::error_code ec;
    char buffer[1024];

    // Constructors

    urdl::read_stream stream1(io_service);

    // get_io_service()

    want<boost::asio::io_service>(stream1.get_io_service());

    // set_option()

    stream1.set_option(0);
    stream1.set_option<char>(0);

    // set_options()

    stream1.set_options(urdl::option_set());

    // get_option()

    const urdl::read_stream& const_stream1 = stream1;
    want<int>(const_stream1.get_option<int>());
    want<char>(const_stream1.get_option<char>());

    // get_options()

    want<urdl::option_set>(const_stream1.get_options());

    // is_open()

    want<bool>(const_stream1.is_open());

    // open()

    stream1.open("file://xyz");
    stream1.open(urdl::url("file://xyz"));
    want<boost::system::error_code>(stream1.open("file://xyz", ec));
    want<boost::system::error_code>(stream1.open(urdl::url("file://xyz"), ec));

    // async_open()

    stream1.async_open("file://xyz", open_handler);
    stream1.async_open(urdl::url("file://xyz"), open_handler);

    // close()

    stream1.close();
    want<boost::system::error_code>(stream1.close(ec));

    // content_type()

    want<std::string>(const_stream1.content_type());

    // content_length()

    want<std::size_t>(const_stream1.content_length());

    // headers()

    want<std::string>(const_stream1.headers());

    // read_some()

    want<std::size_t>(stream1.read_some(boost::asio::buffer(buffer)));
    want<std::size_t>(stream1.read_some(boost::asio::buffer(buffer), ec));

    // async_read_some()

    stream1.async_read_some(boost::asio::buffer(buffer), read_handler);
  }
  catch (std::exception&)
  {
  }
}
Exemple #27
0
int main()
{
    
    // --- OpenCV Init ---
    //0 is the id of video device. 0 if you have only one camera.
    cv::VideoCapture stream1(1);

    if (!stream1.isOpened()) { //check if video device has been initialised
            std::cerr << "cannot open camera" << std::endl;
    }
         
    // --- GLFW Init ---
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // --- Create window ---
    GLFWwindow* window = glfwCreateWindow(800, 600,
                                      "OpenGL", nullptr, nullptr); // Windowed
    if(window == NULL) return 2;
    glfwMakeContextCurrent(window);
    
    // --- GLEW/GL Init ---
    glewExperimental = GL_TRUE;
    glewInit();

    // --- Application Specific Setup ---
    
    
    // Create FG Vertex Array Object
    GLuint bd_vao;
    glGenVertexArrays(1, &bd_vao);
    glBindVertexArray(bd_vao);
    
    // Create FG Vertex Buffer Object
    GLuint bd_vbo;
    glGenBuffers(1, &bd_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, bd_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(backdrop_vert),
                                  backdrop_vert, GL_STATIC_DRAW);
    
    glBindVertexArray(0);
    
    // Create BG Vertex Array Object
    GLuint bb_vao;
    glGenVertexArrays(1, &bb_vao);
    glBindVertexArray(bb_vao);

    // Create BG Vertex Buffer Object
    GLuint bb_vbo;
    glGenBuffers(1, &bb_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, bb_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(backdrop_vert),
                                  backdrop_vert, GL_STATIC_DRAW);
    
    glBindVertexArray(0);
    // Create Axis Vertex Array Object
    GLuint axis_vao;
    glGenVertexArrays(1, &axis_vao);
    glBindVertexArray(axis_vao);

    // Create Axis Vertex Buffer Object
    GLuint axis_vbo;
    glGenBuffers(1, &axis_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, axis_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(axis_vertices),
                                  axis_vertices, GL_STATIC_DRAW);
    
    glBindVertexArray(0);

    // Compile color vertex shader
    GLuint colorVert = glCreateShader(GL_VERTEX_SHADER);
    //const char *cvSource = readFile("3dvert.glsl").c_str();
    const char *cvSource = SHADER_VERT3D_COLOR;

    glShaderSource(colorVert, 1, &cvSource, NULL);
    glCompileShader(colorVert);
    GLint cvStatus;
    glGetShaderiv(colorVert, GL_COMPILE_STATUS, &cvStatus);
    if(cvStatus != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(colorVert, 512, NULL, buffer);
        std::cerr << buffer << std::endl;
        return 1;
    }

    // Compile color fragment shader
    GLuint colorFrag = glCreateShader(GL_FRAGMENT_SHADER);
    //const char* cfSource = readFile("colorfrag.glsl").c_str();
    const char *cfSource = SHADER_FRAG_COLOR;

    glShaderSource(colorFrag, 1, &cfSource, NULL);
    glCompileShader(colorFrag);
    GLint cfStatus;
    glGetShaderiv(colorFrag, GL_COMPILE_STATUS, &cfStatus);
    if(cfStatus != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(colorFrag, 512, NULL, buffer);
        std::cerr << buffer << std::endl;
        return 2;
    }

    // Compile pretty vertex shader
    GLuint prettyVert = glCreateShader(GL_VERTEX_SHADER);
    //const char *pvSource = readFile("3dvert.glsl").c_str();
    const char *pvSource = SHADER_VERT3D;

    glShaderSource(prettyVert, 1, &pvSource, NULL);
    glCompileShader(prettyVert);
    GLint pvStatus;
    glGetShaderiv(prettyVert, GL_COMPILE_STATUS, &pvStatus);
    if(pvStatus != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(prettyVert, 512, NULL, buffer);
        std::cerr << buffer << std::endl;
        return 3;
    }

    // Compile pretty fragment shader
    GLuint prettyFrag = glCreateShader(GL_FRAGMENT_SHADER);
    //const char* pfSource = readFile("prettyfrag.glsl").c_str();
    const char* pfSource = SHADER_FRAG_PRETTY;

    glShaderSource(prettyFrag, 1, &pfSource, NULL);
    glCompileShader(prettyFrag);
    GLint pfStatus;
    glGetShaderiv(prettyFrag, GL_COMPILE_STATUS, &pfStatus);
    if(pfStatus != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(prettyFrag, 512, NULL, buffer);
        std::cerr << buffer << std::endl;
        return 4;
    }

    // Compile blank vertex shader
    GLuint blankVert = glCreateShader(GL_VERTEX_SHADER);
    //const char *bvSource = readFile("3dvert.glsl").c_str();
    const char *bvSource = SHADER_VERT3D;

    glShaderSource(blankVert, 1, &bvSource, NULL);
    glCompileShader(blankVert);
    GLint bvStatus;
    glGetShaderiv(blankVert, GL_COMPILE_STATUS, &bvStatus);
    if(bvStatus != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(blankVert, 512, NULL, buffer);
        std::cerr << buffer << std::endl;
        return 5;
    }

    // Compile blank fragment shader
    GLuint blankFrag = glCreateShader(GL_FRAGMENT_SHADER);
    //const char* bfSource = readFile("simplefrag.glsl").c_str();
    const char* bfSource = SHADER_FRAG_SIMPLE;

    glShaderSource(blankFrag, 1, &bfSource, NULL);
    glCompileShader(blankFrag);
    GLint bfStatus;
    glGetShaderiv(blankFrag, GL_COMPILE_STATUS, &bfStatus);
    if(bfStatus != GL_TRUE) {
        char buffer[512];
        glGetShaderInfoLog(blankFrag, 512, NULL, buffer);
        std::cerr << buffer << std::endl;
        return 6;
    }

    // Make color shader program.
    GLuint colorShaderProgram = glCreateProgram();
    glAttachShader(colorShaderProgram, colorVert);
    glAttachShader(colorShaderProgram, colorFrag);
    glBindFragDataLocation(colorShaderProgram, 0, "outColor");
    glLinkProgram(colorShaderProgram);
    glUseProgram(colorShaderProgram);
    

    //GLint ctAttrib = glGetAttribLocation(colorShaderProgram, "texcoord`");
    //glEnableVertexAttribArray(ctAttrib);
    //glVertexAttribPointer(ctAttrib, 3, GL_FLOAT, GL_FALSE,
    //            6 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
    
    glBindVertexArray(axis_vao);
    glBindBuffer(GL_ARRAY_BUFFER, axis_vbo);
    GLint cvpAttrib = glGetAttribLocation(colorShaderProgram, "position");
    glEnableVertexAttribArray(cvpAttrib);
    glVertexAttribPointer(cvpAttrib, 3, GL_FLOAT, GL_FALSE,
                 6*sizeof(GLfloat), 0);

    GLint cvcAttrib = glGetAttribLocation(colorShaderProgram, "v_color");
    glEnableVertexAttribArray(cvcAttrib);
    glVertexAttribPointer(cvcAttrib, 3, GL_FLOAT, GL_FALSE,
                 6*sizeof(GLfloat), (void*)(3*sizeof(GLfloat)));

    // Make pretty shader program.
    GLuint prettyShaderProgram = glCreateProgram();
    glAttachShader(prettyShaderProgram, prettyVert);
    glAttachShader(prettyShaderProgram, prettyFrag);
    glBindFragDataLocation(prettyShaderProgram, 0, "outColor");
    glLinkProgram(prettyShaderProgram);
    glUseProgram(prettyShaderProgram);
    

    glBindVertexArray(bd_vao);
    glBindBuffer(GL_ARRAY_BUFFER, bd_vbo);
    GLint pvpAttrib = glGetAttribLocation(prettyShaderProgram, "position");
    glEnableVertexAttribArray(pvpAttrib);
    glVertexAttribPointer(pvpAttrib, 3, GL_FLOAT, GL_FALSE,
                 5*sizeof(GLfloat), 0);

    GLint pvtAttrib = glGetAttribLocation(prettyShaderProgram, "texcoord");
    glEnableVertexAttribArray(pvtAttrib);
    glVertexAttribPointer(pvtAttrib, 2, GL_FLOAT, GL_FALSE,
                5 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));

    // Make blank shader program.
    GLuint blankShaderProgram = glCreateProgram();
    glAttachShader(blankShaderProgram, blankVert);
    glAttachShader(blankShaderProgram, blankFrag);
    glBindFragDataLocation(blankShaderProgram, 0, "outColor");
    glLinkProgram(blankShaderProgram);
    glUseProgram(blankShaderProgram);

    glBindVertexArray(bb_vao);
    glBindBuffer(GL_ARRAY_BUFFER, bb_vbo);
    GLint bvpAttrib = glGetAttribLocation(blankShaderProgram, "position");
    glEnableVertexAttribArray(bvpAttrib);
    glVertexAttribPointer(bvpAttrib, 3, GL_FLOAT, GL_FALSE,
                 5*sizeof(GLfloat), 0);

    GLint bvtAttrib = glGetAttribLocation(blankShaderProgram, "texcoord");
    glEnableVertexAttribArray(bvtAttrib);
    glVertexAttribPointer(bvtAttrib, 2, GL_FLOAT, GL_FALSE,
                5 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));

    // Setup view
    glm::mat4 view = glm::lookAt(
                   glm::vec3( 0.5f,  2.0f,  1.5f),
                   glm::vec3( 0.5f,  0.0f,  0.0f),
                   glm::vec3( 0.0f,  0.0f,  1.0f)
                   );
    glm::mat4 proj = 
          glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 1.0f, 10.0f);
    glm::mat4 model = glm::mat4();

    glUniformMatrix4fv(glGetUniformLocation(colorShaderProgram, "view" ),
                                            1, GL_FALSE, glm::value_ptr(view));
    glUniformMatrix4fv(glGetUniformLocation(colorShaderProgram, "proj" ),
                                            1, GL_FALSE, glm::value_ptr(proj));
    glUniformMatrix4fv(glGetUniformLocation(colorShaderProgram, "model"),
                                            1, GL_FALSE, glm::value_ptr(model));

    glUniformMatrix4fv(glGetUniformLocation(prettyShaderProgram, "view" ),
                                            1, GL_FALSE, glm::value_ptr(view));
    glUniformMatrix4fv(glGetUniformLocation(prettyShaderProgram, "proj" ),
                                            1, GL_FALSE, glm::value_ptr(proj));
    glUniformMatrix4fv(glGetUniformLocation(prettyShaderProgram, "model"),
                                            1, GL_FALSE, glm::value_ptr(model));
    
    glUniformMatrix4fv(glGetUniformLocation(blankShaderProgram, "view" ),
                                            1, GL_FALSE, glm::value_ptr(view));
    glUniformMatrix4fv(glGetUniformLocation(blankShaderProgram, "proj" ),
                                            1, GL_FALSE, glm::value_ptr(proj));
    glUniformMatrix4fv(glGetUniformLocation(blankShaderProgram, "model"),
                                            1, GL_FALSE, glm::value_ptr(model));

    // Create texture
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glGenerateMipmap(GL_TEXTURE_2D);


    glEnable(GL_DEPTH_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    float xco = 0.0f;
    float yco = 0.0f;
    // --- Main Loop ---
    while(!glfwWindowShouldClose(window))
    {
        // Reset
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       


        // Move camera
        //GLfloat radius = 2.0f;
        //GLfloat camX = sin(glfwGetTime()) * radius;
        //GLfloat camY = cos(glfwGetTime()) * radius;
        //view = glm::lookAt(glm::vec3(camX,camY,1.5f),
        //        glm::vec3(0.0f, 0.0f, 0.0f),
        //        glm::vec3(0.0f, 0.0f, 1.0f));

        // Capture Image
        cv::Mat cameraFrame;
        stream1 >> cameraFrame;
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                      cameraFrame.cols, cameraFrame.rows, 0, GL_BGR,
                      GL_UNSIGNED_BYTE, cameraFrame.data);
        glGenerateMipmap(GL_TEXTURE_2D);


        // Draw Backboard
        model = glm::mat4();
        model = glm::translate(model,glm::vec3(0.5f,0.0f,0.0f));

        glUseProgram(prettyShaderProgram);
        glUniformMatrix4fv(glGetUniformLocation(prettyShaderProgram, "view"),
          1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(prettyShaderProgram, "proj"),
          1, GL_FALSE, glm::value_ptr(proj));
        glUniformMatrix4fv(glGetUniformLocation(prettyShaderProgram, "model"),
          1, GL_FALSE, glm::value_ptr(model));

        glBindVertexArray(bd_vao);
          glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);

        // Draw Baseboard
        model = glm::rotate(
                  model,
                  glm::radians(90.0f),
                  glm::vec3(1.0f, 0.0f, 0.0f)
                );
        model = glm::translate(model,glm::vec3(-0.5f,0.0f,0.0f));

        glUseProgram(blankShaderProgram);
        glUniformMatrix4fv(glGetUniformLocation(blankShaderProgram, "view"),
          1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(blankShaderProgram, "proj"),
          1, GL_FALSE, glm::value_ptr(proj));
        glUniformMatrix4fv(glGetUniformLocation(blankShaderProgram, "model"),
          1, GL_FALSE, glm::value_ptr(model));

        glBindVertexArray(bb_vao);
          glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);

        // Draw Axis
        model = glm::mat4();

        // Process Image
        vector<float> point = findObject(cameraFrame);

        if (point.size() != 0) {
            xco = ((point[0] / cameraFrame.cols));
            yco = ((point[1] / cameraFrame.rows));
            cerr << "#" << point[0] << ", " << point[1] << endl;
            cerr << "!" << xco << ", " << yco << endl;
        }
        model = glm::translate(glm::mat4(1.0f), glm::vec3(xco, yco, 0.0f));

        glUseProgram(colorShaderProgram);
        glUniformMatrix4fv(glGetUniformLocation(colorShaderProgram, "view"),
                1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(colorShaderProgram, "proj"),
                1, GL_FALSE, glm::value_ptr(proj));
        glUniformMatrix4fv(glGetUniformLocation(colorShaderProgram, "model"),
                1, GL_FALSE, glm::value_ptr(model));

        glBindVertexArray(axis_vao);
        glDrawArrays(GL_LINES, 0, 6);
        glBindVertexArray(0);

        //Display
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // --- Cleanup/Shutdown ---
    glDeleteProgram(colorShaderProgram);
    glDeleteProgram(prettyShaderProgram);
    glDeleteProgram(blankShaderProgram);
    
    glDeleteShader(colorFrag);
    glDeleteShader(colorVert);

    glDeleteShader(prettyFrag);
    glDeleteShader(prettyVert);

    glDeleteShader(blankVert);
    glDeleteShader(blankFrag);

    glDeleteBuffers(1, &axis_vbo);
    glDeleteBuffers(1, &bd_vbo);
    glDeleteBuffers(1, &bb_vbo);

    glDeleteVertexArrays(1, &axis_vao);
    glDeleteVertexArrays(1, &bd_vao);
    glDeleteVertexArrays(1, &bb_vao);

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}
void EvolverController::run()
{
    double TIME_STEP = getBasicTimeStep();
    
    receiver->enable(TIME_STEP);
    while (receiver->getQueueLength() > 0)
    {
        receiver->nextPacket();
    }
    
    
    /****************************************
     ***** WAIT UNTIL ENVIRONMENT IS OK *****
     ****************************************/
    
    // wait unitil EnvironmentModifierController sais the environment is ok
    bool environmentOk = false;
    while (step(TIME_STEP) != -1 && !environmentOk)
    {
        while(receiver->getQueueLength() > 0)
        {
            std::string message = (char*)receiver->getData();
            if (message.substr(0,24).compare("[ENVIRONMENT_OK_MESSAGE]") == 0)
            {
                environmentOk = true;
                simulationDateAndTime = MessagesManager::get(message, "SDAT");
            }
            receiver->nextPacket();
        }
    }
    
    
    /***************************************
     ******* CREATE THE FIRST GENOME *******
     ***************************************/
    random = Utils::Random::getInstance();
    
    
    CppnGenome genome = createRandomGenome();
    sendGenomeToBirthClinic(genomeManager->genomeToString(genome), "", 0, 0, 0, 0);
    
    
    // MAIN CYCLE
    
    initialization = true;
    initPopulationWaitingTime = getRandomWait();
    initialPopulationSize = 0;
    lastGeneratedTime = 0;
    currentTime = 0;
    lastMating = 0;      // FOR CENTRALIZED REPRODUCTION BY THE EVOLVER
    lastDeath = 0;       // FOR CENTRALIZED DEATH BY THE EVOLVER
    lastEvolutionEndCheck = 0;
    lastOffspringLoggingTime = 30;
    
    logger.noticeStream() << BOLDGREEN << "Initializing next individual in " << initPopulationWaitingTime << " seconds" << RESET;
    while (step(TIME_STEP) != -1)
    {
        
        currentTime = getTime();
        
        
        /***********************************
         ******* CHECK END EVOLUTION *******
         ***********************************/
        
        checkEndEvolution(currentTime);
        
        
        /*************************************
         ***** POPULATION INITIALIZATION *****
         *************************************/
        
        if (initialization && (currentTime - lastGeneratedTime > initPopulationWaitingTime))
        {
            CppnGenome newGenome = createRandomGenome();
            sendGenomeToBirthClinic(genomeManager->genomeToString(newGenome), "", 0, 0, 0, 0);
            lastGeneratedTime = getTime();
            initialPopulationSize++;
            
            if(initialPopulationSize >= INITIAL_POPULATION_MAX_SIZE) {
                initialization = false;
                logger.noticeStream() << BOLDGREEN << "Finished initialising population" << RESET;
            }else{
                initPopulationWaitingTime = getRandomWait();
                logger.noticeStream() << BOLDGREEN << "Initializing next individual in " << initPopulationWaitingTime << " seconds" << RESET;
            }
        }
        
        
        /***************************************************************
         ************************** MANAGE MESSAGES ********************
         ***************************************************************/
        while(receiver->getQueueLength() > 0)
        {
            std::string message = (char*)receiver->getData();
            
            /**************************************
             ****** UPDATE BECAUSE OF DEATH  ******
             **************************************/
            if (message.substr(0,28).compare("[DEATH_ANNOUNCEMENT_MESSAGE]") == 0)
            {
                deathMessage(message,currentTime);
            }
            
            /*************************************
             ****** UPDATE BECAUSE OF BIRTH ******
             *************************************/
            else if (message.substr(0,24).compare("[ORGANISM_BUILT_MESSAGE]") == 0)
            {
                birthMessage(message,currentTime);
            }
            
            /*************************************
             ****** UPDATE BECAUSE OF ADULT ******
             *************************************/
            else if (message.substr(0,20).compare("[ADULT_ANNOUNCEMENT]") == 0)
            {
                adultMessage(message,currentTime);
            }
            
            /*************************************
             ***** UPDATE BECAUSE OF FERTILE *****
             *************************************/
            else if (message.substr(0,20).compare("[FERTILE_ANNOUNCEMENT]") == 0)
            {
                fertileMessage(message,currentTime);
            }
            
            /******************************
             ******* UPDATE FITNESS *******
             ******************************/
            // should be useful only for distributed
            else if (message.substr(0,16).compare("[FITNESS_UPDATE]") == 0)
            {
                fitnessUpdateMessage(message,currentTime);
            }
            
            /**************************************************************
             ******* CREATE NEW GENOME AFTER SELECTION BY ORGANISMS *******
             **************************************************************/
            else if (matingType == MATING_SELECTION_BY_ORGANISMS)
            {
                
                if (message.substr(0,16).compare("[COUPLE_MESSAGE]") == 0)
                {
                    coupleMessage(message,currentTime);
                }
            }
            
            /*************************************************
             ******* GET GENOMES FOR MATING BY EVOLVER *******
             *************************************************/
            else if (matingType == MATING_SELECTION_BY_EVOLVER)
            {
            
                if (message.substr(0,23).compare("[GENOME_SPREAD_MESSAGE]") == 0)
                {
                    genomeSpreadMessage(message,currentTime);
                }
            }
            
            receiver->nextPacket();
        }
        
        /***************************************************************
         ********************* INTERVAL OPERATIONS *********************
         ***************************************************************/
        
        /************************************************************
         ******* CREATE NEW GENOME USING SELECTION BY EVOLVER *******
         ************************************************************/
        if (matingType == MATING_SELECTION_BY_EVOLVER)
        {
        
            if(currentTime - lastMating > MATING_TIME)
            {
                logger.debugStream() << "time to mate";
                
                std::vector<id_t> forMating = selectForMating();
                
                if (forMating.size() == 2)
                {
                    try {
                        std::vector<CppnGenome> parentsGenomes = std::vector<CppnGenome>();
                        std::stringstream stream1(organismsList[searchForOrganism(forMating[0])].getGenome());
                        std::stringstream stream2(organismsList[searchForOrganism(forMating[1])].getGenome());
                        
                        parentsGenomes.push_back(CppnGenome(stream1));
                        parentsGenomes.push_back(CppnGenome(stream2));
                        
                        bool empty = true;
                        for (int i = 0; i < 100 && empty; i++)
                        {
                            CppnGenome newGenome = genomeManager->createGenome(parentsGenomes);
                            empty = checkEmptyPlan(newGenome);
                        
                            if(!empty) {
                                std::vector<boost::shared_ptr<MindGenome> > parentMindGenomes;
                                std::stringstream mind1(organismsList[searchForOrganism(forMating[0])].getMind());
                                std::stringstream mind2(organismsList[searchForOrganism(forMating[1])].getMind());
                                
                                boost::shared_ptr<MindGenome> mindGenome1 = mindGenomeManager->getGenomeFromStream(mind1);
                                boost::shared_ptr<MindGenome> mindGenome2 = mindGenomeManager->getGenomeFromStream(mind2);
                                
                                parentMindGenomes.push_back(mindGenome1);
                                parentMindGenomes.push_back(mindGenome2);
                                boost::shared_ptr<MindGenome> newMind = mindGenomeManager->createGenome(parentMindGenomes);
                                
                                logger.debugStream() << "NEW GENOME CREATED FROM organism_" << forMating[0] << " and organism_" << forMating[1];
                                
                                std::string log = std::to_string(getTime()) + " NEW GENOME CREATED FROM " + std::to_string(forMating[0]) + " and " + std::to_string(forMating[1]);
                                storeEventOnFile(log);
                                
                                double fitness1 = organismsList[searchForOrganism(forMating[0])].getFitness();
                                double fitness2 = organismsList[searchForOrganism(forMating[1])].getFitness();
                                sendGenomeToBirthClinic(genomeManager->genomeToString(newGenome), newMind->toString(), forMating[0], forMating[1], fitness1, fitness2);
                                
                                initialization = false;
                                logger.noticeStream() << BOLDGREEN << "Finished initialising population" << RESET;
                            }
                        }
                    }catch(LocatedException &e){
                        logger.warnStream() << "Evolver Mating failed, genomeManager threw a located exception: " << e.what();
                    }catch(std::exception &e){
                        logger.warnStream() << "Evolver Mating failed, genomeManager threw a normal exception: " << e.what();
                    }
                }
                if (forMating.size() == 1)
                {
                    try{
                        std::vector<CppnGenome> parentsGenomes = std::vector<CppnGenome>();
                        std::stringstream stream1(organismsList[searchForOrganism(forMating[0])].getGenome());
                        
                        parentsGenomes.push_back(CppnGenome(stream1));
                        
                        bool empty = true;
                        for (int i = 0; i < 100 && empty; i++)
                        {
                            CppnGenome newGenome = genomeManager->createGenome(parentsGenomes);
                            empty = checkEmptyPlan(newGenome);
                        
                            if(!empty){
                                std::vector<boost::shared_ptr<MindGenome> > parentMindGenomes;
                                std::stringstream mind1(organismsList[searchForOrganism(forMating[0])].getMind());

                                boost::shared_ptr<MindGenome> mindGenome1 = mindGenomeManager->getGenomeFromStream(mind1);
                                
                                parentMindGenomes.push_back(mindGenome1);
                                boost::shared_ptr<MindGenome> newMind = mindGenomeManager->createGenome(parentMindGenomes);
                                
                                logger.debugStream() << "NEW GENOME CREATED FROM SINGLE PARENT organism_" << forMating[0];
                                
                                std::string log = std::to_string(getTime()) + " NEW GENOME CREATED FROM " + std::to_string(forMating[0]);
                                storeEventOnFile(log);
                                
                                double fitness = organismsList[searchForOrganism(forMating[0])].getFitness();
                                sendGenomeToBirthClinic(genomeManager->genomeToString(newGenome), newMind->toString(), forMating[0], 0, fitness, -1);
                                
                                initialization = false;
                            }
                        }
                    }catch(LocatedException &e){
                        logger.warnStream() << "Evolver Mating failed, genomeManager threw a located exception: " << e.what();
                    }catch(std::exception &e){
                        logger.warnStream() << "Evolver Mating failed, genomeManager threw a normal exception: " << e.what();
                    }
                }
                if (forMating.size() == 0)
                {
                    logger.debugStream() << "couple of parents not found";
                    
                    std::string log = std::to_string(getTime()) + " couple of parents not found";
                    storeEventOnFile(log);
                }
                
                lastMating = getTime();
            }
        }
        
        /***********************************
         ********** LOG OFFSPRING **********
         ***********************************/
        if(currentTime - lastOffspringLoggingTime > MATING_TIME)
        {
            storeParentsOnFile(currentTime);
            lastOffspringLoggingTime = getTime();
        }
        
        /******************************************
         ******* DEATH BY EVOLVER SELECTION *******
         ******************************************/
        if (deathType == DEATH_SELECTION_BY_EVOLVER)
        {
            if(currentTime - lastDeath > DYING_TIME)
            {
                std::vector<id_t> forDying = selectForDying();
                
                for (int i = 0; i < forDying.size(); i++)
                {
                    sendDeathMessage(forDying[i]);
                    
                    logger.debugStream() << "organism_" << forDying[i] << " SELECTED FOR DEATH";
                }
                
                lastDeath = getTime();
            }
        }
        
    }
}
Exemple #29
0
bool ReadPairReads(const std::string& file1, const std::string& file2, PairReadList& pair_reads) {
    std::ifstream stream1(file1.c_str()), stream2(file2.c_str());
    return ReadPairReads(stream1, stream2, pair_reads);
}