Ejemplo n.º 1
0
void
QcMapGestureArea::update_pan()
{
  qInfo();

  // Not used by animation/flick
  // Map follows the mouse pointer: move the map center according to delta px
  // Fixme: delta px -> delta projected coordinate -> new center

  QcVectorDouble start_point = m_map->from_coordinate(m_start_coordinate, false);
  // Fixme: start_coordinate is no longer in the viewport
  if (isnan(start_point.x())) {
    qWarning() << "Screen coordinate are nan";
    return;
  }
  QcVectorDouble delta = m_current_position - start_point;
  QcVectorDouble map_center_px = QcVectorDouble(m_map->width(), m_map->height()) * .5;
  QcVectorDouble map_center_point = map_center_px - delta;
  QcWgsCoordinate new_center = m_map->to_coordinate(map_center_point, false);
  m_map->set_center(new_center);
}
Ejemplo n.º 2
0
    void ArtworksRepository::cleanupEmptyDirectories() {
        qDebug() << "Cleaning empty directories";
        int count = m_DirectoriesList.length();
        QVector<int> indicesToRemove;
        indicesToRemove.reserve(count);

        for (int i = 0; i < count; ++i) {
            const QString &directory = m_DirectoriesList[i];
            if (m_DirectoriesHash[directory] == 0) {
                indicesToRemove.append(i);
            }
        }

        if (!indicesToRemove.isEmpty()) {
            qInfo() << "Removing" << indicesToRemove.length() << "empty directory(ies)...";

            QVector<QPair<int, int> > rangesToRemove;
            Helpers::indicesToRanges(indicesToRemove, rangesToRemove);
            removeItemsAtIndices(rangesToRemove);
        }
    }
