Esempio n. 1
0
void MainWindow::import()
{
    QDir dir=QFileDialog::getExistingDirectory();
    QStringList filters;
    filters<<"*.jpg"<<"*.bmp"<<"*.png";
    QTime time;
    time.start();
    QFileInfoList files=dir.entryInfoList(filters);

    foreach(QFileInfo file,files)
    {


        QRgb rgb;

        QImage img(file.absoluteFilePath());
        img=img.scaled(128,128);
        for(int i=0;i<128;i++)
            for(int j=0;j<128;j++)
            {
                rgb=img.pixel(i,j);
                yiq[0][i][j].setColor(rgb);
            }
        //YIQ **Pyiq=(YIQ**)yiq,**Pyiqh=(YIQ**)yiqh;
        //Now we need Haar 7 times
        for(int i=6;i>=0;i--)
        {
            int n=1<<i;
            int rule=0,rule1=1;
            //if(rule) rule1=0;
            double norm=sqrt(2<<(i-1));
            if(!norm) norm=1;
            for(int i=0;i<n;i++)
                for(int j=0;j<2*n;j++)
                {
                    yiq[rule1][i][j].setColor(( yiq[rule][2*i][j].Y + yiq[rule][2*i+1][j].Y )/2,
                                         ( yiq[rule][2*i][j].I + yiq[rule][2*i+1][j].I )/2,
                                         ( yiq[rule][2*i][j].Q + yiq[rule][2*i+1][j].Q )/2);
                    yiq[rule1][i+n][j].setColor(( yiq[rule][2*i][j].Y - yiq[rule][2*i+1][j].Y )/norm,
                                         ( yiq[rule][2*i][j].I - yiq[rule][2*i+1][j].I )/norm,
                                         ( yiq[rule][2*i][j].Q - yiq[rule][2*i+1][j].Q )/norm);

                }
            for(int i=0;i<2*n;i++)
                for(int j=0;j<n;j++)
                {
                    yiq[rule][i][j].setColor(( yiq[rule1][i][2*j].Y + yiq[rule1][i][2*j+1].Y )/2,
                                         ( yiq[rule1][i][2*j].I + yiq[rule1][i][2*j+1].I )/2,
                                         ( yiq[rule1][i][2*j].Q + yiq[rule1][i][2*j+1].Q )/2);
                    yiq[rule][i][j+n].setColor(( yiq[rule1][i][2*j].Y - yiq[rule1][i][2*j+1].Y )/norm,
                                         ( yiq[rule1][i][2*j].I - yiq[rule1][i][2*j+1].I )/norm,
                                         ( yiq[rule1][i][2*j].Q - yiq[rule1][i][2*j+1].Q )/norm);

                }
        }
        //______________________Now I need to sort results for 60 koefs__________________
        SortArray sArray[3];
        sArray[0].n=0;
        sArray[1].n=0;
        sArray[2].n=0;
        sArray[0].nmax=0;
        sArray[1].nmax=0;
        sArray[2].nmax=0;

                           //means to be 128
        for(int i=0;i<k;i++)
            for(int j=0;j<k;j++)
            {
                if(i!=0 && j!=0)
                {
                    if(yiq[0][i][j].Y != 0)
                    {
                        sArray[0].points[sArray[0].n].V = fabs(yiq[0][i][j].Y);
                        sArray[0].points[sArray[0].n].X = i;
                        sArray[0].points[sArray[0].n].Y = j;
                        if(sArray[0].points[sArray[0].nmax].V <fabs(yiq[0][i][j].Y)) sArray[0].nmax=sArray[0].n;
                        sArray[0].n++;
                    }
                    if(yiq[0][i][j].I != 0)
                    {
                        sArray[1].points[sArray[1].n].V = fabs(yiq[0][i][j].I);
                        sArray[1].points[sArray[1].n].X = i;
                        sArray[1].points[sArray[1].n].Y = j;
                        if(sArray[1].points[sArray[1].nmax].V <fabs(yiq[0][i][j].I)) sArray[1].nmax=sArray[1].n;
                        sArray[1].n++;
                    }
                    if(yiq[0][i][j].Q != 0)
                    {
                        sArray[2].points[sArray[2].n].V = fabs(yiq[0][i][j].Q);
                        sArray[2].points[sArray[2].n].X = i;
                        sArray[2].points[sArray[2].n].Y = j;
                        if(sArray[2].points[sArray[2].nmax].V <fabs(yiq[0][i][j].Q)) sArray[2].nmax=sArray[2].n;
                        sArray[2].n++;
                    }
                }
            }



        PointInfo cap;
        int nY=(sArray[0].n>20)?20:sArray[0].n;
        int nI=(sArray[1].n>20)?20:sArray[1].n;
        int nQ=(sArray[2].n>20)?20:sArray[2].n;
        if(nY)
        {
            for(int k=0;k<=nY;k++)
            {
            cap.V=sArray[0].points[k].V;
            cap.X=sArray[0].points[k].X;
            cap.Y=sArray[0].points[k].Y;
            sArray[0].points[k].V=sArray[0].points[sArray[0].nmax].V;
            sArray[0].points[k].X=sArray[0].points[sArray[0].nmax].X;
            sArray[0].points[k].Y=sArray[0].points[sArray[0].nmax].Y;
            sArray[0].points[sArray[0].nmax].V=cap.V;
            sArray[0].points[sArray[0].nmax].X=cap.X;
            sArray[0].points[sArray[0].nmax].Y=cap.Y;
            sArray[0].nmax=k+1;
            for(int i=k+1 ; i < sArray[0].n ; i++)
                if(sArray[0].points[sArray[0].nmax].V < sArray[0].points[i].V)
                    sArray[0].nmax=i;
            }
        }
        if(nI)
        {
            for(int k=0;k<=nI;k++)
            {
            cap.V=sArray[1].points[k].V;
            cap.X=sArray[1].points[k].X;
            cap.Y=sArray[1].points[k].Y;
            sArray[1].points[k].V=sArray[1].points[sArray[1].nmax].V;
            sArray[1].points[k].X=sArray[1].points[sArray[1].nmax].X;
            sArray[1].points[k].Y=sArray[1].points[sArray[1].nmax].Y;
            sArray[1].points[sArray[1].nmax].V=cap.V;
            sArray[1].points[sArray[1].nmax].X=cap.X;
            sArray[1].points[sArray[1].nmax].Y=cap.Y;
            sArray[1].nmax=k+1;
            for(int i=k+1 ; i < sArray[1].n ; i++)
                if(sArray[1].points[sArray[1].nmax].V < sArray[1].points[i].V)
                    sArray[1].nmax=i;
            }
        }
        if(nQ)
        {
            for(int k=0;k<=nQ;k++)
            {
            cap.V=sArray[2].points[k].V;
            cap.X=sArray[2].points[k].X;
            cap.Y=sArray[2].points[k].Y;
            sArray[2].points[k].V=sArray[2].points[sArray[2].nmax].V;
            sArray[2].points[k].X=sArray[2].points[sArray[2].nmax].X;
            sArray[2].points[k].Y=sArray[2].points[sArray[2].nmax].Y;
            sArray[2].points[sArray[2].nmax].V=cap.V;
            sArray[2].points[sArray[2].nmax].X=cap.X;
            sArray[2].points[sArray[2].nmax].Y=cap.Y;
            sArray[2].nmax=k+1;
            for(int i=k+1 ; i < sArray[2].n ; i++)
                if(sArray[2].points[sArray[2].nmax].V < sArray[2].points[i].V)
                    sArray[2].nmax=i;
            }
        }
        //qDebug()<<time.elapsed();
        //_______________ Ok now we have 60 main points, lets transform it in sign______________
        Sign sign[3];
        for(int i=0;i<nY;i++)
        {
            sign[0].points[i].V = (yiq[0][sArray[0].points[i].X][sArray[0].points[i].Y].Y > 0) ? 1 : -1;
            sign[0].points[i].X = sArray[0].points[i].X;
            sign[0].points[i].Y = sArray[0].points[i].Y;
        }
        for(int i=0;i<nI;i++)
        {
            sign[1].points[i].V = (yiq[0][sArray[1].points[i].X][sArray[1].points[i].Y].I > 0) ? 1 : -1;
            sign[1].points[i].X = sArray[1].points[i].X;
            sign[1].points[i].Y = sArray[1].points[i].Y;
        }
        for(int i=0;i<nQ;i++)
        {
            sign[2].points[i].V = (yiq[0][sArray[2].points[i].X][sArray[2].points[i].Y].Q > 0) ? 1 : -1;
            sign[2].points[i].X = sArray[2].points[i].X;
            sign[2].points[i].Y = sArray[2].points[i].Y;
        }

        QSqlQuery q;
        q.prepare(QLatin1String("INSERT INTO images(genreId, bigPath, smallPath,Y,I,Q) VALUES (1,'C:/1.jpg','C:/2.jpg',?,?,?)"));
        q.addBindValue(yiq[0][0][0].Y);
        q.addBindValue(yiq[0][0][0].I);
        q.addBindValue(yiq[0][0][0].Q);
        q.exec();
        int id=q.lastInsertId().toInt();
        q.prepare(QLatin1String("INSERT INTO Y(imageId, x, y, sign) VALUES (?,?,?,?)"));

        for(int i=0;i<nY;i++)
        {
            q.addBindValue(id);
            q.addBindValue(sign[0].points[i].X);
            q.addBindValue(sign[0].points[i].Y);
            q.addBindValue(sign[0].points[i].V);
            q.exec();
        }
        q.prepare(QLatin1String("INSERT INTO I(imageId, x, y, sign) VALUES (?,?,?,?)"));
        for(int i=0;i<nI;i++)
        {
            q.addBindValue(id);
            q.addBindValue(sign[1].points[i].X);
            q.addBindValue(sign[1].points[i].Y);
            q.addBindValue(sign[1].points[i].V);
            q.exec();
        }
        q.prepare(QLatin1String("INSERT INTO Q(imageId, x, y, sign) VALUES (?,?,?,?)"));
        for(int i=0;i<nQ;i++)
        {
            q.addBindValue(id);
            q.addBindValue(sign[2].points[i].X);
            q.addBindValue(sign[2].points[i].Y);
            q.addBindValue(sign[2].points[i].V);
            q.exec();
        }
        //qDebug()<<QString("/cache/%1.jpg").arg(id);

        img.save(QString("cache/%1.jpg").arg(id));

    }
bool DatabaseManager::insertBubble(int type, int number, std::vector<bubblePoint> bubble)
{

    // bool ret = false;

    if (db.isOpen())
    {

        QSqlQuery query;

        //  query.exec("PRAGMA journal_mode = MEMORY");
        //  query.exec("PRAGMA synchronous = OFF");
        query.prepare(QString("replace into bubble values( ?, ?, ?, ?, ?, ?)"));

        //    query.prepare(QString("insert into bubble values( :type, :number, :pan, :tilt, :val) ON DUPLICATE KEY update val = :val)"));

        //    updateQuery.prepare("update bubble set val = :val where type = %type and number = %2 and pan = %3 and tilt = %4");
        QVariantList typee;
        QVariantList numberr;
        QVariantList placeLabel;
        QVariantList pan;
        QVariantList tilt;
        QVariantList val;

        db.transaction();

        // Insert new bubble
        for(uint i = 0; i < bubble.size(); i++)
        {

            bubblePoint pt;

            pt = bubble.at(i);

            typee<<type;
            numberr<<number;
            pan<<pt.panAng;
            tilt<<pt.tiltAng;
            val<<pt.val;

            if(placeLabels.size() >= number)
            {
                placeLabel<<placeLabels.at(number-1);
            }

            else
                placeLabel<<-1;


            /*      query.bindValue(":type",type);
                 query.bindValue(":number",number);
                  query.bindValue(":pan",pt.panAng);
                   query.bindValue(":tilt",pt.tiltAng);
                   query.bindValue(":val",pt.val);*/
            //  query.exec();

            //query.exec(QString("insert into bubble values('%1', '%2', '%3', '%4', %5)").arg(type).arg(number).arg(pt.panAng).arg(pt.tiltAng).arg(pt.val));


        }



        query.addBindValue(typee);
        query.addBindValue(numberr);
        query.addBindValue(placeLabel);
        query.addBindValue(pan);
        query.addBindValue(tilt);
        query.addBindValue(val);


        if (!query.execBatch())
            qDebug() << query.lastError();

        db.commit();

        return true;

    }



    return false;



}
Esempio n. 3
0
int LoadAppScript::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (_name.isEmpty())
  {
    errMsg = TR("<font color=orange>The script does not have"
                         " a name.</font>");
    return -1;
  }

  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The script %1 is empty.</font>")
                         .arg(_filename);
    return -2;
  }

  if (_grade == INT_MIN)
  {
    QSqlQuery minOrder;
    minOrder.prepare("SELECT MIN(script_order) AS min "
                     "FROM script "
                     "WHERE (script_name=:name);");
    minOrder.bindValue(":name", _name);
    minOrder.exec();
    if (minOrder.first())
      _grade = minOrder.value(0).toInt();
    else if (minOrder.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = minOrder.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -3;
    }
    else
      _grade = 0;
  }
  else if (_grade == INT_MAX)
  {
    QSqlQuery maxOrder;
    maxOrder.prepare("SELECT MAX(script_order) AS max "
                     "FROM script "
                     "WHERE (script_name=:name);");
    maxOrder.bindValue(":name", _name);
    maxOrder.exec();
    if (maxOrder.first())
      _grade = maxOrder.value(0).toInt();
    else if (maxOrder.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = maxOrder.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -4;
    }
    else
      _grade = 0;
  }

  QSqlQuery select;
  QSqlQuery upsert;

  int scriptid  = -1;
  int pkgheadid = -1;
  int pkgitemid = -1;
  if (pkgname.isEmpty())
    select.prepare(QString("SELECT script_id, -1, -1"
                         "  FROM %1script "
                         " WHERE ((script_name=:name)"
                         "   AND  (script_order=:grade));")
                       .arg(_system ? "" : "pkg"));
  else
    select.prepare(_pkgitemQueryStr);
  select.bindValue(":name",    _name);
  select.bindValue(":pkgname", pkgname);
  select.bindValue(":grade",   _grade);
  select.bindValue(":type",    _pkgitemtype);
  select.exec();
  if(select.first())
  {
    scriptid  = select.value(0).toInt();
    pkgheadid = select.value(1).toInt();
    pkgitemid = select.value(2).toInt();
  }
  else if (select.lastError().type() != QSqlError::NoError)
  {
    QSqlError err = select.lastError();
    errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
    return -5;
  }

  if (scriptid >= 0)
  upsert.prepare(QString("UPDATE %1script "
                         "   SET script_order=:grade, "
                         "       script_enabled=:enabled,"
                         "       script_source=:source,"
                         "       script_notes=:notes "
                         " WHERE (script_id=:id); ")
                       .arg(_system ? "" : "pkg"));
  else
  {
    upsert.prepare("SELECT NEXTVAL('script_script_id_seq');");
    upsert.exec();
    if (upsert.first())
      scriptid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }

    upsert.prepare(QString("INSERT INTO %1script "
                           "       (script_id, script_name, script_order, "
                           "        script_enabled, script_source, script_notes) "
                           "VALUES (:id, :name, :grade, "
                           "        :enabled, :source, :notes);")
                        .arg(_system ? "" : "pkg"));
  }

  upsert.bindValue(":id",      scriptid);
  upsert.bindValue(":grade",   _grade);
  upsert.bindValue(":enabled", _enabled);
  upsert.bindValue(":source",  QString(pdata));
  upsert.bindValue(":notes",   _comment);
  upsert.bindValue(":name",    _name);

  if (!upsert.exec())
  {
    QSqlError err = upsert.lastError();
    errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
    return -7;
  }

  if (pkgheadid >= 0)
  {
    int tmp = upsertPkgItem(pkgitemid, pkgheadid, scriptid, errMsg);
    if (tmp < 0)
      return tmp;
  }

  return scriptid;
}
Esempio n. 4
0
/**
 * @brief eine Transition wird anhand der Eingabe durchgefuehrt
 * Die IDs der Zustaende idle(IDLE), selected(SELECTED), amountset(AMOUNTSET) und finished(FINISHED) werden gesetzt.
 * 
 * Anhand der ID des aktuellen Zustandes wird entschieden:
 * -IDLE: Anhand der Eingabe wird entschieden:
 *		 *SELECT: Der neue Zustand ist selected. Die Produkt ID wird (Aufruf getDetectedPid()) bestimmt.
 *		 *sonst: Fehlermeldung
 * -SELECTED: Anhand der Eingabe wird entschieden:
 *		 *ONE: Der neue Zustand ist amountset. Die Produktmenge ist 1.
 *		 *TWO: Der neue Zustand ist amountset. Die Produktmenge ist 2.
 *		 *BACK: Der neue Zustand ist idle.
 *		 *CANCEL: Der neue Zustand ist idle.
 *		 *sonst: Fehlermeldung
 * -AMOUNTSET: Anhand der Eingabe wird entschieden:
 *		 *PUTINCART: der neue Zustand ist finished. Das Produkt wird in den Warenkorb abgelegt.
 *		 *BACK: der neue Zustand ist selected. Die Produkt Menge wird zurueckgesetzt.
 *		 *CANCEL: der neue Zustand ist idle. Die Produkt Menge wird zurueckgesetzt.
 *		 *sonst: Fehlermeldung
 * -FINISHED: Anhand der Eingabe wird entschieden:
 *		 *MORE: der neue Zustand ist idle. Die Produkt Menge wird zurueckgesetzt.
 *		 *sonst: Fehlermeldung
 * @param input Eine Zahl, von der abhaengig ist, welche Aktion als naechstes ausgefuehrt wird.
 * @return void
 * @see IDLE 0
 * @see SELECTED 1
 * @see AMOUNTSET 2
 * @see FINISHED 3
 * @see ONE 1
 * @see TWO 2
 * @see SELECT 100
 * @see PUTINCART 101
 * @see BACK 102
 * @see CANCEL 103
 * @see MORE 104
 */
