Exemple #1
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow fenetre;

    TacheManager* tm = TacheManager::getInstance();
    ProjetManager* pm = ProjetManager::getInstance();
    EvenementManager* em = EvenementManager::getInstance();

    // Creates directory if non existent
    QDir directory(QDir::homePath()+QDir::separator()+".projectCalendar");
    directory.mkdir(directory.path());

    // Connect to DB
    QSqlDatabase sdb = QSqlDatabase::addDatabase("QSQLITE");
    sdb.setDatabaseName(directory.absolutePath()+QDir::separator()+"projets_taches.sqlite");

    if (sdb.open()) {
        QSqlQuery query1(sdb);
        bool res1 = query1.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='PROJETS'");

        QSqlQuery query2(sdb);
        bool res2 = query2.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='TACHES'");

        QSqlQuery query3(sdb);
        bool res3 = query3.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='EVENEMENTS'");

        QSqlQuery query4(sdb);
        bool res4 = query4.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='TACHES_PRECEDENTES'");

        if (!res1 || !res2 || !res3 || !res4 ||
                !query1.next() || !query2.next() || !query3.next() || !query4.next()) {
            query1.clear();
            query2.clear();
            qDebug()<<"Invalid DB. Creating new one...";
            fenetre.showError("Project Calendar", "La base de donnée locale actuelle est vide ou invalide. Elle va être recréée. Vous êtes susceptible de perdre des données.");
            QFile sql_ldd(":/assets/TABLES.sql");
            if (!sql_ldd.open(QIODevice::ReadOnly | QIODevice::Text)) {
                fenetre.showError("Project Calendar", "Erreur lors de la lecture de TABLES.sql");
                sdb.close();
                app.exit(0);
                return 0;
            }
            QTextStream in(&sql_ldd);
            QString sql = in.readAll();
            QStringList sqlStatements = sql.split(';', QString::SkipEmptyParts);
            int successCount = 0;

            foreach(const QString& statement, sqlStatements) {
                if (statement.trimmed() != "") {
                    QSqlQuery query(sdb);
                    if (query.exec(statement))
                        successCount++;
                    else
                        qDebug() << "Failed:" << statement << "\nReason:" << query.lastError();
                }
            }
            qDebug()<<"Successfully";
        }
Model Model::create(string path){

    ostringstream s4, s5;
    s4 << "INSERT INTO Model(directory) VALUES('" + path + ".txt');";
    QSqlQuery query4(QString(s4.str().c_str()));
    int idModel = query4.lastInsertId().toInt();

    cout << s4.str() << endl;

    string command = "bash createCSV.sh " + path + " > FaceRecognition/modelos.csv";
    cout << command << endl;
    system(command.c_str());

    vector<Mat> images;
    vector<int> labels;

    try{
        read_csv("FaceRecognition/modelos.csv", images, labels);
    }catch (cv::Exception& e) {
        cerr << "ERROR OPENING CSV FILE" << endl;
        exit(1);
    }

    s5 << "INSERT INTO ModelStudent("
          "id_model,"
          "id_student) VALUES";

    set<int> ids(labels.begin(), labels.end());
    map<int, int> pairs;

    for(auto it = ids.begin(); it != ids.end(); ++it){
        Alumno* a = Alumno::create("", string(path + "/" + to_string(*it)));
        pairs[(*it)] = a->getId();
        s5 << "(" << idModel << ", " << a->getId() << ")";
        if(next(it) == ids.end()) s5 << ";";
        else s5 << ", \n";
    }
    cout << s5.str() << endl;
    vector<int> newLabels;
    for(int i = 0; i < labels.size(); i++){
        newLabels.push_back(pairs[labels[i]]);
    }

    for(int i = 0; i < images.size(); i++){
        equalizeHist(images[i], images[i]);
        cv::resize(images[i], images[i], Size(48,48));
    }


    QSqlQuery query5(QString(s5.str().c_str()));

    Model model = Model(createEigenFaceRecognizer(0, 3000));
    model->train(images, newLabels);
    model->save(string(path + ".txt"));
    cout << "END" << endl;

    return model;
}
bool SQLiteKeyValueStore::open(const QString &filename, QString *error)
{
    if (_db.isOpen())
        return true;

    _db = QSqlDatabase::addDatabase("QSQLITE",filename);
    _db.setDatabaseName(filename);

    if (!_db.open())
    {
        if (error)
            *error = "Failed to open database.";
        return false;
    }

    if (!_db.isOpen())
    {
        if (error)
            *error = "Still failed to open database";
        return false;
    }

    QSqlQuery query("CREATE TABLE IF NOT EXISTS keyValueStore (key BLOB PRIMARY KEY NOT NULL, value BLOB NOT NULL);",_db);
    if (!query.exec())
    {
        if (error)
            *error = "Failed to initialize database.";
        qDebug() << query.lastError();
        return false;
    }

    QSqlQuery query2("PRAGMA locking_mode = EXCLUSIVE;",_db);
    if (!query2.exec())
    {
        if (error)
            *error = "Failed to enable exclusive locking";
        return false;
    }

    QSqlQuery query3("PRAGMA auto_vacuum = FULL;",_db);
    if (!query3.exec())
    {
        if (error)
            *error = "Failed to enable auto_vacuum mode";
        return false;
    }

    QSqlQuery query4("VACUUM;",_db);
    if (!query4.exec())
    {
        if (error)
            *error = "Failed to do vaccuum";
        return false;
    }
    return true;
}
void ordersfrm::complete()
{
	int r = QMessageBox::question(this, tr("Complete items..."),tr("Change status for completed items?"),QMessageBox::Yes, QMessageBox::No);
    if(r == QMessageBox::Yes)
    {
		int i;
		QTreeWidgetItem *item = new QTreeWidgetItem;
		for(i=0;i<treemain->topLevelItemCount();i++)
		{
				item = treemain->topLevelItem(i);
		    if(item->checkState(0))
		    {
		    	QString qstr = QString("SELECT STATUS, STOCK, DEF FROM `orders` WHERE `ID`=%1;").arg(item->text(0));
				QSqlQuery query1(qstr);
				query1.next();
		
				if(query1.value(0).toInt() < 2)
				{
				    QSqlQuery query2;
				    query2.prepare("UPDATE `orders` SET `STATUS`= :status, `DATE"+QString("%1").arg(query1.value(0).toInt()+2, 0, 10)+"`= :date WHERE `ID`=:ID LIMIT 1;");
				    query2.bindValue(":status", query1.value(0).toInt()+1);
				    query2.bindValue(":date", QDate::currentDate().toString("yyyy-MM-dd"));
				    query2.bindValue(":ID", item->text(0));
				    query2.exec();
				}
		
				if(query1.value(0).toInt() == 2)
				{
					qstr = QString("UPDATE `orders` SET `STATUS`= '%1' WHERE `ID`='%2' LIMIT 1;").arg(query1.value(0).toInt()+1).arg(item->text(0));
				    QSqlQuery query2(qstr);
		    
		    		qstr = QString("SELECT NAME, USERS FROM datatables WHERE `DESCRIPTION`='%1';").arg(query1.value(1).toString());
				    QSqlQuery query3(qstr);
				    query3.next();
				    QString stock = query3.value(0).toString();
		    
		    		qstr = QString("SELECT ID, col3 FROM %1 WHERE `col1`= '%2';").arg(stock).arg(item->text(2));
		    		QSqlQuery query4(qstr);
				    query4.next();
				    QString id = query4.value(0).toString();
				    QString old_q = query4.value(1).toString();
		    	    
		    	    qstr = QString("UPDATE `%1` SET `col3`= '%2' WHERE `ID`= '%3' LIMIT 1;").arg(stock).arg(old_q.toInt() + item->text(4).toInt()).arg(id);
				    QSqlQuery query5(qstr);
				    QMessageBox::question(this, tr("Complete items..."), query5.executedQuery());
				}
		    }
		}
		loadentries();
		countentries();
    }
}
void query4(int now,int w,int h)
{
	int th;
	if(now==2)
	{
		query4(now+1,w>a[now]?w:a[now],h+b[now]);
		query4(now+1,w>b[now]?w:b[now],h+a[now]);
	}
	else if(now==4)
	{
		th=h>b[now]?h:b[now];
		if((w+a[now])*th<max)
		{
			max=(w+a[now])*th;
			cur=0;
			p[cur++]=(w+a[now])>th?th:(w+a[now]);
		}
		else if((w+a[now])*th==max)
		{
			p[cur++]=(w+a[now])>th?th:(w+a[now]);
		}
		th=h>a[now]?h:a[now];
		if((w+b[now])*th<max)
		{
			max=(w+b[now])*th;
			cur=0;
			p[cur++]=(w+b[now])>th?th:(w+b[now]);
		}
		else if((w+b[now])*th==max)
		{
			p[cur++]=(w+b[now])>th?th:(w+b[now]);
		}
	}
	else
	{
		query4(now+1,w+a[now],b[now]>h?b[now]:h);
		query4(now+1,w+b[now],a[now]>h?a[now]:h);
	}
}
Exemple #6
0
void Database::NewDatabase(const std::string& filename)
{
    m_db.setDatabaseName(filename.c_str());
    if(!m_db.open())
    {
        std::cerr << "error: Unknown error" << std::endl;
        QMessageBox::information(0,"Ok","Unknown error");
    }
    QSqlQuery query1("CREATE TABLE FileInfo ( id int )");
    QSqlQuery query2("insert into FileInfo (id) values (1)");
    QSqlQuery query3("CREATE TABLE Log(ID INT PRIMARY KEY NOT NULL, \
                                       Log TEXT, \
                                       Date DATE, \
                                       PersonID INT, Title TEXT);");
    QSqlQuery query4("CREATE TABLE Person( \
                                     ID INT PRIMARY KEY NOT NULL, \
                                     Name   TEXT \
                                     );");
}
void addDataFromLocalFile(QString fileName, MyModel* model)
{
    QSqlQuery delete_query("DELETE from result3", model->database());

    QSqlQuery reset_pk("alter table result3 auto_increment=1");
    QSqlQuery query(model->database());
    fileName.prepend("'");
    fileName.append("'");
    query.prepare("LOAD DATA INFILE " + fileName + " replace INTO table result3 fields terminated by ' '" );
    qDebug() << "Start importing on thread " <<  QThread::currentThread();
    qDebug() << query.exec();

    QSqlQuery query2("delete from gap_all_sp", model->database());
    QSqlQuery query3("delete from gap_all_nsp", model->database());

    QSqlQuery query4("INSERT INTO gap_all_sp (Serial) SELECT Serial from result3", model->database());
    QSqlQuery query5("INSERT INTO gap_all_nsp (Serial) SELECT Serial from result3", model->database());

    for (int blueBall = 1; blueBall <= 16; ++blueBall)
    {
        QString sp_table = "gap_blue" + QString::number(blueBall)+ "_sp";
        QString nsp_table = "gap_blue" + QString::number(blueBall)+ "_nsp";
        QSqlQuery gap_table_query1("DELETE FROM " + sp_table, model->database());
        QSqlQuery gap_table_query2("DELETE FROM " + nsp_table, model->database());

        QSqlQuery insert_query_sp;
        insert_query_sp.prepare("INSERT INTO " + sp_table + " (Serial) SELECT Serial from result3 where Blue1 = :Blue1");
        insert_query_sp.bindValue(":Blue1", blueBall);
        insert_query_sp.exec();

        QSqlQuery insert_query_nsp;
        insert_query_nsp.prepare("INSERT INTO " + nsp_table + " (Serial) SELECT Serial from result3 where Blue1 = :Blue1");
        insert_query_nsp.bindValue(":Blue1", blueBall);
        insert_query_nsp.exec();

    }

    model->calculateGaps();

    model->select();
}
void parejasStats::getData (int anyo, int *vuelo, int *desaparecido, int *reproduccion)
{
	QString consulta;
	/* Número de hijos en vuelo... */
	consulta = "select count(anilla) from paloma where anyo = " + QString::number(anyo)
		+ " AND estado = \"V\" AND \
		madreID =(\
			select palomaID from idCompacto where idCompacto =\"" + madre + "\"\
		) AND padreID = (\
			select palomaID from idCompacto where idCompacto = \"" + padre + "\")";
	QSqlQuery query3 (consulta, QSqlDatabase::database("palomar" ));
	if (query3.next())
		*vuelo = query3.value(0).toInt();

	/* Número de hijos desaparecidos... */
	consulta = "select count(anilla) from paloma where anyo = " + QString::number(anyo)
		+ " AND estado = \"D\" AND \
		madreID =(\
			select palomaID from idCompacto where idCompacto =\"" + madre + "\"\
		) AND padreID = (\
			select palomaID from idCompacto where idCompacto = \"" + padre + "\")";
	QSqlQuery query4 (consulta, QSqlDatabase::database("palomar" ));
	if (query4.next())
		*desaparecido = query4.value(0).toInt();

	/* Número de hijos en reproduccion... */
	consulta = "select count(anilla) from paloma where anyo = " + QString::number(anyo)
		+ " AND estado = \"R\" AND \
		madreID =(\
			select palomaID from idCompacto where idCompacto =\"" + madre + "\"\
		) AND padreID = (\
			select palomaID from idCompacto where idCompacto = \"" + padre + "\")";
	QSqlQuery query5 (consulta, QSqlDatabase::database("palomar" ));
	if (query5.next())
		*reproduccion = query5.value(0).toInt();
}
Exemple #9
0
QList<photo*>* db::getUnlabeledPhotos(){

	bool a=false;
	QSqlQuery query(database);
	query.prepare("SELECT DISTINCT Iid FROM HasFaces WHERE Pid = 1 ");
	a=query.exec();
	//	QList<int> photoId;
	QList<photo*>* pl = new QList<photo*>();
	while(query.next()){
		int imageId=query.value(0).toInt();
		//		photoId.append(imageId);
		QList<face*>* fl = new QList<face*>();

		QSqlQuery query4(database);
		query4.prepare("SELECT DISTINCT path FROM Images WHERE Iid = :imageId ");
		query4.bindValue(":imageId", imageId);
		bool k4 = query4.exec();
		query4.next();
		QString imagePath(query4.value(0).toString()); 


		QSqlQuery query2(database);
		query2.prepare("SELECT DISTINCT Fid,Pid FROM HasFaces WHERE Iid = :imageId ");
		query2.bindValue(":imageId", imageId);
		bool k=query2.exec();
		while(query2.next()){
			int faceId = query2.value(0).toInt(); 
			int personId = query2.value(1).toInt(); 
			QSqlQuery query3(database);
			query3.prepare("SELECT * FROM Faces WHERE Fid = :FId ");
			query3.bindValue(":FId", faceId);
			bool k3=query3.exec();
			//facelist olcak
			while(query3.next()){
				double x=query3.value(1).toDouble();
				double y=query3.value(2).toDouble();
				double width=query3.value(3).toDouble();
				double height=query3.value(4).toDouble();
				double tw=query3.value(5).toDouble(); 
				double th=query3.value(6).toDouble();
				QString featureListStr = query3.value(7).toString();

				QSqlQuery query5(database);
				query5.prepare("SELECT name FROM Person WHERE Pid = :PId ");
				query5.bindValue(":PId", personId);
				bool k5=query5.exec();
				query5.next();
				QString lbl(query5.value(0).toString());

				double* featureList = returnFacialFeatures(featureListStr);

				face* f = new face(faceId,QStringToString(imagePath),x,y,width,height,tw,th,featureList,QStringToString(lbl));
				f->setPhotoID(imageId);
				fl->append(f);
			}
		}
		photo* p = new photo(imagePath,fl);
		p->setID(imageId);
		pl->append(p);
	}


	return pl;
}
Exemple #10
0
int loadMETATables(QSqlDatabase mydb, bool deletePrevious, bool includeViews)
{
    QSqlQuery query(mydb);
    QStringList sqls;

    int pos;
    bool error;
    error = false;

    if (deletePrevious)
    {

        sqls << "DELETE FROM dict_lkpiso639";
        sqls << "DELETE FROM dict_dctiso639";
        sqls << "DELETE FROM dict_iso639";
        sqls << "DELETE FROM audit_log";
        sqls << "DELETE FROM dict_childinfo";
        sqls << "DELETE FROM dict_relinfo";
        sqls << "DELETE FROM dict_clminfo";
        sqls << "DELETE FROM user_log";
        sqls << "DELETE FROM auth_user_user_permissions";
        sqls << "DELETE FROM auth_user_groups";
        sqls << "DELETE FROM auth_user";
        sqls << "DELETE FROM auth_group_permissions";
        sqls << "DELETE FROM auth_permission";
        sqls << "DELETE FROM dict_tblinfo";
        sqls << "DELETE FROM dict_grpinfo";
        sqls << "DELETE FROM auth_group";


        for (pos = 0; pos <= sqls.count()-1;pos++)
        {
            query.exec(sqls[pos]);
        }
    }

    QString sqlStr;
    QSqlQuery query2(mydb);
    QSqlQuery query3(mydb);
    QSqlQuery query4(mydb);

    //Start of procees

    if (!includeViews)
        sqlStr = "select table_name from information_schema.tables where table_schema = '" + mydb.databaseName() + "' and table_type = 'BASE TABLE'";
    else
        sqlStr = "select table_name from information_schema.tables where table_schema = '" + mydb.databaseName() + "'";
    query.exec(sqlStr);
    QString tablename;
    QString fieldname;
    QString fieldtype;
    bool mainDesc;
    bool key;
    int poscol;
    int tbllkp;
    while (query.next())
    {
        tablename = query.value(0).toString().trimmed();
        if (!isIgnoreTable(tablename))
        {
            if (tablename.toLower().left(3) == "lkp")
                tbllkp = 1;
            else
                tbllkp = 0;
            sqlStr = "INSERT INTO dict_tblinfo (tbl_cod,tbl_des,tbl_lkp,tbl_pos) VALUES (";
            sqlStr = sqlStr + "'" + tablename.toLower() + "',";
            sqlStr = sqlStr + "'Description of " + tablename + "',";
            sqlStr = sqlStr + "" + QString::number(tbllkp) + "," + QString::number(tables.indexOf(tablename)) + ")";
            if (!query2.exec(sqlStr))
            {
                log("Error inserting in Table Information");
                log(query2.lastError().databaseText());
                return 1;
            }

            sqlStr = "desc " + tablename;
            query3.exec(sqlStr);
            poscol = 0;
            mainDesc = false;
            while (query3.next())
            {
                poscol++;
                fieldname = query3.value(0).toString().trimmed();
                fieldtype = query3.value(1).toString().trimmed();
                if (query3.value(3).toString().trimmed() == "PRI")
                    key = true;
                else
                    key = false;

                sqlStr = "INSERT INTO dict_clminfo (tbl_cod,clm_cod,clm_pos,clm_des,clm_key,clm_typ,clm_maindesc) VALUES (";
                sqlStr = sqlStr + "'" + tablename.toLower() + "',";
                sqlStr = sqlStr + "'" + fieldname + "',";
                sqlStr = sqlStr + QString::number(poscol) + ",";
                sqlStr = sqlStr + "'Description of " + fieldname + "',";
                if (key)
                    sqlStr = sqlStr + "1,";
                else
                    sqlStr = sqlStr + "0,";
                sqlStr = sqlStr + "'" + fieldtype + "',";
                if (mainDesc == false)
                {
                    if (fieldname.contains("_des") || fieldname.contains("_name"))
                    {
                        mainDesc = true;
                        sqlStr = sqlStr + "1)";
                    }
                    else
                    {
                        sqlStr = sqlStr + "0)";
                    }
                }
                else
                    sqlStr = sqlStr + "0)";

                if (!query4.exec(sqlStr))
                {
                    log("Error inserting in Column Information");
                    log(query4.lastError().databaseText());
                    return 1;
                }

            }

        }
    }

    if (!includeViews)
        sqlStr = "select table_name from information_schema.tables where table_schema = '" + mydb.databaseName() + "' and table_type = 'BASE TABLE'";
    else
        sqlStr = "select table_name from information_schema.tables where table_schema = '" + mydb.databaseName() + "'";

    query.exec(sqlStr);
    QString errorMsg;
    while (query.next())
    {
        tablename = query.value(0).toString().trimmed();
        if (!isIgnoreTable(tablename))
        {
            sqlStr = "select table_name,column_name,REFERENCED_TABLE_NAME,";
            sqlStr = sqlStr + "REFERENCED_COLUMN_NAME,CONSTRAINT_NAME from ";
            sqlStr = sqlStr + "information_schema.KEY_COLUMN_USAGE where ";
            sqlStr = sqlStr + "table_schema = '" + mydb.databaseName() + "' and ";
            sqlStr = sqlStr + "table_name = '" + tablename + "' and ";
            sqlStr = sqlStr + "REFERENCED_TABLE_NAME is not null";

            //qDebug() << sqlStr;

            query3.exec(sqlStr);
            while (query3.next())
            {
                sqlStr = "INSERT INTO dict_relinfo (tbl_cod,clm_cod,rtbl_cod,rclm_cod,cnt_name,error_msg,error_notes) VALUES (";
                sqlStr = sqlStr + "'" + query3.value(0).toString().trimmed().toLower() + "',";
                sqlStr = sqlStr + "'" + query3.value(1).toString().trimmed() + "',";
                sqlStr = sqlStr + "'" + query3.value(2).toString().trimmed().toLower() + "',";
                sqlStr = sqlStr + "'" + query3.value(3).toString().trimmed() + "',";
                sqlStr = sqlStr + "'" + query3.value(4).toString().trimmed() + "',";

                errorMsg = "The value in column \"" + query3.value(1).toString().trimmed() + "\" is not included in the list of possible values in table \"" + query3.value(2).toString().trimmed() + "\"";
                errorMsg = errorMsg + ". Correct the value in table \"" + query3.value(0).toString().trimmed() + "\" or add the value to table \"" + query3.value(2).toString().trimmed() + "\"";

                sqlStr = sqlStr + "'" + errorMsg + "','')";

                if (!query4.exec(sqlStr))
                {
                    log("Error inserting in the Relation Table");
                    log(query4.lastError().databaseText());
                }
            }
        }
    }

    if (!error)
        log("META's tables sucessfully loaded");
    return 0;
}
Exemple #11
0
int main()
{
	int i;
	FILE *fin  = fopen ("packrec.in", "r");
    FILE *fout = fopen ("packrec.out", "w");
	for(i=1;i<=4;i++)
	{
		fscanf(fin,"%d %d",a+i,b+i);
	}
	query1(1,0,0);
	query2(1,0,0);
	swap(1,4);
	query2(1,0,0);
	swap(1,4);
	swap(2,4);
	query2(1,0,0);
	swap(2,4);
	swap(3,4);
	query2(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(1,3);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(1,3);
	swap(2,3);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(2,3);
	swap(1,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(1,4);
	swap(2,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(2,4);
	swap(1,3);
	swap(2,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(2,4);
	swap(1,3);
	query4(1,0,0);
	swap(1,3);
	query4(1,0,0);
	swap(1,3);
	swap(1,4);
	query4(1,0,0);
	swap(1,4);
	swap(2,3);
	query4(1,0,0);
	swap(2,3);
	swap(2,4);
	query4(1,0,0);
	swap(2,4);
	swap(1,3);
	swap(2,4);
	query4(1,0,0);
	swap(2,4);
	swap(1,3);
	query5(1,0,0,0,0);
	swap(1,3);
	query5(1,0,0,0,0);
	swap(1,3);
	swap(1,4);
	query5(1,0,0,0,0);
	swap(1,4);
	swap(2,3);
	query5(1,0,0,0,0);
	swap(2,3);
	swap(2,4);
	query5(1,0,0,0,0);
	swap(1,3);	swap(1,3);
	swap(2,4);
	query5(1,0,0,0,0);
	swap(2,4);
	swap(1,3);
	quick_sort(0,cur-1);
	flag=p[0];
	wa=0;
	fprintf(fout,"%d\n%d %d\n",max,p[0],max/p[0]);
	while(wa<cur)
	{
		if(p[wa]==flag)
		{
			wa++;
			continue;
		}
		else
		{
			if(p[wa]>max/p[wa])
				break;
			fprintf(fout,"%d %d\n",p[wa],max/p[wa]);
			flag=p[wa];
		}
	}
	return 0;
}
Exemple #12
0
int Bench(int argc,char **argv)
{
	REF(Module)  moduleH;
	REF(any) r;
	char moduleName[40];
	// ProcessStats    totalTime;
	// ServerStats     totalSrvTime;
	//char*	purgeVar;
	char  resultText[200];  // buffer to hold result of operation for
                                // printing outside of timing region.
	char *configfile;
	int opIndex = 2;
	int repeatCount = 1;
	BenchmarkOp whichOp = Trav1;
	bool manyXACTS = 0;

	w_rc_t rc;

#ifdef PARSETS

	LOID objtype;

	int NumNodes;

	//reinitialize some globals.
	nextAtomicId=0; 
	nextCompositeId=0;
	nextComplexAssemblyId=0;
	nextBaseAssemblyId=0;
	nextModuleId = TotalModules;
	initParSets(argc, argv);

	if (argc < 6){
	    fprintf(stderr, "Usage: %s %s\n", argv[0], usage1);
	    fprintf(stderr, "%s\n", usage3);
	    fprintf(stderr, "%s\n", usage4);

	    exit(1);
	}

	sscanf(argv[5], "%d", &NumNodes);
	printf("NUMNODES = %d\n", NumNodes);

	for (int j=0; j< NumNodes; j++)
	  CompNodes.Add(j+1);

#endif

	rc = initialize(argc, argv, usage1);
	if(rc) {
	    return 1;
	}

	rc = Shore::begin_transaction(3);
	if(rc){
	    cerr << "can't begin transaction: " << rc << endl;
	    return 1;
	}

	// initialize parameters for benchmark.
	ParseCommandLine(argc, argv, opIndex, repeatCount, whichOp, manyXACTS,
		&configfile);

#ifdef PARSETS
	SetParams(argv[1], slArgs);
#else
	SetParams(configfile);
#endif
	rc = InitGlobals();
	if(rc){
	    cerr << "Error in InitGlobals: " << rc << endl;
	    exit(1);
	}

	nextAtomicId  = TotalAtomicParts + 1;
	nextCompositeId = TotalCompParts + 1;

	rc = Shore::commit_transaction();
	if(rc){
	    cerr << "can't commit transaction: " << rc << endl;
	    return 1;
	}

#ifdef PARSETS


	SlaveRPC(CompNodes, (char *) slaveGenInit, (char *)&slArgs, sizeof(SlaveArgs));	
	SlaveRPC(CompNodes, (char *)slaveOpenPools, NULL, -1);	

#ifdef NEWCOMMUNICATION
	myParSetServer->CreateParSet("oo7db", "CompositePart", ParSet::kPrimary, objtype,(char *)createCompositePart, 4, CompNodes, ParSet::kUserDef, 
		     (char *)declusterCompositeParts);
#else
	CreateParSet("oo7db", "CompositePart", ParSet::kPrimary, objtype,
		     4, (char *)createCompositePart, CompNodes, 
		     ParSet::kUserDef, (char *)declusterCompositeParts);

#endif

	compositeParSet = new PrimaryParSet <REF(CompositePart)>("oo7db", "CompositePart");
#endif

	// Compute structural info needed by the update operations,
        // since these operations need to know which id's should
        // be used next.

	int baseCnt = NumAssmPerAssm;
	int complexCnt = 1;	for (int i = 1; i < NumAssmLevels-1; i++) {
            baseCnt = baseCnt * NumAssmPerAssm;
            complexCnt += complexCnt * NumAssmPerAssm;
	}
	nextBaseAssemblyId = TotalModules*baseCnt + 1;
	nextComplexAssemblyId = TotalModules*complexCnt + 1;
	nextAtomicId = TotalAtomicParts + 1;
	nextCompositeId = TotalCompParts + 1;


	// needed for insert and delete tests
	shared_cp = new BAIdList[TotalCompParts+NumNewCompParts+1];
	private_cp = new BAIdList[TotalCompParts+NumNewCompParts+1];


	// See if debug mode is desired, see which operation to run,
	// and how many times to run it.



	// totalTime.Start();
	// totalSrvTime.Start();

	enum {do_commit, do_chain, do_nothing, do_begin } choice=do_begin;

        // Actually run the darn thing.
	for (int iter = 0; iter < repeatCount; iter++) 
	{
	    //////////////////////////////////////////////////////////////////
	    // Run an OO7 Benchmark Operation
	    //
	    //////////////////////////////////////////////////////////////////

	    printf("RUNNING OO7 BENCHMARK OPERATION %s, iteration = %d.\n", 
	           argv[opIndex], iter);

  	    // get wall clock time
            gettimeofday(&startWallTime, IGNOREZONE &ignoreTimeZone);

	    // get starting usage values.
	    getrusage(RUSAGE_SELF, &startUsage);

	    // Start a new transaction if either this is the first iteration
	    // of a multioperation transaction or we we are running each
	    // operate as a separate transaction

#ifdef PARSETS
	    if(choice == do_begin) {
		W_COERCE(Shore::begin_transaction(3));
		SlaveRPC(CompNodes, (char *)slaveBeginTransaction, NULL, -1);
	    }

#else
	    if(choice == do_begin) {
		// E_BeginTransaction();
		W_COERCE(Shore::begin_transaction(3));
	    }
#endif

            // set random seed so "hot" runs are truly hot
            srandom(1);

	    // Use random module for the operation
//            int moduleId = (int) (random() % TotalModules) + 1;
	for (int moduleId = 1 ; moduleId <= TotalModules; moduleId++){
			
#ifdef USE_MODULE_INDEX
            sprintf(moduleName, "Module %08d", moduleId);
//	    printf("moduleName=%s\n",moduleName);
	    moduleH =  tbl->ModuleIdx.find(moduleName);
#else
	    sprintf(moduleName,"Module%d", moduleId);
	    rc = REF(Module)::lookup(moduleName, moduleH);
	    if(rc){
		cerr << "Can't find module " << moduleName << ": "
		     << rc << endl;
		return 1;
	    }
#endif
	    printf("Traversing Module= %s\n", moduleName);
	    if (moduleH == NULL)
	    {
	        fprintf(stderr, "ERROR: Unable to access %s.\n", moduleName);
		// E_AbortTransaction();
		W_COERCE(Shore::abort_transaction());
	        exit(1);
	    }

	    // Perform the requested operation on the chosen module
	    long count = 0;
	    int docCount = 0;
	    int charCount = 0;
	    int replaceCount = 0;

	    switch (whichOp) {
	        case Trav1:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 1 DFS visited %d atomic parts.\n",
			             count);
  		    break;
		 case Trav1WW:
                    RealWork = 1;
                    whichOp = Trav1;  // so traverse methods don't complain
                    count = moduleH->traverse(whichOp);
                    whichOp = Trav1WW;  // for next (hot) traversal
                    sprintf(resultText, "Traversal 1WW DFS visited %d atomic parts.\n",
                                     count);
                    break;
	        case Trav2a:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 2A swapped %d pairs of (X,Y) coordinates.\n",
 			         count);
		    break;
	        case Trav2b:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 2B swapped %d pairs of (X,Y) coordinates.\n",
			             count);
		    break;
	        case Trav2c:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 2C swapped %d pairs of (X,Y) coordinates.\n",
			             count);
		    break;
	        case Trav3a:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 3A toggled %d dates.\n",
			             count);
		    break;
	        case Trav3b:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 3B toggled %d dates.\n",
			             count);
		    break;
	        case Trav3c:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 3C toggled %d dates.\n",
			            count);
		    break;
	        case Trav4:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 4: %d instances of the character found\n",
			             count);
		    break;
	        case Trav5do:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 5(DO): %d string replacements performed\n",
			             count);
		    break;
	        case Trav5undo:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 5(UNDO): %d string replacements performed\n",
			         count);
		    break;
	        case Trav6:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 6: visited %d atomic part roots.\n",
			             count);
		    break;
	        case Trav7:
	            count = traverse7();
		    sprintf(resultText, "Traversal 7: found %d assemblies using rand om atomic part.\n", 
			count);
		    break;
	        case Trav8:
	            count = moduleH->scanManual();
		    sprintf(resultText, "Traversal 8: found %d occurrences of character in manual.\n", 
			count);
		    break;
	        case Trav9:
	            count = moduleH->firstLast();
		    sprintf(resultText, "Traversal 9: match was %d.\n", 
			count);
		    break;

                case Trav10:
                    // run traversal #1 on every module.
                    count = 0;
                    whichOp = Trav1;  // so object methods don't complain
                    for (moduleId = 1; moduleId <= TotalModules; moduleId++) {
                        sprintf(moduleName, "Module %08d", moduleId);
			bool found;
	  	        shrc rc =tbl->ModuleIdx.find(moduleName,moduleH,found);
   	                if (rc || !found ||moduleH == NULL) {
                                fprintf(stderr,
                                        "ERROR: t10 Unable to access %s.\n",
                                         moduleName);
				W_COERCE(Shore::abort_transaction());
                                exit(1);
                        }
                        count += moduleH->traverse(whichOp);
                    }
                    sprintf(resultText,
                           "Traversal 10 visited %d atomic parts in %d modules.\\n",
                                     count, TotalModules);
                    whichOp = Trav10;  // for next time around
                    break;           

	        case Query1:
	            count = query1();
	            sprintf(resultText, "Query one retrieved %d atomic parts.\n",
			             count);
		    break;
	        case Query2:
	            count = query2();
	            sprintf(resultText, "Query two retrieved %d qualifying atomic parts.\n",
			         count);
		    break;
	        case Query3:
	            count = query3();
	            sprintf(resultText, "Query three retrieved %d qualifying atomic parts.\n",
			         count);
		    break;
	        case Query4:
	            count = query4();
	            sprintf(resultText, "Query four retrieved %d (document, base assembly) pairs.\n",
			         count);
		    break;
	        case Query5:
	            count = query5();
	            sprintf(resultText, "Query five retrieved %d out-of-date base assemblies.\n",
			             count);
		    break;
	        case Query6:
	            count = query6();
	            sprintf(resultText, "Query six retrieved %d out-of-date assemblies.\n",
			         count);
		    break;
	        case Query7:
	            count = query7();
		    sprintf(resultText, "Query seven iterated through %d atomic part s.\n",
			             count);
		    break;
	        case Query8:
	            count = query8();
		    sprintf(resultText, "Query eight found %d atomic part/document m atches.\n",
			 count);
		    break;
	        case Insert:
	            insert1();
	            sprintf(resultText, "Inserted %d composite parts (a total of %d atomic parts.)\n",
		      NumNewCompParts, NumNewCompParts*NumAtomicPerComp);
		    break;
	        case Delete:
	            delete1();
	            sprintf(resultText, "Deleted %d composite parts (a total of %d atomic parts.)\n",
	             NumNewCompParts, NumNewCompParts*NumAtomicPerComp);
		    break;

		 case Reorg1:
		     count = reorg1();
		     sprintf(resultText, "Reorg1 replaced %d atomic parts.\n", 
			count);
		     break;

	    	 case Reorg2:
		     count = reorg2();
		     sprintf(resultText, "Reorg2 replaced %d atomic parts.\n", 
			count);
		     break;