Ejemplo n.º 3
0
void SMActionVideoVLC::load(int time)
{
    if (!isLoaded())
    {
        SMAction::load(time);qInfo() << mediaVLC();
        _m = libvlc_media_new_path(_vlcinstance, mediaVLC());
        if (!_m)
        {
            setStatus(STATUS_ERROR);
            setLoadStatus(STATUS_ERROR);
            return;
        }
        libvlc_media_player_set_media (_mp, _m);

        QString options = "input-repeat=";
        options += QString::number(repeat());
        libvlc_media_add_option(_m, options.toLatin1());

        setLoadStatus(STATUS_LOADED);
    }
}
Ejemplo n.º 4
0
osg::Vec2f entity::ShaderedEntity2D::getPoint(unsigned int i) const
{
    const osg::Vec3Array* verts = static_cast<const osg::Vec3Array*>(this->getVertexArray());
    if (!verts){
        qWarning("Stroke vertices are not initialized. Cannot obtain a point.");
        return osg::Vec2f(0.f, 0.f);
    }
    unsigned int sz = verts->size();
    if (i>=sz){
        qWarning("Stroke's index is out of range. Cannot obtain  a point");
        return osg::Vec2f(0.f, 0.f);
    }
    osg::Vec3f p = (*verts)[i];
    if (std::fabs(p.z()) > cher::EPSILON){
        qWarning("Stroke::getPoint : unexpected value of z-coordinate");
        qInfo() << p.z();
        return osg::Vec2f(0.f, 0.f);
    }

    return osg::Vec2f(p.x(), p.y());
}
Ejemplo n.º 5
0
int main(int argc, char *argv[])
{
    Logger::Init("Tombola.log.txt");
    qInfo() << "\n\n" << "========== Startup ==========";

    CrashHandler crashHandler;

    QApplication app(argc, argv);
    QCoreApplication::setApplicationName("Tombola");     // QSettings init early enough
    QCoreApplication::setOrganizationName("Kúr Attila"); // QSettings init early enough

    DynamicTranslation dynamicTranslation(app);

    TombolaDocument document;

//    qmlRegisterType<BlockColorsSet_ViewModel>("com.quatso.tombola", 1, 0, "BlockColorSetListModel");
    TicketDrawExecutor ticketDrawExecutor(  document
                                          , new SingleTicketDraw_ViewModel()
                                          , new SingleTicketDraw_ViewModel());

    Controller controller(document, ticketDrawExecutor);
    controller.OnAppStartup();

    TicketsSellingPoint_ViewModel ticketsSellingPoint_ViewModel(document);
    ticketsSellingPoint_ViewModel.Init(ticketDrawExecutor.IsPrizeDrawingRunning());

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("ticketsSellingPoint", QVariant::fromValue(&ticketsSellingPoint_ViewModel));
    engine.rootContext()->setContextProperty("ticketDrawExecutor", QVariant::fromValue(&ticketDrawExecutor));
    engine.rootContext()->setContextProperty("dynamicTranslation", &dynamicTranslation);
    engine.rootContext()->setContextProperty("crashHandler", &crashHandler);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QIcon appIcon(":///Images/TombolaAppIcon.png");
    app.setWindowIcon(appIcon);

    int appRetVal = app.exec();
    controller.OnAppExit();
    return appRetVal;
}
Ejemplo n.º 6
0
void dbIfaceBase::getApparatusList(QStringList* p_pList)
{
    if (m_bInitialized)
    {
        QSqlDatabase db = QSqlDatabase::database("ConnMG");
        QSqlQuery query(db);
        query.exec("SELECT id, name_it, name_en, gender FROM apparatus");

        while (query.next())
        {
            QString name = query.value(0).toString() + ","  // id
                         + query.value(1).toString() + ","  // name_it
                         + query.value(2).toString() + ","  // name_en
                         + query.value(3).toString();       // gender
            *p_pList << name;
        }
    }
    else
    {
        qInfo() << "dbInterface::getApparatusList(): Db not initialized";
    }
}
void UnixSocketCommandTransport::initialize()
{
    QString name = m_options.value(1);
    QFileInfo fileInfo(name);

    if (!fileInfo.isAbsolute())
        name = name.prepend(QDir::currentPath() + "/");

    QLocalServer::removeServer(name);

    m_server = new QLocalServer;
    m_server->listen(name);

    if (m_server->isListening()) {
        qInfo().noquote() << QString("unixsocket: Listening on %1").arg(name);
    } else {
        qDebug().noquote() << QString("unixsocket: Failed to listen on %1").arg(name);
        QTimer::singleShot(0, [=]() {
            QCoreApplication::exit(-1);
        });
    }

    connect(m_server, &QLocalServer::newConnection, [=]() {
        QLocalSocket *socket = m_server->nextPendingConnection();

        UnixSocketCommandClient *client = new UnixSocketCommandClient;
        client->setSocket(socket);
        client->initialize();

        connect(socket, &QLocalSocket::disconnected, [=]() {
            socket->deleteLater();
            client->deleteLater();
        });

        connect(client, &UnixSocketCommandClient::newData, [=](const QByteArray &data) {
            emit newData(client, data);
        });
    });
}
Ejemplo n.º 8
0
bool
QcMapGestureArea::is_press_and_hold()
{
  qInfo();

  // if (!m_map)
  //   return false;

  if (!m_all_points.size())
    return false;

  if (is_pan_active() or is_pinch_active())
    return false;

  // if (m_press_time.isValid() and m_press_time.elapsed() > MINIMUM_PRESS_AND_HOLD_TIME) {
  QcVectorDouble p1 = first_point().pos();
  QcVectorDouble delta_from_press = p1 - m_start_position1;
  return (qAbs(delta_from_press.x()) <= MAXIMUM_PRESS_AND_HOLD_JITTER or
          qAbs(delta_from_press.y()) <= MAXIMUM_PRESS_AND_HOLD_JITTER);
  // } else
  //   return false;
}
Ejemplo n.º 9
0
    void SpellCheckerService::submitItems(const QVector<ISpellCheckable *> &itemsToCheck) {
        if (!m_WorkerIsAlive) { return; }

        if (m_SpellCheckWorker != NULL && !m_SpellCheckWorker->isCancelled()) {
            QVector<SpellCheckItemBase *> items;
            int length = itemsToCheck.length();

            items.reserve(length);

            for (int i = 0; i < length; ++i) {
                SpellCheck::ISpellCheckable *itemToCheck = itemsToCheck.at(i);
                SpellCheckItem *item = new SpellCheckItem(itemToCheck, Common::SpellCheckAll);
                itemToCheck->connectSignals(item);
                items.append(item);
            }

            qInfo() << "SpellCheck service: about to submit" << length << "items";

            m_SpellCheckWorker->submitItems(items);
            m_SpellCheckWorker->submitItem(new SpellCheckSeparatorItem());
        }
    }
Ejemplo n.º 10
0
QNetworkReply *AccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
    QNetworkRequest newRequest(request);

    if (newRequest.hasRawHeader("cookie")) {
        // This will set the cookie into the QNetworkCookieJar which will then override the cookie header
        setRawCookie(request.rawHeader("cookie"), request.url());
    }

    newRequest.setRawHeader(QByteArray("User-Agent"), Utility::userAgentString());

    // Some firewalls reject requests that have a "User-Agent" but no "Accept" header
    newRequest.setRawHeader(QByteArray("Accept"), "*/*");

    QByteArray verb = newRequest.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray();
    // For PROPFIND (assumed to be a WebDAV op), set xml/utf8 as content type/encoding
    // This needs extension
    if (verb == "PROPFIND") {
        newRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml; charset=utf-8"));
    }

    // Generate a new request id
    QByteArray requestId = generateRequestId();
    qInfo(lcAccessManager) << op << verb << newRequest.url().toString() << "has X-Request-ID" << requestId;
    newRequest.setRawHeader("X-Request-ID", requestId);

