Ejemplo n.º 1
0
vector<int> Minisat::SatToVertexCover() {

    ifstream resultFile ("minisat-result", ios_base::in);
   std::string resultMinisat;
   resultFile>>resultMinisat;

   vector<int> cover;
   int i;
   cout<<"Couverture"<<endl;
   while(resultFile.good()) {
                  resultFile >> i;
                  //On ne récupére que les sommets dans la couverture
                  if (i>0) {
                          cover.push_back(i);
                  }
          }

          resultFile.close();
          //Affichage
          for(int i=0;i<cover.size();i++){

              cout<<cover[i]<<endl;
          }

   resultFile.close();
   return cover;

}
void KisAslLayerStyleSerializerTest::testWriting()
{
    QVector<KisPSDLayerStyleSP> styles;

    QByteArray refXMLDoc;

    {
        KisAslLayerStyleSerializer s;

        QString srcFileName(TestUtil::fetchDataFileLazy("asl/test_all_and_pattern.asl"));
        QFile aslFile(srcFileName);
        aslFile.open(QIODevice::ReadOnly);
        s.readFromDevice(&aslFile);

        styles = s.styles();

        {
            aslFile.seek(0);

            KisAslReader reader;
            QDomDocument doc = reader.readFile(&aslFile);
            refXMLDoc = doc.toByteArray();
        }
    }

    // now we have an initialized KisPSDLayerStyle object
    {
        KisAslLayerStyleSerializer s;

        s.setStyles(styles);

        QFile dstFile("test_written.asl");
        dstFile.open(QIODevice::WriteOnly);
        s.saveToDevice(&dstFile);
        dstFile.close();
    }

    QByteArray resultXMLDoc;

    {
        QFile resultFile("test_written.asl");
        resultFile.open(QIODevice::ReadOnly);

        KisAslReader reader;
        QDomDocument doc = reader.readFile(&resultFile);
        resultXMLDoc = doc.toByteArray();
    }

    QFile refXMLFile("save_round_trip_src.xml");
    refXMLFile.open(QIODevice::WriteOnly);
    refXMLFile.write(refXMLDoc);
    refXMLFile.close();

    QFile resultXMLFile("save_round_trip_dst.xml");
    resultXMLFile.open(QIODevice::WriteOnly);
    resultXMLFile.write(resultXMLDoc);
    resultXMLFile.close();

    QCOMPARE(resultXMLDoc, refXMLDoc);
}
void utils::StrokeTester::testOneStroke(bool cancelled,
                                        bool indirectPainting,
                                        bool externalLayer,
                                        bool testUpdates)
{
    QString testName = formatTestName(m_name,
                                      cancelled,
                                      indirectPainting,
                                      externalLayer);

    dbgKrita << "Testcase:" << testName
             << "(comare against " << (testUpdates ? "projection" : "layer") << ")";

    QImage resultImage;
    resultImage = doStroke(cancelled, indirectPainting, externalLayer, testUpdates);

    QImage refImage;
    refImage.load(referenceFile(testName));

    QPoint temp;
    if(!TestUtil::compareQImages(temp, refImage, resultImage, m_baseFuzziness, m_baseFuzziness)) {
        refImage.save(dumpReferenceFile(testName));
        resultImage.save(resultFile(testName));

        QFAIL("Images do not coincide");
    }
}
Ejemplo n.º 4
0
void TestTfpconverter::otamaconvertStrong()
{
    QFETCH(QString, htmlFileName);
    QFETCH(QString, olgFileName);
    QFETCH(QString, resultFileName);

    QFile htmlFile(htmlFileName);
    QVERIFY(htmlFile.open(QIODevice::ReadOnly | QIODevice::Text));
    QTextStream tshtml(&htmlFile);
    tshtml.setCodec("UTF-8");

    QFile olgFile(olgFileName);
    QVERIFY(olgFile.open(QIODevice::ReadOnly | QIODevice::Text));
    QTextStream tsolg(&olgFile);
    tsolg.setCodec("UTF-8");

    QFile resultFile(resultFileName);
    QVERIFY(resultFile.open(QIODevice::ReadOnly | QIODevice::Text));
    QTextStream tsres(&resultFile);
    tsres.setCodec("UTF-8");

    QString result = OtamaConverter::convertToErb(tshtml.readAll(), tsolg.readAll(), 2);
    QString expect = tsres.readAll();
    QCOMPARE(result, expect);
}
Ejemplo n.º 5
0
void AssertMessageBox(UINT type, UINT nRetExpected, const char* expectedStr,
	const wchar_t* captionStr = L"caption", const wchar_t* textStr = L"text")
{

	std::string filename(tmpnam(0));
	std::ostringstream expectedRetValue;
	expectedRetValue << nRetExpected;

	setenv("XMESSAGE", "./messageboxdouble", true);
	setenv("MB_RESULTFILE", filename.c_str(), true);
	setenv("MB_EXPECTED", expectedStr, true);
	setenv("MB_RESULT", expectedRetValue.str().c_str(), true);

	UINT nRet = MessageBox(NULL, textStr, captionStr, type);

	std::ifstream resultFile(filename.c_str());
	if (resultFile.is_open())
	{
		std::string line;
		nRet++;
		while (!resultFile.eof())
		{
			std::getline(resultFile, line);
			std::cerr << line << std::endl;
		}
		resultFile.close();
	}

	Assert_eq(nRetExpected, nRet, "MessageBox returned wrong value");

	remove(filename.c_str());
}
Ejemplo n.º 6
0
std::vector<int>* MetisWrapper::cluster(const MatrixWrapper& graph, int numClusters)
{
	if (graph.getRows() != graph.getCols()) {
		assert(graph.getRows() != graph.getCols());
	}

	int nodes = graph.getRows();
	int edges = graph.countNonZeros();
	std::ofstream tempFile(MetisWrapper::TEMP_METIS_FILENAME.c_str());
	tempFile<<nodes<<" "<<(int) (edges / 2)<<" "<<1<<"\n";

	for (int node = 0; node < nodes; ++node) {
		bool firstNeighbor = true;

		for (int neighbor = 0; neighbor < nodes; neighbor++) {
			if (graph.get(node, neighbor) > 0) {
				if (graph.get(neighbor, node) != graph.get(node, neighbor)) {
					assert(graph.get(neighbor, node) != graph.get(node, neighbor));
				}

				if (firstNeighbor) {
					firstNeighbor = false;
				}

				else {
					tempFile<<" ";
				}

				tempFile<<(neighbor + 1)<<" "<<(int) graph.get(node, neighbor);
			}
		}

		tempFile<<"\n";
	}

	tempFile.close();
	std::string nclusters = convertToString(numClusters);
	char* command [3]= {&MetisWrapper::METIS_COMMAND[0], &MetisWrapper::TEMP_METIS_FILENAME[0], &nclusters[0]};
	std::string output = MetisWrapper::run(3, command);
	std::ifstream resultFile((MetisWrapper::TEMP_METIS_FILENAME + ".part." + convertToString(numClusters)).c_str());
	/*
	 * if (resultFile no existe)
	 * poner error de que no se genero el archivo de salida
	 *
	 */
	std::vector<int> *result = new std::vector<int>(nodes);
	std::string line;
	int node = 0;

	while(getline(resultFile, line, '\n')) {
		int cluster = atoi(line.c_str());
		(*result)[node] = cluster;
		++node;
	}

	resultFile.close();
	return result;
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    KLUPD::CoreError result = KLUPD::CORE_ADMKIT_FAILURE;

    IniConfiguration iniConfiguration;
    if(iniConfiguration.parse(argc, argv))
    {
        if(iniConfiguration.writeDump())
        {
            MiniDumper::enable();
            if(iniConfiguration.suppressErrorDialog())
                MiniDumper::suppressErrorDialog();
        }

        // protection against multiple instances
        #if defined(UNICODE) || defined(_UNICODE)
            #ifdef WSTRING_SUPPORTED
                HANDLE h = CreateMutex(0, FALSE, KLUPD::asciiToWideChar(iniConfiguration.applicaitonInstanceMutexName()).c_str());
            #else
                HANDLE h = CreateMutexA(0, FALSE, iniConfiguration.applicaitonInstanceMutexName().c_str());
            #endif
        #else
                HANDLE h = CreateMutex(0, FALSE, iniConfiguration.applicaitonInstanceMutexName().c_str());
        #endif

        // there is already an instance of this application running, or failed to create mutex
        if(!h || (GetLastError() == ERROR_ALREADY_EXISTS))
        {
            // TODO: change to code: failed to run several updater instances
        }
        else
            result = mainLoop(iniConfiguration);

        if(h)
            CloseHandle(h);
    }

    // writing single line result report to file
    KLUPD::AutoStream resultFile(0);
    const KLUPD::CoreError openResultFileResult = resultFile.open(iniConfiguration.updateReadableResultFileName(), L"w");
    if(isSuccess(openResultFileResult))
    {
        #ifdef WSTRING_SUPPORTED
            fwprintf(resultFile.stream(), L"%d\n%s", result, KLUPD::toString(result).toWideChar());
        #else
            fprintf(resultFile.stream(), "%d\n%s", result, KLUPD::toString(result).toAscii());
        #endif
    }
    else
    {
        std::cerr << "Failed to open trace file '" << iniConfiguration.updateReadableResultFileName().toAscii()
            << "', result " << KLUPD::toString(openResultFileResult).toAscii();
    }

    return result;
}
Ejemplo n.º 8
0
void CompareFiles(const std::string & first, const std::string & second)
{
	std::ifstream resultFile(first);
	std::ifstream rightResultFile(second);

	std::istream_iterator<char> iterResultFile(resultFile), endIter;
	std::istream_iterator<char> iterRightRsultFile(rightResultFile);

	BOOST_CHECK_EQUAL_COLLECTIONS(iterResultFile, endIter, iterRightRsultFile, endIter);
};
Ejemplo n.º 9
0
        void testSslJobs()
        {
            const QString aFile = QFINDTESTDATA("sendfiletest.cpp");
            const QString destFile = QDir::tempPath() + "/kdeconnect-test-sentfile";
            QFile(destFile).remove();

            const QString deviceId = KdeConnectConfig::instance()->deviceId()
                        , deviceName = "testdevice"
                        , deviceType = KdeConnectConfig::instance()->deviceType();

            KdeConnectConfig* kcc = KdeConnectConfig::instance();
            kcc->addTrustedDevice(deviceId, deviceName, deviceType);
            kcc->setDeviceProperty(deviceId, QString("certificate"), QString::fromLatin1(kcc->certificate().toPem())); // Using same certificate from kcc, instead of generating

            QSharedPointer<QFile> f(new QFile(aFile));
            UploadJob* uj = new UploadJob(f, deviceId);
            QSignalSpy spyUpload(uj, &KJob::result);
            uj->start();

            auto info = uj->transferInfo();
            info.insert("deviceId", deviceId);
            info.insert("size", aFile.size());

            DownloadJob* dj = new DownloadJob(QHostAddress::LocalHost, info);

            QVERIFY(dj->getPayload()->open(QIODevice::ReadOnly));

            FileTransferJob* ft = new FileTransferJob(dj->getPayload(), uj->transferInfo()["size"].toInt(), QUrl::fromLocalFile(destFile));

            QSignalSpy spyDownload(dj, &KJob::result);
            QSignalSpy spyTransfer(ft, &KJob::result);

            ft->start();
            dj->start();

            QVERIFY(spyTransfer.count() || spyTransfer.wait(1000000000));

            if (ft->error()) qWarning() << "fterror" << ft->errorString();

            QCOMPARE(ft->error(), 0);
            QCOMPARE(spyDownload.count(), 1);
            QCOMPARE(spyUpload.count(), 1);

            QFile resultFile(destFile), originFile(aFile);
            QVERIFY(resultFile.open(QIODevice::ReadOnly));
            QVERIFY(originFile.open(QIODevice::ReadOnly));

            const QByteArray resultContents = resultFile.readAll(), originContents = originFile.readAll();
            QCOMPARE(resultContents.size(), originContents.size());
            QCOMPARE(resultFile.readAll(), originFile.readAll());
        }
