Example #1
0
int
MDBImageManager::admitRegisterPatient(const MPatient& patient,
				     const MVisit& visit)
{
  // first do sanity check
  if (!mDBInterface)
    return 0;

  if (patient.mapEmpty())
    return -1;

  if (recordExists(patient))
    updateRecord(patient);
  else
    addRecord(patient);

  if (visit.mapEmpty())
    return -1;

  if (recordExists(visit))
    updateRecord(visit);
  else
    addRecord(visit);

  return 0;
}
// TODO: see if we can make this one command
static void bulkSetRecords(stKVDatabase *database, stList *records) {
    startTransaction(database);
    stTry {
        for(int32_t i=0; i<stList_length(records); i++) {
            stKVDatabaseBulkRequest *request = stList_get(records, i);
            switch(request->type) {
                case UPDATE:
                updateRecord(database, request->key, request->value, request->size);
                break;
                case INSERT:
                insertRecord(database, request->key, request->value, request->size);
                break;
                case SET:
                setRecord(database, request->key, request->value, request->size);
                break;
            }
        }
        commitTransaction(database);
    }stCatch(ex) {
        abortTransaction(database);
        stThrowNewCause(
                ex,
                ST_KV_DATABASE_EXCEPTION_ID,
                "MySQL bulk set records failed");
    }stTryEnd;
}
static void setRecord(stKVDatabase *database, int64_t key,
                         const void *value, int64_t sizeOfRecord) {
    if (containsRecord(database, key)) {
        updateRecord(database, key, value, sizeOfRecord);
    } else {
        insertRecord(database, key, value, sizeOfRecord);
    }
}
Example #4
0
AudioRecorder::AudioRecorder()
{
    connect(&m_updateRecordTimer, SIGNAL(timeout()), this, SLOT(updateRecord()));

    memset(&m_recordBuffer[0], 0, sizeof(m_recordBuffer));

    m_filePath = "tmp/record.ogg";
}
Example #5
0
PropertyModel::PropertyModel(TracksModel *database, QObject *parent):
	QAbstractItemModel(parent), mDatabase(database), mRecord(NULL)
{
	connect(mDatabase, SIGNAL(dbChanged()), this, SLOT(updateRowList()));
	connect(mDatabase, SIGNAL(recordChanged()), this, SLOT(updateRecord()));
	connect(mDatabase, SIGNAL(recordSelected(Record*)),
		this, SLOT(setRecord(Record*)));
	updateRowList();
}
int main()
{ 
   FILE *cfPtr; /* credit.dat file pointer */
   int choice;  /* user's choice */

   /* fopen opens the file; exits if file cannot be opened */
   if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL ) {
      printf( "File could not be opened.\n" );
   } /* end if */
   else { 

      /* enable user to specify action */
      while ( ( choice = enterChoice() ) != 6 ) { 

         switch ( choice ) { 

            /* create text file from record file */
            case 1:
               textFile( cfPtr );
               break;

            /* update record */
            case 2:
               updateRecord( cfPtr );
               break;

            /* create record */
            case 3:
               newRecord( cfPtr );
               break;

            /* delete existing record */
            case 4:
               deleteRecord( cfPtr );
               break;

			/* sum up balances of valid records and record sum in text file */
			case 5:
				sumRecords( cfPtr );
				break;

            /* display message if user does not select valid choice */
            default:
               printf( "Incorrect choice\n" );
               break;
       
         } /* end switch */

      } /* end while */

      fclose( cfPtr ); /* fclose closes the file */
   } /* end else */
 
   return 0; /* indicates successful termination */

} /* end main */
Example #7
0
int
MDBImageManager::updateADTInfo(const MPatient& patient, const MVisit& visit)
{
  // first do sanity check
  if (!mDBInterface)
    return 0;

  if (patient.mapEmpty())
    return -1;

  updateRecord(patient);

  if (visit.mapEmpty())
    return -1;

  updateRecord(visit);

  return 0;
}
Example #8
0
bool recordDatabase::addToRecord(Field field, int valueToAdd){
	if (isLoggedIn()){
		DatabaseEntry *prevValue[MAX_FIELDS];
		bool recordGotten = getRecord({ &field }, 1, prevValue);
		if (recordGotten){
			return updateRecord(field, prevValue[0]->intValue + valueToAdd, false);
		}
	}
	return false;
}
Example #9
0
void MainWindow::record(bool start) {
    if(start) {
        QSqlDatabase db = QSqlDatabase::database();
        QSqlQuery qInilisation(db);
        qInilisation.prepare("INSERT INTO `tau_record`(`date`, `minutes`, `version`) VALUES(:date, 0, :version)");
        qInilisation.bindValue(":date", QDate::currentDate().toString("yyyy-MM-dd"));
        qInilisation.bindValue(":version", APP_VERSION);
        qInilisation.exec();
        m_idRecord = qInilisation.lastInsertId().toInt();
        if(m_idRecord >= 0) {
            m_timer = new QTimer(this);
            connect(m_timer, SIGNAL(timeout()), this, SLOT(updateRecord()));
            m_timer->start(60*1000);
        }
    } else if(!start && m_idRecord>=0) {
        m_idRecord = -1;
        disconnect(m_timer, SIGNAL(timeout()), this, SLOT(updateRecord()));
        m_timer->stop();
    }
}
void CR823_TVolDetailQuery::onFirstSelect()
{
    memset(chconf, 0, MAX_PATH);
    int cul = m_record.GetCurSel();
    POSITION Tailpos = list.GetHeadPosition();
    for (int i = 0;i<cul;i++)
    {
        list.GetNext(Tailpos);
    }
    CString str = list.GetNext(Tailpos);
    WideCharToMultiByte(CP_ACP, 0,  str.GetBuffer(), -1, chconf, sizeof(chconf), NULL, NULL);
    updateRecord(chconf);
}
Example #11
0
void displayMenu()
{
    int mode;

    puts("Выберите команду:");
    puts("1 - Создать файл");
    puts("2 - Показать содержимое файла");
    puts("3 - Добавить запись в файл");
    puts("4 - Удалить запись из файла");
    puts("5 - Изменить запись из файла");
    puts("6 - Отсортировать по фамилии и отобразить");
    puts("7 - Показать количество телефонов с определенного года");
    scanf("%d", &mode);

    switch (mode)
    {
        case 1:
            createFile();
            displayMenu();
            break;
        case 2:
            displayFileContent();
            displayMenu();
            break;
        case 3:
            createRecord();
            displayMenu();
            break;
        case 4:
            deleteRecord();
            displayMenu();
            break;
        case 5:
            updateRecord();
            displayMenu();
            break;
        case 6:
            displayBySurname();
            displayMenu();
            break;
        case 7:
            displayCountSinceYear();
            displayMenu();
            break;
        default:
            puts("Выходим...");
    }
}
Example #12
0
void
MDBImageManager::updateRecord(const MFillerOrder& order)
{
  if (mDBInterface == 0)
    return;

  MCriteriaVector cv;
  MUpdateVector   uv;

  setCriteria(order, cv);
  setCriteria(order, uv);

  mDBInterface->update(order, cv, uv);

  for (int inx = 0; inx < order.numOrders(); inx++)
    updateRecord(order.order(inx));
}
Example #13
0
void
MDBImageManager::updateModalitiesInStudy(const MStudy& study,
					 const MString& modality)
{
  MStudyVector v;

  MString uid = study.studyInstanceUID();
  MStudy tempStudy;
  tempStudy.studyInstanceUID(uid);
  MStudyVector::iterator studyStart = mStudyVector.begin();
  MStudyVector::iterator studyEnd = mStudyVector.end();
  mStudyVector.erase(studyStart, studyEnd);
  this->fillStudyVector(tempStudy, v);
  if (v.size() != 1) {
    cerr << "Error when trying to select one MStudy object " << endl;
    cerr << "Study UID = " << uid << endl;
    cerr << "Count = " << v.size() << endl;
    return;
  }

  tempStudy = v[0];
  MString x = tempStudy.modalitiesInStudy();
  bool done = false;
  bool found = false;
  int index = 0;
  for (index = 0; !done; index++) {
    if (!x.tokenExists('+', index))
      break;
    MString s = x.getToken('+', index);
    if (s == modality) {
      found = true;
      done = true;
    }
  }
  if (!found) {
    if (x == "") {
      x = modality;
    } else {
      x = x + "+" + modality;
    }

    tempStudy.modalitiesInStudy(x);
    updateRecord(tempStudy);
  }
}
// - delete record
bferr TBinFileBase::deleteRecord(uInt32 aIndex)
{
  if (!platformFileIsOpen()) return BFE_NOTOPEN;
  if (aIndex>=fBinFileHeader.numrecords) return BFE_BADINDEX;
  if (aIndex<fBinFileHeader.numrecords-1) {
    // we need to move last record
    void *recP = malloc(fBinFileHeader.recordsize);
    if (!recP) return BFE_IOERR; // no memory
    // read last record
    readRecord(fBinFileHeader.numrecords-1,recP);
    // write it to new position
    updateRecord(aIndex,recP);
    free(recP);
  }
  fBinFileHeader.numrecords--;
  fHeaderDirty=true;
  return BFE_OK;
} // TBinFileBase::deleteRecord
Example #15
0
/*!
Detailed qso editing dialog
*/
DetailedEdit::DetailedEdit(QWidget *parent) : QDialog(parent)
{
    setupUi(this);
    connect(this,SIGNAL(accepted()),this,SLOT(updateRecord()));
    for (int i=0;i<nModes;i++) {
        modeComboBox->insertItem(i,modes[i]);
    }
    rec.clear();
    callLineEdit->setValidator(new UpperValidator(callLineEdit));
    sentExch1LineEdit->setValidator(new UpperValidator(sentExch1LineEdit));
    sentExch2LineEdit->setValidator(new UpperValidator(sentExch2LineEdit));
    sentExch3LineEdit->setValidator(new UpperValidator(sentExch3LineEdit));
    sentExch4LineEdit->setValidator(new UpperValidator(sentExch4LineEdit));
    rcvExch1LineEdit->setValidator(new UpperValidator(rcvExch1LineEdit));
    rcvExch2LineEdit->setValidator(new UpperValidator(rcvExch2LineEdit));
    rcvExch3LineEdit->setValidator(new UpperValidator(rcvExch3LineEdit));
    rcvExch4LineEdit->setValidator(new UpperValidator(rcvExch4LineEdit));
    freqLineEdit->setValidator(new QIntValidator(freqLineEdit));
    callLineEdit->setFocus();
}
Example #16
0
static int64_t incrementInt64(stKVDatabase *database, int64_t key, int64_t incrementAmount) {
    startTransaction(database);
    int64_t returnValue = INT64_MIN;
    stTry {
        int64_t recordSize;
        int64_t *record = getRecord2(database, key, &recordSize);
        assert(recordSize >= sizeof(int64_t));
        record[0] += incrementAmount;
        returnValue = record[0];
        updateRecord(database, key, record, recordSize);
        free(record);
        commitTransaction(database);
    }stCatch(ex) {
        abortTransaction(database);
        stThrowNewCause(
                ex,
                ST_KV_DATABASE_EXCEPTION_ID,
                "MySQL increment record failed");
    }stTryEnd;
    return returnValue;
}
Example #17
0
int main( int argc, char ** argv )
{
        FILE *cfPtr;
	char cmd;
	
	if ( ( cfPtr = fopen( "commodity.dat", "w+" ) ) == NULL )
		printf( "file could not be opened." );
	else
	{
		initialize( cfPtr );
		showMenu();
		
		printf( "\ncmd: " );
		cmd = getchar(); 
		while ( cmd != '4' )
		{
			switch ( cmd )
			{
				case '1':	
					showList( cfPtr );
					break;
				case '2': 
					updateRecord( cfPtr );
					break;
				case '3':
					deleteRecord( cfPtr );
					break;
				default:
					puts ( "bad command, please input a valid command." );
			}
			printf( "\ncmd: " );
			fflush( stdin );
			cmd = getchar(); 
		}
	}
	
	fclose( cfPtr );
	system( "pause" );
	return 0;
}
Example #18
0
int run_gvpr(Agraph_t * srcGraph, int argc, char *argv[])
{
    int i, rv = 1;
    gvpropts opts;
    Agraph_t *gs[2];
    static int count;
    char buf[SMALLBUF];

    gs[0] = srcGraph;
    gs[1] = 0;
    memset (&opts, 0, sizeof(opts));
    opts.ingraphs = gs;
    opts.out = outfn;
    opts.err = outfn;
    opts.flags = GV_USE_OUTGRAPH;

    rv = gvpr(argc, argv, &opts);

    if (rv) {			/* error */
	fprintf(stderr, "Error in gvpr\n");
    } else if (opts.n_outgraphs) 
    {
	refreshViewport(0);
	sprintf(buf, "<%d>", ++count);
	if (opts.outgraphs[0] != view->g[view->activeGraph])
	    add_graph_to_viewport(opts.outgraphs[0], buf);
	if (opts.n_outgraphs > 1)
	    fprintf(stderr, "Warning: multiple output graphs-discarded\n");
	for (i = 1; i < opts.n_outgraphs; i++) {
	    agclose(opts.outgraphs[i]);
	}
    } else 
    { 
	/* set_refresh(view,argv[1]); */
	updateRecord (srcGraph);
        update_graph_from_settings(srcGraph);
//	update_topview(srcGraph, view->Topview, 0);
    }
    return rv;
}
Example #19
0
int
MDBImageManager::transferPatient(const MVisit& visit)
{
  // first do sanity check
  if (!mDBInterface)
    return 0;

  if (visit.mapEmpty())
    return -1;

  MPatient patient;

  patient.patientID(visit.patientID());
  patient.issuerOfPatientID(visit.issuerOfPatientID());

  if (!recordExists(patient))
    return 0;

  updateRecord(visit);

  return 0;
}
int main( void )
{
FILE *cfPtr; // credit.dat file pointer
unsigned int choice; // user's choice
// fopen opens the file; exits if file cannot be opened
if ( ( cfPtr = fopen( "/home/abubakr/test.txt", "rb+" ) ) == NULL ) {
puts( "File could not be opened." );
} // end if
else {
// enable user to specify action
while ( ( choice = enterChoice() ) != 5 ) {
switch ( choice ) {
// create text file from record file
case 1:
textFile( cfPtr );
break;
// update record
case 2:
updateRecord( cfPtr );
break;
// create record
case 3:
newRecord( cfPtr );
break;
// delete existing record
case 4:
deleteRecord( cfPtr );
break;
// display message if user does not select valid choice
default:
puts( "Incorrect choice" );
break;
} // end switch
} // end while
fclose( cfPtr ); // fclose closes the file
} // end else
} // end main
Example #21
0
bool DataOp::updateItem(QString id, int itemIndex, QString item)
{
    QString oldRecord = selectRecord(id);
    if(oldRecord==""){
        error = "未找到该条数据:" + id;
        return 0;
    }
    int index=0, n=0, len=0;
    while(index != -1){
        //找到该项元素
        if(n==itemIndex){
            len = oldRecord.indexOf('#',index+1)-index-1;
            len = (len>=0) ? len : oldRecord.length()-index-1;

            oldRecord.replace(index+1,len,item);
            if(updateRecord(oldRecord)){
                return 1;
            }
        }
        n++;
        index = oldRecord.indexOf('#',index+1);
    }
    return 0;
}
void menu(){
    char selection[1];
    printf("\n1) Create a new record \n2) Display All Records \n3) Update a Record \n4) Exit Program \nPlease enter a valid number to make your choice:\n");
    lineFlush();
    scanf("%d",selection);
    lineFlush();
	switch(selection[0]){
		case 1:
			createRecord();
			break;
		case 2:
			displayRecords();
			break;
		case 3:
			updateRecord();
			break;
		case 4:
			exit(0);
			break;
		default:
			printf("\nIncorrect option.\n");
			break;
	}
}
void history::createGUI()
{
    mainWidget = new QWidget(this);
    mainWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding);
    setCentralWidget(mainWidget);

    model = new QSqlTableModel(mainWidget);
    model->setTable("complains");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    model->select();

    //hiding or removing columns that are not required
    model->removeColumns(2,4);
    model->removeColumns(3,3);

    //renaming the headers for cleaner look
    model->setHeaderData(0, Qt::Horizontal, tr("ID"));
    model->setHeaderData(1, Qt::Horizontal, tr("Date"));
    model->setHeaderData(2, Qt::Horizontal, tr("Complain"));
    model->setHeaderData(3, Qt::Horizontal, tr("Status"));
    model->setHeaderData(4, Qt::Horizontal, tr("Code"));

    view = new QTableView;

    view->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //view->setSelectionMode(QAbstractItemView::MultiSelection);
    view->setSelectionMode(QAbstractItemView::SingleSelection);
    view->setSelectionBehavior(QAbstractItemView::SelectRows);

    view->setModel(model);
    view->resizeColumnsToContents();

    btnDetail = new QPushButton(tr("Detail"));
    btnUpdateStatus = new QPushButton(tr("Update Status"));
    btnDeleteRecord = new QPushButton(tr("Delete"));

    connect(btnDetail, SIGNAL(clicked()), this, SLOT(viewDetail()));
    connect(btnUpdateStatus, SIGNAL(clicked()), this, SLOT(updateRecord()));
    connect(btnDeleteRecord, SIGNAL(clicked()), this, SLOT(delRecord()));