#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 4)
    // only enable HTTP2 with Qt 5.9.4 because old Qt have too many bugs (e.g. QTBUG-64359 is fixed in >= Qt 5.9.4)
    if (newRequest.url().scheme() == "https") { // Not for "http": QTBUG-61397
        // Don't enable by default until QTBUG-73947 is fixed
        static auto http2EnabledEnv = qgetenv("OWNCLOUD_HTTP2_ENABLED");
        if (http2EnabledEnv == "1") {
            newRequest.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true);
        }
    }
#endif

    return QNetworkAccessManager::createRequest(op, newRequest, outgoingData);
}
Ejemplo n.º 11
0
void dbIfaceBase::getCountriesList(QStringList* p_pList)
{
    if (m_bInitialized)
    {
        QSqlDatabase db = QSqlDatabase::database("ConnMG");
        QSqlQuery query(db);
        query.exec("SELECT nicename FROM nations");

        *p_pList << "Nazione..";
        while (query.next())
        {
            QString name = query.value(0).toString();
            *p_pList << name;
        }

        qSort(*p_pList);
    }
    else
    {
        qInfo() << "dbInterface::getCountriesList(): Db not initialized";
    }
}
Ejemplo n.º 12
0
AllScores dbIfaceBase::getAllScores(const int p_iAthleteId, const int p_iApparatusId)
{
    AllScores allScores = {0.0, 0.0, 0, false};

    if (m_bInitialized)
    {
        QSqlDatabase db = QSqlDatabase::database("ConnMG");
        QSqlQuery query(db);

        int iEventId = getCurrentEventId();

        QString strQuery = "SELECT start_score, final_score, force_score, final_apparatus FROM scores WHERE "
                  " sport_event_id = "   + QString::number(iEventId, 10) +
                  " AND athlete_id = "   + QString::number(p_iAthleteId, 10)+
                  " AND apparatus_id = " + QString::number(p_iApparatusId, 10);

        query.exec(strQuery);

        while (query.next())
        {
            allScores.StartScore = query.value(0).toFloat();
            allScores.FinalScore = query.value(1).toFloat();
            allScores.ForceScore = query.value(2).toInt();
            allScores.IsFinalApparatus = query.value(3).toBool();
        }

        if (iEventId == 0)
        {
            qCritical() << "No Id found for event year: " << m_iCurrentYear;
        }
    }
    else
    {
        qInfo() << "dbInterface::getAllScores(): Db not initialized";
    }

    return allScores;
}
Ejemplo n.º 13
0
void Ledger::historySuccess(QNetworkReply& reply) {
    // here we send a historyResult with some extra stuff in it
    // Namely, the styled text we'd like to show.  The issue is the
    // QML cannot do that easily since it doesn't know what the wallet
    // public key(s) are.  Let's keep it that way
    QByteArray response = reply.readAll();
    QJsonObject data = QJsonDocument::fromJson(response).object();
    qInfo(commerce) << "history" << "response" << QJsonDocument(data).toJson(QJsonDocument::Compact);

    // we will need the array of public keys from the wallet
    auto wallet = DependencyManager::get<Wallet>();
    auto keys = wallet->listPublicKeys();

    // now we need to loop through the transactions and add fancy text...
    auto historyArray = data.find("data").value().toObject().find("history").value().toArray();
    QJsonArray newHistoryArray;

    // TODO: do this with 0 copies if possible
    for (auto it = historyArray.begin(); it != historyArray.end(); it++) {
        // We have 2 text fields to synthesize, the one on the left is a listing
        // of the HFC in/out of your wallet.  The one on the right contains an explaination
        // of the transaction.  That could be just the memo (if it is a regular purchase), or
        // more text (plus the optional memo) if an hfc transfer
        auto valueObject = (*it).toObject();
        valueObject["hfc_text"] = hfcString(valueObject["sent_money"], valueObject["received_money"]);
        valueObject["transaction_text"] = transactionString(valueObject);
        newHistoryArray.push_back(valueObject);
    }
    // now copy the rest of the json -- this is inefficient
    // TODO: try to do this without making copies
    QJsonObject newData;
    newData["status"] = "success";
    QJsonObject newDataData;
    newDataData["history"] = newHistoryArray;
    newData["data"] = newDataData;
    newData["current_page"] = data["current_page"].toInt();
    emit historyResult(newData);
}
Ejemplo n.º 14
0
PluginInterface::InitResult PortAudioPlugin::initialise( fugio::GlobalInterface *pApp, bool pLastChance )
{
	Q_UNUSED( pLastChance )

	mApp = pApp;

#if defined( PORTAUDIO_SUPPORTED )
	if( Pa_Initialize() != paNoError )
	{
		return( INIT_FAILED );
	}

	qInfo() << Pa_GetVersionText();
#endif

	DevicePortAudio::deviceInitialise();

	mApp->registerNodeClasses( mNodeClasses );

	mApp->registerPinClasses( mPinClasses );

	return( INIT_OK );
}
Ejemplo n.º 15
0
bool DB::addOrUpdateUser(User & user, const QString & password)
{
	TRANSACTION(ta);
	QSqlQuery query(ta.db);

	UserId userId = DB::getUserId(user.getLogin());
	if (!userId.isValid()) {
		if (!addUser(user, password)) return false;
		userId = DB::getUserId(user.getLogin());
		user.setId(userId);
	} else {
		if (!updateUser(user, password)) return false;
	}

	if (!userId.isValid()) {
		qInfo() << "Some error occured during changing the user with the login:" << user.getLogin();
		return false;
	}

	if (!updatePermissions(userId, user.getPermissions())) return false;

	return ta.commit();
}
Ejemplo n.º 16
0
	RESULT YaDiskRVFSDriver::renameElement(const QString& path, const QString& newTitle)
	{
		RESULT res = eERROR_GENERAL;
		QFileInfo qInfo(path);
		VFSCache* cache = WebMounter::getCache();
		VFSCache::iterator elem = cache->find(qInfo.absoluteFilePath());

		if(elem != cache->end())
		{
			QString response;
            res = m_httpConnector->renameElement(elem->getId(), elem->getType(), newTitle, response);
			if(res == eNO_ERROR)
			{
				qInfo = qInfo.dir().absolutePath() + QString(QDir::separator()) + newTitle;
				VFSElement newElem(elem->getType()
					, qInfo.absoluteFilePath()
					, newTitle
					, elem->getEditMetaUrl()
					, elem->getEditMediaUrl()
					, elem->getSrcUrl()
					, elem->getId()
					, elem->getParentId()
					, elem->getModified()
					, elem->getPluginName());

				cache->erase(elem);
				cache->insert(newElem);

				if(newElem.getType() == VFSElement::DIRECTORY)
				{
					updateChildrenPath(newElem);
				}
			}
		}

		return res;
	}