void automaton::transitions(int input){

    idle.setId(IDLE);
    selected.setId(SELECTED);
    amountset.setId(AMOUNTSET);
    finished.setId(FINISHED);

    QMessageBox msgBox;
    msgBox.setText("Die StateId ist: "+QString::number(currentState.getId())+"\nDer Input ist: "+QString::number(input));
    msgBox.exec();

    switch (currentState.getId()){

    case IDLE:
        switch (input) {
        case SELECT:
            // neue pid hier setzen
            setState(selected);
            this->setPid(connectedKinect->getDetectedPid());
            break;
        default:
            qDebug() << "FEHLER: case IDLE";
            break;
        }
    break;

    case SELECTED:
        switch (input) {
        case ONE:
            setState(amountset);
            setAmount(1);
            break;
        case TWO:
            setState(amountset);
            setAmount(2);
            break;
        case BACK:
            setState(idle);
            break;
        case CANCEL:
            setState(idle);
            break;
        default:
            qDebug() << "FEHLER: case SELECTED";
            break;
        }
    break;

    case AMOUNTSET:
        switch (input) {
        case PUTINCART:
        {
            setState(finished);
            QSqlQuery query;
            query.prepare("SELECT price, title FROM products WHERE id = :pid");
            query.bindValue(":pid", pid);
            query.exec();
            query.next();
            double price = query.value(0).toDouble();
            QString title = query.value(1).toString();
            connectedObj->addToCart(pid,amount,price,title);
            break;
        }
        case BACK:
            setState(selected);
            setAmount(0);
            break;
        case CANCEL:
            setState(idle);
            setAmount(0);
            break;
        default:
            qDebug() << "FEHLER: case AMOUNTSET";
            break;
        }
    break;

    case FINISHED:
        switch (input) {
        case MORE:
            setState(idle);
            setAmount(0);
            break;
        default:
            qDebug() << "FEHLER: case FINISHED";
            break;
        }
    break;

    default:
        qDebug() << "FEHLER: switch";
        break;
    }
}
void FrmFrameDetails::setFrameDetails(const Mode mode, const Persistence persistence, Sample* sample, 
                                      QList<int>& blackList, const Options options)
{
    qApp->setOverrideCursor( QCursor(Qt::BusyCursor ) );

    if (treeView==0) return;

    if (blackList.size()>0)
        treeView->setBlackList(blackList);

    treeView->setSupportNewItems(options & FrmFrameDetails::ALLOW_NEW);

    m_sample=sample;
    m_mode=mode;
    m_persistence=persistence;
    m_verified=false;
    m_submitted=false;

    //Now fix the UI
    lbPersistence->setText
        (persistence==FrmFrameDetails::PERMANENT?tr("Permanent"):tr("Temporary"));

    pushVerify->setEnabled(true);
    pushApply->setEnabled(!pushVerify->isEnabled());
    pushUndo->setEnabled(!pushVerify->isEnabled());

    pushVerify->setVisible(mode!=FrmFrameDetails::VIEW || persistence==FrmFrameDetails::TEMPORARY);
    pushApply->setVisible(mode!=FrmFrameDetails::VIEW || persistence==FrmFrameDetails::TEMPORARY);
    pushUndo->setVisible(mode!=FrmFrameDetails::VIEW || persistence==FrmFrameDetails::TEMPORARY);
    pushBack->setVisible(true);

    lineName->clear();
    textComments->clear();
    textDesc->clear();

    if (!initModel(mode,sample,options)){
        qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
        emit showError(tr("Could not create frame view!"));
        return;
    }

    if (mode==FrmFrameDetails::VIEW){// read-only on Permanent mode
        groupBox->setEnabled(false);
        setTreeReadOnly(true);
        horizontalLayout->addWidget(pushBack);
        persistence==FrmFrameDetails::PERMANENT? horizontalLayout->removeWidget(pushVerify):horizontalLayout->addWidget(pushVerify);
        persistence==FrmFrameDetails::PERMANENT? horizontalLayout->removeWidget(pushApply): horizontalLayout->addWidget(pushApply);
        persistence==FrmFrameDetails::PERMANENT? horizontalLayout->removeWidget(pushUndo): horizontalLayout->addWidget(pushUndo);

        persistence==FrmFrameDetails::PERMANENT?setTreeReadOnly(true):setTreeReadOnly(false);

        initMapper();//TODO: maybe throw an error here later?
        modelInterface->tRefFrame->setFilter(tr("Fr_Frame.ID=") + QVariant(sample->frameId).toString());
        mapper->toLast();

    }else{
        if (!modelInterface->insertNewRecord(modelInterface->tRefFrame)){
            qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
            QString strErrors;
            if (modelInterface->getErrors(strErrors))
                emit showError(strErrors);
            else
                emit showError(tr("Could not insert new record!"));
        }else{
            initMapper();//TODO: maybe throw an error here later?
            mapper->toLast();

            if (mode==FrmFrameDetails::EDIT){
                //set Frame Name
                QSqlQuery query;
                query.prepare(tr("SELECT dbo.FR_Frame.Name FROM dbo.FR_Frame ") + 
                              tr("WHERE     (dbo.FR_Frame.ID = ?)"));
                query.addBindValue(sample->frameId);
                if (!query.exec() || query.numRowsAffected()<1){
                    qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
                    if (query.lastError().type()!=QSqlError::NoError)
                        emit showError(query.lastError().text());
                    else
                        emit showError(tr("Could not retrieve the type of the cloned frame!"));
                    return;
                }
                query.first();
                this->cmbCloned->setCurrentIndex(this->cmbCloned->findText(
                    query.value(0).toString()));

                //Set src ID
                query.prepare(tr("SELECT dbo.Ref_Source.Name FROM dbo.FR_Frame INNER JOIN ") + 
                              tr("dbo.Ref_Source ON dbo.FR_Frame.id_source = dbo.Ref_Source.ID ") +
                              tr("WHERE     (dbo.FR_Frame.ID = ?)"));
                query.addBindValue(sample->frameId);
                if (!query.exec() || query.numRowsAffected()<1){
                    qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
                    if (query.lastError().type()!=QSqlError::NoError)
                        emit showError(query.lastError().text());
                    else
                        emit showError(tr("Could not retrieve the type of the cloned frame!"));
                    return;
                }
                query.first();

                this->cmbType->setCurrentIndex(this->cmbType->findText(query.value(0).toString()));

            }else if (mode==FrmFrameDetails::CREATE)

                this->cmbCloned->setCurrentIndex(this->cmbCloned->findText(
                    qApp->translate("null_replacements", strNa)));

            emit showStatus(tr("Record successfully initialized!"));
        }

        groupBox->setEnabled(true);
        setTreeReadOnly(false);

        horizontalLayout->addWidget(pushVerify);
        horizontalLayout->addWidget(pushApply);
        horizontalLayout->addWidget(pushUndo);
        horizontalLayout->addWidget(pushBack);

    }

    qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
}
Esempio n. 6
0
bool DataManager::saveDatabaseTimeRecord(Map map) {
    qDebug("DataManager::saveDatabaseTimeRecord");
    QString userName;

#if defined(UNICODE)
    if ( QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)
    {
        TCHAR winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
        DWORD winUserNameSize = sizeof(winUserName);
        GetUserName( winUserName, &winUserNameSize );
        userName = QString::fromWCharArray( winUserName );
    } else
#endif
    {
        char winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
        DWORD winUserNameSize = sizeof(winUserName);
        GetUserNameA( winUserName, &winUserNameSize );
        userName = QString::fromLocal8Bit( winUserName );
    }

    qDebug("DataManager::saveDatabaseTimeRecord windows user: %s", userName.toStdString().c_str());
    QString userGuid;
    std::string userGuidSql = "select id from dbo.CoreUser where AccountName = 'VIS_BOG_HQ\\" + userName.toStdString() + "'";
    QSqlQuery sqlUserGuid(QString(userGuidSql.c_str()));
    if (sqlUserGuid.next()) {
        userGuid = sqlUserGuid.value(0).toString();
        qDebug("DataManager::saveDatabaseTimeRecord user guid: %s", userGuid.toStdString().c_str());
    } else {
        qDebug("User %s not found", userName.toStdString().c_str());
        return false;
    }

    int periodId = period(map.date.toQDateTime());
    qDebug("DataManager::saveDatabaseTimeRecord period id: %d", periodId);
    if (periodId == -1) {
        return false;
    }

    int displayOrder = 1;
    QSqlQuery displayOrderSql;
    if (displayOrderSql.prepare("select Max(displayOrder) from dbo.TimeEntry where PeriodId = :Period and CoreUserId = :CoreUserId")) {
        displayOrderSql.bindValue(":Period", periodId);
        displayOrderSql.bindValue(":CoreUserId", userGuid);
        if (displayOrderSql.exec() && displayOrderSql.next()) {
            displayOrder = displayOrderSql.value(0).toInt() + 1;
        } else {
            displayOrder = 1;
        }
    } else {
        qDebug("Error getting the displayOrder");
        return false;
    }
    qDebug("DataManager::saveDatabaseTimeRecord displayOrder: %d", displayOrder);
    std::stringstream ssSql;
    ssSql << "INSERT INTO TimeEntry (PeriodId,ProjectId,TaskId,CoreUserId,Date,Hours,Description,UpdatedOn,DisplayOrder,Version)";
    ssSql << " VALUES (:PeriodId,:ProjectId,:TaskId,:CoreUserId,:Date,:Hours,:Description,:UpdatedOn,:DisplayOrder,:Version)";
    QSqlQuery insert;
    insert.prepare(QString(ssSql.str().c_str()));
    insert.bindValue(":PeriodId", periodId);
    insert.bindValue(":ProjectId", map.coreProject.id);
    insert.bindValue(":TaskId", map.coreTask.id);
    insert.bindValue(":CoreUserId", userGuid);
    insert.bindValue(":Date", map.date.toQDateTime());
    double minutes = ((double)((int)(map.time.totalMinutes() * 100))/(double)100);

    insert.bindValue(":Hours", minutes);
    insert.bindValue(":Description", map.description);
    insert.bindValue(":UpdatedOn", QDateTime::currentDateTime());
    insert.bindValue(":DisplayOrder", displayOrder);
    insert.bindValue(":Version", 2);
    bool updated = insert.exec();
    if (!updated) {
        qDebug("An error has ocurred executing the insertion. Error: %s", insert.lastError().text().toStdString().c_str());
    }

    qDebug("out DataManager::saveDatabaseTimeRecord");
    return updated;
}
void Login::on_pushButton_Login_clicked()
{

    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();
    QSqlQuery query;
    QString employID;
    QString isTempPass;
    QString islocked;
    roleSel *roleDash = new roleSel();
    query.bindValue(":username", username);
    query.bindValue(":password", password);
    bool debug = true;

    if (debug)
    {
        if ((username == "root") & (password == "root"))
        {
            accountCreate *ACDash = new accountCreate();
            this->close();
            ACDash->show();
            ACDash->activateWindow();
            ACDash->raise();
        }
    }
    setLoginCount(username);

                //checks login if correct
                query.prepare("SELECT * FROM Account WHERE accountID = '"+username+"' and password = '******'");
                if (query.exec())
                {
                    qDebug()<<"Code has entered login check";
                    int count=0;
                    while(query.next())
                    {
                        employeeID = query.value(1).toString();
                       // qDebug()<<"I have entered this";
                        isTempPass = query.value(6).toString();
                        islocked = query.value(7).toString();
                        count++;
                        qDebug()<<"The count is: "<<count;
                     }
                     if (count==1)
                     {
                        ui->label_status->setText("Login Successful");

                        //user needs to change password because current is temporary
                        if (isTempPass == "1")
                        {
                            changePass *passDash = new changePass();
                            QObject::connect(this, SIGNAL(sendData(QString)), &*passDash, SLOT(receiveData(QString)));
                            emit sendData(employeeID);
                            passDash->setModal(true);
                            passDash->show();
                            passDash->activateWindow();
                            passDash->raise();
                        }
                        else //information is correct
                        {
                            //check if account is locked
                            if (islocked == "1")
                            {
                                QMessageBox msgbox;
                                msgbox.setText("Your Account is locked, please see a system administrator");
                                msgbox.exec();
                            }
                            //account is not locked
                            else
                            {
                                QObject::connect(this, SIGNAL(sendData(QString)), &*roleDash, SLOT(receiveData(QString)));
                                qDebug()<<"Sending data: "<<employeeID;
                                qDebug()<<"Temporary pass is: "<<isTempPass;
                                emit sendData(employeeID);
                                query.prepare("UPDATE Account SET loginCountID = '0' FROM Account WHERE accountID = '"+username+"'");
                                if(query.exec())
                                {
                                     qDebug()<<"The loginCount being reset to is : "<<loginCount;
                                     ui->label_loginCount->setText("");
                                }
                                this->hide();
                                roleDash->show();
                                roleDash->activateWindow();
                                roleDash->raise();
                            }
                        }
                      }
                        //login information is incorrect
                        if (count<1)
                        {
                            qDebug()<<"Code has entered the fail to vertify section";
                            ui->label_status->setText("username or password is incorrect");
                            //check if loginCount has been maxed
                            //if loginCount is over 6 then lock the account
                            if (loginCount >6)
                            {
                                QMessageBox msgbox;
                                msgbox.setText("You have failed to login 6 times, your account is now locked. "
                                                 "Please see the system administrator for further assistance");
                                query.prepare("UPDATE Account SET islocked = '1' FROM Account WHERE accountID = '"+username+"'");
                                query.exec();
                                msgbox.exec();

                                //reset count and label
                                //loginCount = 1;
                                query.prepare("UPDATE Account SET loginCountID = '0' FROM Account WHERE accountID = '"+username+"'");
                                if(query.exec())
                                {
                                     qDebug()<<"The loginCount being reset to is : "<<loginCount;
                                     ui->label_loginCount->setText("");
                                }

                            }
                            //or just increase loginCount and display warning
                            else
                            {
                                //increase login count for failed login
                                loginCount++;
                                qDebug()<<(QString("Currently trying to insert: %1 into loginCountID").arg(loginCount));
                                qDebug()<<"The username's loginCountID being changed is: "<<username;
                                query.prepare("UPDATE Account SET loginCountID = :loginCountID FROM Account WHERE accountID = '"+username+"'");
                                query.bindValue(":loginCountID", loginCount);
                                query.exec();
                                qDebug()<<(loginCount)<<"times has been tried";
                                ui->label_loginCount->setText(QString("You have tried to login: %1 times").arg(loginCount));
                            }

                        }
                    }


}
Esempio n. 8
0
int main(int argc, char *argv[]) {

    QCoreApplication app(argc, argv);
    QTextCodec* codec = QTextCodec::codecForName("Windows-1251");

    // Подготовка SQLite базы данных
    QSqlDatabase sdb = QSqlDatabase::addDatabase("QSQLITE");
    sdb.setDatabaseName("pdd.db");
    if(!sdb.open()) {
       std::cout << sdb.lastError().text().toStdString() << std::endl;
       return EXIT_FAILURE;
    }

    QString category_name = "ab";
    do {
        std::string pe_main_name(category_name.toStdString() + "/text.dat");
        //pe_main_name.append(category_name.toStdString() + "/text.dat");
        std::string pe_comment_name(category_name.toStdString() + "/comment.dat");
        //pe_comment_name.append(category_name.toStdString() + "/comment.dat");

        // Открываем файл
        std::ifstream pe_main(pe_main_name.c_str(), std::ios::in | std::ios::binary);
        if(!pe_main) {
            std::cout << "Error on open " << pe_main_name << std::endl;
            return EXIT_FAILURE;
        }

        // Открываем файл
        std::ifstream pe_comment(pe_comment_name.c_str(), std::ios::in | std::ios::binary);
        if(!pe_comment){
            std::cout << "Error on open " << pe_comment_name << std::endl;
            return EXIT_FAILURE;
        }

        Themes themes;

        try {
            //Создаем экземпляр PE или PE+ класса с помощью фабрики
            pe_base image( pe_factory::create_pe(pe_main) );
            //Проверим, есть ли ресурсы у файла
            if(!image.has_resources()) {
                std::cout << pe_main_name << " does not have resources" << std::endl;
                return EXIT_FAILURE;
            }
            //Получаем корневую директорию ресурсов
            const resource_directory root(get_resources(image));
            pe_resource_viewer res(root);

            //Создаем экземпляр PE или PE+ класса с помощью фабрики
            pe_base imageComment( pe_factory::create_pe(pe_comment) );
            //Проверим, есть ли ресурсы у файла
            if(!imageComment.has_resources()) {
                std::cout << pe_comment_name << " does not have resources" << std::endl;
                return EXIT_FAILURE;
            }
            //Получаем корневую директорию ресурсов
            const resource_directory rootComment(get_resources(imageComment));
            pe_resource_viewer resComment(rootComment);

            // Правильные ответы по номерам вопросов
            std::map<uint, uint> ans;
            {
                resource_data_info info("", 0);
                if(res.get_language_count(L"OTV", 1018) > 1)
                    info = res.get_resource_data_by_id( 0, L"OTV", 1018 );
                else
                    info = res.get_resource_data_by_id( 1049, L"OTV", 1018 );

                std::string raw( info.get_data() );
                for(unsigned int i = 4; i < raw.size(); i+=2 ) {
                    uint16_t answer = raw[i] + (raw[i+1]<<8);
                    unsigned int n = i/2 - 2;
                    ans.insert( std::make_pair( n, answer ));
                }
            }

            // Вопросы по темам (номер вопроса - номер темы)
            {
                // Количество тем
                resource_data_info info = res.get_resource_data_by_id(1049, L"COUNTTEM", 1021);
                std::string raw( info.get_data() );
                uint totalThemes = raw[0] + (raw[1] << 8);

                themes.resize(totalThemes);

                for( uint t = 0; t < totalThemes; ++t ) {
                    resource_data_info info("", 0);
                    if( res.get_language_count(L"POTEMAM", 1022+t) > 1 )
                        info = res.get_resource_data_by_id( 0, L"POTEMAM", 1022+t );
                    else
                        info = res.get_resource_data_by_id( 1049, L"POTEMAM", 1022+t );

                    std::string raw( info.get_data() );
                    uint32_t questionsInTheme = (raw.size() - 4)/6; // количество вопросов в теме
                    themes[t].questions.resize(questionsInTheme);

                    for( unsigned int i = 0; i < questionsInTheme; ++i ) {
                        uint16_t n = 20*(raw[4 + i*6] - 1) + raw[6 + i*6] - 1;
                        Question& question = themes[t].questions[i];
                        question.themeNumber = t;
                        question.number = n+1;
                        question.imageName = QString("jpg%1.jpg").arg(n+1);
                        uint qid = n + 217;

                        // правильный ответ
                        std::map<uint,uint>::iterator a = ans.find(n);
                        if(a != ans.end())
                            question.answer = a->second;

                        // задание и варианты ответов
                        {
                            resource_data_info info( "", 0 );
                            if( res.get_language_count( L"TEXT", qid ) > 1 )
                                info = res.get_resource_data_by_id( 0, L"TEXT", qid );
                            else
                                info = res.get_resource_data_by_id( 1049, L"TEXT", qid );

                            std::string raw( info.get_data() );
                            question.set_task_and_answers(codec->toUnicode(raw.c_str()));
                        }

                        // комментарий
                        {
                            resource_data_info info( "", 0 );
                            if( resComment.get_language_count( L"TEXT", qid ) > 1 )
                                info = resComment.get_resource_data_by_id( 0, L"TEXT", qid );
                            else
                                info = resComment.get_resource_data_by_id( 1049, L"TEXT", qid );

                            std::string raw( info.get_data() );
                            question.comment = codec->toUnicode(raw.c_str()).replace("\n", " ");
                        }
                    }

                    { // Названия тем
                        resource_data_info info = res.get_resource_data_by_id(1049, L"THEME_NAME", 1050 + t);
                        themes[t].name = codec->toUnicode(info.get_data().c_str());
                    }
                }
            }

        } catch( const pe_exception& e ) { //Если возникла ошибка
            std::cout << e.what() << std::endl;
            return EXIT_FAILURE;
        }

        // Данные из PE файлов загружены. Формируем таблицы новой базы данных

        for(uint t = 0; t < themes.size(); ++t) {
            QSqlQuery addTheme;
            addTheme.prepare(QString("INSERT INTO themes_%1"\
                             "(theme_num, name, quest_count)"\
                             " VALUES"\
                             "(:theme_num, :name, :quest_count);").arg(category_name));

            addTheme.bindValue(":theme_num", t+1);
            addTheme.bindValue(":name", themes[t].name);
            addTheme.bindValue(":quest_count", themes[t].questions.size());

            if(!addTheme.exec()) {
                std::cout << addTheme.lastError().text().toStdString() << std::endl;
            }
        }

        uint i = 1;
        for(uint t = 0; t < themes.size(); ++t) {

            uint in_theme_num = 1;
            Questions& questions = themes[t].questions;
            for(Questions::iterator q = questions.begin(); q != questions.end(); ++q) {
                QSqlQuery addQuestion;
                addQuestion.prepare(QString("INSERT INTO questions_%1"\
                                    "(number, task, vars_count, right_ans, comment, ans_v1, ans_v2, ans_v3, ans_v4, ans_v5, image, theme_num, in_theme_num)"
                                    "VALUES"\
                                    "(:number, :task, :vars_count, :right_ans, :comment, :ans_v1, :ans_v2, :ans_v3, :ans_v4, :ans_v5, :image, :theme_num, :in_theme_num);").arg(category_name));

                addQuestion.bindValue(":number", i++);
                addQuestion.bindValue(":task", q->task);
                QStringList& answers = q->answers;
                uint vars_count = answers.size();
                addQuestion.bindValue(":vars_count", vars_count);
                addQuestion.bindValue(":right_ans", q->answer);
                addQuestion.bindValue(":comment", q->comment);

                for(uint v = 0; v < vars_count; ++v) {
                    addQuestion.bindValue(QString(":ans_v%1").arg(v+1), answers[v]);
                }

                for(uint k = vars_count; k < 6; ++k) {
                    addQuestion.bindValue(QString(":ans_v%1").arg(k+1), "");
                }

                addQuestion.bindValue(":image", q->imageName);
                addQuestion.bindValue(":theme_num", q->themeNumber+1);
                addQuestion.bindValue(":in_theme_num", in_theme_num++);

                if(!addQuestion.exec()) {
                    std::cout << addQuestion.lastError().text().toStdString() << std::endl;
                } else {
                    std::cout << category_name.toStdString() << " add question " << i-1 << std::endl;
                }
            }
        }

        if(category_name == "ab") category_name = "cd";
        else category_name = "";

    } while(category_name != "");

    std::cout << "Complited." << std::endl;
    return app.exec();
}
Esempio n. 9
0
void MainWindow::on_pushButton_2_clicked()
{
    if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("不能为空"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    QSqlQuery query;
    QString s_num="";
    QString b_num="";
    QString o_name="";
    QString o_author="";
    QString o_price ="";
    QString s_name="";
    QString b_id="";
    query.prepare("select C_NUM from  COUNT where C_NO = :uid");
    query.bindValue(":uid",ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_num = query.value(0).toString();
    }
    query.prepare("select * from  BOOKS where O_ISBN = :bid");
    query.bindValue(":bid",ui->B_NIO->text());
    query.exec();
    if(query.next()){
        o_name = query.value(1).toString();
        o_author = query.value(2).toString();
        o_price = query.value(4).toString();
        b_num = query.value(5).toString();
    }
    qDebug()<<s_num<<b_num;
    query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?");
    query.addBindValue(ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_name = query.value(0).toString();
        qDebug()<<s_name;
    }
    if(s_num.isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    if(b_num.isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    int ss_num=s_num.toInt();
    int bb_num=b_num.toInt();
    ++bb_num;
    ++ss_num;
    qDebug()<<ss_num<<bb_num;
    query.prepare("UPDATE BOOKS SET  O_STORAGE = ? WHERE O_ISBN = ?");
    query.addBindValue(QString::number(bb_num,10));
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    query.prepare("UPDATE COUNT SET  C_NUM = ? WHERE C_NO = ?");
    query.addBindValue(QString::number(ss_num,10));
    query.addBindValue(ui->S_NO->text());
    query.exec();
    QDate date;
    QDate oldDate;
    QString oldDatetem;
    date=date.currentDate();
    QString newdate=date.toString("yyyy.M.d");
    qDebug()<<newdate;
    int countI = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(countI);
    ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text()));
    ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name));
    ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text()));
    ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name));
    ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author));
    ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price));
    ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("还回"))));
    ui->tableWidget->setItem(countI,8,new QTableWidgetItem(newdate));
    query.prepare("SELECT B_ID,B_TIME FROM BORROW WHERE B_NO = ? AND B_ISBN = ? AND B_ISRENT = 0");
    query.addBindValue(ui->S_NO->text());
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    if(query.first()){
        b_id = query.value(0).toString();
        oldDatetem = query.value(1).toString();
        oldDatetem.replace(QString("-"),QString(""));
        qDebug()<<b_id<<oldDatetem;
    }
    query.prepare("UPDATE BORROW SET B_ISRENT=?,B_RENTTIME=? WHERE B_ID = ?");
    query.addBindValue(1);
    query.addBindValue(newdate);
    query.addBindValue(b_id);
    query.exec();
    oldDate=oldDate.fromString(oldDatetem,"yyyyMMdd");
    qDebug()<<oldDate.toString("yyyy.M.d");
    int timeforBorrow = oldDate.daysTo(date);
    if(timeforBorrow > 30){
        qDebug()<<timeforBorrow;
        QString temOfMessage=QString(tr("超期 %1 天")).arg((timeforBorrow-30));
        QMessageBox::information(this,tr("提示"),temOfMessage,QMessageBox::Ok);
        return;
    }
    query.clear();
}
void SelectUser::on_commandLinkButton_delete_clicked()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "AvisionR - Delete",
                                  "Are you sure you want to DELETE this Employee from your Database?", QMessageBox::Yes|QMessageBox::No);
    if(reply == QMessageBox::Yes)
    {
        {
            Database conn;
            if(!conn.connOpen("Employee"))
            {
                qDebug()<<"Failed to open Data";
                return;
            }

            QSqlQuery * qry = new QSqlQuery(conn.mydb);

            QString queryString;
            QTextStream queryStream(&queryString);

            queryStream << "DELETE FROM Employees WHERE ID = '" << ui->label_id->text() << "'";

            qry->prepare(queryString);

            if(qry->exec())
            {}
            else
            {
                QMessageBox::critical(this, tr("Error"), qry->lastError().text());
            }

            conn.connClose();
        }

        {
            Database conn;
            if(!conn.connOpen("Clock"))
            {
                qDebug()<<"Failed to open Data";
                return;
            }

            QSqlQuery * qry = new QSqlQuery(conn.mydb);

            QString queryString;
            QTextStream queryStream(&queryString);

            queryStream << "DROP TABLE '" << ui->label_id->text() << "'";

            qry->prepare(queryString);

            if(qry->exec())
            {
                thisUser->setup();
                QMessageBox::information(this, tr("AvisionR - Delete"), "Employee Deleted");
            }
            else
            {
                QMessageBox::critical(this, tr("Error"), qry->lastError().text());
            }

            conn.connClose();
        }


        this->hide();
    }
}
Esempio n. 11
0
void PlurkDbManager::addPlurk(QString plurk_id, QString plurk_type,
                              QString owner_id, QString content,
                              QString is_unread, QString favorite,
                              QString qual_trans, QString res_seen,
                              QString res_cnt, QString posted) {
    QSqlQuery query;
    QString dummy;
    query.exec("SELECT * FROM plurks WHERE plurk_id='" + plurk_id + "'");
    if(query.next()) {
        //Update record
        query.prepare(dummy + "UPDATE plurks SET plurk_type=:plurk_type,"
                      + "content=:content,"
                      + "is_unread=:is_unread,"
                      + "favorite=:favorite,"
                      + "reponses_seen=:res_seen,"
                      + "response_cnt=:res_cnt"
                      + " WHERE plurk_id=:plurk_id");
        query.bindValue(":plurk_type",plurk_type);
        query.bindValue(":content",content);
        query.bindValue(":is_unread",is_unread);
        query.bindValue(":favorite",favorite);
        query.bindValue(":res_seen",res_seen);
        query.bindValue(":res_cnt",res_cnt);
        query.bindValue(":plurk_id",plurk_id);
        query.exec();
    } else {
        //Add record
        query.prepare(dummy + "INSERT INTO plurks("
                      + "plurk_id,"
                      + "plurk_type,"
                      + "owner_id,"
                      + "content,"
                      + "is_unread,"
                      + "favorite,"
                      + "qualifier_translated,"
                      + "responses_seen,"
                      + "response_count,"
                      + "posted) VALUES("
                      + ":plurk_id,"
                      + ":plurk_type,"
                      + ":owner_id,"
                      + ":content,"
                      + ":is_unread,"
                      + ":favorite,"
                      + ":qual_trans,"
                      + ":res_seen,"
                      + ":res_cnt,"
                      + ":posted)");
        query.bindValue(":plurk_id",plurk_id);
        query.bindValue(":plurk_type",plurk_type);
        query.bindValue(":owner_id",owner_id);
        query.bindValue(":content",content);
        query.bindValue(":is_unread",is_unread);
        query.bindValue(":favorite",favorite);
        query.bindValue(":qual_trans",qual_trans);
        query.bindValue(":res_seen",res_seen);
        query.bindValue(":res_cnt",res_cnt);
        query.bindValue(":posted",posted);
        query.exec();
    }
}
TableauDeRemplissage::TableauDeRemplissage(int idEvenement, QObject *parent)
    : Etat(tr("Tableau de remplissage"), idEvenement, parent)
{
    QSqlQuery query;
    if (query.prepare("select *"
                      " from tableau_de_remplissage"
                      " where id_evenement=:id_evenement")) {
        query.bindValue(":id_evenement", idEvenement);
        if (query.exec()) {
            // FIXME : ce rapport devrait être une feuille de calcul

            QString symboleAcceptee = "●";
            QString symboleProposee = "◍";
            QString symbolePossible = "○";
            QString symboleManquante = "◌";

            QTextCursor c(this);

            QTextBlockFormat formatDuTitreDeLaLegende;
            formatDuTitreDeLaLegende.setBottomMargin(10);

            QTextCharFormat formatDesCaracteresDuTitreDeLaLegende;
            formatDesCaracteresDuTitreDeLaLegende.setUnderlineStyle(QTextCharFormat::SingleUnderline);

            QTextBlockFormat formatDesBlocsDeLaLegende;

            QTextCharFormat formatDesCaracteresDeLaLegende;

            QTextListFormat formatDeLaListeDeLaLegende;

            QTextBlockFormat formatDuBlocJour;
            formatDuBlocJour.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
            formatDuBlocJour.setAlignment(Qt::AlignCenter);
            formatDuBlocJour.setBottomMargin(20);

            QTextCharFormat formatDesCaracteresDuJour;
            formatDesCaracteresDuJour.setFontCapitalization(QFont::Capitalize);
            formatDesCaracteresDuJour.setFontPointSize(14);
            formatDesCaracteresDuJour.setFontWeight(QFont::Bold);

            QTextBlockFormat formatDuBlocTour;
            formatDuBlocTour.setTopMargin(20);

            QTextCharFormat formatDesCaracteresDuTour;
            formatDesCaracteresDuTour.setFontWeight(QFont::Bold);

            QTextBlockFormat formatDuBlocDesResponsables;

            QTextCharFormat formatDesCaracteresDesResponsables;

            QTextBlockFormat formatDuBlocDuRemplissage;

            QTextCharFormat formatDesCaracteresDuRemplissage;

            if (query.first()) {
                c.movePosition(QTextCursor::End);
                c.insertBlock(formatDuTitreDeLaLegende, formatDesCaracteresDuTitreDeLaLegende);
                c.insertText(tr("Légende"));
                c.insertBlock(formatDesBlocsDeLaLegende, formatDesCaracteresDeLaLegende);
                c.insertList(formatDeLaListeDeLaLegende);
                c.insertText(tr("%1 affectation acceptée ou validée").arg(symboleAcceptee));
                c.insertText("\n");
                c.insertText(tr("%1 affectation proposée, en attente d'acceptation").arg(symboleProposee));
                c.insertText("\n");
                c.insertText(tr("%1 affectation possible, à proposer ou valider").arg(symbolePossible));
                c.insertText("\n");
                c.insertText(tr("%1 affectation manquante, reste à créer").arg(symboleManquante));
                QSqlRecord r = query.record();
                do {
                    QDate jour = r.value("debut_tour").toDate();
                    c.insertBlock(formatDuBlocJour, formatDesCaracteresDuJour);
                    c.insertText(QLocale().toString(jour));
                    do {
                        int
                                min = r.value("min").toInt(),
                                max = r.value("max").toInt(),
                                possibles = r.value("nombre_affectations_possibles").toInt(),
                                proposees = r.value("nombre_affectations_proposees").toInt(),
                                acceptees = r.value("nombre_affectations_validees_ou_acceptees").toInt(),
                                trouvees = acceptees + proposees + possibles,
                                manquantes = trouvees < min ? min - trouvees : 0,
                                enTrop = max < trouvees ? trouvees - max : 0;
                        QString responsables = r.value("liste_responsables").toString();
                        c.insertBlock(formatDuBlocTour, formatDesCaracteresDuTour);
                        c.insertText(tr("De %1 à %2 / %3")
                                     .arg(r.value("debut_tour").toTime().toString("H:mm"))
                                     .arg(r.value("fin_tour").toTime().toString("H:mm"))
                                     .arg(r.value("nom_poste").toString())
                                     );
                        if (!responsables.isEmpty()) {
                            c.insertBlock(formatDuBlocDesResponsables, formatDesCaracteresDesResponsables);
                            c.insertText(tr("Responsable(s) : %1").arg(responsables));
                        }
                        c.insertBlock(formatDuBlocDuRemplissage, formatDesCaracteresDuRemplissage);
                        c.insertText(symboleAcceptee.repeated(acceptees));
                        c.insertText(symboleProposee.repeated(proposees));
                        c.insertText(symbolePossible.repeated(possibles));
                        c.insertText(symboleManquante.repeated(manquantes));
                        if (enTrop) c.insertText(tr(" (%n affectation(s) en trop)", "", enTrop));
                        query.next();
                        r = query.record();
                    } while (query.isValid()
                             && r.value("debut_tour").toDate() == jour);
                } while (query.isValid());
            } else {
                qWarning() << tr("Aucune affectation trouvée");
            }
        } else {
            qCritical() << query.lastError();
        }
    } else {
        qCritical() << query.lastError();
    }
}
Esempio n. 13
0
void DocDigestDetailView::documentListing( TextTemplate *tmpl, int year, int month )
{

    QString minDate;
    QString maxDate;
    if( month > -1 ) {
        QDate theDate(year, month, 1);
        // not a year
        minDate = theDate.toString("yyyy-MM-dd");
        int lastDay = theDate.daysInMonth();
        theDate.setDate(year, month, lastDay);
        maxDate = theDate.toString("yyyy-MM-dd");
    } else {
        // is is a year
        minDate = QString::number(year)+"-01-01";
        maxDate = QString::number(year)+"-12-31";
    }

    // read data in the given timeframe from database
    QSqlQuery q;
    const QString query = QString("SELECT archDocID, ident, MAX(printDate) FROM archdoc WHERE "
                                  "date BETWEEN date('%1') AND date('%2') "
                                  "GROUP BY ident").arg(minDate, maxDate);

    // qDebug() << "***" << query;
    QMap<QString, QPair<int, Geld> > docMatrix;
    q.prepare(query);
    q.exec();
    while( q.next() ) {
       dbID archDocId(q.value(0).toInt());

       const ArchDoc doc(archDocId);
       const QString docType = doc.docType();
       Geld g;
       int n = 0;
       if( docMatrix.contains(docType)) {
           g = docMatrix[docType].second;
           n = docMatrix[docType].first;
       }
       Geld g1 = doc.nettoSum();
       g += g1;
       docMatrix[docType].first = n+1;
       docMatrix[docType].second = g;
     }

    // now create the template

    tmpl->setValue("I18N_AMOUNT", i18n("Amount"));
    tmpl->setValue("I18N_TYPE",   i18n("Type"));
    tmpl->setValue("I18N_SUM",    i18n("Sum"));

    QStringList doctypes = docMatrix.keys();
    doctypes.sort();

    foreach( const QString dtype, doctypes ) {
        qDebug() << "creating doc list for "<<dtype;
        tmpl->createDictionary( "DOCUMENTS" );
        tmpl->setValue("DOCUMENTS", "DOCTYPE", dtype);
        const QString am = QString::number(docMatrix[dtype].first);
        tmpl->setValue("DOCUMENTS", "AMOUNT", am);
        const QString sm = docMatrix[dtype].second.toString(DefaultProvider::self()->locale());
        tmpl->setValue("DOCUMENTS", "SUM", sm);
    }
Esempio n. 14
0
/*!
  Эта реализация writeResults только для League!
  */
void League::writeResults() {
    //проверяем, мб мы уже записали
QSettings stg (workdir + "/settings.ini", QSettings::IniFormat, this);
bool isbonus = QFile::exists(workdir+"/bonus.ini");
QSettings bonus (workdir +"/bonus.ini", QSettings::IniFormat, this);
qDebug() << "writing final!";
stg.beginGroup("Tournament");
bool wrote  = false;
wrote = stg.value("stored", false).toBool();
qDebug() << wrote;

    QSqlDatabase db = QSqlDatabase::database("players");
    QSqlQuery q(db) ;
    QSqlQuery sq;
    QString team, nick;
    sq.prepare("SELECT nick, displayname, points FROM Teams ORDER by ABS (points)");
    if (!sq.exec()) {qDebug() << "write result error!" << sq.lastError().text();}
    else {qDebug() << "Query done! " << sq.lastQuery();}
    int rank = 0;
    while (sq.next()) {
        qDebug() << rank;
        rank ++;
        QString result;
        if (rank == 1)
            result.append("Чемпион, ");
         else
             result.append(QVariant (rank).toString() + " место, ");

         result.append(sq.value(2).toString() + " очко(а, ов)");
         nick = sq.value(0).toString();
         team = sq.value(1).toString();
         qDebug() << nick << team << result;
        q.prepare("SELECT smallname FROM Players WHERE nick=:nick");
        q.bindValue(":nick", nick);
        if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();

QString table = q.value(0).toString();
//проверяем
q.prepare("SELECT COUNT (*) FROM "+ table + " WHERE team=:team AND trn=:trn");
      if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();
if (q.value(0).toInt() == 0) {
q.prepare("INSERT INTO " + table + "(team, result) VALUES (:team, :result)");
q.bindValue(":team", team);
q.bindValue(":trn", _title);
 if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
//здесь будет выдача бонусов
if (isbonus)
{
    int bpoints = bonus.value(QVariant(rank).toString(), -1).toInt();
    if (bpoints != -1){
        q.prepare("UPDATE Rating SET bonus=(SELECT bonus FROM Rating WHERE nick=:nick)+"+QVariant(bpoints).toString()+" WHERE nick=:nick");
        q.bindValue(":nick", nick);
         if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
syncPoints(nick);
    }

}
}
    }
    stg.setValue("stored", true);
stg.endGroup();
stg.sync();
}
Esempio n. 15
0
bool NoteTable::updateNoteList(qint32 lid, Note &t, bool isDirty) {

    NotebookTable notebookTable;
    qint32 notebookLid = notebookTable.getLid(t.notebookGuid);
    Notebook notebook;
    notebookTable.get(notebook, notebookLid);
    // Now let's update the user table
    QSqlQuery query;

    query.prepare("Delete from NoteTable where lid=:lid");
    query.bindValue(":lid", lid);
    query.exec();

    query.prepare(QString("Insert into NoteTable (lid, title, author, ") +
                  QString("dateCreated, dateUpdated, dateSubject, dateDeleted, source, sourceUrl, sourceApplication, ") +
                  QString("latitude, longitude, altitude, hasEncryption, hasTodo, isDirty, size, notebook, notebookLid, tags) ") +
                  QString("Values (:lid, :title, :author, ") +
                  QString(":dateCreated, :dateUpdated, :dateSubject, :dateDeleted, :source, :sourceUrl, :sourceApplication, ") +
                  QString(":latitude, :longitude, :altitude, :hasEncryption, :hasTodo, :isDirty, :size, :notebook, :notebookLid, :tags) ")) ;

    query.bindValue(":lid", lid);

    if (t.__isset.title)
        query.bindValue(":title", QString::fromStdString(t.title));
    else
        query.bindValue(":title", "");
    if (t.__isset.attributes && t.attributes.__isset.author)
        query.bindValue(":author", QString::fromStdString(t.attributes.author));
    else
        query.bindValue(":author", "");
    if (t.__isset.created)
        query.bindValue(":dateCreated", QVariant::fromValue(t.created));
    else
        query.bindValue(":dateCreated", 0);
    if (t.__isset.updated)
        query.bindValue(":dateUpdated", QVariant::fromValue(t.updated));
    else
        query.bindValue(":dateUpdated", 0);
    if (t.__isset.attributes && t.attributes.__isset.subjectDate)
        query.bindValue(":dateSubject", QVariant::fromValue(t.attributes.subjectDate));
    else
        query.bindValue(":dateSubject", 0);
    if (t.__isset.deleted)
        query.bindValue(":dateDeleted", QVariant::fromValue(t.deleted));
    else
        query.bindValue(":dateDeleted", 0);
    if (t.__isset.attributes && t.attributes.__isset.source)
        query.bindValue(":source", QString::fromStdString(t.attributes.source));
    else
        query.bindValue(":source", "");
    if (t.__isset.attributes && t.attributes.__isset.sourceURL)
        query.bindValue(":sourceUrl", QString::fromStdString(t.attributes.sourceURL));
    else
        query.bindValue(":sourceUrl", "");
    if (t.__isset.attributes && t.attributes.__isset.sourceApplication)
        query.bindValue(":sourceApplication", QString::fromStdString(t.attributes.sourceApplication));
    else
        query.bindValue(":sourceApplication", "");
    if (t.__isset.attributes && t.attributes.__isset.latitude)
        query.bindValue(":latitude", QVariant::fromValue(t.attributes.latitude));
    else
        query.bindValue(":latitude", 0);
    if (t.__isset.attributes && t.attributes.__isset.longitude)
        query.bindValue(":longitude", QVariant::fromValue(t.attributes.longitude));
    else
        query.bindValue(":longitude", 0);
    if (t.__isset.attributes && t.attributes.__isset.altitude)
        query.bindValue(":altitude", QVariant::fromValue(t.attributes.altitude));
    else
        query.bindValue(":altitude", 0);


    bool hasEncryption;
    if (t.content.find("<en-crypt") != string::npos)
        hasEncryption = true;
    else
        hasEncryption = false;
    query.bindValue(":hasEncryption", hasEncryption);
    bool hasTodo;
    if (t.content.find("<en-todo") != string::npos)
        hasTodo = true;
    else
        hasTodo = false;
    query.bindValue(":hasTodo", hasTodo);
    query.bindValue(":isDirty", isDirty);
    qlonglong size = t.content.length();
    for (unsigned int i=0; i<t.resources.size(); i++) {
        size+=t.resources[i].data.size;
    }
    query.bindValue(":size", size);

    query.bindValue(":notebook", QString::fromStdString(notebook.name));
    query.bindValue(":notebookLid", notebookLid);

    QString tagNames;
    QStringList sortedNames;
    for (unsigned int i=0; i<t.tagNames.size(); i++) {
        sortedNames.append(QString::fromStdString(t.tagNames.at(i)).toLower());
    }
    sortedNames.sort();

    TagTable tagTable;
    LinkedNotebookTable linkedTable;
    qint32 account = 0;
    notebookLid = notebookTable.getLid(t.notebookGuid);
    if (linkedTable.exists(notebookLid))
        account = notebookLid;

    for (int i=0; i<sortedNames.size(); i++) {
        if (i>0)
            tagNames = tagNames+", ";
        Tag currentTag;
        qint32 tagLid = tagTable.findByName(sortedNames[i], account);
        tagTable.get(currentTag, tagLid);
        tagNames = tagNames + QString::fromStdString(currentTag.name);
    }

    query.bindValue(":tags", tagNames);

    if (!query.exec()) {
        QLOG_ERROR() << "Error inserting into NoteTable: " << query.lastError();
        return false;
    }
    return true;
}
Esempio n. 16
0
void MainWindow::on_pushButton_3_clicked()
{
    if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){
        QMessageBox::information(this,tr("提示"),tr("不能为空"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    QSqlQuery query;
    QString s_num="";
    QString b_num="";
    QString o_name="";
    QString o_author="";
    QString o_price ="";
    QString s_name="";
    query.prepare("select C_NUM from  COUNT where C_NO = :uid");
    query.bindValue(":uid",ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_num = query.value(0).toString();
    }
    query.prepare("select * from  BOOKS where O_ISBN = :bid");
    query.bindValue(":bid",ui->B_NIO->text());
    query.exec();
    if(query.next()){
        o_name = query.value(1).toString();
        o_author = query.value(2).toString();
        o_price = query.value(4).toString();
        b_num = query.value(5).toString();
    }
    qDebug()<<s_num<<b_num;
    query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?");
    query.addBindValue(ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_name = query.value(0).toString();
        qDebug()<<s_name;
    }
    if(s_num.isEmpty() || s_num.toInt() < 1){
        QMessageBox::information(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    if(b_num.isEmpty() || b_num.toInt() < 1){
        QMessageBox::information(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    int ss_num=s_num.toInt();
    int bb_num=b_num.toInt();
    --bb_num;
    --ss_num;
    QString temss = QString(tr("%1还能借%2本书")).arg(s_name).arg(ss_num);
    QMessageBox::information(this,tr("提示"),temss,QMessageBox::Ok);
    query.prepare("UPDATE BOOKS SET  O_STORAGE = ? WHERE O_ISBN = ?");
    query.addBindValue(QString::number(bb_num,10));
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    query.prepare("UPDATE COUNT SET  C_NUM = ? WHERE C_NO = ?");
    query.addBindValue(QString::number(ss_num,10));
    query.addBindValue(ui->S_NO->text());
    query.exec();
    QDate date;
    date=date.fromString("2012.9.1","yyyy.M.d");
    //date=date.currentDate();
    QString newdate=date.toString("yyyy.M.d");
    qDebug()<<newdate;
    int countI = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(countI);
    ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text()));
    ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name));
    ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text()));
    ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name));
    ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author));
    ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price));
    ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("借出"))));
    ui->tableWidget->setItem(countI,7,new QTableWidgetItem(newdate));
    query.prepare("INSERT INTO BORROW (B_NO,B_ISBN,B_TIME,B_ISRENT) VALUES(?,?,?,?)");
    query.addBindValue(ui->S_NO->text());
    query.addBindValue(ui->B_NIO->text());
    query.addBindValue(newdate);
    query.addBindValue(0);
    query.exec();
    query.clear();
}
Esempio n. 17
0
// Return a note structure given the LID
bool NoteTable::get(Note &note, qint32 lid,bool loadResources, bool loadResourceRecognition) {

    QSqlQuery query;
    query.prepare("Select key, data from DataStore where lid=:lid");
    query.bindValue(":lid", lid);

    query.exec();
    while (query.next()) {
        qint32 key = query.value(0).toInt();
        switch (key) {
        case (NOTE_GUID):
            note.guid = query.value(1).toString().toStdString();
            note.__isset.guid = true;
            break;
        case (NOTE_UPDATE_SEQUENCE_NUMBER):
            note.updateSequenceNum = query.value(1).toInt();
            note.__isset.updateSequenceNum = true;
            break;
        case (NOTE_ACTIVE):
            note.active = query.value(1).toBool();
            note.__isset.active = true;
            break;
        case (NOTE_DELETED_DATE):
            note.active = query.value(1).toLongLong();
            note.__isset.deleted = true;
            break;
        case (NOTE_ATTRIBUTE_SOURCE_URL):
            note.attributes.sourceURL = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.sourceURL = true;
            break;
        case (NOTE_ATTRIBUTE_SOURCE_APPLICATION):
            note.attributes.sourceApplication = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.sourceApplication = true;
            break;
        case (NOTE_CONTENT_LENGTH):
            note.contentLength = query.value(1).toLongLong();
            note.__isset.contentLength = true;
            break;
        case (NOTE_ATTRIBUTE_LONGITUDE):
            note.attributes.longitude = query.value(1).toFloat();
            note.__isset.attributes = true;
            note.attributes.__isset.longitude = true;
            break;
        case (NOTE_TITLE):
            note.title = query.value(1).toString().toStdString();
            note.__isset.title = true;
            break;
        case (NOTE_ATTRIBUTE_SOURCE):
            note.attributes.source = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.source = true;
            break;
        case (NOTE_ATTRIBUTE_ALTITUDE):
            note.attributes.altitude = query.value(1).toFloat();
            note.__isset.attributes = true;
            note.attributes.__isset.altitude = true;
            break;
        case (NOTE_NOTEBOOK_LID): {
            qint32 notebookLid = query.value(1).toInt();
            NotebookTable ntable;
            QString notebookGuid;
            ntable.getGuid(notebookGuid, notebookLid);
            note.notebookGuid = notebookGuid.toStdString();
            note.__isset.notebookGuid = true;
            break;
        }
        case (NOTE_UPDATED_DATE):
            note.updated = query.value(1).toLongLong();
            note.__isset.updated = true;
            break;
        case (NOTE_CREATED_DATE):
            note.created = query.value(1).toLongLong();
            note.__isset.created = true;
            break;
        case (NOTE_ATTRIBUTE_SUBJECT_DATE):
            note.attributes.subjectDate = query.value(1).toLongLong();
            note.__isset.attributes = true;
            note.attributes.__isset.subjectDate = true;
            break;
        case (NOTE_ATTRIBUTE_LATITUDE):
            note.attributes.latitude = query.value(1).toFloat();
            note.__isset.attributes = true;
            note.attributes.__isset.latitude = true;
            break;
        case (NOTE_CONTENT):
            note.content = query.value(1).toByteArray().data();
            note.__isset.content = true;
            break;
        case (NOTE_CONTENT_HASH):
            note.contentHash = query.value(1).toString().toStdString();
            note.__isset.contentHash = true;
            break;
        case (NOTE_ATTRIBUTE_AUTHOR):
            note.attributes.author = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.author = true;
            break;
        case (NOTE_ISDIRTY):
            break;
        case (NOTE_ATTRIBUTE_SHARE_DATE) :
            note.attributes.shareDate = query.value(1).toLongLong();
            note.__isset.attributes = true;
            note.attributes.__isset.shareDate = true;
            break;
        case (NOTE_ATTRIBUTE_PLACE_NAME) :
            note.attributes.placeName = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.placeName = true;
            break;
        case (NOTE_ATTRIBUTE_CONTENT_CLASS) :
            note.attributes.contentClass = query.value(1).toString().toStdString();
            note.__isset.attributes = true;
            note.attributes.__isset.contentClass = true;
            break;
        case (NOTE_TAG_LID) :
            TagTable tagTable;
            qint32 tagLid = query.value(1).toInt();
            Tag tag;
            tagTable.get(tag, tagLid);
            note.__isset.tagGuids = true;
            note.__isset.tagNames = true;
            note.tagGuids.push_back(tag.guid);
            note.tagNames.push_back(tag.name);
            break;
        }
    }

    ResourceTable resTable;
    QList<qint32> resList;
    if (resTable.getResourceList(resList, lid)) {
        for (int i=0; i<resList.size(); i++) {
            Resource resource;
            if (loadResources) {
                resTable.get(resource, resList[i]);
            } else {
                QString resGuid = resTable.getGuid(resList[i]);
                resource.guid = resGuid.toStdString();
                resource.__isset.guid = true;
            }
            note.__isset.resources = true;
            note.resources.push_back(resource);
        }
    }

    /*
    TagScanner test;
    test.setData(QString::fromStdString(note.content));
    QList<TagScannerRecord> retval;
    int k = test.findAll(retval, QString("en-note"));
    */

    if (note.__isset.guid)
        return true;
    else
        return false;
}
void TableEditor::setupLayout()
{
    // set up agents tab
    agentsModel = new QSqlTableModel(this);
    agentsModel->setTable("agents");
    if (!tableFilter.isEmpty())
        agentsModel->setFilter(tableFilter);
    agentsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    agentsModel->select();

    agentsTable = new QTableView(this);
    agentsTable->setModel(agentsModel);
    agentsTable->resizeColumnsToContents();
    agentsTable->sortByColumn(0,Qt::AscendingOrder);
    agentsTable->setSortingEnabled(true);

    // set up determinations tab
    determinationsModel = new QSqlTableModel(this);
    determinationsModel->setTable("determinations");
    if (!tableFilter.isEmpty())
        determinationsModel->setFilter(tableFilter);
    determinationsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    determinationsModel->select();

    determinationsTable = new QTableView(this);
    determinationsTable->setModel(determinationsModel);
    determinationsTable->resizeColumnsToContents();
    determinationsTable->sortByColumn(0,Qt::AscendingOrder);
    determinationsTable->setSortingEnabled(true);

    // set up images tab
    imagesModel = new QSqlTableModel(this);
    imagesModel->setTable("images");
    if (!tableFilter.isEmpty())
        imagesModel->setFilter(tableFilter);
    imagesModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    imagesModel->select();

    imagesTable = new QTableView(this);
    imagesTable->setModel(imagesModel);
    imagesTable->resizeColumnsToContents();
    imagesTable->sortByColumn(19,Qt::AscendingOrder);
    imagesTable->setSortingEnabled(true);

    // set up taxa tab
    taxaModel = new QSqlTableModel(this);
    taxaModel->setTable("taxa");
    if (!tableFilter.isEmpty())
        taxaModel->setFilter(tableFilter);
    taxaModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    taxaModel->select();

    taxaTable = new QTableView(this);
    taxaTable->setModel(taxaModel);
    taxaTable->resizeColumnsToContents();
    taxaTable->sortByColumn(1,Qt::AscendingOrder);
    taxaTable->setSortingEnabled(true);

    // set up organisms tab
    organismsModel = new QSqlTableModel(this);
    organismsModel->setTable("organisms");
    if (!tableFilter.isEmpty())
        organismsModel->setFilter(tableFilter);
    organismsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    organismsModel->select();

    organismsTable = new QTableView(this);
    organismsTable->setModel(organismsModel);
    organismsTable->resizeColumnsToContents();
    organismsTable->sortByColumn(0,Qt::AscendingOrder);
    organismsTable->setSortingEnabled(true);

    // set up sensu tab
    sensuModel = new QSqlTableModel(this);
    sensuModel->setTable("sensu");
    if (!tableFilter.isEmpty())
        sensuModel->setFilter(tableFilter);
    sensuModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    sensuModel->select();

    sensuTable = new QTableView(this);
    sensuTable->setModel(sensuModel);
    sensuTable->resizeColumnsToContents();
    sensuTable->sortByColumn(0,Qt::AscendingOrder);
    sensuTable->setSortingEnabled(true);

    tabWidget = new QTabWidget(this);
    tabWidget->addTab(agentsTable,"Agents");
    tabWidget->addTab(determinationsTable,"Determinations");
    tabWidget->addTab(imagesTable,"Images");
    tabWidget->addTab(taxaTable,"Names");
    tabWidget->addTab(organismsTable,"Organisms");
    tabWidget->addTab(sensuTable,"Sensu");

    submitButton = new QPushButton(tr("&Save changes"));
    submitButton->setDefault(true);
    refreshButton = new QPushButton(tr("&Revert unsaved changes\nand refresh database"));
    deleteButton = new QPushButton(tr("&Delete selected rows"));
    quitButton = new QPushButton(tr("&Close"));

    buttonBox = new QDialogButtonBox(Qt::Vertical);
    buttonBox->addButton(submitButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(deleteButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::ActionRole);

    connect(submitButton, SIGNAL(clicked()), this, SLOT(submit())); // this needs to save (submit) all changes from all tables
    connect(refreshButton, SIGNAL(clicked()), this, SLOT(refreshAll())); // this needs to refresh all tables to their current database values
    connect(deleteButton, SIGNAL(clicked()), this, SLOT(removeSelectedRows())); // this needs to remove selected rows ONLY from current tab
    connect(quitButton, SIGNAL(clicked()), this, SLOT(confirmClose()));

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(tabWidget);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle("Table view");

    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();

    QSqlQuery qry;
    qry.prepare("SELECT value FROM settings WHERE setting = (?)");
    qry.addBindValue("view.table.location");
    qry.exec();
    if (qry.next())
        restoreGeometry(qry.value(0).toByteArray());

    bool wasMaximized = false;
    qry.prepare("SELECT value FROM settings WHERE setting = (?)");
    qry.addBindValue("view.table.fullscreen");
    qry.exec();
    if (qry.next())
        wasMaximized = qry.value(0).toBool();

    if (!db.commit())
    {
        qDebug() << "Problem committing changes to database in TableEditor::setupLayout()";
        db.rollback();
    }

    if (wasMaximized)
        this->showMaximized();
}
void UpdateMediaVolumeInfo::run()
{
    QThread backend;
    backend.start();

    QNetworkAccessManager manager;
    manager.moveToThread(&backend);

    MediaLibrary library(m_log);

    QSqlQuery query;
    query.prepare("SELECT media.id, media.filename, mime_type.name from media LEFT OUTER JOIN mime_type ON media.mime_type=mime_type.id WHERE media.is_reachable=1");

    if (query.exec())
    {
        while (query.next())
        {
            int idMedia = query.record().value("id").toInt();
            QString filename = query.record().value("filename").toString();
            QString mime_type = query.record().value("name").toString();
            QHash<QString, double> volumeInfo = library.volumeInfo(idMedia);

            if (volumeInfo.isEmpty())
            {
                if (mime_type.startsWith("audio/"))
                {
                    qWarning() << "Analyze audio" << filename;

                    DlnaMusicTrackFile track(m_log, filename, "HOST", 80);
                    if (!library.setVolumeInfo(idMedia, track.volumeInfo()))
                        qWarning() << "Unable to set volume information for" << filename;
                }
                else if (mime_type.startsWith("video/")  && !filename.startsWith("http"))
                {
                    qWarning() << "Analyze local video" << filename;

                    DlnaVideoFile movie(m_log, filename, "HOST", 80);
                    if (!library.setVolumeInfo(idMedia, movie.volumeInfo(-1)))
                        qWarning() << "Unable to set volume information for" << filename;
                }
                else if (mime_type.startsWith("video/") && filename.startsWith("http"))
                {
                    qWarning() << "Analyze internet video" << filename;

                    DlnaYouTubeVideo video(m_log, "HOST", 80);
                    video.moveToThread(&backend);
                    video.setNetworkAccessManager(&manager);
                    video.setUrl(filename);
                    bool res = video.waitUrl(30000);

                    if (res && video.isValid())
                    {
                        if (!library.setVolumeInfo(idMedia, video.volumeInfo(-1)))
                            qWarning() << "Unable to set volume information for" << filename;
                    }
                    else
                    {
                        qWarning() << "NO VOLUME INFO (TIMEOUT)" << filename;
                    }

                }
                else
                {
                    qWarning() << "NO VOLUME INFO" << filename;
                }
            }
        }
    }
    else
    {
        qWarning() << "ERROR in request" << query.lastError().text();
    }

    backend.quit();
}
Esempio n. 20
0
void FrmFrame::apply()
{
    bool bError=false;

    //We call a stored procedure to see if there are GLS available outside the bin
     QSqlQuery query;
     query.setForwardOnly(true);

     int id= cmbPrexistent->model()->index(cmbPrexistent->currentIndex(),0).data().toInt();

    int n=0;
    query.prepare("{CALL spCountGLS4Frame(?,?)}");
    query.bindValue(0,id);
    query.bindValue("Number",n,QSql::Out);

     if (!query.exec()){
         emit showError(query.lastError().text());
         bError=true;;
     }

    n = query.boundValue("Number").toInt();

    if (n<1){
        emit showError(tr("There are no Group of Landing Sites for this frame!"));
        bError=true;
    }else{

        //First insert the dates...
        if (!mapperStartDt->submit() || !mapperEndDt->submit()){
            if (m_tDateTime->lastError().type()!=QSqlError::NoError)
                emit showError(m_tDateTime->lastError().text());
            else
                emit showError(tr("Could not submit mapper!"));
            bError=true;
        }
        else{
            if (!m_tDateTime->submitAll()){
                if (m_tDateTime->lastError().type()!=QSqlError::NoError)
                    emit showError(m_tDateTime->lastError().text());
                else
                    emit showError(tr("Could not write DateTime in the database!"));

                bError=true;
            }
        }

        while(m_tDateTime->canFetchMore())
            m_tDateTime->fetchMore();

        mapperStartDt->setCurrentIndex(m_tDateTime->rowCount()-2);
        mapperEndDt->setCurrentIndex(m_tDateTime->rowCount()-1);

        int startIdx=mapperStartDt->currentIndex();
        int endIdx=mapperEndDt->currentIndex();

        if (bError) {
            emit showError(tr("Could not create dates in the database!"));
        }else{

        //Now insert the record
        while(tFrameTime->canFetchMore())
            tFrameTime->fetchMore();

        tFrameTime->insertRow(tFrameTime->rowCount());
        QModelIndex idx=tFrameTime->index(tFrameTime->rowCount()-1,1);//id frame
        if (idx.isValid()){
                int idFrame;
                if (getCurrentFrame(idFrame)){
                    tFrameTime->setData(idx,idFrame);
                    QModelIndex idx=tFrameTime->index(tFrameTime->rowCount()-1,2);//start dt
                    if (idx.isValid()){
                        int idStart;
                        if (getDtId(startIdx,idStart)){
                            tFrameTime->setData(idx,idStart);
                            idx=tFrameTime->index(tFrameTime->rowCount()-1,3);//end dt
                            if (idx.isValid()){
                                int idEnd;
                                if (getDtId(endIdx,idEnd)){
                                    tFrameTime->setData(idx,idEnd);
                                }else bError=true;
                            }
                        }else bError=true;
                    }else bError=true;
                }else bError=true;
            }else bError=true;
        }
        bError=!tFrameTime->submitAll();
    }

    if (!bError){
        QList<QWidget*> lWidgets;
        lWidgets << this->groupPhysical;
        lWidgets << this->groupTime;
        emit lockControls(true,lWidgets);
    }else{
        if (tFrameTime->lastError().type()!=QSqlError::NoError)
            emit showError(tFrameTime->lastError().text());
    }

    pushNext->setEnabled(!bError);
    pushApply->setEnabled(bError);

    if (!bError)
    {
        emit showStatus(tr("Record successfully inserted in the database!"));
        m_submitted=true;

        while(tFrameTime->canFetchMore())
            tFrameTime->fetchMore();

        m_curFrameTime=tFrameTime->rowCount()-1;
        updateSample();//update sample here, because of the save
    }
}
Esempio n. 21
0
			void Storage::RemoveComponent (int repoId, const QString& component)
			{
				Util::DBLock lock (DB_);
				try
				{
					lock.Init ();
				}
				catch (const std::exception& e)
				{
					qWarning () << Q_FUNC_INFO
							<< "unable to start transaction";
					throw std::runtime_error ("Unable to start transaction");
				}

				int compId = FindComponent (repoId, component);
				if (compId == -1)
				{
					qWarning () << Q_FUNC_INFO
							<< "component"
							<< component
							<< "not found.";
					throw std::runtime_error ("Requested component not found");
				}

				QSqlQuery idsSelector (DB_);
				idsSelector.prepare ("SELECT DISTINCT package_id "
						"FROM locations WHERE component_id = :component_id");
				idsSelector.bindValue (":component_id", compId);
				if (!idsSelector.exec ())
				{
					Util::DBLock::DumpError (idsSelector);
					throw std::runtime_error ("Fetching of possibly affected packages failed.");
				}

				QList<int> possiblyAffected;
				while (idsSelector.next ())
					possiblyAffected << idsSelector.value (0).toInt ();

				idsSelector.finish ();

				QSqlQuery remover (DB_);
				remover.prepare ("DELETE FROM locations WHERE component_id = :component_id;");
				remover.bindValue (":component_id", compId);
				if (!remover.exec ())
				{
					Util::DBLock::DumpError (remover);
					throw std::runtime_error ("Unable to remove component from locations.");
				}
				remover.prepare ("DELETE FROM components WHERE component_id = :component_id;");
				remover.bindValue (":component_id", compId);
				if (!remover.exec ())
				{
					Util::DBLock::DumpError (remover);
					throw std::runtime_error ("Unable to remove component from components.");
				}

				remover.finish ();

				QSqlQuery checker (DB_);
				checker.prepare ("SELECT COUNT (package_id) FROM locations WHERE package_id = :package_id;");
				Q_FOREACH (int packageId, possiblyAffected)
				{
					checker.bindValue (":package_id", packageId);
					if (!checker.exec ())
					{
						Util::DBLock::DumpError (checker);
						throw std::runtime_error ("Unable to remove check affected.");
					}

					if (!checker.next ())
					{
						qWarning () << Q_FUNC_INFO
								<< "zarroo rows";
						throw std::runtime_error ("Unable to move to the next row");
					}

					if (checker.value (0).toInt ())
						continue;

					checker.finish ();

					emit packageRemoved (packageId);

					remover.prepare ("DELETE FROM packages WHERE package_id = :package_id;");
					remover.bindValue (":package_id", packageId);
					if (!remover.exec ())
					{
						Util::DBLock::DumpError (remover);
						throw std::runtime_error ("Unable to remove orphaned package.");
					}

					remover.finish ();
				}
void Availability_Window::on_RemoveAMBtn_clicked()
{
	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
	db.setConnectOptions();
	db.setHostName("localhost");
	db.setDatabaseName("scheduler");
	db.setUserName("root");
	db.setPassword("Inception2194");
	bool pm=false; 

	if (ui->listWidget_2->currentItem() != NULL)
	{
		

			QString selected = ui->listWidget_2->currentItem()->text();
			QString employee;


			for (int j = 0; j < ui->listWidget->count(); j++)
			{
				if (selected == ui->listWidget->item(j)->text())
				{
					db.open();
					QString sQuery = "update " + get_month(date) + " set Day" + get_day(date) + "='3' where EmployeeId = '" + get_id(selected) + "'";
					QSqlQuery q;
					q.prepare(sQuery);
					q.exec();
					db.close();
				
				}

				else
				{
					db.open();
					QString sQuery1 = "update " + get_month(date) + " set Day" + get_day(date) + "='0' where EmployeeId = '" + get_id(selected) + "'";
					QSqlQuery q1;
					q1.prepare(sQuery1);
					q1.exec();
					db.close();
					
				}
			}
	if (ui->listWidget->count() == 0)
		{

			db.open();
			QString sQuery1 = "update " + get_month(date) + " set Day" + get_day(date) + "='0' where EmployeeId = '" + get_id(selected) + "'";
			QSqlQuery q1;
			q1.prepare(sQuery1);
			q1.exec();
			db.close();
		}

	}	ui->listWidget_2->takeItem(ui->listWidget_2->row(ui->listWidget_2->currentItem()));
	
	
	/*if (ui->listWidget_2->currentItem()!=NULL)
	{
		if (ui->listWidget_2->count() > 0)
			{
				amList.clear();
				QString selected = ui->listWidget_2->currentItem()->text(); 
				QString employee;
		
	
				int size = ui->listWidget_2->count(); 
				for (int i = 0; i < size; i++)
				{
					employee = ui->listWidget_2->item(i)->text();
					amList.push_back(employee);
					if (selected == employee)
					{
						if (ui->listWidget->count() != 0)
						{
							for (int x = 0; x < ui->listWidget->count(); x++)
								{
									if (selected == ui->listWidget->item(x)->text())
										{
											pm = true;
											db.open();
											QString sQuery = "update " + get_month(date) + " set Day" + get_day(date) + "='3' where EmployeeId = '" + get_id(amList.at(i)) + "'";
											QSqlQuery q;
											q.prepare(sQuery);
											q.exec();
											db.close();
										}
								}
						}
				

						if (pm == false)
						{
							db.open();
							QString sQuery = "update " + get_month(date) + " set Day" + get_day(date) + "='0' where EmployeeId = '" + get_id(amList.at(i)) + "'";
							QSqlQuery q;
							q.prepare(sQuery);
							q.exec();
							db.close();

						}
				
						int x = amList.size(); 
						if (x > 1)
						{
							amList.erase(amList.begin() + i);
						}
						else
							amList.erase(amList.begin() + 0);
					}
				}
				ui->listWidget_2->clear();
				if (amList.empty() == false)
				{
			
					for (int j = 0; j < amList.size(); j++)
					{
						ui->listWidget_2->addItem(amList.at(j));
					}

				}
		

			}

			amList.clear(); 
	}
	
	*/
}
Esempio n. 23
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    canUpdate=false;
    QSettings settings;
    QString dir=QFileDialog::getExistingDirectory(NULL,"Folder containing region directory",settings.value("mapfolder").toString());
    if(dir.isEmpty())
        abort();
    if(!QString(TMPDATA).endsWith("/"))
        abort();
    if(!dir.endsWith("/"))
        dir+="/";
    settings.setValue("mapfolder",dir);
    QDir().mkpath(TMPDATA);

    QDir dir2("/tmp/map-metadata/");
    dir2.setFilter(QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot);
    QFileInfoList list = dir2.entryInfoList();
    if(!QDir("/tmp/map-metadata/").exists() || list.size()==0)
    {
        process.setArguments(QStringList() << "/home/user/Desktop/CatchChallenger/datapack-pkmn/map/main/gen4/map/");
        process.setProgram("/home/user/Desktop/CatchChallenger/tools/build-map2png-Desktop-Debug/map2png");
        process.setWorkingDirectory("/tmp/map-metadata/");
        process.start();
        process.waitForFinished(999999999);
        std::cerr << process.errorString().toStdString() << std::endl;
        std::cout << process.readAll().toStdString() << std::endl;
        if(process.exitCode()!=0)
            std::cerr << "Process exit code: " << process.exitCode() << std::endl;
    }

    QString path=QCoreApplication::applicationDirPath()+"/changes.db";
    QFile destinationFile(path);
    if(!destinationFile.exists())
    {
        if(QFile::copy(":/changes.db",path))
        {
            if(!destinationFile.setPermissions(destinationFile.permissions() | QFileDevice::WriteOwner | QFileDevice::WriteUser))
                std::cerr << "Unable to set db permissions" << std::endl;
        }
        else
            std::cerr << "Unable to copy the :/changes.db" << std::endl;
    }
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(path);

    if (!m_db.open())
    {
        qDebug() << "Error: connection with database fail";
        abort();
    }

    QHash<QString,MapContent> db_finishedFile;
    QHash<QString,MapContent> db_not_finishedFile;
    QSqlQuery query;
    if(!query.exec("SELECT file, region, zone, subzone, name, type, finished FROM maps"))
    {
        qDebug() << query.lastError().text();
        abort();
    }
    while(query.next())
    {
        QString file = query.value(0).toString();
        MapContent mapContent;
        mapContent.region=query.value(1).toString();
        mapContent.zone=query.value(2).toString();
        mapContent.subzone=query.value(3).toString();
        mapContent.name=query.value(4).toString();
        mapContent.type=query.value(5).toString();
        if(mapContent.region.isEmpty())
            abort();
        mapContent.officialzone=query.value(7).toInt()>0;
        if(query.value(6).toInt()>0)
            db_finishedFile[file]=mapContent;
        else
            db_not_finishedFile[file]=mapContent;
    }

    {
        QDirIterator it(dir,QDirIterator::Subdirectories);
        QRegularExpression regex("\\.tmx$");
        QRegularExpression regexRemove("^/");
        while (it.hasNext()) {
            QString element=it.next();
            if(element.contains(regex))
            {
                QString sortPath=element;
                sortPath.remove(0,dir.size());
                sortPath.remove(regexRemove);
                QString pngDest=TMPDATA+sortPath;
                pngDest.replace(".tmx",".png");
                //std::cout << sortPath.toStdString() << " -> " << pngDest.toStdString() << std::endl;

                const QStringList elementList=sortPath.split("/");
                if(elementList.size()>=2 && elementList.size()<=3)
                {
                    QString file = sortPath;
                    if(db_finishedFile.contains(file))
                        finishedFile[file]=db_finishedFile.value(file);
                    else if(db_not_finishedFile.contains(file))
                        not_finishedFile[file]=db_not_finishedFile.value(file);
                    else
                    {
                        MapContent mapContent;
                        mapContent.region=elementList.at(0);
                        if(mapContent.region.isEmpty())
                            abort();
                        mapContent.zone=elementList.at(1);
                        mapContent.zone.replace(".tmx","");
                        if(elementList.size()==3)
                        {
                            mapContent.subzone=elementList.at(2);
                            mapContent.subzone.replace(".tmx","");
                        }
                        mapContent.officialzone=true;
                        //get from xml
                        QDomDocument domDocument;
                        QString xmlpath=element;
                        xmlpath.replace(".tmx",".xml");
                        QFile xmlfile(xmlpath);
                        if (xmlfile.open(QIODevice::ReadOnly))
                        {
                            if (!domDocument.setContent(&xmlfile)) {
                                xmlfile.close();
                                return;
                            }
                            xmlfile.close();

                            const tinyxml2::XMLElement root = domDocument.RootElement();
                            if(root.tagName()=="map")
                            {
                                //load the content
                                const tinyxml2::XMLElement nameItem = root.FirstChildElement("name");
                                if(!nameItem.isNull())
                                    mapContent.name=nameItem.text();

                                if(root.hasAttribute("type"))
                                    mapContent.type=root.attribute("type");
                                if(root.hasAttribute("zone"))
                                {
                                    mapContent.officialzone=true;
                                    mapContent.zone=root.attribute("zone");
                                }
                                else
                                {
                                    if(mapContent.name.startsWith("Route "))
                                    {
                                        mapContent.officialzone=false;
                                        mapContent.zone="route";
                                    }
                                    else
                                        mapContent.officialzone=true;
                                }
                            }
                        }

                        not_finishedFile[file]=mapContent;
                        //insert into database
                        QSqlQuery query;
                        if(!query.prepare("INSERT INTO maps (file, region, zone, subzone, name, type, finished) "
                                      "VALUES (:file, :region, :zone, :subzone, :name, :type, :finished)"))
                        {
                            qDebug() << query.lastError().text();
                            abort();
                        }
                        query.bindValue(":file", file);
                        query.bindValue(":region", mapContent.region);
                        query.bindValue(":zone", mapContent.zone);
                        query.bindValue(":subzone", mapContent.subzone);
                        query.bindValue(":name", mapContent.name);
                        query.bindValue(":type", mapContent.type);
                        query.bindValue(":finished", 0);
                        if(!query.exec())
                        {
                            qDebug() << query.lastError().text();
                            abort();
                        }
                    }
                }
            }
        }
    }
    preload_the_map(dir.toStdString());
    for(auto& n:map_list)
    {
        CatchChallenger::MapServer * map=n.second;
        unsigned int index=0;
        while(index<map->linked_map.size())
        {
            CatchChallenger::CommonMap * const newMap=map->linked_map.at(index);
            if(!vectorcontainsAtLeastOne(newMap->linked_map,static_cast<CatchChallenger::CommonMap *>(map)))
                newMap->linked_map.push_back(map);
            index++;
        }
    }

    displayNewNotFinishedMap();
    updateProgressLabel();
}
void Availability_Window::on_Submit_clicked()
{
	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
	db.setConnectOptions();
	db.setHostName("localhost");
	db.setDatabaseName("scheduler");
	db.setUserName("root");
	db.setPassword("Inception2194");

	QString am_name;
		QString pm_name;
	//checks for doubles 

	for (int i = 0; i < ui->listWidget_2->count(); i++)
	{
		am_name = ui->listWidget_2->item(i)->text();
		for (int j = 0; j < ui->listWidget->count(); j++)
		{
			pm_name = ui->listWidget->item(j)->text(); 
			if (am_name == pm_name)
			{
				doubles.push_back(am_name);
			}

		else if (am_name != pm_name)
			{
				db.open();
				QString Query = "update " + get_month(date) + " set Day" + get_day(date) + "='2' where EmployeeId = '" + get_id(am_name) + "'";
				QSqlQuery q3;
				q3.prepare(Query);
				q3.exec();
				db.close();
			}

		}

		if (ui->listWidget->count() == 0)
		{
			db.open();
			QString Query = "update " + get_month(date) + " set Day" + get_day(date) + "='2' where EmployeeId = '" + get_id(am_name) + "'";
			QSqlQuery q3;
			q3.prepare(Query);
			q3.exec();
			db.close();
		}

	}


	for (int x = 0; x < ui->listWidget->count(); x++)
	{
		pm_name = ui->listWidget->item(x)->text();
		for (int y = 0; y < ui->listWidget_2->count(); y++)
		{
			am_name = ui->listWidget_2->item(y)->text();
			
			if (pm_name != am_name)
			{
				db.open();
				QString Q = "update " + get_month(date) + " set Day" + get_day(date) + "='3' where EmployeeId = '" + get_id(pm_name) + "'";
				QSqlQuery q4;
				q4.prepare(Q);
				q4.exec();
				db.close();
			}

		}

		if (ui->listWidget_2->count() == 0)
		{
			db.open();
			QString Query = "update " + get_month(date) + " set Day" + get_day(date) + "='2' where EmployeeId = '" + get_id(pm_name) + "'";
			QSqlQuery q3;
			q3.prepare(Query);
			q3.exec();
			db.close();
		}
	}

	if (doubles.empty() == false)
	{
		for (int l = 0; l < doubles.size(); l++)
		{
			
			db.open();
			QString sQuery = "update " + get_month(date) + " set Day" + get_day(date) + "='4' where EmployeeId = '" + get_id(doubles.at(l)) + "'";
			QSqlQuery q;
			q.prepare(sQuery);
			q.exec();
			db.close();

		}
	}

	/*
	
	QString m_name;
	//checks for working AM 
	for (int i = 0; i < ui->listWidget_2->count(); i++)
	{
		m_name = ui->listWidget_2->item(i)->text();
		if(doubles.empty())
		{
			db.open();
			QString Query = "update " + get_month(date) + " set Day" + get_day(date) + "='2' where EmployeeId = '" + get_id(m_name) + "'";
			QSqlQuery q3;
			q3.prepare(Query);
			q3.exec();
			db.close();
		}
		for (int j = 0; j < doubles.size(); j++)
		{
			if (m_name != doubles.at(j)||doubles.empty())
			{
				db.open();
				QString sQuery5 = "update " + get_month(date) + " set Day" + get_day(date) + "='2' where EmployeeId = '" + get_id(m_name) + "'";
				QSqlQuery q5;
				q5.prepare(sQuery5);
				q5.exec();
				db.close();
			}

		}
	}
	QString n_name;
	for (int k = 0; k < ui->listWidget->count(); k++)
	{
		n_name= ui->listWidget->item(k)->text();
		if (doubles.empty())
		{
			db.open();
			QString Q= "update " + get_month(date) + " set Day" + get_day(date) + "='3' where EmployeeId = '" + get_id(n_name) + "'";
			QSqlQuery q4;
			q4.prepare(Q);
			q4.exec();
			db.close();
		}
		
		for (int h = 0; h < doubles.size(); h++)
		{
			if (n_name != doubles.at(h) || doubles.empty())
			{
				db.open();
				QString sQuery1 = "update " + get_month(date) + " set Day" + get_day(date) + "='3' where EmployeeId = '" + get_id(n_name) + "'";
				QSqlQuery q1;
				q1.prepare(sQuery1);
				q1.exec();
				db.close();
			}

		}
	}
	*/
	doubles.clear(); 
	check_Available(date); 
	update_lists();

}
Esempio n. 25
0
void FenVente::BoutonValider()
{
	float somme=0.0;
	for(int i=0;i<liste->rowCount();i++)
	{
		somme+=liste->item(i,6)->text().toFloat();
	}
	FenPayement pay(somme); 
	pay.setValue(somme);
	if(pay.exec()==QDialog::Rejected)
	{
		return;
	}
	QSqlQuery req;
	req.prepare("INSERT INTO Ticket (client,prixb,prixc,prixd,num,date) VALUES (:cli,:b,:c,:d,:num,NOW())");
	req.bindValue(":cli",clients[curclient]);
	req.bindValue(":b",pay.Banque());
	req.bindValue(":c",pay.Cash());
	req.bindValue(":d",pay.Cheque());
	req.bindValue(":num",ui->spinBox_3->value());
	req.exec();
	req.prepare("SELECT id FROM Ticket WHERE num=:num AND DATE(date)=CURDATE() AND client=:cli");
	req.bindValue(":cli",clients[curclient]);
	req.bindValue(":num",ui->spinBox_3->value());
	req.exec();
	req.next();
	int idticket=req.value(0).toInt();
	for(int i=0,c=liste->rowCount();i<c;i++)
	{
		QString entete=liste->item(i)->text();
		if(entete=="A-")
		{
			req.prepare("SELECT id FROM Acompte WHERE client = :cli AND valeur= :mon AND datededuit='0000-00-00'");
			req.bindValue(":mon",-(liste->item(i,6)->text().toInt()));
			req.bindValue(":cli",clients[curclient]);
			req.exec();
			if(req.next())
			{
				int idacompte=req.value(0).toInt();
				req.prepare("UPDATE Acompte SET datededuit=CURDATE(),tickdeduit=:tic WHERE id=:id");
				req.bindValue(":id",idacompte);
				req.bindValue(":tic",idticket);
				req.exec();
			}
			else
			{
				QMessageBox::critical(this,"Erreur","Une déduction d'acompte n'a pu être correctement effectuée : l'acompte n'a pu être retrouvé");
			}
		}
		else if(entete=="A+")
		{
			req.prepare("INSERT INTO Acompte(client,valeur,dateintro,tickintro) VALUES (:cli,:mon,CURDATE(),:tic)");
			req.bindValue(":cli",clients[curclient]);
			req.bindValue(":mon",liste->item(i,6)->text().toInt());
			req.bindValue(":tic",idticket);
			req.exec();
		}
		else if(entete=="?")
		{
			req.prepare("INSERT INTO ventenonreconnue(Modele,NArticle,Coloris,Taille,Qt,Prix,Ticket) VALUES (:mod,:art,:col,:tai,:qt,:prix,:tic)");
			req.bindValue(":mod",liste->item(i,1)->text());
			req.bindValue(":art",liste->item(i,2)->text());
			req.bindValue(":col",liste->item(i,3)->text());
			req.bindValue(":tai",liste->item(i,4)->text());
			req.bindValue(":qt",liste->item(i,5)->text().toInt());
			req.bindValue(":prix",(liste->item(i,6)->text().toFloat())/(liste->item(i,5)->text().toInt()));
			req.bindValue(":tic",idticket);
			req.exec();
		}
		else
		{
			req.prepare("CALL vendre(:tic,:code,:qt,:prix)");
			req.bindValue(":tic",idticket);
			req.bindValue(":code",liste->item(i,0)->text().toInt());
			req.bindValue(":qt",liste->item(i,5)->text().toInt());
			req.bindValue(":prix",liste->item(i,6)->text().toFloat());
			req.exec();
		}
	}
	system((QDir::homePath()+QString("/Gestion/ElixiP 0 %1").arg(idticket)).toStdString().c_str());
	req.exec("SELECT id,nom,prenom, adresse, codepostal,localite FROM Client ORDER BY nom,prenom,adresse");
	ui->clientComboBox->clear();
	ui->clientComboBox->addItem("DIVERS");
	clients.clear();
	clients.push_back(1);
	while(req.next())
	{
		if(req.value(0).toInt()!=1)
		{
			ui->clientComboBox->addItem(QString("%1 %2 %3 %4 %5").arg(req.value(1).toString()).arg(req.value(2).toString()).arg(req.value(3).toString()).arg(req.value(4).toString()).arg(req.value(5).toString()));
			clients.push_back(req.value(0).toInt());
		}
	}
	req.exec("CALL TicNum(CURDATE())");
	req.next();
	ui->spinBox_3->setValue(req.value(0).toInt());
	liste->removeRows(0,liste->rowCount());
	listecompte=0;
}
Esempio n. 26
0
qint32 NoteTable::duplicateNote(qint32 oldLid) {
    ConfigStore cs;
    qint32 newLid = cs.incrementLidCounter();

    QSqlQuery query;
    QString tempTableName = "notecopy" + QString::number(oldLid);
    query.exec("drop temporary table " +tempTableName);
    query.prepare("create temporary table " +tempTableName +" as select * from datastore where lid=:oldLid");
    query.bindValue(":oldLid", oldLid);
    query.exec();

    query.prepare("Update " +tempTableName +" set lid=:newLid");
    query.bindValue(":newLid", newLid);
    query.exec();

    query.exec("insert into datastore select lid, key, data from " +tempTableName);
    query.exec("drop " +tempTableName);

    query.prepare("update datastore set data=:data where lid=:lid and key=:key");
    query.bindValue(":data", 0);
    query.bindValue(":lid", newLid);
    query.bindValue(":key", NOTE_UPDATE_SEQUENCE_NUMBER);
    query.exec();

    Note n;
    get(n, newLid, false,false);
    updateNoteList(newLid, n, true);

    setDirty(newLid, true);

    // Update all the resources
    ResourceTable resTable;
    QList<qint32> lids;
    resTable.getResourceList(lids, oldLid);
    for (int i=0; i<lids.size(); i++) {
        qint32 newResLid = cs.incrementLidCounter();
        query.prepare("create temporary table " +tempTableName +" as select * from datastore where lid=:oldLid");
        query.bindValue(":oldLid", lids[i]);
        query.exec();


        query.prepare("Update " +tempTableName +" set lid=:newLid");
        query.bindValue(":newLid", newResLid);
        query.exec();

        query.exec("insert into datastore select lid, key, data from " +tempTableName);
        query.exec("drop " +tempTableName);

        query.prepare("update datastore set data=:data where lid=:lid and key=:key");
        query.bindValue(":data", 0);
        query.bindValue(":lid", newResLid);
        query.bindValue(":key", RESOURCE_UPDATE_SEQUENCE_NUMBER);
        query.exec();

        query.prepare("update datastore set data=:data where lid=:lid and key=:key");
        query.bindValue(":data", 0);
        query.bindValue(":lid", newResLid);
        query.bindValue(":key", RESOURCE_NOTE_LID);
        query.exec();

        QStringList filter;
        QDir resDir(global.fileManager.getDbaDirPath());
        filter << QString::number(lids[i])+".*";
        QStringList files = resDir.entryList(filter);
        for (int j=0; j<files.size(); j++) {
            QFile file(global.fileManager.getDbaDirPath()+files[j]);
            int pos = files[j].indexOf(".");
            QString type = files[j].mid(pos);
            file.open(QIODevice::ReadOnly);
            file.copy(global.fileManager.getDbaDirPath()+
                      QString::number(newResLid) +type);
            file.close();
        }
    }

    return newLid;
}
bool DatabaseManager::insertInvariants(int type, int number, std::vector< std::vector<float> > invariants)
{

    //bool ret = false;

    if (db.isOpen())
    {

        QSqlQuery query;

        // First check, if a bubble has already entered to the table
        /*    bool exists = query.exec(QString("select * from invariant where type = %1 and number = %2").arg(type).arg(number));

        // If query is successfully executed
        if(exists)
        {
            // if there are elements received from the table, then there exists a bubble, we should delete those entries
            if(query.next())
            {
                ret = query.exec(QString("delete from invariant where type = %1 and number = %2").arg(type).arg(number));

                // If deletion is not successfuly executed return false
                if(!ret)

                    return false;

            }
        */
        //else return false;

        // Speed up the multiple-row insertion by using transactions
        //query.exec(QString("BEGIN TRANSACTION"));

        query.prepare(QString("replace into invariant values(?, ?, ?, ?)"));

        QVariantList typee;
        QVariantList numberr;
        QVariantList placeLabel;
        QVariantList val;


        db.transaction();

        // Insert new bubble
        for(uint i = 0; i <invariants.size(); i++)
        {
            for(uint j = 0; j < invariants[i].size(); j++) {


                val<< invariants[i][j];
                typee<<type;
                numberr<<number;

                if(placeLabels.size() >= number)
                {
                    placeLabel<<placeLabels.at(number-1);
                }

                else
                    placeLabel<<-1;


                //query.exec(QString("replace into invariant values('%1', '%2', '%3')").arg(type).arg(number).arg(val));


            }
        }

        query.addBindValue(typee);
        query.addBindValue(numberr);
        query.addBindValue(placeLabel);
        query.addBindValue(val);

        // query.exec(QString("COMMIT TRANSACTION"));

        if (!query.execBatch())
            qDebug() << query.lastError();
        db.commit();

        return true;

    }



    //  }

    return false;

}
Esempio n. 28
0
// Add a new note to the database
qint32 NoteTable::add(qint32 l, Note &t, bool isDirty) {
    QLOG_DEBUG() << "Adding note: " << QString::fromStdString(t.title);
    ResourceTable resTable;
    ConfigStore cs;
    QSqlQuery query;
    qint32 position;
    TagScanner scanner;
    qint32 lid = l;
    qint32 notebookLid;

    query.prepare("Insert into DataStore (lid, key, data) values (:lid, :key, :data)");
    if (lid <= 0)
        lid = cs.incrementLidCounter();

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_GUID);
    query.bindValue(":data", QString::fromStdString(t.guid));
    query.exec();

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_INDEX_NEEDED);
    query.bindValue(":data", true);
    query.exec();

    if (t.__isset.title) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_TITLE);
        query.bindValue(":data", QString::fromStdString(t.title.c_str()));
        query.exec();
    }

    if (t.__isset.content) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CONTENT);
        QByteArray b;
        b.append(QString::fromStdString(t.content).toAscii());
        query.bindValue(":data", b);
        query.exec();
    }

    if (t.__isset.contentHash) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CONTENT_HASH);
        query.bindValue(":data", QString::fromStdString(t.contentHash));
        query.exec();
    }

    if (t.__isset.contentLength) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CONTENT_LENGTH);
        query.bindValue(":data", t.contentLength);
        query.exec();
    }

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_UPDATE_SEQUENCE_NUMBER);
    query.bindValue(":data", t.updateSequenceNum);
    query.exec();

    query.bindValue(":lid", lid);
    query.bindValue(":key", NOTE_ISDIRTY);
    query.bindValue(":data", isDirty);
    query.exec();

    if (t.__isset.created) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_CREATED_DATE);
        query.bindValue(":data", QVariant::fromValue(t.created));
        query.exec();
    }

    if (t.__isset.updated) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_UPDATED_DATE);
        query.bindValue(":data", QVariant::fromValue(t.updated));
        query.exec();
    }

    if (t.__isset.deleted) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_DELETED_DATE);
        query.bindValue(":data", QVariant::fromValue(t.deleted));
        query.exec();
    }

    if (t.__isset.active) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_ACTIVE);
        query.bindValue(":data", QVariant::fromValue(t.active));
        query.exec();
    }

    if (t.__isset.notebookGuid) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_NOTEBOOK_LID);
        NotebookTable notebookTable;
        notebookLid = notebookTable.getLid(QString::fromStdString(t.notebookGuid));

        // If not found, we insert one to avoid problems.  We'll probably get the real data later
        if (notebookLid == 0) {
            notebookLid = cs.incrementLidCounter();
            Notebook notebook;
            notebook.guid = t.notebookGuid;
            notebook.name = "";
            notebook.__isset.guid = true;
            notebook.__isset.name = true;
            notebookTable.add(notebookLid, notebook, false, false);
        }
        query.bindValue(":data", notebookLid);
        query.exec();
    }

    for (unsigned int i=0; t.__isset.tagGuids && i<t.tagGuids.size(); i++) {
        TagTable tagTable;
        qint32 tagLid = tagTable.getLid(t.tagGuids.at(i));
        if (tagLid == 0) {
            // create a dummy tag to avoid later problems
            Tag newTag;
            newTag.guid = t.tagGuids.at(i);
            newTag.name = "";
            newTag.__isset.guid = true;
            newTag.__isset.name = true;
            tagLid = cs.incrementLidCounter();
            tagTable.add(tagLid, newTag, false, 0);
        }

        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_TAG_LID);
        query.bindValue(":data", tagLid);
        query.exec();
    }

    for (unsigned int i=0; t.__isset.resources && i<t.resources.size(); i++) {
        qint32 resLid;
        Resource *r;
        r = &t.resources[i];
        resLid = resTable.getLid(t.guid,t.resources[i].guid);
        if (resLid == 0)
            resLid = cs.incrementLidCounter();
        resTable.add(resLid, t.resources[i], isDirty);

        if (r->__isset.mime) {
            QString mime = QString::fromStdString(r->mime);
            if (!mime.startsWith("image/") && mime != "vnd.evernote.ink") {
                query.bindValue(":lid", lid);
                query.bindValue(":key", NOTE_HAS_ATTACHMENT);
                query.bindValue(":data", true);
                query.exec();
            }
        }
    }

    if (t.__isset.attributes) {
        if (t.attributes.__isset.subjectDate) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SUBJECT_DATE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.subjectDate));
            query.exec();
        }
        if (t.attributes.__isset.latitude) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_LATITUDE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.latitude));
            query.exec();
        }
        if (t.attributes.__isset.latitude) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_LONGITUDE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.longitude));
            query.exec();
        }
        if (t.attributes.__isset.altitude) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_ALTITUDE);
            query.bindValue(":data", QVariant::fromValue(t.attributes.altitude));
            query.exec();
        }
        if (t.attributes.__isset.author) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_AUTHOR);
            query.bindValue(":data", QString::fromStdString(t.attributes.author));
            query.exec();
        }
        if (t.attributes.__isset.source) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SOURCE);
            query.bindValue(":data", QString::fromStdString(t.attributes.source));
            query.exec();
        }
        if (t.attributes.__isset.sourceURL) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SOURCE_URL);
            query.bindValue(":data", QString::fromStdString(t.attributes.sourceURL));
            query.exec();
        }
        if (t.attributes.__isset.sourceApplication) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SOURCE_APPLICATION);
            query.bindValue(":data", QString::fromStdString(t.attributes.sourceApplication));
            query.exec();
        }
        if (t.attributes.__isset.shareDate) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_SHARE_DATE);
            query.bindValue(":data",QVariant::fromValue(t.attributes.shareDate));
            query.exec();
        }
        if (t.attributes.__isset.placeName) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_PLACE_NAME);
            query.bindValue(":data", QString::fromStdString(t.attributes.placeName));
            query.exec();
        }
        if (t.attributes.__isset.contentClass) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_ATTRIBUTE_CONTENT_CLASS);
            query.bindValue(":data", QString::fromStdString(t.attributes.contentClass));
            query.exec();
        }
    }

    // No determine some attributes of the note based upon the content
    // This should probably happen every time a note changes? Or at least something simular:
    QString content;
    if (t.__isset.content)
        content = QString::fromStdString(t.content);
    else
        content = "";

    position = content.indexOf("<en-crypt");
    if (position > 0) {
        query.bindValue(":lid", lid);
        query.bindValue(":key", NOTE_HAS_ENCRYPT);
        query.bindValue(":data", true);
        query.exec();
    }
    position = content.indexOf("<en-todo");
    if (position > 0) {
        position = content.indexOf("<en-todo checked=\"true\"");
        if (position > 0) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_HAS_TODO_COMPLETED);
            query.bindValue(":data", true);
            query.exec();
        }
        position = qMax(content.indexOf("<en-todo checked=\"false\""), content.indexOf("<en-todo>"));
        if (position > 0) {
            query.bindValue(":lid", lid);
            query.bindValue(":key", NOTE_HAS_TODO_UNCOMPLETED);
            query.bindValue(":data", true);
            query.exec();
        }
    }

    updateNoteList(lid, t, isDirty);
    return lid;
}
Esempio n. 29
0
void Report_000::FuncBuild()
{
    QSqlQuery Query = QSqlQuery(Global.DataBase);
    QSqlRecord Rec;
    QString QueryString;
    // ======= Заголовок -------------------------------------
    R += "<b><center><font face=\"Times New Roman\" size=\"4\">Анализ базы данных на типовые ошибки</font></center></b>";
    R += "<b><center><font face=\"Times New Roman\" size=\"2\">сформирован "+QDate::currentDate().toString("dd/MM/yyyy")+" в "+QTime::currentTime().toString("HH:mm:ss")+"</font></center></b><br>";
    // --- Карточки клиентов
    R +="<b><font face=\"Times New Roman\" size=\"3\">Карточки Клиентов</font></b>";
    R +="<table border=\"1\" width=\"100%\" cellspacing=\"0\" cellpadding=\"4\" bordercolor=\"#000000\">";
    R +="<tr>";
    R +="<td width=\"1%\" align=\"center\" nowrap><b>№ карточки</b></td>";
    R +="<td width=\"1%\" align=\"center\"><b>Ф.И.О. клиента</b></td>";
    R +="<td width=\"98%\" align=\"center\"><b>Описание возможной ошибки</b></td>";
    R +="</tr>";
    // поиск ошибок
    QueryString =
            "SELECT x.\"CardNumber\", CONCAT(x.\"Surname\",x.\"FirstName\",x.\"Patronymic\") AS \"Name\", x.\"Reason\" FROM ( "
            // "-- Разница в возрасте с ребенком менее 13 лет "
            "SELECT c1.\"Id\", CONCAT(c1.\"CardNumber\"::text,'-',Extract(YEAR FROM c1.\"DateContact\"::date )) AS \"CardNumber\" ,  "
            "  CASE WHEN c1.\"Surname\" > '' THEN CONCAT(c1.\"Surname\", ' ') ELSE '' END AS \"Surname\",  "
            "  CASE WHEN c1.\"FirstName\" > '' THEN CONCAT(c1.\"FirstName\", ' ') ELSE '' END AS \"FirstName\",  "
            "  c1.\"Patronymic\", "
            "  'Разница в возрасте с ребенком менее 13 лет' AS \"Reason\" "
            "FROM "
            "  public.\"Clients\" AS c1, public.\"Clients\" AS c2, public.\"Family\" AS f "
            "WHERE "
            "  c1.\"CardNumber\" > 0 AND c1.\"Id\" = f.\"ClientOne\" AND c2.\"Id\" = f.\"ClientTwo\" AND f.\"Relation\" IN (15,16,19,20) AND c2.\"YearOfBirth\"-c1.\"YearOfBirth\" < 13 "
            "UNION "
            // "-- Разница в возрасте с родителем менее 13 лет "
            "SELECT c1.\"Id\", CONCAT(c1.\"CardNumber\"::text,'-',Extract(YEAR FROM c1.\"DateContact\"::date )) AS \"CardNumber\" ,  "
            "  CASE WHEN c1.\"Surname\" > '' THEN CONCAT(c1.\"Surname\", ' ') ELSE '' END AS \"Surname\",  "
            "  CASE WHEN c1.\"FirstName\"  > '' THEN CONCAT(c1.\"FirstName\", ' ') ELSE '' END AS \"FirstName\",  "
            "  c1.\"Patronymic\", "
            "  'Разница в возрасте с родителем менее 13 лет' AS \"Reason\" "
            "FROM "
            "  public.\"Clients\" AS c1, public.\"Clients\" AS c2, public.\"Family\" AS f "
            "WHERE "
            "  c1.\"CardNumber\" > 0 AND c1.\"Id\" = f.\"ClientOne\" AND c2.\"Id\" = f.\"ClientTwo\" AND f.\"Relation\" IN (10,21,22,30) AND c1.\"YearOfBirth\"-c2.\"YearOfBirth\" < 13 "
            "UNION "
            // "-- Возможно ошибка в возрасте родителя "
            "SELECT c1.\"Id\", CONCAT(c1.\"CardNumber\"::text,'-',Extract(YEAR FROM c1.\"DateContact\"::date )) AS \"CardNumber\" ,  "
            "  CASE WHEN c1.\"Surname\" > '' THEN CONCAT(c1.\"Surname\", ' ') ELSE '' END AS \"Surname\",  "
            "  CASE WHEN c1.\"FirstName\" > '' THEN CONCAT(c1.\"FirstName\", ' ') ELSE '' END AS \"FirstName\",  "
            "  c1.\"Patronymic\", "
            "  'Возможно ошибка в возрасте родителя' AS \"Reason\" "
            "FROM "
            "  public.\"Clients\" AS c1, public.\"Clients\" AS c2, public.\"Family\" AS f "
            "WHERE "
            "   (c1.\"CardNumber\" > 0 AND  "
            "    c1.\"Id\" = f.\"ClientOne\" AND  "
            "    c2.\"Id\" = f.\"ClientTwo\" AND  "
            "    f.\"Relation\" IN (15,16,19,20) AND  "
            "    ((EXTRACT(year FROM now()) - c1.\"YearOfBirth\") < 13))  "
            "   OR "
            "   (c2.\"CardNumber\" > 0 AND  "
            "    c1.\"Id\" = f.\"ClientOne\" AND  "
            "    c2.\"Id\" = f.\"ClientTwo\" AND  "
            "    f.\"Relation\" IN (10,21,22,30) AND  "
            "    ((EXTRACT(year FROM now()) - c2.\"YearOfBirth\") < 13)) "
            "UNION "
            // "-- Возможна ошибка в отчестве или неверно указан пол "
            "SELECT c1.\"Id\", CONCAT(c1.\"CardNumber\"::text,'-',Extract(YEAR FROM c1.\"DateContact\"::date )) AS \"CardNumber\" ,  "
            "  CASE WHEN c1.\"Surname\" > '' THEN CONCAT(c1.\"Surname\", ' ') ELSE '' END AS \"Surname\",  "
            "  CASE WHEN c1.\"FirstName\"  > '' THEN CONCAT(c1.\"FirstName\", ' ') ELSE '' END AS \"FirstName\",  "
            "  c1.\"Patronymic\", "
            "  'Возможна ошибка в отчестве или неверно указан пол' AS \"Reason\" "
            "FROM "
            "  public.\"Clients\" AS c1 "
            "WHERE "
            "  c1.\"CardNumber\" > 0 AND (((c1.\"Patronymic\" ~* '.+ич$') AND c1.\"Gender\") OR ((c1.\"Patronymic\" ~* '.+на$') AND c1.\"Gender\" = FALSE)) "
            "UNION "
            // "-- КК без обслуживания "
            "SELECT "
            "  c1.\"Id\", CONCAT(c1.\"CardNumber\"::text,'-',Extract(YEAR FROM c1.\"DateContact\"::date)) AS \"CardNumber\", "
            "  CASE WHEN c1.\"Surname\" > '' THEN CONCAT(c1.\"Surname\", ' ') ELSE '' END AS \"Surname\", "
            "  CASE WHEN c1.\"FirstName\"  > '' THEN CONCAT(c1.\"FirstName\", ' ') ELSE '' END AS \"FirstName\", "
            "  c1.\"Patronymic\", "
            "  'К карточке клиента не привязано ни одно обслуживание' AS \"Reason\" "
            "FROM "
            "  public.\"Clients\" AS c1 "
            "WHERE "
            "  c1.\"CardNumber\" > 0 AND "
            "  c1.\"Id\" NOT IN ( "
            "    SELECT "
            "      sc.\"Client\" "
            "    FROM "
            "      public.\"Service2Clients\" AS sc "
            "  ) "
            "UNION "
            // "-- Заригистрирован однополый брак? "
            "SELECT c1.\"Id\", CONCAT(c1.\"CardNumber\"::text,'-',Extract(YEAR FROM c1.\"DateContact\"::date )) AS \"CardNumber\" ,  "
            "  CASE WHEN c1.\"Surname\" > '' THEN CONCAT(c1.\"Surname\", ' ') ELSE '' END AS \"Surname\",  "
            "  CASE WHEN c1.\"FirstName\"  > '' THEN CONCAT(c1.\"FirstName\", ' ') ELSE '' END AS \"FirstName\",  "
            "  c1.\"Patronymic\", "
            "  'Однополый брак?' AS \"Reason\" "
            "FROM "
            "  public.\"Clients\" AS c1, public.\"Clients\" AS c2, public.\"Family\" AS f "
            "WHERE "
            "  (c1.\"CardNumber\" > 0 AND c1.\"Id\" = f.\"ClientOne\" AND c2.\"Id\" = f.\"ClientTwo\" AND c1.\"Gender\" AND c2.\"Gender\" AND f.\"Relation\" IN (3,7,12)) OR "
            "  (c1.\"CardNumber\" > 0 AND c1.\"Id\" = f.\"ClientTwo\" AND c2.\"Id\" = f.\"ClientOne\" AND c1.\"Gender\" AND c2.\"Gender\" AND f.\"Relation\" IN (3,7,12)) OR "
            "  (c1.\"CardNumber\" > 0 AND c1.\"Id\" = f.\"ClientOne\" AND c2.\"Id\" = f.\"ClientTwo\" AND c1.\"Gender\" = FALSE AND c2.\"Gender\" = FALSE AND f.\"Relation\" IN (4,8,17)) OR "
            "  (c1.\"CardNumber\" > 0 AND c1.\"Id\" = f.\"ClientTwo\" AND c2.\"Id\" = f.\"ClientOne\" AND c1.\"Gender\" = FALSE AND c2.\"Gender\" = FALSE AND f.\"Relation\" IN (4,8,17)) "
            ") AS x "
            "ORDER BY x.\"CardNumber\" ";
    Query.prepare(QueryString);
    if (!Query.exec()) GuiSqlError("Ошибка работы с базой данных!");
    Rec = Query.record();
    while (Query.next()) {
        R +="<tr>";
        R +="<td width=\"1%\" align=\"center\" nowrap>"+Query.value(Rec.indexOf("CardNumber")).toString()+"</td>";
        R +="<td width=\"1%\" nowrap>"+Query.value(Rec.indexOf("Name")).toString()+"</td>";
        R +="<td width=\"98%\">"+Query.value(Rec.indexOf("Reason")).toString()+"</td>";
        R +="</tr>";
    }
    R +="</table><br>";
}
Esempio n. 30
0
void ImageRecordListModel::populateList()
{
	// prep db
	(void)ImageRecord::db();
	
	m_populating = true;
	
	if(m_list.size() > 0)
	{
		beginRemoveRows(QModelIndex(),0,m_list.size());
	
		foreach(ImageRecord *record, m_list)
			removeRecord(record);
	
		endRemoveRows();
	}
	
	QString clause = "";
	if(!m_filter.trimmed().isEmpty())
		clause = "WHERE file like ?";
	
	QSqlQuery query;
	QString sql = QString("SELECT * FROM %1 %2 ORDER BY file").arg(IMAGEDB_TABLE).arg(clause);
	//qDebug() << "ImageRecordListModel::populateList(): sql:"<<sql;
	
	query.prepare(sql); 
	if(!m_filter.trimmed().isEmpty())
	{
		QString filter = QString("%%1%").arg(m_filter.trimmed());
		query.addBindValue(filter);
		//qDebug() << "ImageRecordListModel::populateList(): filter:"<<filter;
	}
	
	query.exec();
	
	if (query.lastError().isValid())
	{
		qDebug() << "ImageRecordListModel::populateList(): Error loading records from database:"<<query.lastError();
		return;
	}
	else
	//if(query.size() > 0)
	{
		int sz = query.size();
		//beginInsertRows(QModelIndex(),0,sz);
		
		// hack hack hack
		beginInsertRows(QModelIndex(),0,100);
		
		while(query.next())
			addRecord(ImageRecord::fromQuery(query));
		
		
		endInsertRows();
		
		//qDebug() << "ImageRecordListModel::populateRecordList(): query.size():"<<sz<<", m_list.size():"<<m_list.size();
	}
// 	else
// 	{
// 		qDebug() << "ImageRecordListModel::populateRecordList(): 
// 	}
	
	m_populating = false;
}