int main(int argc, char ** argv) { //omp_set_num_threads(4); std::atomic<unsigned> val(0); std::string alphabet = "abcdefghijklmnopqrstuvwxyz0123456789_"; //"b781cbb29054db12f88f08c6e161c199" bf_t bforcer(md5_crypter(), md5("grape_p12"), alphabet); openmp_engine<bf_t> eng(bforcer); eng(); return 0; }
void NaiveBayesGibbs::updateTheta(int round) { std::mt19937 eng(int(time(0))); //#pragma omp parallel for for (int c=0; c<numCategories_; c++) { std::vector<double> y; double sum = 0.0; HashMap::iterator iter = thetaCur_.begin(); for (; iter!=thetaCur_.end(); iter++) { std::gamma_distribution<double> gamma(wordCount_[iter->first][c] + DIRICHLET_HYPERPARAMETER); double tmp = log(1.0 * gamma(eng)); y.push_back(tmp); sum = logsumexp(sum, tmp, iter==thetaCur_.begin()); } int num=0; for (iter=thetaCur_.begin(); iter!=thetaCur_.end(); iter++) { double value = y[num]-sum; iter->second[c] = value; // thetaHistory_[iter->first][c] += value; double tmp = thetaHistory_[iter->first][c]; if (round % INTERVAL == 0) thetaHistory_[iter->first][c] = logsumexp(tmp, value, tmp==0); num++; } } }
bool FuncCallScriptAction::check(const QString &xmlFile, const TypeRule *rule, SymFactory *factory) { Q_UNUSED(rule); Q_UNUSED(factory); // Delete old program if (_program) { delete _program; _program = 0; } // Read the contents of the script file QFile scriptFile(_scriptFile); if (!scriptFile.open(QFile::ReadOnly)) ioError(QString("Error opening file \"%1\" for reading.") .arg(_scriptFile)); _program = new QScriptProgram(scriptFile.readAll(), _scriptFile); // Basic syntax check QScriptSyntaxCheckResult result = QScriptEngine::checkSyntax(_program->sourceCode()); if (result.state() != QScriptSyntaxCheckResult::Valid) { typeRuleError2(xmlFile, srcLine(), -1, QString("Syntax error in file %1 line %2 column %3: %4") .arg(ShellUtil::shortFileName(_scriptFile)) .arg(result.errorLineNumber()) .arg(result.errorColumnNumber()) .arg(result.errorMessage())); } // Check if the function exists ScriptEngine eng(0); ScriptEngine::FuncExistsResult ret = eng.functionExists(_function, *_program); if (ret == ScriptEngine::feRuntimeError) { QString err; if (eng.hasUncaughtException()) { err = QString("Uncaught exception at line %0: %1") .arg(eng.uncaughtExceptionLineNumber()) .arg(eng.lastError()); QStringList bt = eng.uncaughtExceptionBacktrace(); for (int i = 0; i < bt.size(); ++i) err += "\n " + bt[i]; } else err = eng.lastError(); typeRuleError2(xmlFile, srcLine(), -1, QString("Runtime error in file %1: %2") .arg(ShellUtil::shortFileName(_scriptFile)) .arg(err)); } else if (ret == ScriptEngine::feDoesNotExist) { typeRuleError2(xmlFile, srcLine(), -1, QString("Function \"%1\" is not defined in file \"%2\".") .arg(_function) .arg(ShellUtil::shortFileName(_scriptFile))); } return true; }
int main(){ sf::VideoMode videoMode = sf::VideoMode(800, 800); sf::RenderWindow window(videoMode, "Circle Wars"); GameEngine eng(sf::Vector2f(800, 800), 15); sf::Clock clock; while (window.isOpen()){ window.clear(); sf::Event event; while (window.pollEvent(event)){ switch (event.type){ case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: eng.keyPressed(); break; } } sf::Time elapsed = clock.restart(); eng.update(elapsed); window.draw(eng); window.display(); } return 0; }
int rand_range(int min, int max){ std::random_device rd; // obtain a random number from hardware std::mt19937 eng(rd()); // seed the generator std::uniform_int_distribution<> distribution(min, max); // define the range return distribution(eng); }
//' Random Uniform Number Generator with sitmo //' //' The function provides an implementation of sampling from a random uniform distribution //' //' @param n An \code{unsigned integer} denoting the number of realizations to generate. //' @param min A \code{double} indicating the minimum \eqn{a} value //' in the uniform's interval \eqn{\left[a,b\right]} //' @param max A \code{double} indicating the maximum \eqn{b} value //' in the uniform's interval \eqn{\left[a,b\right]} //' @param seed A special \code{unsigned integer} containing a single seed. //' @return A \code{numeric vector} containing the realizations. //' @export //' @examples //' a = runif_sitmo(10) // [[Rcpp::export]] Rcpp::NumericVector runif_sitmo(unsigned int n, double min = 0.0, double max = 1.0, uint32_t seed = 1) { Rcpp::NumericVector o(n); // Create a prng engine sitmo::prng eng(seed); // Obtain the range between max and min double dis = max - min; for(unsigned int i = 0; i < n; ++i) { // Sample from the RNG and divide it by the maximum value possible (can also use SITMO_RAND_MAX, which is 4294967295) // Apply appropriate scale (MAX-MIN) o[i] = min + ((double) eng() / (sitmo::prng::max())) * (dis); } return o; }
// M/M/1 workload generator to generate a stream of jobs. void generateWorkloadMM1(const double serviceTime, const double utilization, vector<Job> &jobStream){ // this->logOut << "[GEN_MM1] Generating M/M/1 workload..." << endl; double interArrival = (1 / utilization) * serviceTime; // ms double newArrival = 0; double newService = 0; double arrTime = 0; const int noOfJobs = JOB_LOG_LENGTH; random_device rd; // Random seed default_random_engine eng(rd()); // Random engine exponential_distribution<double> distriSer(1.0 / serviceTime); // Service time distribution exponential_distribution<double> distriArr(1.0 / interArrival); // Arrival time interval distribution for (int i = 0; i < noOfJobs; i++){ newService = distriSer(eng); newArrival = distriArr(eng); // Draw an arrival time interval sample arrTime = arrTime + newArrival; // Actual arrival time Job newJob(arrTime, newService, newArrival, utilization); jobStream.push_back(newJob); } }
void crossover(Configuration conf, Individual &ind1, Individual &ind2){ // Random Number Generation std::default_random_engine eng(std::random_device{}()); std::uniform_real_distribution<> dist(0,10); for (int i=0; i<ind1.chromosomes.size(); i++) { // This is individual chromosome -> ind1.chromosomes[i] if (dist(eng) < conf.crossover_rate) { // slice is the position of division on a single chromosome: int slice = (int)dist(eng) % conf.chromosome_length; Chromosome in1 = ind1.chromosomes[i]; Chromosome in2 = ind2.chromosomes[i]; Chromosome out1 = ind1.chromosomes[i]; Chromosome out2 = ind2.chromosomes[i]; for (int j=0; j<ind1.chromosomes[i].size(); j++) { // This is individual gene -> inX or outX if (j < slice) { out1[j] = in1[j]; out2[j] = in2[j]; } else { out2[i] = in1[j]; out1[i] = in2[j]; } } ind1.chromosomes[i] = out1; ind2.chromosomes[i] = out2; } } }
Generator::Generator(const std::string addr, unsigned count) noexcept : addr(addr), count(count) { std::random_device rd; std::mt19937 eng(rd()); std::normal_distribution<double> dist(5.0, 3.0); // N(5.0, 3.0) data.resize(count); std::generate_n(data.begin(), count, std::bind(dist, std::ref(eng))); std::sort(data.begin(), data.end()); uuid_t uuid; uuid_generate_random(uuid); identifier.resize(36); uuid_unparse_lower(uuid, (char *)identifier.data()); context.reset(new zmq::context_t); socket.reset(new zmq::socket_t(*context, ZMQ_REP)); socket->bind(addr.c_str()); { std::lock_guard<std::mutex> _{print_mutex}; std::clog << "generator [" << identifier << "] initilized [" << count << "] values @ [" << addr << "]" << std::endl; std::cout << "generator [" << identifier << "]: " << std::endl; std::copy(data.begin(), data.end(), std::ostream_iterator<double>(std::cout, ", ")); std::cout << std::endl << "--------------------------------" << std::endl; } }
int main(int argc, char *argv[]) { if (argc == 2) { std::vector<std::string> texture; texture.push_back("wall"); // texture.push_back("snakepart"); texture.push_back("snakepart-left"); texture.push_back("snakepart-right"); texture.push_back("snakepart-top"); texture.push_back("snakepart-bottom"); texture.push_back("snakepart-top-right"); texture.push_back("snakepart-right-top"); texture.push_back("snakepart-top-left"); texture.push_back("snakepart-left-top"); texture.push_back("snake"); texture.push_back("floor"); texture.push_back("food"); Config conf(10,10, texture, "./ressource/", 1, 1, 500000, argv[1]); Map map(&conf, "./ressource/map/map-1.conf"); Engine eng(argv[1]); eng.init(conf); eng.run(map); return (0); } std::cout << "Usage: " << argv[0] << " lib.so" << std::endl; return (1); }
int main() { double w; for (w = 1e-19; w < 1e16; w *= 42) printf(" %g W = %sW\n", w, eng(w, 3)); return 0; }
void init_info(people & pps){ default_random_engine eng(1);//uclock()); for(size_t i = 0; i < NUM_PEOPLE; i++){ Point home = rand_p(eng); uniform_int_distribution<int32_t> Xdist(max(0,home.X-int32_t(HOME_WORK_MAX_DIS)),min(int32_t(WORLD_SIZE-1),int32_t(home.X+HOME_WORK_MAX_DIS))); uniform_int_distribution<int32_t> Ydist(max(0,home.Y-int32_t(HOME_WORK_MAX_DIS)),min(int32_t(WORLD_SIZE-1),int32_t(home.Y+HOME_WORK_MAX_DIS))); Point work(Xdist(eng),Ydist(eng)); pps.add_person(home,work); } }
TEST_P(engine_test_cpp, GetBackend) { engine::kind engine_kind = static_cast<engine::kind>(GetParam()); SKIP_IF(engine::get_count(engine_kind) == 0, "Engine kind is not supported."); engine eng(engine_kind, 0); compare_backend(static_cast<mkldnn_engine_kind_t>(engine_kind), static_cast<mkldnn_backend_kind_t>(eng.get_backend_kind())); }
// Generate a random vector of length n // uniformly from all n! permutations std::vector<int> generate_random(size_t n) { std::random_device rd; std::default_random_engine eng(rd()); std::vector<int> vector(n); for (int i = 0; i < n; i++) vector[i] = i; std::shuffle(vector.begin(), vector.end(),eng); return vector; }
//Fill a vector with random numbers in the range [lower, upper] void randomFill( std::vector<long int> &V, const long int lower, const long int upper, const unsigned int seed) { //use the default random engine and an uniform distribution std::default_random_engine eng(seed); std::uniform_real_distribution<long double> distr(lower, upper); for( auto &elem : V){ elem = distr(eng); } }
void rnd_fill(std::vector<T> &V, const T lower, const T upper, const T seed) { // use the default random engine and an uniform distribution std::mt19937 eng(static_cast<unsigned int>(seed)); std::uniform_real_distribution<double> distr{double(lower), double(upper)}; for (auto &elem : V) { elem = static_cast<T>(distr(eng)); } }
void ScriptEngineTest::script(){ QFETCH(QString, script); QFETCH(QString, newText); scriptengine eng(0); eng.setEditorView(edView); eng.setScript(script); eng.run(); QEQUAL(edView->editor->document()->text(), newText); }
int main() { // inverse temperature double beta = 1 / T; // random number generator boost::mt19937 eng(SEED); boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random_01(eng, boost::uniform_real<>()); // spin configuration std::vector<int> spins(L); for (int s = 0; s < L; ++s) spins[s] = (random_01() < 0.5 ? 1 : -1); // measurement double ene = 0; double mag = 0; double mag2 = 0; double mag4 = 0; // timer boost::timer tm; for (int mcs = 0; mcs < MCSTEP + MCTHRM; ++mcs) { for (int s = 0; s < L; ++s) { double diff = 2 * spins[s] * (spins[left(s)] + spins[right(s)]); if (random_01() < 0.5 * (1 + std::tanh(-0.5 * beta * diff))) spins[s] = -spins[s]; } if (mcs >= MCTHRM) { double m = 0; double g = 0; for (int s = 0; s < L; ++s) { g -= spins[s] * spins[right(s)]; m += spins[s]; } g /= L; m /= L; ene += g; mag += m; mag2 += m * m; mag4 += std::pow(m, 4); } } // output results std::cout << "Energy = " << ene / MCSTEP << std::endl; std::cout << "Magnetization = " << mag / MCSTEP << std::endl; std::cout << "Magnetization^2 = " << mag2 / MCSTEP << std::endl; std::cout << "Magnetization^4 = " << mag4 / MCSTEP << std::endl; std::cout << "Binder Ratio of Magnetization = " << mag2 * mag2 / mag4 / MCSTEP << std::endl; std::cerr << "Elapsed time = " << tm.elapsed() << " sec\n"; return 0; }
/* * used to spawn a new piece of Food onto the screen * return: a new Food object that the snake can eat */ Food Window::create_food() { std::random_device rd; // obtain a random number from hardware std::mt19937 eng(rd()); // seed the generator std::uniform_int_distribution<> distrx(2, max_x - 2); // define the range int x = distrx(eng); std::uniform_int_distribution<> distry(2, max_y - 2); // define the range int y = distry(eng); return Food(Pos(x, y)); }
int GroupDomain_cube::update( uint test_mode_t ) { int newfault = 0; uint64_t location=0; //Check if TSVs are enabled if(enable_tsv) { // determine whether any faults happened. // if so, record them. double random = gen(); if( random <= tsv_transientFIT) { // only record un-correctable faults for overall simulation success determination tsv_n_faults_transientFIT_class++; newfault = 1; //Record the fault and update the info for TSV location = eng()%total_tsv; if(tsv_bitmap[location]==false) { tsv_bitmap[location]=true; tsv_info[location]=1; } } random = gen(); if( random <= tsv_permanentFIT) { // only record un-correctable faults for overall simulation success determination tsv_n_faults_permanentFIT_class++; newfault = 1; //Record the fault in a tsv and update its info location = eng()%total_tsv; if(tsv_bitmap[location]==false) { tsv_bitmap[location]=true; tsv_info[location]=2; } } } FaultDomain::update(test_mode_t); return newfault; }
void MainWindowImpl::doSomethingExperimental() { qDebug() << "MainWindowImpl::doSomethingExperimental()"; //new QGraphicsLineItem( 0,0, 200, 200 ) //impl->gstate.scene()->addItem( ); //impl->gstate.scene()->addWidget( new QFrame ); if(0) { QString fileName("eval.js"); QFile scriptFile(fileName); if (!scriptFile.open(QIODevice::ReadOnly)) return; qDebug() << "[ running script"<<fileName<<"]"; QScriptEngine & eng( impl->gstate.jsEngine() ); QTextStream stream(&scriptFile); QString contents = stream.readAll(); scriptFile.close(); eng.evaluate(contents, fileName); qDebug() << "[ done running script"<<fileName<<"]"; } if(0) { QBoardHomeView * v = new QBoardHomeView(0); v->show(); connect( v, SIGNAL(itemActivated(QFileInfo const &)), this, SLOT(loadFile(QFileInfo const &)) ); #if 0 QDirModel *model = new QDirModel; model->setIconProvider( impl->fb->iconProvider() ); QTreeView *tree = new QTreeView(0); tree->setModel(model); for( int i = 1; i < 4; ++i ) { tree->setColumnHidden(i, true); } tree->setRootIndex(model->index(QDir::currentPath())); tree->show(); QString fn("QBoard/manual/index.html"); QModelIndex sel; #define FP sel = model->index(fn); \ qDebug() << fn << "sel.isValid() =="<<sel.isValid() \ << "filePath =="<<model->filePath(sel); FP; fn = QString("%1/QBoard/manual/index.html").arg(qboard::home().absolutePath()); FP; fn = "/foo"; FP; #undef FP #endif }
int main() { std::tr1::ranlux64_base_01 eng; std::tr1::normal_distribution<float> dist(1.5f, 2.0f); std::tr1::normal_distribution<float>::input_type engval = eng(); std::tr1::normal_distribution<float>::result_type distVal = dist(eng); dist.reset(); std::cerr << "a random value => " << dist(eng) << std::endl; dist.reset(); std::cerr << "a random value => " << dist(eng) << std::endl; dist.reset(); std::cerr << "a random value => " << dist(eng) << std::endl; }
inline void rng_aes_validation_cbc (unsigned bits, unsigned char *plain_key, unsigned char plain_cipher[64]) { typedef Eng<uint32_t, 1> eng_type; typename eng_type::key_type key; vsmc::Array<typename eng_type::ctr_block_type, 4> text; vsmc::Array<typename eng_type::buffer_type, 5> cipher; std::memcpy(key.data(), plain_key, sizeof(key)); std::memcpy(text.data(), plain_text, 64); std::memcpy(cipher[0].data(), plain_vector, 16); eng_type eng(key); for (std::size_t i = 0; i != 4; ++i) { rng_aes_validation_xor(text[i].data(), cipher[i].data()); eng(text[i], cipher[i + 1]); } unsigned char test_cipher[64]; std::memcpy(test_cipher, cipher[1].data(), 64); rng_aes_validation(bits, test_cipher, plain_cipher); }
// Generate an almost sorted vector of length n // by starting with a sorted list and randomly // swapping pairs of elements k times std::vector<int> generate_almost_sorted_1(size_t n) { int k = 100; std::random_device rd; std::default_random_engine eng(rd()); std::uniform_int_distribution<int> dis(0, n-1); std::vector<int> vector(n); for (int i = 0; i < n; i++) vector[i] = i; for (int i = 0; i < k; i++) vector[dis(eng)] = dis(eng); return vector; }
//' Test Generation using sitmo and C++11 //' //' The function provides an implementation of creating realizations from the default engine. //' //' @param n An \code{unsigned integer} denoting the number of realizations to generate. //' @param seeds A \code{vec} containing a list of seeds. Each seed is run on its own core. //' @return A \code{vec} containing the realizations. //' @details //' The following function's true power is only accessible on platforms that support OpenMP (e.g. Windows and Linux). //' However, it does provide a very good example as to how to make ones code applicable across multiple platforms. //' //' With this being said, how we determine how many cores to split the generation to is governed by the number of seeds supplied. //' In the event that one is using OS X, only the first seed supplied is used. //' //' @export //' @examples //' a = sitmo_parallel(10, c(1)) //' //' b = sitmo_parallel(10, c(1,2)) //' //' c = sitmo_parallel(10, c(1,2)) //' //' # True on only OS X or systems without openmp //' isTRUE(all.equal(a,b)) //' //' isTRUE(all.equal(b,c)) // [[Rcpp::export]] Rcpp::NumericVector sitmo_parallel(unsigned int n, Rcpp::NumericVector& seeds){ unsigned int ncores = seeds.size(); Rcpp::NumericVector q(n); #ifdef _OPENMP #pragma omp parallel num_threads(ncores) if(ncores > 1) { #endif // Engine requires uint32_t inplace of unsigned int uint32_t active_seed; // Write the active seed per core or just write one of the seeds. #ifdef _OPENMP active_seed = static_cast<uint32_t>(seeds[omp_get_thread_num()]); #else active_seed = static_cast<uint32_t>(seeds[0]); #endif sitmo::prng eng( active_seed ); // Parallelize the Loop #ifdef _OPENMP #pragma omp for schedule(static) #endif for (unsigned int i = 0; i < n; i++){ q[i] = eng(); } #ifdef _OPENMP } #endif return q; }
Individual mutate(Configuration conf, Individual indi){ // Random Number Generation std::default_random_engine eng(std::random_device{}()); std::uniform_real_distribution<> dist(-5,5); for (int i=0; i<indi.chromosomes.size(); i++) { for (int j=0; j<indi.chromosomes[i].size(); j++) { if (dist(eng) < conf.mutation_rate && i > conf.elitism) { indi.chromosomes[i][j] = dist(eng); } } } return indi; }
int main() { std::mt19937 eng{std::random_device{}()}; auto r = eng(); std::cout << "# Unnamed RVO\n"; auto t1 = make_urvo(r); std::cout << "# Named RVO\n"; auto t2 = make_nrvo(r); std::cout << "# No RVO\n"; auto t3 = make_no_rvo(r); std::cout << "# Move\n"; auto t4 = make_move(r); std::cout << "Exiting\n"; }
void setSimplexSeed(const int32_t seed){ std::mt19937 eng(seed); std::uniform_int_distribution<int> dist(0, 255); for(int i = 0; i < 256; i ++) perm[i] = i; for(int i = 0; i < 10000; i ++){ uint8_t firstID = dist(eng); uint8_t secondID = dist(eng); int h = perm[firstID]; perm[firstID] = perm[secondID]; perm[secondID] = h; } memcpy(&perm[256], &perm[0], 256); }
TEST_P(ocl_engine_test, BasicInteropCpp) { auto p = GetParam(); cl_device_id ocl_dev = (p.adev_kind == dev_kind::gpu) ? gpu_ocl_dev : (p.adev_kind == dev_kind::cpu) ? cpu_ocl_dev : nullptr; cl_context ocl_ctx = (p.actx_kind == ctx_kind::gpu) ? gpu_ocl_ctx : (p.actx_kind == ctx_kind::cpu) ? cpu_ocl_ctx : nullptr; SKIP_IF(p.adev_kind != dev_kind::null && !ocl_dev, "Required OpenCL device not found."); SKIP_IF(p.actx_kind != ctx_kind::null && !ocl_ctx, "Required OpenCL context not found."); SKIP_IF(cpu_ocl_dev == gpu_ocl_dev && (p.adev_kind == dev_kind::cpu || p.actx_kind == ctx_kind::cpu), "OpenCL CPU-only device not found."); catch_expected_failures( [&]() { { engine eng(engine::kind::gpu, ocl_dev, ocl_ctx); if (p.expected_status != mkldnn_success) { FAIL() << "Success not expected"; } cl_device_id dev = eng.get_ocl_device(); cl_context ctx = eng.get_ocl_context(); EXPECT_EQ(dev, ocl_dev); EXPECT_EQ(ctx, ocl_ctx); cl_uint ref_count; OCL_CHECK(clGetContextInfo(ocl_ctx, CL_CONTEXT_REFERENCE_COUNT, sizeof(ref_count), &ref_count, nullptr)); int i_ref_count = int(ref_count); EXPECT_EQ(i_ref_count, 2); } cl_uint ref_count; OCL_CHECK(clGetContextInfo(ocl_ctx, CL_CONTEXT_REFERENCE_COUNT, sizeof(ref_count), &ref_count, nullptr)); int i_ref_count = int(ref_count); EXPECT_EQ(i_ref_count, 1); }, p.expected_status != mkldnn_success, p.expected_status); }
void RandomHits( std::vector < int > & hits){ hits.clear(); // O vector é limpo para previnir que não armazene mais de 20 elementos int RandomNum; std::random_device r; std::default_random_engine eng(r()); std::uniform_real_distribution<double> distr(1, 80); // Gerando números dentro da faixa de hits possíveis do Keno for(int i = 0; i < 20;){ RandomNum = distr(eng); if(std::binary_search(hits.begin(), hits.end(), RandomNum)){ continue; }else{ hits.push_back(RandomNum); i++; } } }