Ejemplo n.º 17
0
QString dbIfaceBase::getNationName(int p_iNationId, enum NationInfo infoType)
{
    QString strName;

    if (m_bInitialized)
    {
        QSqlDatabase db = QSqlDatabase::database("ConnMG");
        QSqlQuery query(db);

        query.exec("SELECT id,nicename,ioc,iso FROM nations WHERE id = '" + QString::number(p_iNationId, 10) + "'");

        if (query.first())
        {
            int iValNbr = 1;
            switch(infoType)
            {
            case NI_Nicename:  iValNbr = 1; break;
            case NI_IocName:   iValNbr = 2; break;
            case NI_IsoName:   iValNbr = 3; break;

            default: qWarning() << "Invalid nation info " << infoType;
            }

            strName = query.value(iValNbr).toString();
        }
        else
        {
            qCritical() << "No name found for Id: " << p_iNationId;
        }
    }
    else
    {
        qInfo() << "dbInterface::getNationName(): Db not initialized";
    }

    return strName;
}
Ejemplo n.º 18
0
float dbIfaceBase::getStartScore(const int p_iAthleteId, const int p_iApparatusId)
{
    float fScore = 0.0;

    if (m_bInitialized)
    {
        QSqlDatabase db = QSqlDatabase::database("ConnMG");
        QSqlQuery query(db);

        int iEventId = getCurrentEventId();

         QString strQuery = "SELECT start_score FROM scores WHERE "
                   " sport_event_id = "   + QString::number(iEventId, 10) +
                   " AND athlete_id = "   + QString::number(p_iAthleteId, 10)+
                   " AND apparatus_id = " + QString::number(p_iApparatusId, 10);

         query.exec(strQuery);

        while (query.next())
        {
//            qDebug() << query.value(0).typeName()
//                    << ", " << query.value(0).toString();
            fScore = query.value(0).toFloat();
        }

        if (iEventId == 0)
        {
            qCritical() << "No Id found for event year: " << m_iCurrentYear;
        }
    }
    else
    {
        qInfo() << "dbInterface::getStartScore(): Db not initialized";
    }

    return fScore;
}
Ejemplo n.º 19
0
void
TestIndexer::test()
{
  // Fixme: init ok ???
  TextDocumentIndexer<TextDocument> indexer; // new Tokenizer()

  Tokenizer & tokenizer = indexer.tokenizer();
  tokenizer << new PreLanguageFilter();
  tokenizer << new CaseFoldingFilter();
  tokenizer << new AccentFoldingFilter(); // Must run language filter before !
  tokenizer << new LocalizedStopWordFilter("../ressources/data/stop-words.json");
  tokenizer << new LocalizedStemmerFilter();

  QString text1 = "Wikipédia est un projet d’encyclopédie collective en ligne, universelle, multilingue et fonctionnant sur le principe du wiki. Wikipédia a pour objectif d’offrir un contenu librement réutilisable, objectif et vérifiable, que chacun peut modifier et améliorer.";
  auto document1 = QSharedPointer<TextDocument>(new TextDocument(QLocale::French, text1));
  indexer.insert(*document1, document1);
  qInfo() << text1;
  for (const auto & token : indexer.document_tokens(document1))
    qInfo() << token;

  QString text2 = "Because QMultiMap inherits QMap, all of QMap's functionality also applies to QMultiMap. For example, you can use isEmpty() to test whether the map is empty, and you can traverse a QMultiMap using QMap's iterator classes (for example, QMapIterator). But in addition, it provides an insert() function that corresponds to QMap::insertMulti(), and a replace() function that corresponds to QMap::insert(). It also provides convenient operator+() and operator+=().";
  auto document2 = QSharedPointer<TextDocument>(new TextDocument(QLocale::English, text2));
  indexer.insert(*document2, document2);
  qInfo() << text2;
  for (const auto & token : indexer.document_tokens(document2))
    qInfo() << token;

  QString text3 = "Wikipédia est une encyclopédie.";
  auto document3 = QSharedPointer<TextDocument>(new TextDocument(QLocale::French, text3));
  indexer.insert(*document3, document3);
  qInfo() << text3;
  for (const auto & token : indexer.document_tokens(document3))
    qInfo() << token;

  QString query_text = "Wikipédia projet";
  auto matches = indexer.query(TextDocument(QLocale::French, query_text));
  for (const auto & match : matches)
    qInfo() << query_text << "Matched" << match.pertinence() << match.document()->document();
}
Ejemplo n.º 20
0
QStringList Api::getContentUrls(const QString& appSecret, int versionId, CancellationToken cancellationToken) const
{
    qInfo() << "Getting the content urls for app " << appSecret << " version " << versionId;
    auto path = QString("1/apps/%1/versions/%2/content_urls")
            .arg(appSecret).arg(versionId);

    QJsonDocument document = get(path, cancellationToken);

    QStringList contentUrls;

    if (!document.isArray())
    {
        throw InvalidFormatException("Expected document root to be array");
    }

    auto arr = document.array();

    for (auto item : arr)
    {
        if (!item.isObject())
        {
            throw InvalidFormatException("Expected array item to be object");
        }

        QJsonObject obj = item.toObject();

        if (!obj.contains("url"))
        {
            throw InvalidFormatException("Did not contain the 'url' field");
        }

        contentUrls.push_back(obj["url"].toString());
    }

    return contentUrls;
}
Ejemplo n.º 21
0
void
TestEphemeride::test_compute_sunrise_set()
{
  QFETCH(QDate, date);
  QFETCH(QTime, sunrise);
  QFETCH(QTime, noon);
  QFETCH(QTime, sunset);

  double latitude = 48.87; // for Paris
  double longitude = 2.67;

  double julian_day = compute_julian_day(date);

  QTime _sunrise = to_local_time(compute_sunrise_utc(julian_day, latitude, longitude));
  QTime _sunset = to_local_time(compute_sunset_utc(julian_day, latitude, longitude));
  QTime _noon = to_local_time(compute_solar_noon_utc(julian_day, longitude));
  qInfo() << _sunrise << _noon << _sunset;
  QVERIFY(_sunrise == sunrise);
  QVERIFY(_noon == noon);
  QVERIFY(_sunset == sunset);

  // QDateTime sunrise_date(date, _sunrise, Qt::UTC);
  // qInfo() << sunrise_date << sunrise_date.toLocalTime();
}
Ejemplo n.º 22
0
void LayoutTest::pageSegmentation(const cv::Mat & src) const {

	// TODOS
	// - line spacing needs smoothing -> graphcut
	// - DBScan is very sensitive to the line spacing

	// Workflow:
	// - implement noise/text etc classification on SuperPixel level
	// - smooth labels using graphcut
	// - perform everything else without noise pixels
	// Training:
	// - open mode (whole image only contains e.g. machine printed)
	// - baseline mode -> overlap with superpixel

	cv::Mat img = src.clone();
	//cv::resize(src, img, cv::Size(), 0.25, 0.25, CV_INTER_AREA);

	Timer dt;

	// find super pixels
	rdf::PageSegmentation pageSeg(img);

	if (!pageSeg.compute())
		qWarning() << "could not compute page segmentation!";

	qInfo() << "algorithm computation time" << dt;

	// drawing
	cv::Mat rImg = img.clone();

	// save super pixel image
	rImg = pageSeg.draw(rImg);
	QString maskPath = rdf::Utils::instance().createFilePath(mConfig.outputPath(), "-page-seg");
	rdf::Image::save(rImg, maskPath);
	qDebug() << "debug image added" << maskPath;
}
void
QcLocationCircleNode::update(const QcLocationCircleData & location_circle_data)
{
  // QSGGeometry * location_circle_geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 1);
  // location_circle_geometry->setLineWidth(100); // point size, max is 255
  // location_circle_geometry->setDrawingMode(GL_POINTS);

  QSGGeometry * geometry = new QSGGeometry(LocationCirclePoint2D_AttributeSet, 4);
  geometry->setDrawingMode(GL_TRIANGLE_STRIP);
  m_geometry_node->setGeometry(geometry);
  m_geometry_node->setFlag(QSGNode::OwnsGeometry);

  LocationCirclePoint2D * vertices = static_cast<LocationCirclePoint2D *>(geometry->vertexData());
  float x, y;
  if (location_circle_data.visible()) {
    QcVectorDouble screen_coordinate = m_viewport->coordinate_to_screen(location_circle_data.coordinate());
    x = screen_coordinate.x();
    y = screen_coordinate.y();
    qInfo() << screen_coordinate;
  } else {
    x = .5 * m_viewport->width(); // Fixme: vector
    y = .5 * m_viewport->height();
  }
  float accuracy_radius = m_viewport->to_px(location_circle_data.horizontal_precision());
  constexpr float dot_radius_minimum = 10.;
  constexpr float cone_scale_factor = 5.;
  float dot_radius = qMax(accuracy_radius, dot_radius_minimum);
  float radius = cone_scale_factor * dot_radius_minimum;
  float margin = 10;
  float size = radius + margin;
  float angle = location_circle_data.bearing() + 90.; // North point to y
  vertices[0].set(QcVectorDouble(x - size, y - size), QcVectorDouble(-size, -size), radius, dot_radius, accuracy_radius, angle);
  vertices[1].set(QcVectorDouble(x - size, y + size), QcVectorDouble(-size,  size), radius, dot_radius, accuracy_radius, angle);
  vertices[2].set(QcVectorDouble(x + size, y - size), QcVectorDouble( size, -size), radius, dot_radius, accuracy_radius, angle);
  vertices[3].set(QcVectorDouble(x + size, y + size), QcVectorDouble( size,  size), radius, dot_radius, accuracy_radius, angle);
}
Ejemplo n.º 24
0
/**
 * @brief Start listening
 *
 * If the preferred port is not available, a random port is chosen.
 *
 * @param preferredPort the default port to listen on
 */