// NEW
	        case WarmUpdate:
		    // first do the t1 traversal to warm the cache
	            count = moduleH->traverse(Trav1);
		    // then call T2 to do the update
	            count = moduleH->traverse(Trav2a);
	            sprintf(resultText, 
			"Warm update swapped %d pairs of (X,Y) coordinates.\n",
 			         count);
		     break;
	        default:
	            fprintf(stderr, "Sorry, that operation isn't available yet.\n");
		    // E_AbortTransaction();
		    W_COERCE(Shore::abort_transaction());
	            exit(1);
	    }
		printf("Visited=%d\n", count);
	}
	{ 
#ifdef PARSETS

	    if ((iter == repeatCount-1) || manyXACTS){
		printf("Calling commit transaction\n");
		SlaveRPC(CompNodes, (char *)slaveCommitTransaction, NULL, -1);
		choice = do_commit;
	    }
#else
	    // Commit the current transaction if 
	    // we are running the last iteration 
	    // or running a multitransaction test and not chaining
	    // Chain the tx if we are chaining and not on
	    // the last iteration

	    if (iter == repeatCount-1) {
		choice=do_commit;
		// commit 
	    } else if(manyXACTS) {
		// not last iteration, multi tx test
		if(chain_tx) {
		    choice=do_chain;
		} else {
		    choice=do_commit;
		}
	    } else choice=do_nothing;
#endif
	    if(choice==do_commit) {
		//E_CommitTransaction();
		W_COERCE(Shore::commit_transaction());
		choice = do_begin;
	    } else if (choice==do_chain) {
		W_COERCE(Shore::chain_transaction());
		choice = do_nothing;
	    } 
	}

            // compute and report wall clock time
            gettimeofday(&endWallTime, IGNOREZONE &ignoreTimeZone);
	    printf("SHORE, operation= %s, iteration= %d, elapsedTime= %f seconds\n",
               argv[opIndex], iter,
               ComputeWallClockTime(&startWallTime, &endWallTime));
            if (iter == 1) startWarmTime = startWallTime;

            // Compute and report CPU time.
	    getrusage(RUSAGE_SELF, &endUsage);
            fprintf(stdout, resultText);
	    fprintf(stdout, "CPU time: %f seconds.\n", 
	                ComputeUserTime(&startUsage, &endUsage) +
			ComputeSystemTime(&startUsage, &endUsage));
	    fprintf(stdout, "(%f seconds user, %f seconds system.)\n", 
	                ComputeUserTime(&startUsage, &endUsage),
			ComputeSystemTime(&startUsage, &endUsage));

	    if ((repeatCount > 2) && (iter == repeatCount-2)) 
	    {
	       // compute average hot time for 2nd through n-1 th iterations
               printf("SHORE, operation=%s, average hot elapsedTime=%f seconds\n",
	       	  argv[opIndex], 
	          ComputeWallClockTime(&startWarmTime, &endWallTime)/(repeatCount-2)); 
	    }
	  }

	//////////////////////////////////////////////////////////////////
	//
	// Shutdown 
	//
	//////////////////////////////////////////////////////////////////