//    submitButton = new QPushButton(tr("Submit"));
//    submitButton->setDefault(true);
//    revertButton = new QPushButton(tr("&Revert"));
//    quitButton = new QPushButton(tr("Quit"));

    buttonBox = new QDialogButtonBox(Qt::Horizontal);
    buttonBox->addButton(btnDetail, QDialogButtonBox::ActionRole);
    buttonBox->addButton(btnUpdateStatus, QDialogButtonBox::ActionRole);
    buttonBox->addButton(btnDeleteRecord, QDialogButtonBox::ActionRole);

//    buttonBox->addButton(submitButton, QDialogButtonBox::ActionRole);
//    buttonBox->addButton(revertButton, QDialogButtonBox::ActionRole);
//    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

//    connect(submitButton, SIGNAL(clicked()), this, SLOT(submit()));
//    connect(revertButton, SIGNAL(clicked()), model, SLOT(revertAll()));
//    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

    QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->addWidget(view);
    mainLayout->addWidget(buttonBox);
    //setLayout(mainLayout);

    setWindowTitle(tr("Complain History"));
}
void 
testInsertManyRecords(void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  TestRecord realInserts[10000];
  TestRecord updates[] = {
    {3333, "iiii", 6}
  };
  int numInserts = 10000, i, numcheck=50;
  int randomRec = 3333;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test creating a new table and inserting 10000 records then updating record from rids[3333]";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_t",schema));
  TEST_CHECK(openTable(table, "test_table_t"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
    {
      realInserts[i] = inserts[i%10];
      realInserts[i].a = i;
      r = fromTestRecord(schema, realInserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
    }
  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_t"));

  // retrieve records from the table and compare to expected final stage
  for(i = 0; i < numcheck; i++)
    {
      RID rid = rids[i];
      TEST_CHECK(getRecord(table, rid, r));
      ASSERT_EQUALS_RECORDS(fromTestRecord(schema, realInserts[i]), r, schema, "compare records");
    }
  
  r = fromTestRecord(schema, updates[0]);
  r->id = rids[randomRec];
  TEST_CHECK(updateRecord(table,r));
  TEST_CHECK(getRecord(table, rids[randomRec], r)); 
  ASSERT_EQUALS_RECORDS(fromTestRecord(schema, updates[0]), r, schema, "compare records");
   
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_t"));
  TEST_CHECK(shutdownRecordManager());

  freeRecord(r);
  free(table);
  TEST_DONE();
}
void 
testUpdateTable (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  TestRecord updates[] = {
    {1, "iiii", 6},
    {2, "iiii", 6},
    {3, "iiii", 6}
  };
  int deletes[] = {
    9,
    6,
    7,
    8,
    5
  };
  TestRecord finalR[] = {
    {1, "iiii", 6},
    {2, "iiii", 6},
    {3, "iiii", 6},
    {4, "dddd", 3},
    {5, "eeee", 5},
  };
  int numInserts = 10, numUpdates = 3, numDeletes = 5, numFinal = 5, i;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test creating a new table and insert,update,delete tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
    {
      r = fromTestRecord(schema, inserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
    }

  // delete rows from table
  for(i = 0; i < numDeletes; i++)
    {
      TEST_CHECK(deleteRecord(table,rids[deletes[i]]));
    }

  // update rows into table
  for(i = 0; i < numUpdates; i++)
    {
      r = fromTestRecord(schema, updates[i]);
      r->id = rids[i];
      TEST_CHECK(updateRecord(table,r)); 
    }

  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r"));

  // retrieve records from the table and compare to expected final stage
  for(i = 0; i < numFinal; i++)
    {
      RID rid = rids[i];
      TEST_CHECK(getRecord(table, rid, r));
      ASSERT_EQUALS_RECORDS(fromTestRecord(schema, finalR[i]), r, schema, "compare records");
    }
  
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  free(table);
  TEST_DONE();
}
Example #26
0
  void cbranch ()
  {
    int tid;
    pthread_mutex_lock(&mMutRec);
    tid = mThreadId ++;
    mTids[tid] = tid;
    pthread_setspecific(mTidKey, (void*)(mTids + tid));
    MMRegistry::registerMemManager(mManagers[tid]);
    pthread_mutex_unlock(&mMutRec);
    SmartArrayPtr < Set > aq(mMaxLocalQueueSize);
    FixedVector < Set > ltq((Set*)aq, mMaxLocalQueueSize);
    Solution asolv[2];
    FixedVector < Solution > solv(asolv, 2);
    SmartArrayPtr < Set > alsetv(mMaxLocalSetBufferSize);
    FixedVector < Set > lsetv(alsetv, mMaxLocalSetBufferSize);
    SmartArrayPtr < Solution > alsolv(mMaxLocalSolutionBufferSize);
    FixedVector < Solution > lsolv(alsolv, mMaxLocalSolutionBufferSize);
    for(int step = 1; ; step ++) {
      Set s;
      if(ltq.empty()) {
        pthread_mutex_lock(&mMutTaskQueue);
        mStarv ++;
	mSteps = BNBMAX(mSteps, step);
        while(mTaskQueue.empty() && (mStarv != mNumThreads) && (mSteps < mLocalSteps)) {
	  mLocalCounters[tid].mStarv ++;
	  struct timeval tv;
	  double t1, t2;
	  gettimeofday(&tv, NULL);
	  t1 = (double)tv.tv_sec + (double)tv.tv_usec * 0.000001;
          pthread_cond_wait(&mCV, &mMutTaskQueue); 
	  gettimeofday(&tv, NULL);
	  t2 = (double)tv.tv_sec + (double)tv.tv_usec * 0.000001;
	  mLocalCounters[tid].mStarvTime += (t2 - t1);
        }       
	if(mSteps >= mLocalSteps) {
	  pthread_cond_broadcast(&mCV);
          pthread_mutex_unlock(&mMutTaskQueue);
          break;
	} else if(!mTaskQueue.empty()) {
          s = mTaskQueue.top ();
          mTaskQueue.pop ();
          mStarv --;
	  mLocalCounters[tid].mGet ++;
	  pthread_mutex_unlock(&mMutTaskQueue);
        } else {
	  pthread_cond_broadcast(&mCV);
          pthread_mutex_unlock(&mMutTaskQueue);
          break;
        }
      } else {
        s = ltq.back();
        ltq.pop_back();
      }
      if (!mSetFactory->discard (s, getRecord())){
        mSetFactory->branch (s, lsetv, lsolv, getRecord(),  mInfos + tid, ltq.size());
        typename ProblemFactory::ValueType rec = getRecord();
        while(!lsolv.empty()) {
          Solution s = lsolv.back();
          lsolv.pop_back();
          if(((Factory::getProblemType() == BNB_MAXIMIZE) && (s.getValue() > rec)) ||
	     ((Factory::getProblemType() == BNB_MINIMIZE) && (s.getValue() < rec))) {
            rec = s.getValue();
            if(!solv.empty())
              solv.pop_back();
            solv.push_back(s);
          }
        }
	updateRecord(rec);
        while(!lsetv.empty()) {
          Set s = lsetv.back();
          lsetv.pop_back();
          if(!mSetFactory->discard (s, rec))
            ltq.push_back(s);
          else 
            mInfos[tid].mDiscardedByRecord ++;         
        }
        
	mSteps = BNBMAX(mSteps, step);
	if(mSteps >= mLocalSteps) {
	  pthread_mutex_lock(&mMutTaskQueue);
	  if(mStarv)
	    pthread_cond_broadcast(&mCV);
	  pthread_mutex_unlock(&mMutTaskQueue);
	  break;
	}

        if((step % mUpdateRatio) == 0) {
          if(!ltq.empty()) {
	    pthread_mutex_lock(&mMutTaskQueue);
	    struct timeval tv;
	    double t1, t2;
	    gettimeofday(&tv, NULL);
	    t1 = (double)tv.tv_sec + (double)tv.tv_usec * 0.000001;
	    mLocalCounters[tid].mDonat ++;
	    for(int i = 0; i < mPutChunk; i ++) {
	      if(!ltq.empty()) {
                MMRegistry::registerMemManager(mAuxMemManager);
		Set s = ltq.back();
		mTaskQueue.push(s);
                MMRegistry::registerMemManager(mManagers[tid]);
		ltq.pop_back();
	        mLocalCounters[tid].mPut ++;
	      } else
		break;
	    }
	    mQLen = mTaskQueue.size();
	    mMaxQLen = BNBMAX(mQLen, mMaxQLen);
	    if(mStarv)
	      pthread_cond_broadcast(&mCV);
	    t2 = (double)tv.tv_sec + (double)tv.tv_usec * 0.000001;
	    mLocalCounters[tid].mDonatTime += t2 - t1;
	    pthread_mutex_unlock(&mMutTaskQueue);
	  }
        }
      } else {
        mInfos[tid].mDiscardedByRecord ++;
      }
    }
    
    pthread_mutex_lock(&mMutTaskQueue);
    while(!ltq.empty()) {
      Set s = ltq.back();
      ltq.pop_back();
      mTaskQueue.push(s);
    }   
    pushSolutions (solv, mInfos + tid);
    pthread_mutex_unlock(&mMutTaskQueue);
  }
Example #27
0
int32
main(int32 argc, char **argv) {
   int32 arg = 1;
   int32 err = 0;
   int32 hlp = 0;

   char * gkpStoreName  = NULL;
   int32  gkpStorePart  = 0;
   char * msgFile       = NULL;
   char * outputFileName= NULL;
   char * seqAn         = NULL;
   char * wrkDir        = NULL;
   char * seqStoreName  = NULL;
   int32  seqStoreVer   = 0;
   int32  seqStorePart  = 0;     

   argc = AS_configure(argc, argv);

   while (arg < argc) {
      if (strcmp(argv[arg], "-c") == 0) {
         msgFile = argv[++arg];
      } else if (strcmp(argv[arg], "-G") == 0) {
         gkpStoreName = argv[++arg];
      } else if (strcmp(argv[arg], "-S") == 0) {
         gkpStorePart = atoi(argv[++arg]);
      } else if (strcmp(argv[arg], "-o") == 0) {
         outputFileName = argv[++arg];
      } else if (strcmp(argv[arg], "-s") == 0) {
         seqAn = argv[++arg];
      } else if (strcmp(argv[arg], "-w") == 0) {
         wrkDir = argv[++arg];
      } else if (strcmp(argv[arg], "-u") == 0) {
         seqStoreName = argv[++arg];
      } else if (strcmp(argv[arg], "-V") == 0) {
         seqStoreVer = atoi(argv[++arg]);
      } else if (strcmp(argv[arg], "-p") == 0) {
         seqStorePart = atoi(argv[++arg]);
      } else {
         err++;
      }
      arg++;
   }

   if ((err) || (gkpStoreName == NULL) || (msgFile == NULL) || (outputFileName == NULL) || seqAn == NULL) {
      fprintf(stderr, "USAGE: SeqAn_CNS -G <gkpStore> -c <input.cgb> -o <output.cgi> -s <seqan_executable> [-u seqstore, required for contig consensus] [-w working directory]\n");      
      exit(1);
   }

   gkStore        *gkpStore = new gkStore(gkpStoreName, FALSE, FALSE);

   gkpStore->gkStore_loadPartition(gkpStorePart);
   
   gkFragment      fr;
   GenericMesg    *pmesg;
   tSequenceDB    *sequenceDB = NULL;   

   FILE *infp = fopen(msgFile,"r");
   FILE *tempReads;
   FILE *outfp = fopen(outputFileName, "w");
   char fileName[AS_SEQAN_MAX_BUFFER_LENGTH];
   char *prefix = outputFileName;
   getFileName(prefix, wrkDir, AS_SEQAN_INPUT_NAME, fileName);

   int32 i = 0;
   
   while ((EOF != ReadProtoMesg_AS(infp, &pmesg))) {
      int32 freeMem = 0;
     
      if (pmesg->t == MESG_IUM) {
         IntUnitigMesg *ium_mesg = (IntUnitigMesg *)pmesg->m;         
         
         if (strlen(ium_mesg->consensus) == 0) {
            tempReads = fopen(fileName,"w");

            for (i =0; i < ium_mesg->num_frags; i++) {
               // get the fragment sequence
               gkpStore->gkStore_getFragment(ium_mesg->f_list[i].ident, &fr, GKFRAGMENT_QLT);
               uint32   clrBeg = fr.gkFragment_getClearRegionBegin();
               uint32   clrEnd = fr.gkFragment_getClearRegionEnd  ();
               char    *seqStart = fr.gkFragment_getSequence();
               char     *seq      = seqStart+clrBeg;

               seq[clrEnd] = 0;
               AS_UTL_writeFastA(tempReads,
                  seq, clrEnd-clrBeg,
                   ">"F_IID","F_IID"\n", ium_mesg->f_list[i].position.bgn, ium_mesg->f_list[i].position.end);
            }
            fclose(tempReads);
            updateRecord(ium_mesg, fileName, seqAn, prefix, wrkDir);
            freeMem = 1;
         }
         WriteProtoMesg_AS(outfp, pmesg);

         if (freeMem) {
            safe_free(ium_mesg->consensus);
            safe_free(ium_mesg->quality);
         }
      }
      else if (pmesg->t == MESG_ICM) {         
         IntConConMesg *icm_mesg = (IntConConMesg *)pmesg->m;

         if (seqStoreName == NULL) {
            fprintf(stderr, "USAGE: The -u option is required for contig consensus\n");
            exit(1);
         }
         if (sequenceDB == NULL) {
            sequenceDB = openSequenceDB(seqStoreName, FALSE, seqStoreVer);
            openSequenceDBPartition(sequenceDB, seqStorePart);
         }
         
         if (strlen(icm_mesg->consensus) == 0) {
            tempReads = fopen(fileName,"w");

            for (i =0; i < icm_mesg->num_pieces; i++) {
               // get the fragment sequence
               gkpStore->gkStore_getFragment(icm_mesg->pieces[i].ident, &fr, GKFRAGMENT_QLT);
               uint32   clrBeg   = fr.gkFragment_getClearRegionBegin();
               uint32   clrEnd   = fr.gkFragment_getClearRegionEnd  ();
               char    *seqStart = fr.gkFragment_getSequence();
               char    *seq      = seqStart+clrBeg;

               seq[clrEnd] = 0;
               AS_UTL_writeFastA(tempReads,
                  seq, clrEnd-clrBeg,
                   ">"F_IID","F_IID"\n", icm_mesg->pieces[i].position.bgn, icm_mesg->pieces[i].position.end);
            }
            
            // now handle the unitig messages
            for (i =0; i < icm_mesg->num_unitigs; i++) {
               VA_TYPE(char) *ungappedSequence = CreateVA_char(0);
               VA_TYPE(char) *ungappedQuality  = CreateVA_char(0);
               MultiAlignT *uma = loadMultiAlignTFromSequenceDB(sequenceDB, icm_mesg->unitigs[i].ident, 1);
               assert(uma != NULL);
               
               GetMultiAlignUngappedConsensus(uma, ungappedSequence, ungappedQuality);
               char * seq = Getchar(ungappedSequence,0);

               AS_UTL_writeFastA(tempReads,
                  seq, strlen(seq),
                   ">"F_IID","F_IID"\n", icm_mesg->unitigs[i].position.bgn, icm_mesg->unitigs[i].position.end);
            }
            fclose(tempReads);

            updateICMRecord(icm_mesg, fileName, seqAn, prefix, wrkDir);
            freeMem = 1;
         }
         WriteProtoMesg_AS(outfp, pmesg);

         if (freeMem) {
            safe_free(icm_mesg->consensus);
            safe_free(icm_mesg->quality);
         }
      }
   }
      
   fclose(infp);
   fclose(outfp);

   return 0;
}
Example #28
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    qDebug()<<"Begin Program\n";

    QFontDatabase fontDB;
    fontDB.addApplicationFont(":/Fonts/CMR_Regular.ttf");
    fontDB.addApplicationFont(":/Fonts/CMR_Bold.ttf");
    fontDB.addApplicationFont(":/Fonts/CMR_Italic.ttf");
    fontDB.addApplicationFont(":/Fonts/CMR_BoldItalic.ttf");
    QFont CMRFont = QFont("Computer Modern Roman");
    QApplication::setFont(CMRFont);




    //Create the central widget where the other frames will be inserted
    QWidget *wdgMain = new QWidget(this);
    qDebug()<<"Widget Initaited";
    setCentralWidget(wdgMain);

    //Create the outermost Layout to divide between the table, the preview and the buttons
    //QGridLayout *mainLayout = new QGridLayout;
    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(15,5,15,10);


    //The frame for the buttons is created and the ADD Record REMOVE Record and MODIFY Button are added in a QHBOX
    QFrame *frmButtons = new QFrame();
    frmButtons->setFrameStyle(QFrame::Box | QFrame::Raised);
    frmButtons->setLineWidth(1);

    //QPushButton *btnAddRecord = new QPushButton("AddRecord",frmButtons);
    btnAddRecord->setEnabled(false);
    //QPushButton *btnRemoveRecord = new QPushButton("Remove Record",frmButtons);
    btnRemoveRecord->setEnabled(false);
    //QPushButton *btnModifyRecord = new QPushButton("Modify Record",frmButtons);
    btnModifyRecord->setEnabled(false);
    //QPushButton *btnPrint = new QPushButton("Export",frmButtons);
    btnPrint->setEnabled(false);

    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->addWidget(btnAddRecord);
    btnLayout->addWidget(btnRemoveRecord);
    btnLayout->addWidget(btnModifyRecord);
    btnLayout->addWidget(btnPrint);
    frmButtons->setLayout(btnLayout);

    //The frame for the preview is created



    frmPreview->setLayout(prwLayout);


    //The Table viewer is created without grid and is added to the main layout
    dbTableView=new QTableView(this);
    dbTableView->setShowGrid(false);
    dbTableView->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding);
    //mainLayout->addWidget(dbTableView,0,0,5,4);
    //The left frame is created and the table and button frames are added
    QVBoxLayout *lftLayout = new QVBoxLayout;
    lftLayout->addWidget(dbTableView);
    lftLayout->addWidget(frmButtons);
    //The main layout is created by adding the left layout and the preview widget
    mainLayout->addLayout(lftLayout);
    mainLayout->addWidget(scrPreview);

    //A value is given to the database and a connetion is made using the custom CreatConnection
    //dbName="/Users/Castro/Documents/Svago/Programmazione/Qt/database/movies.sqlite";
    //CreateConnection(dbName); //Go to method, return bool
    //QSqlQuery querytest (q.createUpdate("Main_table",Update,Where),db);




    //Ther preview frame is populated with the labeled text
    //preview field is enabeled in order to navigate throught he preview fields array

    //The scroll area is set to a fixed width wich allowes to view the whole contents without scrolling to the side
    frmPreview->setMinimumWidth(prwLayout->sizeHint().width());
    scrPreview->setWidget(frmPreview);
    scrPreview->setFixedWidth(frmPreview->width()+20);

    wdgMain->setLayout(mainLayout);
    wdgMain->show();
    createActions();
    createMenu();
    //The table view signal "current changed" is connected to the slot which changes the selected record
    //connect(dbTableView->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),
            //SLOT(currentSelectionChanged(const QModelIndex &)));
    connect(dbTableView,SIGNAL(doubleClicked(QModelIndex)),SLOT(recordDoubleClicked(const QModelIndex)));
    connect(dbmodel, SIGNAL(modelReset()), this, SLOT(modelHasReset()));
    connect(dbmodel, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(dataChangeEmitted()));
    //connect(dbmodel,SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInsertedEmitted(QModelIndex,int,int)));
    connect(btnAddRecord,SIGNAL(clicked()),SLOT(createNewRecord()));
    connect(btnRemoveRecord,SIGNAL(clicked()),SLOT(deleteRecord()));
    connect(btnModifyRecord,SIGNAL(clicked()),SLOT(updateRecord()));
    connect(btnPrint,SIGNAL(clicked()),this,SLOT(printRecord()));

    QDesktopWidget dw;
    QRect dwRect = dw.availableGeometry(this);
            //dw.availablegeometry(this);

    resize(dwRect.size()*0.7);
    //QRect mwRect = this->geometry();
    move(0.15*dwRect.width(),0.15*dwRect.height());


}
Example #29
0
void MainWindow::recordDoubleClicked(const QModelIndex index){
    updateRecord();
}
Example #30
0
/*
 * AUTHOR: Nikhil  
 * DESC: Parse the sql stmts and execute the respective methods
 */
int main(int argc, char *argv[]){

    char readline[ARRAY_LENGTH];
    char temparray[ARRAY_LENGTH];
    char *temp;
    char *temp1;
    char *tableName;
    char *length;
    int charLength;
    int numattr=0,k,count=0,numTuples=0;
    Schema *schema;
    RID *rids;
    char columns[ARRAY_LENGTH][ARRAY_LENGTH];
    
   
    int i=0,j=0;
    
        if(fork() == 0) {
			execv("/usr/bin/clear", argv);
			exit(1);
		}
	else wait(NULL);
        
        printf("\n SQL parser\n");
        
        while(1){
        printf("\n >>");
        
        fflush(stdin);
        gets(readline);
        
        memcpy(temparray,readline,sizeof(readline));
        
        if(strstr(readline,"create table") || strstr(readline,"CREATE TABLE")){
        
            parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp=strstr(temparray,"(");
            
            temp++;
            
            temp1=strtok(temp,",");
            while(temp1!=NULL){
                strcpy(columns[i],temp1);
            temp1=strtok(NULL,",");
            i++;
            }
            j=i;
            numattr=j;
   strcpy(columns[i-1],strtok(columns[i-1],")"));

    char* colname[numattr];
    char* datatype[numattr];
    DataType dt[numattr];
    int sizes[numattr];
     int keyattr[numattr];
            for(i=0;i<j;i++){
          
       
                parser(columns[i],argv);
                
                colname[i]=argv[0];
                datatype[i]=argv[1];
                if(strstr(Upper(datatype[i]),"VARCHAR")) {
                     dt[i]=DT_STRING;
                    length=strtok(datatype[i],"(");
                    length=strtok(NULL,"(");
                    charLength=strtok(length,")");
                    if(length==NULL){
                    
                        printf("\nWrong Format");
                                 break;
                    }
                        sizes[i]=atoi(charLength);
                }
                        if(strstr(Upper(datatype[i]),"INT")){
                        dt[i]=DT_INT;
                        }
                         else if(strstr(Upper(datatype[i]),"FLOAT")){
                            dt[i]=DT_FLOAT;
                        }
                    else if(strstr(Upper(datatype[i]),"BOOL")){
                            dt[i]=DT_BOOL;                        }
                
                
                else{
                 sizes[i]=0;
                }
                
                if(strstr(Upper(datatype[i]),"PRIMARYKEY")){
                    
                keyattr[i]=1;
                    
                }
                else{
                 keyattr[i]=0;
                }
               
                
            }
     
     for(k=0;k<sizeof(keyattr)/sizeof(keyattr[0]);k++){
         if(keyattr[i]==1){
             count++;
          
          }
   
     }
     if(count>0){
         
         printf("wrong format...cannot contain more than one primary key");
         break;
     
     }
 
     schema=testSchema(numattr,colname,dt,sizes,keyattr);
     initRecordManager(NULL);
     createTable(Upper(tableName),schema);
     printf("Table Created Successfully");
     shutdownRecordManager();

        }
        
        if(strstr(Upper(readline),"INSERT INTO")){
        
              parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp=strtok(temparray,"(");
            temp=strtok(NULL,"(");
            strcpy(columns[0],temp);
       strcpy(columns[0],strtok(columns[0],")"));
       
        char* values[i];
        i=0;
       values[0]=strtok(columns[0],",");
       while(values[i]!=NULL){
           i++;
          values[i]=strtok(NULL,",");
       }
       
             numTuples=i;
             rids = (RID *) malloc(sizeof(RID) * numTuples);
             RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
             initRecordManager(NULL);
        int fd = open(Upper(tableName), O_WRONLY);    
        if(fd<0){
            printf("Database Doesn't Exist");
            break;
        }

                openTable(table, tableName);
                schema=table->schema;
                 Record *result;
                 Value *value;
                createRecord(&result, schema);
                for(i = 0; i < numTuples; i++)
                {
                  if(schema->dataTypes[i]==DT_INT || schema->dataTypes[i]==DT_FLOAT || schema->dataTypes[i]==DT_BOOL){
                  MAKE_VALUE(value, schema->dataTypes[i], atoi(values[i]));
                  }
                  if(schema->dataTypes[i]==DT_STRING){
                  MAKE_STRING_VALUE(value, values[i]);
                  }
               
                   setAttr(result, schema, i, value);
                   freeVal(value);
                 
                }
                  insertRecord(table,result); 
                  rids[i] = result->id;
printf("Inserted Successfully");
               closeTable(table);
               shutdownRecordManager();
              
             
                  }
        
         if(strstr(Upper(readline),"UPDATE TABLE")){
             
           parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp1=strtok(temparray,"(");
            temp=strtok(NULL,"(");
            strcpy(columns[0],temp);
       strcpy(columns[0],strtok(columns[0],")"));
       
       temp1=strtok(temp1,"=");
       temp1=strtok(NULL,"=");
       
        char* values[i];
        i=0;
       values[0]=strtok(columns[0],",");
       while(values[i]!=NULL){
           i++;
          values[i]=strtok(NULL,",");
       }
       
             numTuples=i;
             rids = (RID *) malloc(sizeof(RID) * numTuples);
             RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
             initRecordManager(NULL);
        int fd = open(Upper(tableName), O_WRONLY);    
        if(fd<0){
            printf("Database Doesn't Exist");
            break;
        }
       
                openTable(table, Upper(tableName));
                schema=table->schema;
                               
                  Record *result;
                  Value *value;
                  createRecord(&result, schema);
                for(i = 0; i < numTuples; i++)

                {
                  if(schema->dataTypes[i]==DT_INT || schema->dataTypes[i]==DT_FLOAT || schema->dataTypes[i]==DT_BOOL){
                  MAKE_VALUE(value, schema->dataTypes[i], atoi(values[i]));
                  }
                  if(schema->dataTypes[i]==DT_STRING){
                  MAKE_STRING_VALUE(value, values[i]);
                  }
               
                   setAttr(result, schema, i, value);
                   freeVal(value);
            
                   
                }
                       result->id=rids[i] ;
                   updateRecord(table,result);
printf("Updated Successfully");
               closeTable(table);
               shutdownRecordManager();
               
         }
        
         if(strstr(Upper(readline),"DELETE FROM")){
             
           parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp=strtok(temparray,"(");
            temp=strtok(NULL,"(");
            strcpy(columns[0],temp);
       strcpy(columns[0],strtok(columns[0],")"));
       
       int r_id=atoi(columns[0]);
             numTuples=i;
             rids = (RID *) malloc(sizeof(RID) * numTuples);
RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
                           initRecordManager(NULL);
        int fd = open(Upper(tableName), O_WRONLY);    
        if(fd<0){
            printf("Database Doesn't Exist");
            break;
        }

                openTable(table, Upper(tableName));
                schema=table->schema;
               deleteRecord(table,rids[r_id]);
printf("Deleted Successfully");
               closeTable(table);
               shutdownRecordManager();
         }
              
        
        }
        }