bool BuiltinServer::start(quint16 preferredPort) {
	Q_ASSERT(m_state == NOT_STARTED);
	m_state = RUNNING;
	m_server = new QTcpServer(this);

	connect(m_server, &QTcpServer::newConnection, this, &BuiltinServer::newClient);

	bool ok = m_server->listen(QHostAddress::Any, preferredPort);

	if(!ok)
		ok = m_server->listen(QHostAddress::Any, 0);

	if(ok==false) {
		m_error = m_server->errorString();
		qCritical("Error starting server: %s", qPrintable(m_error));
		delete m_server;
		m_server = nullptr;
		m_state = NOT_STARTED;
		return false;
	}

	qInfo("Started listening on port %d", port());
	return true;
}
/**
* Main function: runs plugin based on its ID
* @param plugin ID
* @param image to be processed
**/
QSharedPointer<nmc::DkImageContainer> WriterIdentificationPlugin::runPlugin(
	const QString &runID, 
	QSharedPointer<nmc::DkImageContainer> imgC, 
	const nmc::DkSaveInfo& saveInfo,
	QSharedPointer<nmc::DkBatchInfo>& info) const {

	if (!imgC)
		return imgC;

	if(runID == mRunIDs[id_calcuate_features]) {
		qInfo() << "calculating features for writer identification";
		WriterIdentification wi = WriterIdentification();
		cv::Mat imgCv = nmc::DkImage::qImage2Mat(imgC->image());
		wi.setImage(imgCv);
		wi.calculateFeatures();
		cv::cvtColor(imgCv, imgCv, CV_RGB2GRAY);
		QVector<cv::KeyPoint> kp = wi.keyPoints();
		//QVector<cv::KeyPoint>::iterator kpItr = kp.begin();
		//cv::Mat desc = wi.descriptors();
		//cv::Mat newDesc = cv::Mat(0, desc.cols, desc.type());
		//int r = 0;
		//rdf::Image::imageInfo(desc, "desc");
		//for(auto kpItr = kp.begin(); kpItr != kp.end(); r++) {
		//	kpItr->size *= 1.5 * 4;
		//	if(kpItr->size > 70) {
		//		kpItr = kp.erase(kpItr);
		//	} else if(kpItr->size < 20) {
		//		kpItr = kp.erase(kpItr);
		//	} else {
		//		kpItr++;
		//		newDesc.push_back(desc.row(r).clone());
		//	}
		//}
		//rdf::Image::imageInfo(newDesc, "newDesc");
		//wi.setDescriptors(newDesc);
		//wi.setKeyPoints(kp);
		cv::drawKeypoints(imgCv, kp.toStdVector(), imgCv, cv::Scalar::all(-1), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
		////cv::drawKeypoints(imgCv, wi.getKeyPoints().toStdVector(), imgCv, cv::Scalar::all(-1));
		//
		////QString fFilePath = featureFilePath(imgC->filePath(), true);


		wi.saveFeatures(featureFilePath(imgC->filePath(), true));

		//QImage img = nmc::DkImage::mat2QImage(imgCv);
		//img = img.convertToFormat(QImage::Format_ARGB32);
		//imgC->setImage(img, tr("SIFT keypoints"));

	}
	else if(runID == mRunIDs[id_generate_vocabulary]) {
		qInfo() << "collecting files for vocabulary generation";

		QString ffPath = featureFilePath(imgC->filePath());

		int idxOfMinus = QFileInfo(imgC->filePath()).baseName().indexOf("-");
		int idxOfUScore = QFileInfo(imgC->filePath()).baseName().indexOf("_");
		int idx = -1;
		if(idxOfMinus == -1 && idxOfUScore > 0)
			idx = idxOfUScore;
		else if(idxOfUScore == -1 && idxOfMinus > 0)
			idx = idxOfMinus;
		else if(idxOfMinus > 0 && idxOfUScore > 0)
			idx = idxOfMinus > idxOfUScore ? idxOfMinus : idxOfUScore;
		QString label = QFileInfo(imgC->filePath()).baseName().left(idx);


		QSharedPointer<WIInfo> wInfo(new WIInfo(runID, imgC->filePath()));
		wInfo->setWriter(label);
		wInfo->setFeatureFilePath(ffPath);

		info = wInfo;
	}
	else if(runID == mRunIDs[id_identify_writer]) {
		qInfo() << "identifying writer";
	}
	else if(runID == mRunIDs[id_evaluate_database]) {
		qInfo() << "collecting files evaluation";

		if(mVocabulary.isEmpty()) {
			qWarning() << "batchProcess: vocabulary is empty ... not evaluating";
			return imgC;
		}

		QString fFilePath = featureFilePath(imgC->filePath());

		if(QFileInfo(fFilePath).exists()) {

			int idxOfMinus = QFileInfo(imgC->filePath()).baseName().indexOf("-");
			int idxOfUScore = QFileInfo(imgC->filePath()).baseName().indexOf("_");
			int idx = -1;
			if(idxOfMinus == -1 && idxOfUScore > 0)
				idx = idxOfUScore;
			else if(idxOfUScore == -1 && idxOfMinus > 0)
				idx = idxOfMinus;
			else if(idxOfMinus > 0 && idxOfUScore > 0)
				idx = idxOfMinus < idxOfUScore ? idxOfMinus : idxOfUScore;
			QString label = QFileInfo(imgC->filePath()).baseName().left(idx);
			qDebug() << "label: " << label << "\t\tbaseName:" << QFileInfo(imgC->filePath()).baseName();

			cv::FileStorage fs(fFilePath.toStdString(), cv::FileStorage::READ);
			if(!fs.isOpened()) {
				qWarning() << " unable to read file " << fFilePath;
				return imgC;
			}
			std::vector<cv::KeyPoint> kp;
			fs["keypoints"] >> kp;
			cv::Mat descriptors;
			fs["descriptors"] >> descriptors;
			fs.release();

			if(mVocabulary.minimumSIFTSize() > 0 || mVocabulary.maximumSIFTSize() > 0) {
				cv::Mat filteredDesc = cv::Mat(0, descriptors.cols, descriptors.type());
				int r = 0;
				for(auto kpItr = kp.begin(); kpItr != kp.end(); r++) {
					if(kpItr->size*1.5 * 4 > mVocabulary.maximumSIFTSize() && mVocabulary.maximumSIFTSize() > 0) {
						kpItr = kp.erase(kpItr);
					}
					else if(kpItr->size * 1.5 * 4 < mVocabulary.minimumSIFTSize()) {
						kpItr = kp.erase(kpItr);
					}
					else {
						kpItr++;
						filteredDesc.push_back(descriptors.row(r).clone());
					}
				}
				qDebug() << "filtered " << descriptors.rows - filteredDesc.rows << " SIFT features (maxSize:" << mVocabulary.maximumSIFTSize() << " minSize:" << mVocabulary.minimumSIFTSize() << ")";
				descriptors = filteredDesc;
			}
			else
				qDebug() << "not filtering SIFT features, min or max size not set";

			cv::Mat feature = mVocabulary.generateHist(descriptors);

			rdf::Image::imageInfo(descriptors, "descriptors");
			rdf::Image::imageInfo(feature, "feature");

			QSharedPointer<WIInfo> wInfo(new WIInfo(runID, imgC->filePath()));
			wInfo->setWriter(label);
			wInfo->setFeatureFilePath(fFilePath);
			wInfo->setFeatureVector(feature);

			info = wInfo;
		} else {
Ejemplo n.º 26
0
bool MySqlDataBase::createEmptyDB()
{
    const QString connName("createEmptyDBMySql");
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", connName);
        db.setHostName(info_.hostName());
        db.setUserName(info_.userName());
        db.setPassword(info_.password());

        if(!db.open())
        {
            return false;
        }
        else
        {
            QSqlQuery query(db);
            QString req("create database if not exists %1;");
            if(!query.prepare(req.arg(info_.dataBaseName())))
            {
                db.close();
                return false;
            }
            if(!query.exec())
            {

                qInfo() << query.lastError().text();
                db.close();
                return false;
            }
            db.setDatabaseName(info_.dataBaseName());
        }
        db.close();

        if(!db.open())
        {
            return false;
        }

        if(!executeQuery(db, "create table tItems("
                         "fItem integer primary key, "
                         "fStorage text not null, "
                         "fProduct text not null);"))
        {
            return false;
        }

        executeQuery(db, "create index iItems on tItems"
                         "(fItem);");

        if(!executeQuery(db, "create table tDatas("
                         "fItem integer, "
                         "fDate date not null, "
                         "fSold numeric(15,2) not null, "
                         "fRest numeric(15,2) not null, "
                         "primary key(fItem, fDate), "
                         "foreign key(fItem) references tItems(fItem));"))
        {
            return false;
        }

        executeQuery(db, "create index iDatas on tDatas"
                         "(fItem);");

        if(!executeQuery(db, "create table tAnalogs("
                         "fMain text not null, "
                         "fAnalog text not null);"))
        {
            return false;
        }
        //        executeQuery(db, "create index iAnalogsAnalog on tAnalogs"
        //                         "(fAnalog);");
        //        executeQuery(db, "create index iAnalogsMain on tAnalogs"
        //                         "(fMain);");
        db.close();
    }
    QSqlDatabase::removeDatabase(connName);

    return true;
}
Ejemplo n.º 27
0
bool MySqlDataBase::insertWithManyValues(const QString &tableDescr,
                                         const QList<QVariantList> &data)
{
    if(data.count() == 0
            || tableDescr.isEmpty())
    {
        return false;
    }
    QSqlQuery query(db_);

    const int bufferSizeMax = 2000;
    int counter = 0;
    const int dataSize = data.at(0).count();

    QString valuesRequet("(");
    for(int i = 0; i < data.count(); i++)
    {
        valuesRequet += "?, ";
    }
    valuesRequet = valuesRequet.left(valuesRequet.length()-2);
    valuesRequet += "),";

    beginTransaction();

    while(counter < dataSize)
    {
        int delta = 0;
        if(counter + bufferSizeMax <= dataSize)
        {
            delta = bufferSizeMax;
        }
        else
        {
            delta = dataSize - counter;
        }

        QString request("insert into " + tableDescr + " values");

        for(int j = counter; j < counter + delta ; j++)
        {
            request += valuesRequet;
        }

        request = request.left(request.length() - 1);
        request += ";";
        query.prepare(request);

        for(int k = counter; k < counter + delta; k++)
        {
            foreach (const QVariantList &list, data)
            {
                query.addBindValue(list.at(k));
            }
        }

        if(!query.exec())
        {
            qInfo() << query.lastError().text();
            qInfo() << query.lastQuery();
            rollbackTransaction();
            return false;
        }

        counter += delta;
    }
Ejemplo n.º 28
0
void Structure_Toolbar::sigma_Plot(bool)
{
	// TODO sigma_Plot_toolbutton
	qInfo() << "sigma_Plot is not implemented";
}
Ejemplo n.º 29
0
void Structure_Toolbar::thickness_Plot(bool)
{
	// TODO thickness_Plot_toolbutton
	qInfo() << "thickness_Plot is not implemented";
}
Ejemplo n.º 30
0
bool SecondService::init()
{
    qInfo("second service initializing");
    return true;
}