#ifdef PARSETS
	cleanupParSets();
#endif
	// totalTime.Stop();
	// totalSrvTime.Stop();
	// fprintf(stdout, "Total stats (client,server):\n");
	// totalTime.PrintStatsHeader(stdout);
	// totalTime.PrintStats(stdout, "TotalCli");
	// totalSrvTime.PrintStats(stdout, "TotalSrv");

	// Exit
	W_COERCE(Shore::exit());
	return(0);
}
void Clinic2ruralcooperative::writeindb(QString strNo)
{
	sql.connect2();
	QDateTime date = QDateTime::currentDateTime();
	QSqlQuery query(*sql.db);
	QSqlQuery query2(sql.db2);
	QSqlQuery query3(sql.db2);
	QSqlQuery query4(*sql.db);
	QString strsheetNo;

	query2.prepare("delete from HIS.t_con3 where Mzlsh = '"+strNo+"'");
	query2.exec();
	query2.prepare("delete from HIS.t_con4 where Mzlsh = '"+strNo+"'");
	query2.exec();

	query.exec("select * from mz_chargesheet where sheetno= '"+strNo+"'");
	while(query.next())
	{
		strsheetNo=query.value(1).toString();
		QString strpatient=query.value(5).toString();
		QString strgender=query.value(6).toString();
		QString strID=query.value(11).toString();
		QString strsheetmaker=query.value(15).toString();
		query2.prepare("insert into HIS.t_con3 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		query2.bindValue(0, strsheetNo);
		query2.bindValue(1,strsheetNo);
		query2.bindValue(2,query.value(12).toString());
		query2.bindValue(3, strpatient);
		if (strgender==QString::fromLocal8Bit("男"))
		{
			query2.bindValue(4, 1);
		}
		if (strgender==QString::fromLocal8Bit("女"))
		{
			query2.bindValue(4, 2);
		}

		query2.bindValue(5, strID);
		query2.bindValue(6,NULL);
		query2.bindValue(7, query.value(2).toDateTime());
		query2.bindValue(8, strsheetmaker);
		query2.bindValue(9, 1);
		query2.bindValue(10, NULL);
		query2.bindValue(11, NULL);
		query2.bindValue(12, NULL);
		query2.bindValue(13, NULL);
		query2.bindValue(14,NULL);
		query2.bindValue(15,NULL);
		query2.bindValue(16, NULL);
		query2.bindValue(17, NULL);
		query2.bindValue(18, NULL);
		query2.bindValue(19, NULL);
		query2.bindValue(20, NULL);
		query2.bindValue(21, NULL);
		query2.bindValue(22, NULL);
		if(query2.exec())
		{

//			QMessageBox::information(this,QString ::fromLocal8Bit("提示"),QString::fromLocal8Bit("保存成功!"));
		}

		int count=0;
		query2.exec("select * from HIS.t_con4");
		while(query2.next())
		{
			count++;
		}

		query4.exec("select * from mz_chargedetail where sheetno= '"+strsheetNo+"'");
		while(query4.next())
		{
			count++;
			query3.prepare("insert into HIS.t_con4 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
			query3.bindValue(0, count);
			query3.bindValue(1, NULL);
			query3.bindValue(2,query4.value(1).toString());
			query3.bindValue(3, query4.value(9).toDateTime());
			query3.bindValue(4, NULL);

			int drugflag = query.value(10).toInt();

			query3.bindValue(5,drugflag);//医药分类
			query3.bindValue(6,NULL);
			query3.bindValue(8,NULL);
			QString strdrug =query4.value(4).toString();
			if (drugflag==1)
			{
				QSqlQuery query5(*sql.db);	

				query5.exec("select * from sys_drugcorrespondence where yymc= '"+strdrug+"'");
				while (query5.next())
				{
					query3.bindValue(6, query5.value(1).toString());
					query3.bindValue(7, query5.value(3).toString());
					query3.bindValue(8, query5.value(2).toString());
					query3.bindValue(9, query5.value(4).toString());

					query3.bindValue(20, NULL);//医疗项目分类
				}
			}
			if (drugflag==2)
			{
				QSqlQuery query5(*sql.db);	
				QString strdrugtype,nhcode,nhname,hiscode,hisname;
				query5.exec("select * from sys_projectcorrespondence where yymc= '"+strdrug+"'");
				while (query4.next())
				{
					query3.bindValue(6, query5.value(1).toString());
					query3.bindValue(7, query5.value(3).toString());
					query3.bindValue(8, query5.value(2).toString());
					query3.bindValue(9, query5.value(4).toString());
					query3.bindValue(20, query5.value(7).toString());//医疗项目分类
				}
			}
			if (drugflag==3)
			{
				QSqlQuery query5(*sql.db);	
				QString strdrugtype,nhcode,nhname,hiscode,hisname;
				query5.exec("select * from sys_materialcorrespondence where yymc= '"+strdrug+"'");
				while (query4.next())
				{
					query3.bindValue(6, query5.value(1).toString());
					query3.bindValue(7, query5.value(3).toString());
					query3.bindValue(8, query5.value(2).toString());
					query3.bindValue(9, query5.value(4).toString());
					query3.bindValue(20, NULL);//医疗项目分类
				}
			}

			//query3.bindValue(6, 6);
			//query3.bindValue(7, 7);
			//query3.bindValue(8,"8");
			//query3.bindValue(9, "9");

			query3.bindValue(10, query4.value(6).toDouble());
			query3.bindValue(11,query4.value(7).toDouble());
			query3.bindValue(12, query4.value(8).toDouble());

			QSqlQuery query5(*sql.db);	
			query5.exec("select * from sys_drugdictionary where name= '"+query4.value(4).toString()+"'");
			while (query5.next())
			{
				QString strdrugtype = query5.value(14).toString();
				if (strdrugtype==QString::fromLocal8Bit("西药"))
				{
					query3.bindValue(13, 1);
				}
				else if (strdrugtype==QString::fromLocal8Bit("中成药"))
				{
					query3.bindValue(13, 2);
				}
				else if (strdrugtype==QString::fromLocal8Bit("中草药"))
				{
					query3.bindValue(13, 3);
				}
			}
			query3.bindValue(14,1);//药品属性
			query3.bindValue(15, NULL);
			query3.bindValue(16, NULL);
			query3.bindValue(17,NULL);
			query3.bindValue(18, NULL);
			query3.bindValue(19,NULL);
			query3.bindValue(20,NULL);
			//医疗项目的财务分类

			query3.bindValue(21,NULL);
			query3.bindValue(22, NULL);
			query3.bindValue(23,NULL);
			query3.bindValue(24, NULL);
			query3.bindValue(25, NULL);
			query3.bindValue(26,NULL);
			query3.bindValue(27, NULL);
			query3.bindValue(28, NULL);
			query3.bindValue(29,NULL);
			query3.bindValue(30, NULL);
			query3.bindValue(31, NULL);
			query3.exec();

		}
//		QMessageBox::information(this,QString ::fromLocal8Bit("提示"),QString::fromLocal8Bit("保存成功!"));
		query4.prepare("update mz_chargesheet set out2cooperativeflag= ? where sheetno= '"+strsheetNo+"'");
		query4.bindValue(0,1);
		query4.exec();
	}
	sql.disconnect2();
}
Exemple #14
0
void CreateLog::setDataFields(int booking_id)
{
    this->mBookingId = booking_id;
    DbMysql* d = DbMysql::getInstance();
    QMessageBox msgBox;

    ui->check_in_time->setDateTime(QDateTime::currentDateTime());

    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
    }
    else
    {
        QSqlQuery query1( "select * from booking_details where booking_id="+QString::number(booking_id)+";" ,d->getConnection());
        if(!query1.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            query1.next();
            ui->customer_name->setText(query1.value("customer_name").toString());
            ui->email->setText(query1.value("email").toString());
            ui->phone->setText(query1.value("phone").toString());
            ui->address->setText(query1.value("address").toString());
            ui->id_type->setText(query1.value("id_type").toString());
            ui->id_serial->setText(query1.value("id_serial").toString());

            ui->booking_no->setText(query1.value("booking_id").toString());

            QDate frm_dt = QDate::fromString(query1.value("booking_from").toString(),"yyyy-MM-dd");
            QDate to_dt = QDate::fromString(query1.value("booking_to").toString(),"yyyy-MM-dd");

            if(frm_dt.daysTo(to_dt) == 0)
            {
                ui->label_from_date->setText("Booking Date: ");
                ui->from_date->setText(query1.value("booking_from").toString());
                ui->label_to_date->setText("");
                //ui->to_date->setText(query1.value("booking_to").toString());
            }
            else
            {
                ui->from_date->setText(query1.value("booking_from").toString());
                ui->to_date->setText(query1.value("booking_to").toString());
            }
            ui->nop->setText(query1.value("nop").toString());
            ui->room_no->setText(query1.value("room_numbers").toString());


            if(mEditMode)
            {
                QSqlQuery query4( "select * from booking_log where log_id="+QString::number(mLogId)+";" ,d->getConnection());
                qDebug()<<query4.lastQuery();
                if(!query4.isActive())
                {
                    msgBox.critical(this,"Error","Failed to connect database.");
                }
                else
                {
                    while(query4.next())
                    {
                        //qDebug()<<;
                        ui->check_in_time->setDateTime(query4.value("check_in_time").toDateTime());
                        ui->regSerial->setText(query4.value("reg_serial").toString());
                    }
                }
            }
            else
            {
                qDebug()<<"WTF!!";
            }
        }
    }
}
void CreateBooking::on_saveBookingBtn_clicked()
{

    QMessageBox msgBox;
    //int room_id = ui->roomsList->currentData().toInt();
    //ui->customer_name->completer()->currentIndex()
    //int customer_id = ui->c_customer_name->completer()->currentIndex().data(Qt::UserRole).toInt();
    int customer_id = m_customer_id;
    //customer_id = ui->c_customer_name->completer()->currentIndex().data(Qt::UserRole).toInt();
    /*
    QModelIndex index = ui->c_customer_name->completer()->currentIndex();
    if (index.isValid()) {
        int row = index.row();
        customer_id =  ui->c_customer_name->completer->completionModel()->index(row, 0).data().toInt();
        //qDebug() << key;
    }
    */
    if(customer_id < 0)
    {
        msgBox.warning(this,"Save Booking","Wrong customer details.");
        return;
    }

    qDebug()<<"Customer Id:"<<customer_id;
    QDate booking_date_from = ui->from_date->date();
    QDate booking_date_to = ui->to_date->date();

    if(ui->room_status_table->rowCount() <= 0 )
    {
        msgBox.warning(this,"Save Booking","Please check the availability of rooms before saving the booking.");
        return;
    }

    if(!this->checkRoomAvailability())
    {
        //msgBox.warning(this,"Save Booking","Please check the availability of rooms before saving the booking.");
        return;
    }




    int customer_status = ui->customer_status->currentData().toInt();
    int num_of_persons = ui->num_of_person->text().toInt();
    int booking_status = ui->booking_status->currentData().toInt();
    QString name_of_persons = ui->persons_name->toPlainText();
    QString comments = ui->comments->toPlainText();
    int payment_status  = ui->payment_status->currentData().toInt();

    QString check_in_time;
    if(customer_status == 2)
    {
        check_in_time = ui->check_in_date_time->dateTime().toString("yyyy-MM-dd hh:mm:ss");
    }

    DbMysql* d = DbMysql::getInstance();

    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
    }
    else
    {
        int booking_id = 0;
        if(mEditMode)
        {
            booking_id=mBookingId;
        }
        else
            booking_id = this->genBookingId();


        //QSqlQuery query2("INSERT INTO `room_booking` VALUES (DEFAULT, '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"', '"+QString::number(customer_id)+"', '"+booking_date_from.toString("yyyy-MM-dd")+"', '"+booking_date_to.toString("yyyy-MM-dd")+"', '"+QString::number(room_id)+"', '"+QString::number(booking_status)+"', '"+QString::number(customer_status)+"', '"+QString::number(payment_status)+"', '"+QString::number(num_of_persons)+"','"+name_of_persons+"','"+comments+"');",d->getConnection());


        QString sql0;

        if(mEditMode)
        {
            sql0 = "UPDATE `booking` set customer_id="+QString::number(customer_id)+",booking_from='"+booking_date_from.toString("yyyy-MM-dd")+"',booking_to='"+booking_date_to.toString("yyyy-MM-dd")+"',booking_status="+QString::number(booking_status)+", customer_status='"+QString::number(customer_status)+"',nop='"+QString::number(num_of_persons)+"',persons_name='"+name_of_persons+"',commnets='"+comments+"' where booking_id="+QString::number(mBookingId)+";";
        }
        else
        {
            sql0 = "INSERT INTO `booking` VALUES (DEFAULT, '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"', '"+QString::number(customer_id)+"', '"+booking_date_from.toString("yyyy-MM-dd")+"', '"+booking_date_to.toString("yyyy-MM-dd")+"','"+((check_in_time.length() > 0)?check_in_time:"NULL")+"','NULL','',"+QString::number(booking_status)+", '"+QString::number(customer_status)+"', '"+QString::number(payment_status)+"', '"+QString::number(num_of_persons)+"','"+name_of_persons+"','"+comments+"');";
        }

        QSqlQuery query1(sql0,d->getConnection());
        if(query1.isActive())
        {
            if(mEditMode)
            {
                QSqlQuery query11("delete from room_bookings where booking_id="+QString::number(mBookingId)+";",d->getConnection());
                if(!query11.isActive())
                {
                    qDebug()<<query11.lastQuery();
                }
            }


            QString sql = "Insert into room_bookings values ";


            QString sql2 = "Update rooms set room_state=1 where room_id in (";

            bool comaFlag = false;

            QList<QListWidgetItem*> room_items =  ui->room_list->selectedItems();
            ui->room_status_table->setRowCount(room_items.size());
            int row = 0;
            foreach (QListWidgetItem* item, room_items)
            {
                if(comaFlag)sql+=",";
                sql += "(DEFAULT,"+ui->room_status_table->item(row,1)->text()+","+item->data(Qt::UserRole).toString()+",'"+booking_date_from.toString("yyyy-MM-dd")+"', '"+((ui->single_day->isChecked())?booking_date_from.toString("yyyy-MM-dd"):booking_date_to.toString("yyyy-MM-dd"))+"',"+QString::number(booking_id)+")";
                sql2 += item->data(Qt::UserRole).toString();
                comaFlag = true;
                row++;
            }

            sql2+= ");";

            if(!mEditMode)
            {
                if(check_in_time.length() > 0)
                {
                    QSqlQuery query3(sql2,d->getConnection());
                }
            }

            if(ui->payment_status->currentData(Qt::UserRole).toInt() == 3)
            {

                QSqlQuery query4("insert into advance_payments values (DEFAULT,"+ui->advanceMoney->text()+","+QString::number(booking_id)+",NOW());",d->getConnection());
                if(!query4.isActive())
                {
                    qDebug()<<query4.lastQuery();
                    qDebug()<<query4.lastError();
                    return;
                }
            }


            QSqlQuery query2(sql,d->getConnection());
            if(query2.isActive())
            {
                if(mEditMode)
                {
                    msgBox.information(this,"Edit Booking","Update Booking done.");
                }
                else
                {
                    msgBox.information(this,"Booking","Booking done.");
                }

                this->mpParent->populateBookingLog();
                this->mpParent->createCalendar();

                this->close();
            }
            else
            {
                qDebug()<<query2.lastQuery();
                qDebug()<<query2.lastError();
                return;
            }



        }
        else
        {
            qDebug()<<query1.lastQuery();
            qDebug()<<query1.lastError();
            return;
        }

    }
Exemple #16
0
int main (){
	int i, num = 1, lido=0;
	
	for(i = 0; i < 12; i++){
		contas[i] = NULL;
		compras[i] = NULL;
	}
    
    while(num > 0 && num < 15){
    	system("clear");
   		carregaTextArt("textart-big.txt");
   		puts("\n");
   		num = menuOpcoes();
    	printf("Opção: %d\n",num);
    	switch(num){
    		case 1: {
    			if(lido){
    				for(i = 0; i < 12; i++){
						contas[i] = NULL;
						compras[i] = NULL;
					}
					for(i = 0; i < 26; i++){
						clientes[i] = NULL;
						produtos[i] = NULL;
					}
    			}
                query1(); 
                lido=1; 
                break;
            }    
			case 2: {
                if(lido) query2();
            } break;        
			case 3: {
                if(lido) query3();
            } break;
			case 4: {
                if(lido) query4();
            } break;
                
            case 5: {
                if(lido) query5();
            } break;
                
			case 6: {
                if(lido) query6();
            } break;
                
            case 7: {
                if(lido) query7();
            } break;
                
            case 8: {
                if(lido) query8();
            } break;
                
            case 9: {
                if(lido) query9();
            } break;

            case 10: {
                if(lido) query10();
            } break;

            case 11: {
                if(lido) query11();
            } break;
                
            case 12: {
                if(lido) query12();
            } break;
                
            case 13: {
                if(lido) query13();
            } break;
              
            case 14: {
                if(lido) query14();
            } break;
    	}
    }

    return 0;
}