int main(int argc, char *argv[]){ printf("\n----------------- Testing Card: Adventurer ----------------\n\n"); struct gameState oldState, testState, testState2; int numPlayers = 2; // Randomize the seed to make it interesting int seed = random() % 1000; int k[10] = {smithy, embargo, village, minion, mine, cutpurse, sea_hag, tribute, steward, council_room}; initializeGame(numPlayers, k, seed, &oldState); // copy the game state to a test case memcpy(&testState, &oldState, sizeof(struct gameState)); cardEffectAdventurer(&testState); printf("\n\nTest run 1\n"); processResults(&testState, &oldState); memcpy(&testState2, &testState, sizeof(struct gameState)); cardEffectAdventurer(&testState2); printf("\n\nTest run 2\n"); processResults(&testState2, &testState); memcpy(&oldState, &testState2, sizeof(struct gameState)); cardEffectAdventurer(&oldState); printf("\n\nTest run 3\n"); processResults(&oldState, &testState); memcpy(&testState, &oldState, sizeof(struct gameState)); cardEffectAdventurer(&testState); printf("\n\nTest run 4\n"); processResults(&testState, &oldState); printf("\n\nNOTE: These tests are 'failing' due to 2 known bugs that are documented in bug.c\n"); return 0; }
bool ValidationItem::execute() { if (model_item_ == NULL) { throw InvalidValidationItem(__FILE__,__LINE__); } if(done_) return 0; // do nothing twice... setValidationInput(); if(validation_statistic_>=0) { model_item_->model()->model_val->selectStat(validation_statistic_); } switch(type_) { case 1: model_item_->model()->model_val->testInputData(); break; case 2: model_item_->model()->model_val->crossValidation(k_); break; case 3: model_item_->model()->model_val->bootstrap(num_of_samples_); break; case 4: result_of_rand_test_ = model_item_->model()->model_val->yRandomizationTest(num_of_runs_, k_); break; case 5: q2_ = 0; for(list<ValidationItem*>::iterator it=external_validations_.begin(); it!=external_validations_.end(); it++) { // if one prediction is not yet ready, stop calc. average quality if(!(*it)->isDone()) return 0; q2_ += (*it)->getQ2(); } q2_ /= external_validations_.size(); // average Q^2 obtained from nested cross validation break; case 6: if(!model_item_->getRegistryEntry()->regression) { throw BALL::Exception::GeneralException(__FILE__,__LINE__,"validation error","coefficient stddev can only be calculated for regression models!"); } ((RegressionModel*)model_item_->model())->validation->calculateCoefficientStdErrors(num_of_samples_,1); break; case 7: model_item_->model()->model_val->testInputData(1); break; default: throw InvalidValidationItem(__FILE__,__LINE__); } processResults(); done_ = 1; return 1; }
int main(int argc, char *argv[]){ printf("\n----------------- Testing Card: Cutpurse ----------------\n\n"); struct gameState oldState, testState; int seed = random() % 1000; int handPos = 0, numPlayers = 2, testRuns = 500, i = 0; int k[10] = {smithy, embargo, village, minion, mine, cutpurse, sea_hag, tribute, steward, council_room}; for (i = 1; i <= testRuns; i++) { printf("\nTest run %d\n", i); initializeGame(numPlayers, k, seed, &oldState); // Randomize the last param, which is a flag to add or not add treasure cards. // That should give more variety to the code run. prepareRandomizedHand(&oldState, PLAYER1, (random() % 2)); // Only the second player discards a copper prepareRandomizedHand(&oldState, PLAYER2, (random() % 2)); // copy the game state to a test case memcpy(&testState, &oldState, sizeof(struct gameState)); cardEffectCutpurse(handPos, &testState); processResults(&testState, &oldState); } printf("\n\nNOTE: The Discard & Coin counts are BOTH failing due to a bug documented in bug.c \n"); return 0; }
void loop() { pulses = 0; attachInterrupt(0, spinning, RISING); digitalWrite(WLED, HIGH); delay(MEASURE_PERIOD * 1000); detachInterrupt(0); /* turn interrupts off to make sleeping possible */ digitalWrite(WLED, LOW); processResults(); LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); }
int main(int argc, char *argv[]){ printf("\n----------------- Testing Card: Cutpurse ----------------\n\n"); struct gameState oldState, testState; int seed = random() % 1000; int handPos = 0, numPlayers = 2; int k[10] = {smithy, embargo, village, minion, mine, cutpurse, sea_hag, tribute, steward, council_room}; initializeGame(numPlayers, k, seed, &oldState); // Put the Cutpurse card in the hand oldState.hand[PLAYER1][handPos] = cutpurse; prepareHand(&oldState, PLAYER2); // copy the game state to a test case memcpy(&testState, &oldState, sizeof(struct gameState)); cardEffectCutpurse(handPos, &testState); processResults(&testState, &oldState); return 0; }
void ValidationItem::loadFromFile(String filename) { try { model_item_->model()->model_val->readFromFile(filename); } catch(BALL::Exception::GeneralException e) { QMessageBox::warning(view_,"Error",e.getMessage()); return; } r2_ = model_item_->model()->model_val->getFitRes(); q2_ = model_item_->model()->model_val->getCVRes(); result_of_rand_test_ = model_item_->model()->model_val->getYRandResults(); if(r2_!=-1 || q2_!=-1) // if some result was loaded { processResults(); done_=1; } }
int TestCFSM::runScenario(const int num) { int result = -1; QString scenarioFilename = QString("scenario-%1.txt").arg(num, 2, 10, QChar('0')); QFile inputFile(scenarioFilename); if(inputFile.open(QIODevice::ReadOnly)) { QTextStream in(&inputFile); processActions(in); result = processResults(in); if(result != 0) { // Test failed! QTextStream console(stdout); console << "--" << endl << "Test failed: " << scenarioFilename << endl; if(result == 1) { console << "Model internal state does not match " << "desired state. Model data:" << endl; printModel(); } console << "--" << endl << endl; } } else { QTextStream console(stdout); console << "ERROR: could not read file: " << scenarioFilename << endl; // Don't try to recover. QApplication::exit(1); } inputFile.close(); return (result); }
void LatencyTest::handleMessage(const Message& msg, LatencyTestMessageType latencyTestMessage) { // For debugging. /* if (msg.Type == Message_LatencyTestSamples) { MessageLatencyTestSamples* pSamples = (MessageLatencyTestSamples*) &msg; if (pSamples->Samples.GetSize() > 0) { // Just show the first one for now. Color c = pSamples->Samples[0]; OVR_DEBUG_LOG(("%d %d %d", c.R, c.G, c.B)); } return; } */ if (latencyTestMessage == LatencyTest_Timer) { if (!Device) { reset(); return; } if (State == State_WaitingForSettlePreCalibrationColorBlack) { // Send calibrate message to device and wait a while. Device->SetCalibrate(CALIBRATE_BLACK); State = State_WaitingForSettlePostCalibrationColorBlack; OVR_DEBUG_LOG(("State_WaitingForSettlePreCalibrationColorBlack -> State_WaitingForSettlePostCalibrationColorBlack.")); setTimer(TIME_TO_WAIT_FOR_SETTLE_POST_CALIBRATION); } else if (State == State_WaitingForSettlePostCalibrationColorBlack) { // Change color to white and wait a while. RenderColor = CALIBRATE_WHITE; State = State_WaitingForSettlePreCalibrationColorWhite; OVR_DEBUG_LOG(("State_WaitingForSettlePostCalibrationColorBlack -> State_WaitingForSettlePreCalibrationColorWhite.")); setTimer(TIME_TO_WAIT_FOR_SETTLE_PRE_CALIBRATION); } else if (State == State_WaitingForSettlePreCalibrationColorWhite) { // Send calibrate message to device and wait a while. Device->SetCalibrate(CALIBRATE_WHITE); State = State_WaitingForSettlePostCalibrationColorWhite; OVR_DEBUG_LOG(("State_WaitingForSettlePreCalibrationColorWhite -> State_WaitingForSettlePostCalibrationColorWhite.")); setTimer(TIME_TO_WAIT_FOR_SETTLE_POST_CALIBRATION); } else if (State == State_WaitingForSettlePostCalibrationColorWhite) { // Calibration is done. Switch to color 1 and wait for it to settle. RenderColor = COLOR1; State = State_WaitingForSettlePostMeasurement; OVR_DEBUG_LOG(("State_WaitingForSettlePostCalibrationColorWhite -> State_WaitingForSettlePostMeasurement.")); UInt32 waitTime = TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT + getRandomComponent(TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT_RANDOMNESS); setTimer(waitTime); } else if (State == State_WaitingForSettlePostMeasurement) { // Prepare for next measurement. // Create a new result object. MeasurementResult* pResult = new MeasurementResult(); Results.PushBack(pResult); State = State_WaitingToTakeMeasurement; OVR_DEBUG_LOG(("State_WaitingForSettlePostMeasurement -> State_WaitingToTakeMeasurement.")); } else if (State == State_WaitingForTestStarted) { // We timed out waiting for 'TestStarted'. Abandon this measurement and setup for the next. getActiveResult()->TimedOutWaitingForTestStarted = true; State = State_WaitingForSettlePostMeasurement; OVR_DEBUG_LOG(("** Timed out waiting for 'TestStarted'.")); OVR_DEBUG_LOG(("State_WaitingForTestStarted -> State_WaitingForSettlePostMeasurement.")); UInt32 waitTime = TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT + getRandomComponent(TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT_RANDOMNESS); setTimer(waitTime); } else if (State == State_WaitingForColorDetected) { // We timed out waiting for 'ColorDetected'. Abandon this measurement and setup for the next. getActiveResult()->TimedOutWaitingForColorDetected = true; State = State_WaitingForSettlePostMeasurement; OVR_DEBUG_LOG(("** Timed out waiting for 'ColorDetected'.")); OVR_DEBUG_LOG(("State_WaitingForColorDetected -> State_WaitingForSettlePostMeasurement.")); UInt32 waitTime = TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT + getRandomComponent(TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT_RANDOMNESS); setTimer(waitTime); } } else if (latencyTestMessage == LatencyTest_ProcessInputs) { if (State == State_WaitingToTakeMeasurement) { if (!Device) { reset(); return; } // Send 'StartTest' feature report with opposite target color. if (RenderColor == COLOR1) { RenderColor = COLOR2; } else { RenderColor = COLOR1; } getActiveResult()->TargetColor = RenderColor; // Record time so we can determine usb roundtrip time. getActiveResult()->StartTestSeconds = Timer::GetSeconds(); Device->SetStartTest(RenderColor); State = State_WaitingForTestStarted; OVR_DEBUG_LOG(("State_WaitingToTakeMeasurement -> State_WaitingForTestStarted.")); setTimer(TIMEOUT_WAITING_FOR_TEST_STARTED); LatencyTestDisplay ltd(2, 0x40090040); Device->SetDisplay(ltd); } } else if (msg.Type == Message_LatencyTestButton) { BeginTest(); } else if (msg.Type == Message_LatencyTestStarted) { if (State == State_WaitingForTestStarted) { clearTimer(); // Record time so we can determine usb roundtrip time. getActiveResult()->TestStartedSeconds = Timer::GetSeconds(); State = State_WaitingForColorDetected; OVR_DEBUG_LOG(("State_WaitingForTestStarted -> State_WaitingForColorDetected.")); setTimer(TIMEOUT_WAITING_FOR_COLOR_DETECTED); } } else if (msg.Type == Message_LatencyTestColorDetected) { if (State == State_WaitingForColorDetected) { // Record time to detect color. MessageLatencyTestColorDetected* pDetected = (MessageLatencyTestColorDetected*) &msg; UInt16 elapsedTime = pDetected->Elapsed; OVR_DEBUG_LOG(("Time to 'ColorDetected' = %d", elapsedTime)); getActiveResult()->DeviceMeasuredElapsedMilliS = elapsedTime; if (areResultsComplete()) { // We're done. processResults(); reset(); } else { // Run another measurement. State = State_WaitingForSettlePostMeasurement; OVR_DEBUG_LOG(("State_WaitingForColorDetected -> State_WaitingForSettlePostMeasurement.")); UInt32 waitTime = TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT + getRandomComponent(TIME_TO_WAIT_FOR_SETTLE_POST_MEASUREMENT_RANDOMNESS); setTimer(waitTime); LatencyTestDisplay ltd(2, 0x40400040); Device->SetDisplay(ltd); } } } else if (msg.Type == Message_DeviceRemoved) { reset(); } }
static void thread_DispatchWait(DispatchCommandParms * pParms) { SegmentDatabaseDescriptor *segdbDesc; CdbDispatchResult *dispatchResult; int i, db_count = pParms->db_count; int timeoutCounter = 0; /* * OK, we are finished submitting the command to the segdbs. * Now, we have to wait for them to finish. */ for (;;) { int sock; int n; int nfds = 0; int cur_fds_num = 0; /* * Which QEs are still running and could send results to us? */ for (i = 0; i < db_count; i++) { dispatchResult = pParms->dispatchResultPtrArray[i]; segdbDesc = dispatchResult->segdbDesc; /* * Already finished with this QE? */ if (!dispatchResult->stillRunning) continue; /* * Add socket to fd_set if still connected. */ sock = PQsocket(segdbDesc->conn); if (sock >= 0 && PQstatus(segdbDesc->conn) != CONNECTION_BAD) { pParms->fds[nfds].fd = sock; pParms->fds[nfds].events = POLLIN; nfds++; Assert(nfds <= pParms->nfds); } /* * Lost the connection. */ else { char *msg = PQerrorMessage(segdbDesc->conn); /* * Save error info for later. */ cdbdisp_appendMessage(dispatchResult, DEBUG1, ERRCODE_GP_INTERCONNECTION_ERROR, "Lost connection to %s. %s", segdbDesc->whoami, msg ? msg : ""); /* * Free the PGconn object. */ PQfinish(segdbDesc->conn); segdbDesc->conn = NULL; dispatchResult->stillRunning = false; } } /* * Break out when no QEs still running. */ if (nfds <= 0) break; /* * bail-out if we are dying. We should not do much of cleanup * as the main thread is waiting on this thread to finish. Once * QD dies, QE will recognize it shortly anyway. */ if (proc_exit_inprogress) break; /* * Wait for results from QEs. Block here until input is available. */ n = poll(pParms->fds, nfds, DISPATCH_WAIT_TIMEOUT_SEC * 1000); if (n < 0) { int sock_errno = SOCK_ERRNO; if (sock_errno == EINTR) continue; handlePollError(pParms, db_count, sock_errno); continue; } if (n == 0) { handlePollTimeout(pParms, db_count, &timeoutCounter, true); continue; } cur_fds_num = 0; /* * We have data waiting on one or more of the connections. */ for (i = 0; i < db_count; i++) { bool finished; dispatchResult = pParms->dispatchResultPtrArray[i]; segdbDesc = dispatchResult->segdbDesc; /* * Skip if already finished or didn't dispatch. */ if (!dispatchResult->stillRunning) continue; if (DEBUG4 >= log_min_messages) write_log("looking for results from %d of %d", i + 1, db_count); /* * Skip this connection if it has no input available. */ sock = PQsocket(segdbDesc->conn); if (sock >= 0) { /* * The fds array is shorter than conn array, so the following * match method will use this assumtion. */ Assert(sock == pParms->fds[cur_fds_num].fd); } if (sock >= 0 && (sock == pParms->fds[cur_fds_num].fd)) { cur_fds_num++; if (!(pParms->fds[cur_fds_num - 1].revents & POLLIN)) continue; } if (DEBUG4 >= log_min_messages) write_log("PQsocket says there are results from %d", i + 1); /* * Receive and process results from this QE. */ finished = processResults(dispatchResult); /* * Are we through with this QE now? */ if (finished) { if (DEBUG4 >= log_min_messages) write_log ("processResults says we are finished with %d: %s", i + 1, segdbDesc->whoami); dispatchResult->stillRunning = false; if (DEBUG1 >= log_min_messages) { char msec_str[32]; switch (check_log_duration(msec_str, false)) { case 1: case 2: write_log ("duration to dispatch result received from thread %d (seg %d): %s ms", i + 1, dispatchResult->segdbDesc->segindex, msec_str); break; } } if (PQisBusy(dispatchResult->segdbDesc->conn)) write_log ("We thought we were done, because finished==true, but libpq says we are still busy"); } else if (DEBUG4 >= log_min_messages) write_log("processResults says we have more to do with %d: %s", i + 1, segdbDesc->whoami); } } }
ModelCommons::ReadyFlags TrackerContentModule::refreshModel_chain (LiveNodeModel::RefreshMode mode, InterfaceChain<ModelCommons> chain) { // << "TrackerContentModule(" << this << ")::" << __func__ // << "mode(" << mode << "), running(" << running() << ")" // << "completion_watcher(" << completion_watcher_ << ")"; if(!service_->resources.isValid()) { warning(service_.data()) << service_->resources.lastError(); return ReadyFlags(); } ReadyFlags ret = ContentModule_Simple::refreshModel_chain(mode, chain); // First step of refresh: flush the query if requested. // This is also how a new query is started, the entity creating the // TrackerContentModule passes the query in the constructor, and when the // module is attached(), a flushing refresh is initiated. if(mode & LiveNodeModel::Flush) { abort(); setRunning(true); PERF_EVENT("sequencing %d", query_id_); // will sequence the call to "sequencedStart" // should add sequencing by query_id as a quality, and possibly depend on a pending // query, if one cant be aborted for some reason QSharedPointer<TrackerContentModule> self = sharedFromThis<TrackerContentModule>(); sequenced_ = service_->query_sequencer_.addOperation ( tracker_access_->sequencingQualities() , tracker_access_->sequencingDependencies() , SequencerSlotCall::shared(self, "sequencedStart") , SequencerSignal::shared(self, SIGNAL(sequencedSuccess())) , SequencerSignal::shared(self, SIGNAL(sequencedFailure()))); ret = NothingReady; } // second step of refresh: if blocking, wait for all necessary steps for // query to complete if((mode & LiveNodeModel::Block) && running()) { if(sequenced_ && !pending_sequenced_) { pending_sequenced_ = true; QSharedPointer<SequencedOperation> seq = sequenced_; PERF_EVENT("before_sequence_wait %d", query_id_); // wait for sequencedStart to be called if not already so. // During the wait we might get aborted. Make as little assumptions // as possible seq->waitForStarted(); PERF_EVENT("after_sequence_wait %d", query_id_); if(seq->state() > SequencedOperation::Succeeded) // failed (typically aborted) model()->emitErrorImpl(seq->stateString(), 0, QModelIndex(), false); pending_sequenced_ = false; } // The wait is here because TrackerUpdateModule might have multi-step // completion cycle. tracker_access_->waitForQueryComplete(); } // third step of refresh: if a query has completed, process the results TrackerQueryResult queryResult(tracker_access_->takeQueryResult()); if(queryResult.isFinished()) { setRunning(false); sequenced_.clear(); if(queryResult.isError()) { QString error_message = queryResult.errorMessage(); if(RowStoreModel *m = model()) m->emitErrorImpl(error_message, 0, QModelIndex(), !(mode & LiveNodeModel::Block)); warning(service_.data()) << "error while modeling query (id =" << query_id_ << "):\n" << error_message; debug(4, service_.data()) << " query was:\n" << getQueryText() << "\n"; sharedFromThis(), Q_EMIT sequencedFailure(); ret = NothingReady; } else { ret = processResults(queryResult); } } return ret; }
/* * Receive and process results from QEs. */ static void handlePollSuccess(CdbDispatchCmdAsync* pParms, struct pollfd *fds) { int currentFdNumber = 0; int i = 0; /* * We have data waiting on one or more of the connections. */ for (i = 0; i < pParms->dispatchCount; i++) { bool finished; int sock; CdbDispatchResult *dispatchResult = pParms->dispatchResultPtrArray[i]; SegmentDatabaseDescriptor *segdbDesc = dispatchResult->segdbDesc; /* * Skip if already finished or didn't dispatch. */ if (!dispatchResult->stillRunning) continue; ELOG_DISPATCHER_DEBUG("looking for results from %d of %d (%s)", i + 1, pParms->dispatchCount, segdbDesc->whoami); sock = PQsocket(segdbDesc->conn); Assert(sock >= 0); Assert(sock == fds[currentFdNumber].fd); /* * Skip this connection if it has no input available. */ if (!(fds[currentFdNumber++].revents & POLLIN)) continue; ELOG_DISPATCHER_DEBUG("PQsocket says there are results from %d of %d (%s)", i + 1, pParms->dispatchCount, segdbDesc->whoami); /* * Receive and process results from this QE. */ finished = processResults(dispatchResult); /* * Are we through with this QE now? */ if (finished) { dispatchResult->stillRunning = false; ELOG_DISPATCHER_DEBUG("processResults says we are finished with %d of %d (%s)", i + 1, pParms->dispatchCount, segdbDesc->whoami); if (DEBUG1 >= log_min_messages) { char msec_str[32]; switch (check_log_duration(msec_str, false)) { case 1: case 2: elog(LOG, "duration to dispatch result received from %d (seg %d): %s ms", i + 1, dispatchResult->segdbDesc->segindex, msec_str); break; } } if (PQisBusy(dispatchResult->segdbDesc->conn)) elog(LOG, "We thought we were done, because finished==true, but libpq says we are still busy"); } else ELOG_DISPATCHER_DEBUG("processResults says we have more to do with %d of %d (%s)", i + 1, pParms->dispatchCount, segdbDesc->whoami); } }