Ejemplo n.º 10
0
void SubMdiWindowsResults::saveIntoFile(const QString & filename)
{
    bool result = true;
    QString message = "Sauvegarde des donnees reussie";
    QFile file(filename);

    file.open(QFile::WriteOnly);
    if( ! file.isOpen() )
    {
        message = file.errorString();
        result = false;
    }
    else
    {
        file.write( m_textEdit->toPlainText().toUtf8() ); //bon encodage ??
        file.close();
    }
    emit resultFile(message, result);
}
Ejemplo n.º 11
0
char * genetCall(char * input, int argc, char ** argv)
{
    std::string inName;
    std::string outName;

    {
        Output genetInputData;
        inName = genetInputData.name();
        outName = inName + ".pn";
        Output genetOutputData(outName,"output file for Genet");

        genetInputData.stream() << input << std::flush;
        genetOutputData.stream() << std::endl << std::flush;
    }

    char ** genetArgs = (char **)malloc((argc + 4) * sizeof(char*));
    genetArgs[0] = strdup("genetDLL");
    for(unsigned int argumentIndex = 0; argumentIndex < argc; ++argumentIndex)
    {
        genetArgs[argumentIndex + 1] = strdup(argv[argumentIndex]);
    }
    genetArgs[argc + 1] = strdup(inName.c_str());
    genetArgs[argc + 2] = strdup("-o");
    genetArgs[argc + 3] = strdup(outName.c_str());

    genet_init(argc + 4, genetArgs);

    // do something

    std::ifstream resultFile(outName.c_str(), std::ios_base::in);
    std::string resultData;
    while (not resultFile.eof())
    {
        resultData += resultFile.get();
    }
    resultFile.close();
    resultData = resultData.substr(0, resultData.length()-1);

    remove(inName.c_str());
    remove(outName.c_str());

    return strdup(resultData.c_str());
}
Ejemplo n.º 12
0
QList<Task *> SpideyAlignmentTask::onSubTaskFinished(Task *subTask) {
    QList<Task *> res;

    propagateSubtaskError();

    if (hasError() || isCanceled()) {
        return res;
    }

    if (subTask == prepareDataForSpideyTask) {
        SAFE_POINT(!prepareDataForSpideyTask->getResultPath().isEmpty(), "Invalid result path!",
            res);

        tmpOutputUrl = prepareDataForSpideyTask->getResultPath();
        const QStringList &arguments = prepareDataForSpideyTask->getArgumentsList();

        spideyTask = new ExternalToolRunTask(ET_SPIDEY, arguments, new SpideyLogParser());
        spideyTask->setSubtaskProgressWeight(95);
        res.append(spideyTask);
    } else if (subTask == spideyTask) {
        if (!QFile::exists(tmpOutputUrl)) {
            if (AppContext::getExternalToolRegistry()->getByName(ET_SPIDEY)->isValid()) {
                stateInfo.setError(tr("Output file not found"));
            } else {
                ExternalTool *spideyTool = AppContext::getExternalToolRegistry()->getByName(ET_SPIDEY);
                SAFE_POINT(NULL != spideyTool, "Invalid Spidey tool!", res);
                stateInfo.setError(
                    tr("Output file not found. May be %1 tool path '%2' not valid?")
                    .arg(spideyTool->getName()).arg(spideyTool->getPath()));
            }
            return res;
        }

        // parse result

        QFile resultFile(tmpOutputUrl);

        if (!resultFile.open(QFile::ReadOnly)) {
            setError(tr("Failed to open result file %1").arg(tmpOutputUrl));
            return res;
        }

        QTextStream inStream(&resultFile);
        bool strandDirect = true;

        U2Location location;
        location->op = U2LocationOperator_Join;

        while (!inStream.atEnd()) {
            QByteArray buf = inStream.readLine().toLatin1();
            if (buf.startsWith("Strand")) {
                strandDirect = buf.contains("plus");
            }
            if (buf.startsWith("Exon")) {
                // TODO: better to use reg exp here
                int startPos = buf.indexOf(":") + 1;
                int endPos = buf.indexOf("(gen)");
                if (startPos == -1 || endPos == -1) {
                    continue;
                }
                QByteArray loc = buf.mid(startPos, endPos - startPos).trimmed();
                QList<QByteArray> loci = loc.split('-');
                if (loci.size() < 2) {
                    continue;
                }
                int start = QString(loci.at(0)).toInt();
                int finish = QString(loci.at(1)).toInt();

                if (start == finish) {
                    continue;
                }

               location->regions.append(U2Region(start - 1, finish - start + 1));
            }
        }

        if (!location->isEmpty()) {
            SharedAnnotationData data(new AnnotationData);
            data->location = location;
            data->setStrand(U2Strand(strandDirect ? U2Strand::Direct : U2Strand::Complementary));
            data->type = U2FeatureTypes::Exon;
            data->name = "exon";
            U1AnnotationUtils::addDescriptionQualifier(data, annDescription);
            resultAnnotations.append(data);
        }
    }

    return res;
}
void KisAslLayerStyleSerializerTest::testWritingGradients()
{
    KoStopGradient stopGradient("");

    {
        const KoColorSpace * cs = KoColorSpaceRegistry::instance()->rgb8();
        QList<KoGradientStop> stops;
        stops << KoGradientStop(0.0, KoColor(Qt::black, cs));
        stops << KoGradientStop(0.3, KoColor(Qt::red, cs));
        stops << KoGradientStop(0.6, KoColor(Qt::green, cs));
        stops << KoGradientStop(1.0, KoColor(Qt::white, cs));
        stopGradient.setStops(stops);
    }

    KisPSDLayerStyleSP style(new KisPSDLayerStyle());

    style->outerGlow()->setEffectEnabled(true);
    style->outerGlow()->setFillType(psd_fill_gradient);
    style->outerGlow()->setGradient(toQShared(new KoStopGradient(stopGradient)));

    style->innerGlow()->setEffectEnabled(true);
    style->innerGlow()->setFillType(psd_fill_gradient);
    style->innerGlow()->setGradient(toQShared(new KoStopGradient(stopGradient)));

    style->gradientOverlay()->setEffectEnabled(true);
    style->gradientOverlay()->setGradient(toQShared(new KoStopGradient(stopGradient)));

    style->stroke()->setEffectEnabled(true);
    style->stroke()->setFillType(psd_fill_gradient);
    style->stroke()->setGradient(toQShared(new KoStopGradient(stopGradient)));

    {
        KisAslLayerStyleSerializer s;

        s.setStyles(QVector<KisPSDLayerStyleSP>() << style);

        QFile dstFile("test_written_stop_gradient.asl");
        dstFile.open(QIODevice::WriteOnly);
        s.saveToDevice(&dstFile);
        dstFile.close();
    }

    QString xmlDoc;

    {
        QFile resultFile("test_written_stop_gradient.asl");
        resultFile.open(QIODevice::ReadOnly);

        KisAslReader reader;
        QDomDocument doc = reader.readFile(&resultFile);
        xmlDoc = doc.toString();
    }

    {
        // the reference document has stripped "Idnt" field which is random

        QRegExp rx("<node key=\"Idnt\" type=\"Text\" value=\".+\"/>");
        rx.setMinimal(true);

        int pos = 0;
        while ((pos = rx.indexIn(xmlDoc, pos)) != -1) {
            xmlDoc.remove(pos, rx.matchedLength());
        }

        {
            //QFile xmlFile("reference_gradients.asl.xml");
            //xmlFile.open(QIODevice::WriteOnly);
            //xmlFile.write(xmlDoc.toLatin1());
            //xmlFile.close();
        }

        QString refFileName(TestUtil::fetchDataFileLazy("reference_gradients.asl.xml"));
        QFile refFile(refFileName);
        refFile.open(QIODevice::ReadOnly);
        QString refDoc = QString(refFile.readAll());

        QCOMPARE(xmlDoc, refDoc);
    }
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QApplication::setOrganizationName(_S("Majister"));
    QApplication::setApplicationName(_S("jPos"));

    qRegisterMetaType<SyncState>("SyncState");

    // Имя файла логов
    logFileName.clear();

    // Настройки базы - SQLite
    QString mainBase = _S("db.sqlite3");
    QString dbDriver = _S("QSQLITE");
    QString dbUser;
    QString dbPass;
    QString dbOptions;
    QString executeModule;
    QString executeParams;


    QString styleFileName;
    bool stylefree = false;

    //  Уровни лога, 1- только ошибки, 2 - основные действия, 3 - отладка каждого чиха
    int  loglevel = 1;
    //  Обнулить файл логов
    bool newlog        = false;
    bool resetSettings = false;
    bool showHelp      = false;
    bool saveSources   = false;


    QStringList args = QCoreApplication::arguments();
    for (int i = 1; i < args.count(); ++i)
    {
        QString value = args.at(i);

        if (value == _S("--logfile") && i < args.count())
        {
            logFileName = args.at(++i);
            continue;
        }

        if (value == _S("--loglevel") && i < args.count())
        {
            loglevel = args.at(++i).toInt();
            continue;
        }

        if (value == _S("--newlog"))
        {
            newlog = true;
            continue;
        }

        if (value == _S("--driver") && i < args.count())
        {
            dbDriver = args.at(++i);
            continue;
        }
        if (value == _S("--user") && i < args.count())
        {
            dbUser = args.at(++i);
            continue;
        }
        if (value == _S("--password") && i < args.count())
        {
            dbPass = args.at(++i);
            continue;
        }
        if (value == _S("--resetsettings"))
        {
            resetSettings = true;
            continue;
        }
        if (value == _S("--stylefree"))
        {
            stylefree = true;
            continue;
        }
        if (value == _S("--istyle") && i < args.count())
        {
            styleFileName = args.at(++i);
            continue;
        }
        if (value == _S("--version"))
        {
            qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME);
            return 0;
        }
        if (value == _S("--help"))
        {
            showHelp = true;
            break; // all other params not matter
        }
        if (value == _S("--sources"))
        {
            saveSources = true;
            break; // all other params not matter
        }
        if (value == _S("--execute") && i+1 < args.count())
        {
            executeModule = args.at(++i);
            executeParams = args.at(++i);
            continue;
        }
        // если не параметров - значит название базы
        mainBase = value;
    }


    if (saveSources)
    {
        QFile   sourcesFile(_S(":/sources/sources/sources.7z"));
        if(!sourcesFile.open(QFile::ReadOnly))
        {
            qDebug() << _T("%1 Ошибка доступа к исходникам: %2")
                        .arg(posForLog)
                        .arg(sourcesFile.errorString());
            return 1;
        }

        QFile   resultFile(_S("sources.7z"));
        if(!resultFile.open(QFile::WriteOnly))
        {
            qDebug() << _T("%1 Ошибка создания файла для сохранения: %2")
                        .arg(posForLog)
                        .arg(resultFile.errorString());
            return 1;
        }

        resultFile.write(sourcesFile.readAll());
        resultFile.close();
        sourcesFile.close();

        qDebug()<<"Исходники сохранены в файле sources.7z";
        return 0;
    }

    if (showHelp)
    {
        QFile   helpFile(_S(":/texts/texts/help.txt"));
        helpFile.open(QFile::ReadOnly);
        QString helpText = helpFile.readAll();
        qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME)<<endl;
        qDebug() << helpText;
        return 0;
    }

    if (newlog)
    {
        QFile::remove(logFileName);
    }


    if (!logFileName.isEmpty())
        qInstallMessageHandler(fileMessageHandler);
    //else
    //    qInstallMessageHandler(outputMessageHandler);


    if(!stylefree)
    {
        QFile styleFile;
        if(!styleFileName.isEmpty())
            styleFile.setFileName(styleFileName);
        else
            styleFile.setFileName(":/qss/qss/black-n-orange.qss");

        styleFile.open(QFile::ReadOnly);
        QString styleSheet = QString::fromLatin1(styleFile.readAll());
        qApp->setStyleSheet(styleSheet);
    }

    Datapipe               * data = new Datapipe();
    QMap<QString, QVariant>* vars = data->getVariables();

    if (loglevel > 0)
        qDebug() << _T("%1 Уровень лога: %2").arg(posForLog).arg(loglevel);

    vars->insert(_S("loglevel"), loglevel);


    QSettings *settings = data->getSettings();
    if (resetSettings)
        settings->clear();

    QStringList settingsKeys = settings->allKeys();

    QSettings *defaults = new QSettings(_S(":/defaults/defaults/globalsettings.ini"), QSettings::IniFormat);
    defaults->setIniCodec(QTextCodec::codecForName("UTF-8"));

    QStringList defaultKeys = defaults->allKeys();

    for (int i = 0; i < defaultKeys.count(); i++)
    {
        QString  key   = defaultKeys.at(i);
        QVariant value = defaults->value(key);

        if (!settingsKeys.contains(key))
            settings->setValue(key, value);
    }
    delete defaults;

    QFont font;
    font.setFamily(settings->value("global/default_font","DejaVu Sans").toString());
    font.setPixelSize(settings->value("global/default_font_size",14).toInt());
    font.setBold(settings->value("global/defalut_font_bold",true).toBool());

    qApp->setFont(font);


    // Финт - зададим дефолты для некоторых баз
    if((dbDriver=="QIBASE" || dbDriver=="QFIREBIRD") && dbUser.isEmpty())
        dbUser="******";
    if((dbDriver=="QIBASE" || dbDriver=="QFIREBIRD") && dbPass.isEmpty())
        dbPass="******";


    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);

    db.setDatabaseName(mainBase);
    db.setUserName(dbUser);
    db.setPassword(dbPass);
    db.setConnectOptions(dbOptions);

    if (!db.open())
    {
        qCritical()<<_T("%1 Ошибка подключения: %2").arg(posForLog).arg(db.lastError().text());
        return 2;
    }

    if (loglevel > 0)
    {
        qDebug() << _T("%1 База данных: %2").arg(posForLog).arg(mainBase);
        qDebug() << _T("%1 Драйвер: %2").arg(posForLog).arg(dbDriver);
        qDebug() << _T("%1 Пользователь: %2").arg(posForLog).arg(dbUser);
        qDebug() << _T("%1 Пароль: %2").arg(posForLog).arg(dbPass);
        qDebug() << _T("%1 Настройки: %2").arg(posForLog).arg(dbOptions);
    }
    vars->insert(_S("database"), mainBase);
    vars->insert(_S("database_driver"), dbDriver);
    vars->insert(_S("database_user"), dbUser);
    vars->insert(_S("database_password"), dbPass);
    vars->insert(_S("database_settings"), dbOptions);

    QSqlQuery query;


    query.prepare(settings->value(_S("global/queries/settings")).toString());
    if (query.exec())
    {
        while (query.next())
        {
            vars->insert(query.value(0).toString(), query.value(1));
            if(loglevel > 0)
                qDebug() << _T("%1 Переменные: %2 = %3").arg(posForLog).arg(query.value(0).toString()).arg(query.value(1).toString());
        }
    }
    else
    {
        bool solved = false;
        if(dbDriver=="QSQLITE")
        {
            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(0,
                                          _T("Не обнаружена база данных"),
                                          _T("Не обнаружена база данных\nСоздать новую?"),
                                          QMessageBox::Yes|QMessageBox::No);

            if (reply == QMessageBox::Yes)
            {
                QFile file(":/defaults/defaults/database_sqlite.sql");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qCritical() << _T("%1 Ошибка создания новой базы данных\n%2").arg(posForLog).arg(file.errorString());
                    return  0;
                }


                QStringList queryPartsList = QString::fromUtf8(file.readAll()).split(QRegExp("\\s"), QString::SkipEmptyParts);

                int triggerDepth=0;
                int stringDepth=0;
                bool skipOneBegin=false;
                QString queryFromParts;

                for(int i=0; i<queryPartsList.count();++i)
                {
                    QString part = queryPartsList.at(i).trimmed();

                    if(part.isEmpty())
                        continue;

                    if(part.toUpper() == "CREATE" && i+1 < queryPartsList.count())
                        if(queryPartsList.at(i+1)=="TRIGGER")
                        {
                            triggerDepth++;
                            skipOneBegin=true;
                        }


                    if(triggerDepth > 0 && part.toUpper()=="BEGIN")
                    {
                        if(skipOneBegin)
                            skipOneBegin=false;
                        else
                            triggerDepth++;
                    }
                    if(triggerDepth > 0 && part.toUpper()=="CASE")
                            triggerDepth++;

                    if(triggerDepth > 0 && part.toUpper().startsWith("END"))
                            triggerDepth--;

                    queryFromParts += _S(" %1").arg(part);

                    //qDebug()<<part<<triggerDepth<<stringDepth;

                    if(part.contains(";") && triggerDepth==0 && stringDepth==0)
                    {
                        bool skipQuery = false;
                        if(queryFromParts.contains("CREATE TABLE sqlite_sequence"))
                            skipQuery=true;

                        if(queryFromParts.trimmed().isEmpty())
                            skipQuery=true;

                        if(queryFromParts.trimmed()==";")
                            skipQuery=true;

                        if(!skipQuery)
                        {
                            if (!query.exec(queryFromParts))
                            {
                                qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                                return 1;
                            }
                           // qDebug()<<queryFromParts;
                        }
                        queryFromParts.clear();
                    }

                }

                QDialog dlg;
                QFormLayout layout;
                dlg.setLayout(&layout);

                QLineEdit posID;
                layout.addRow(_T("Код ПОС-а"), &posID);

                QLineEdit generatorMin;
                layout.addRow(_T("Генератор мин"), &generatorMin);

                QLineEdit generatorMax;
                layout.addRow(_T("Генератор макс"), &generatorMax);

                QPushButton bt;
                bt.setText("OK");
                layout.addRow(0, &bt);
                dlg.connect(&bt, SIGNAL(clicked()), &dlg, SLOT(accept()));

                if(dlg.exec()==QDialog::Accepted)
                {
                    query.prepare(settings->value(_S("global/queries/set_pos_id")).toString());
                    query.bindValue(":val", posID.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }
                    query.prepare(settings->value(_S("global/queries/set_generator_min")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_min1_sqlite")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_min2_sqlite")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_max")).toString());
                    query.bindValue(":val", generatorMax.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                }
                else
                {
                    QMessageBox message;
                    message.setText(_T("Создание новой базы данных отменено"));
                    message.exec();
                    return 1;
                }

               solved = true;
            }
        }

        if(!solved){
            qCritical() << _T("%1 Ошибка чтения настроек\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
            return 1;
        }
    }


    int width  = 0;
    int height = 0;

    if (QApplication::desktop()->screenGeometry().width() > QApplication::desktop()->screenGeometry().height())
    {
        width  = QApplication::desktop()->screenGeometry().width();
        height = QApplication::desktop()->screenGeometry().height();
    }
    else
    {
        width  = QApplication::desktop()->screenGeometry().height();
        height = QApplication::desktop()->screenGeometry().width();
    }


    double scale = settings->value("global/button_scale", 1).toDouble();



    vars->insert(_S("standart_button_width"), (int) width / 12 * scale);
    vars->insert(_S("standart_button_height"), (int) height / 12 * scale);
    vars->insert(_S("standart_text_height"), (int) height / 18 * scale);
    vars->insert(_S("standart_margins"), (int) vars->value(_S("standart_button_width")).toInt() * 0.1 * scale);

    // заполняем тут, чтобы не тянуть в плагины все файлы
    data->setPrinter(new ChequePrinter(data->getSettings(), data->getVariables()));


    if (loglevel > 0)
    {
        QStringList keys = settings->allKeys();
        for (int i = 0; i < keys.count(); i++)
            qDebug() << _T("%1 Настройки: %2 %3").arg(posForLog).arg(keys.at(i)).arg(settings->value(keys.at(i)).toString());
    }


    if (loglevel > 0)
        qDebug() << _T("%1 Запуск ").arg(posForLog);


    MainWindow window(data);
    window.showFullScreen();

    // проверка 3
    return a.exec();
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{

	// Check number of parameters

	if (argc < 5)
	{
		fprintf(stdout, "[ERROR] The number of parameters is wrong.\n");
		printHelp();
	}
	else
	{

		// Read parameters
		std::string calFile(argv[1]);
		int Thr = atoi(argv[2]);
		int Exp = atoi(argv[3]);
		int Led = atoi(argv[4]);
		std::string resultFile(argv[5]);

		fprintf(stdout, "Calibration File: %s\n", calFile.c_str());
		fprintf(stdout, "Result File: %s\n", resultFile.c_str());

		// Create Tracker
		Optitrack::OptitrackTracker::Pointer objTracker = Optitrack::OptitrackTracker::New();

		// Load Calibration File
		objTracker->SetCalibrationFile(calFile);

		int result = objTracker->Close();
		std::cout << " Close result: " << result << std::endl;
		std::cout << " State -> " << objTracker->GetState() << std::endl;

		// Open Connection
		result = objTracker->Open();
		std::cout << " Open result: " << result << std::endl;
		std::cout << " State -> " << objTracker->GetState() << std::endl;

		result = objTracker->LoadCalibration();
		std::cout << " LoadCalibration result: " << result << std::endl;
		std::cout << " State -> " << objTracker->GetState() << std::endl;

		int numCam = objTracker->GetCameraNumber();

		// Set Camera Params
		//objTracker->SetCameraParams(Exp, Thr, Led);
		result = objTracker->SetCameraParams(Exp, Thr, Led, 4);
		std::cout << " SetCamParams result: " << result << std::endl;

		// Testing Number of viewed markers
		result = objTracker->CheckNumberOfMarkers();

		if (result == 1)
		{
			fprintf(stdout, "SUCCESS for one marker\n");
			objTracker->TestCalibration(resultFile);
		}

		result = objTracker->Close();
		std::cout << " Close result: " << result << std::endl;
		std::cout << " State -> " << objTracker->GetState() << std::endl;

	}

	system("PAUSE");
    return 0;
}
Ejemplo n.º 16
0
int main()
{
    cv::Mat image = cv::imread("/home/ees/Pictures/images.jpeg");
  BlobDetector<LoG> detector(image);
  cv::Mat blobs = detector.highlightBlobs();
  cv::imshow("b", blobs);
  cv::waitKey();
  return 0;

  const std::string WALL_STR = "./images/wall/";
  const std::string GRAF_STR = "./images/graf/";
  const std::string BIKES_STR = "./images/bikes/";
  const std::string LEUVEN_STR = "./images/leuven/";

  const std::string stringArr[] {WALL_STR, GRAF_STR, BIKES_STR, LEUVEN_STR};

  for (int imagePack = 0; imagePack < 4; ++imagePack)
  {
    HarrisMatcher matcher((Type)imagePack);
    std::vector<Match> result = matcher.getSortedPairSet();
    std::ofstream resultFile(stringArr[imagePack] + "Harris/" + "results.txt");

    int i = 0;
    for (const Match& match : result)
    {
      cv::Mat im1 = match.im1->clone();
      cv::Mat im2 = match.im2->clone();

      cv::Mat stitched = cv::Mat::zeros(std::max(im1.rows, im2.rows), im1.cols + im2.cols, CV_8UC3);
      cv::Mat left(stitched, cv::Rect(0, 0, im1.cols, im1.rows));
      cv::Mat right(stitched, cv::Rect(im1.cols, 0, im2.cols, im2.rows));

      cv::Mat transform = readTransform(transforms[i]);

      im1.copyTo(left);
      im2.copyTo(right);

      cv::RNG rng;
      int totalPairs = match.pairs.size();
      int correctCount = 0;

      for (auto it = match.pairs.begin(); it != match.pairs.end(); ++it)
      {
        cv::Point orig = it->p2;
        cv::Point transformed = applyTransform(transform, it->p1, im1);

        bool isCorrect = false;
        if (std::abs(orig.x - transformed.x) <= 5 && std::abs(orig.y - transformed.y) <= 5)
        {
          ++correctCount;
          isCorrect = true;
        }

        /*if (it->distance < 0.1)*/ {
          cv::Point p(it->p2.x + im1.cols, it->p2.y);
          cv::Scalar color = isCorrect ? cv::Scalar(0,0,0) : cv::Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
          cv::circle(stitched, it->p1, 3, color, 3);
          cv::circle(stitched, p, 3, color, 3);
          cv::line(stitched, it->p1, p, color);
        }
      }

      static std::string pics[] { "img1", "img2", "img3"};
      cv::imwrite(stringArr[imagePack] + "Harris/" + std::string("img0->") + pics[i] + ".jpg", stitched);
      resultFile << "img0 -> " << pics[i] << ":\n"
                 << "Total pairs: " << totalPairs << '\n'
                 << "Correct pairs: " << correctCount << '\n'
                 << "Persentage: " << (int)ceil(((double)correctCount / (double)totalPairs) * 100) << "%\n" << std::endl;
      ++i;
    }
    resultFile.close();
  }

  for (int i = 0; i < 4; ++i)
  {
    SiftMatcher matcher((Type)i);
    matcher.match();
  }

  return 0;
}