double func11(double x) { ++iteration_count; return sin(0.01 / x) - 0.01; };
stacktrace& operator=(stacktrace other) { using std::swap; swap(call_stack_, other.call_stack_); return *this; }
void initBox2DTypeBindings(GameManager& game) { LuaContext& lua = *game.getLuaContext(); lua.writeVariable("Box2D", LuaEmptyArray); { lua.writeVariable("Box2D", "Vector", LuaEmptyArray); { lua.writeFunction("Box2D", "Vector", "new", [](const optional<float>& arg1, const optional<float>& arg2) { if (arg1 && arg2) { // If the scripter passed in two arguments... return b2Vec2(*arg1, *arg2); } else if (!(arg1 || arg2)) { // Else if the scripter passed in *no* arguments... return b2Vec2(0, 0); } else { throw invalid_argument( "Must pass in two numbers or nothing at all" ); } }); lua.registerMember("x", &b2Vec2::x); lua.registerMember("y", &b2Vec2::y); } lua.writeVariable("Box2D", "BodyType", LuaEmptyArray); { lua.writeVariable("Box2D", "BodyType", "Static", b2_staticBody); lua.writeVariable("Box2D", "BodyType", "Dynamic", b2_dynamicBody); lua.writeVariable("Box2D", "BodyType", "Kinematic", b2_kinematicBody); } lua.writeVariable("Box2D", "BodyDef", LuaEmptyArray); { lua.writeFunction("Box2D", "BodyDef", "new", getDefaultConstructorLambda<b2BodyDef>()); lua.registerMember("active", &b2BodyDef::active); lua.registerMember("allowSleep", &b2BodyDef::allowSleep); lua.registerMember("angle", &b2BodyDef::angle); lua.registerMember("angularDamping", &b2BodyDef::angularDamping); lua.registerMember("angularVelocity", &b2BodyDef::angularVelocity); lua.registerMember("awake", &b2BodyDef::awake); lua.registerMember("bullet", &b2BodyDef::bullet); lua.registerMember("fixedRotation", &b2BodyDef::fixedRotation); lua.registerMember("gravityScale", &b2BodyDef::gravityScale); lua.registerMember("linearDamping", &b2BodyDef::linearDamping); lua.registerMember("linearVelocity", &b2BodyDef::linearVelocity); lua.registerMember("position", &b2BodyDef::position); lua.registerMember("type", &b2BodyDef::type); } lua.writeVariable("Box2D", "Body", LuaEmptyArray); { lua.writeFunction("Box2D", "Body", "new", [&game](const b2BodyDef& def) { return game.getPhysicsWorld()->CreateBody(&def); }); lua.registerMember<b2Body, bool>("awake", [](const b2Body& object) { return object.IsAwake(); }, [](b2Body& object, const bool val) { object.SetAwake(val); }); lua.registerMember<b2Body, bool>("fixedRotation", [](const b2Body& object) { return object.IsFixedRotation(); }, [](b2Body& object, const bool val) { object.SetFixedRotation(val); }); lua.registerMember<b2Body, b2Vec2>("position", [](const b2Body& body) { return body.GetPosition(); }, [](b2Body& body, const b2Vec2& pos) { body.SetTransform(pos, body.GetAngle()); }); lua.registerFunction<b2Body, b2Fixture*(b2FixtureDef&)>("CreateFixture", [](b2Body& body, b2FixtureDef& def) { return body.CreateFixture(&def); }); } lua.writeVariable("Box2D", "Filter", LuaEmptyArray); { lua.writeFunction("Box2D", "Filter", "new", getDefaultConstructorLambda<b2Filter>()); lua.registerMember("categoryBits", &b2Filter::categoryBits); lua.registerMember("maskBits", &b2Filter::maskBits); lua.registerMember("groupIndex", &b2Filter::groupIndex); } lua.writeVariable("Box2D", "FixtureDef", LuaEmptyArray); { lua.writeFunction("Box2D", "FixtureDef", "new", getDefaultConstructorLambda<b2FixtureDef>()); lua.registerMember("friction", &b2FixtureDef::friction); lua.registerMember("restitution", &b2FixtureDef::restitution); lua.registerMember("density", &b2FixtureDef::density); lua.registerMember("isSensor", &b2FixtureDef::isSensor); lua.registerMember("filter", &b2FixtureDef::filter); typedef variant<b2CircleShape*, b2EdgeShape*, b2PolygonShape*, b2ChainShape*, shared_ptr<b2Shape>> shapevariant; lua.registerFunction<b2FixtureDef, void(shapevariant)>("setShape", // TODO: Turn this into a member [](b2FixtureDef& def, shapevariant shape) { // NOTE: This depends on the order in which the members of the // b2Shape::Type enum are defined! switch (shape.which()) { case b2Shape::Type::e_circle: def.shape = *get<b2CircleShape*>(&shape); break; case b2Shape::Type::e_edge: def.shape = *get<b2EdgeShape*>(&shape); break; case b2Shape::Type::e_polygon: def.shape = *get<b2PolygonShape*>(&shape); break; case b2Shape::Type::e_chain: def.shape = *get<b2ChainShape*>(&shape); break; default: def.shape = get<shared_ptr<b2Shape>>(shape).get(); break; } }); lua.registerFunction<b2FixtureDef, const b2Shape*(void)>("getShape", [](b2FixtureDef& def) { return def.shape; }); } lua.writeVariable("Box2D", "Fixture", LuaEmptyArray); { lua.registerMember<b2Fixture, float>("friction", [](const b2Fixture& object) { return object.GetFriction(); }, [](b2Fixture& object, const float val) { object.SetFriction(val); }); lua.registerMember<b2Fixture, float>("restitution", [](const b2Fixture& object) { return object.GetRestitution(); }, [](b2Fixture& object, const float val) { object.SetRestitution(val); }); lua.registerMember<b2Fixture, float>("density", [](const b2Fixture& object) { return object.GetDensity(); }, [](b2Fixture& object, const float val) { object.SetDensity(val); }); lua.registerMember<b2Fixture, bool>("isSensor", [](const b2Fixture& object) { return object.IsSensor(); }, [](b2Fixture& object, const bool val) { object.SetSensor(val); }); lua.registerFunction<b2Fixture, const b2Shape*(void)>("getShape", [](b2Fixture& fix) { return fix.GetShape(); }); lua.registerFunction<b2Fixture, const b2Body*(void)>("body", [](b2Fixture& fix) { return fix.GetBody(); }); } lua.writeVariable("Box2D", "Shape", LuaEmptyArray); { lua.writeVariable("Box2D", "Shape", "Type", LuaEmptyArray); { lua.writeVariable("Box2D", "Shape", "Type", "Circle", b2Shape::e_circle); lua.writeVariable("Box2D", "Shape", "Type", "Edge", b2Shape::e_edge); lua.writeVariable("Box2D", "Shape", "Type", "Polygon", b2Shape::e_polygon); lua.writeVariable("Box2D", "Shape", "Type", "Chain", b2Shape::e_chain); lua.writeVariable("Box2D", "Shape", "Type", "Count", b2Shape::e_typeCount); } lua.registerMember("radius", &b2Shape::m_radius); lua.registerMember("type", &b2Shape::m_type); lua.writeVariable("Box2D", "Shape", "Circle", LuaEmptyArray); { lua.writeFunction("Box2D", "Shape", "Circle", "new", [](optional<float> r) { b2CircleShape* shape = new b2CircleShape; if (r) shape->m_radius = *r; return shape; }); lua.registerMember("position", &b2CircleShape::m_p); lua.registerMember<b2CircleShape, float>("radius", [](const b2CircleShape& shape) { return shape.m_radius; }, [](b2CircleShape& shape, const float rad) { shape.m_radius = rad; }); lua.registerMember<b2CircleShape, b2CircleShape::Type, b2CircleShape::Type(const b2CircleShape&)>("type", [](const b2CircleShape& shape) { return shape.m_type; }); } lua.writeVariable("Box2D", "Shape", "Edge", LuaEmptyArray); { lua.writeFunction("Box2D", "Shape", "Edge", "new", getNewDefaultConstructorLambda<b2EdgeShape>()); lua.registerMember("v1", &b2EdgeShape::m_vertex1); lua.registerMember("v2", &b2EdgeShape::m_vertex2); // ^ The two vertices actually in the edge lua.registerMember("v0", &b2EdgeShape::m_vertex0); lua.registerMember("v3", &b2EdgeShape::m_vertex3); lua.registerMember("hasv0", &b2EdgeShape::m_hasVertex0); lua.registerMember("hasv3", &b2EdgeShape::m_hasVertex3); // ^ Two "ghost vertices"; not sure what that means, gotta look // more into it lua.registerMember<b2EdgeShape, b2EdgeShape::Type, b2EdgeShape::Type(const b2EdgeShape&)>("type", [](const b2EdgeShape& shape) { return shape.m_type; }); } lua.writeVariable("Box2D", "Shape", "Polygon", LuaEmptyArray); { lua.writeFunction("Box2D", "Shape", "Polygon", "new", getNewDefaultConstructorLambda<b2PolygonShape>()); } lua.writeVariable("Box2D", "Shape", "Rectangle", LuaEmptyArray); { lua.writeFunction("Box2D", "Shape", "Rectangle", "new", [](const float hx, const float hy, const optional<b2Vec2&> center, const optional<float> angle) { b2PolygonShape* box = new b2PolygonShape; if (center && angle) { box->SetAsBox(hx, hy, *center, *angle); } else { box->SetAsBox(hx, hy); } return box; }); } } } }
HasPtr(const string &s = string()): ps(new string(s)), i(0) { }
void chomp_carriage_return(char* str) { int len = strlen(str); if ( str[len-1] == '\r' ) str[len-1] = '\0'; }
SubsystemRunner (Option& opts) : opts_(opts) , emergency_(false) , start_(bind (&SubsystemRunner::triggerStartup, this,_1)) , stopIt_(bind (&Subsys::triggerShutdown, _1)) { }
void Callback::swap( Callback& rhs ) { using std::swap; swap( m_id, rhs.m_id ); swap( m_callback, rhs.m_callback ); }
double func8(double x) { ++iteration_count; return exp(21000.0 / x) / (1.11e11 * x * x) - 1.0; };
double func9(double x) { ++iteration_count; return 1.0 / x + log(x) - 100.0; };
double func6(double x) { ++iteration_count; return 1e10 * pow(x, 1.0 / x) - 1.0; };
double func7(double x) { ++iteration_count; return pow(x, 20.0) - 1.0; };
double func4(double x) { ++iteration_count; return exp(1.0 / x - 25.0) - 1.0; };
double func3(double x) { ++iteration_count; return 2.0 * x * exp(-20.0) + 1.0 - 2.0 * exp(-20.0 * x); };
double func1(double x) { ++iteration_count; return 4.0 * cos(x) - exp(x); };
void main(int argc, char *argv[]) { ofstream outf; bool do_cmp; string name, dir1(dir_path), dir2(aes_path); if(argc == 1) { cout << endl << "usage: aes_gkat [/t] [/h] [/k] [/e] [/c] where:"; cout << endl << " /t: compare output and reference test file(s)"; cout << endl << " /h: author's byte order (frog, safer+ & serpent)"; cout << endl << " /k: generate ECB Known Answer Test files"; cout << endl << " /e: generate ECB Monte Carlo Test files"; cout << endl << " /c: generate CBC Monte Carlo Test files"; cout << endl << endl; exit(0); } cout << endl << "Generate and verify tests for the " << cipher_name()[0] << " algorithm: (" << cipher_name()[1] << ")" << endl; do_fss_hack = test_args(argc, argv, 'h'); do_cmp = test_args(argc, argv, 't'); if(test_args(argc, argv, 'k')) { name = dir1 + string(cipher_name()[0]) + string("\\ecb_vk.txt"); outf.open(name.c_str(), ios_base::out); if(outf) { header(outf, 0); ecb_vk(outf); outf << endl; outf.close(); if(do_cmp) comp_vecs(dir2 + cipher_name()[2] + "\\ecb_vk.txt", name); } name = dir1 + string(cipher_name()[0]) + string("\\ecb_vt.txt"); outf.open(name.c_str(), ios_base::out); if(outf) { header(outf, 1); ecb_vt(outf); outf << endl; outf.close(); if(do_cmp) comp_vecs(dir2 + cipher_name()[2] + "\\ecb_vt.txt", name); } } if(test_args(argc, argv, 'e')) { name = dir1 + string(cipher_name()[0]) + string("\\ecb_me.txt"); outf.open(name.c_str(), ios_base::out); if(outf) { header(outf, 2); ecb_me(outf); outf << endl; outf.close(); if(do_cmp) comp_vecs(dir2 + cipher_name()[2] + "\\ecb_e_m.txt", name); } name = dir1 + string(cipher_name()[0]) + string("\\ecb_md.txt"); outf.open(name.c_str(), ios_base::out); if(outf) { header(outf, 3); ecb_md(outf); outf << endl; outf.close(); if(do_cmp) comp_vecs(dir2 + cipher_name()[2] + "\\ecb_d_m.txt", name); } } if(test_args(argc, argv, 'c')) { name = dir1 + string(cipher_name()[0]) + string("\\cbc_me.txt"); outf.open(name.c_str(), ios_base::out); if(outf) { header(outf, 4); cbc_me(outf); outf << endl; outf.close(); if(do_cmp) comp_vecs(dir2 + cipher_name()[2] + "\\cbc_e_m.txt", name); } name = dir1 + string(cipher_name()[0]) + string("\\cbc_md.txt"); outf.open(name.c_str(), ios_base::out); if(outf) { header(outf, 5); cbc_md(outf); outf << endl; outf.close(); if(do_cmp) comp_vecs(dir2 + cipher_name()[2] + "\\cbc_d_m.txt", name); } } };
double func10(double x) { ++iteration_count; return exp(exp(x)) - exp(exp(1.0)); };
friend void swap(ResourceHandle<Handle>& a, ResourceHandle<Handle>& b) noexcept { using std::swap; swap(static_cast<Resource&>(a), static_cast<Resource&>(b)); swap(a.handle_, b.handle_); }
Service service; service.publish( resource ); service.set_failed_filter_validation_handler( &failed_filter_validation_handler ); thread service_thread( [ &service, settings ] ( ) { service.start( settings ); } ); WHEN( "I perform a HTTP 'GET' request to '/resources/1' with header 'Content-Type: application/yaml'" ) { Http::Request request; request.port = 1984; request.host = "localhost"; request.path = "/resources/1"; request.headers.insert( make_pair( "Content-Type", "application/yaml" ) ); auto response = Http::get( request ); THEN( "I should see a '-949' (Failed Filter Validation) status code" ) { REQUIRE( -949 == response.status_code ); } AND_THEN( "I should see a repsonse body of 'Yikes! Filters Mismatched.'" ) { Bytes expection { 'Y', 'i', 'k', 'e', 's', '!', ' ', 'F', 'i', 'l', 't', 'e', 'r', 's', ' ', 'M', 'i', 's', 'm', 'a', 't', 'c', 'h', 'e', 'd', '.' }; REQUIRE( response.body == expection ); } AND_THEN( "I should see a 'Connection' header value of 'close'" )
int main () { ::operator new (1, nothrow_t ()); return 0; }
string fields_string() const { return string(); }
int main () { std::cout << "Nonfinite_num_facet very simple example." << std::endl; if((std::numeric_limits<double>::has_infinity == 0) || (std::numeric_limits<double>::infinity() == 0)) { std::cout << "Infinity not supported on this platform." << std::endl; return 0; } if((std::numeric_limits<double>::has_quiet_NaN == 0) || (std::numeric_limits<double>::quiet_NaN() == 0)) { std::cout << "NaN not supported on this platform." << std::endl; return 0; } std::locale default_locale (std::locale::classic ()); // Note the currrent (default C) locale. // Create plus and minus infinity. double plus_infinity = +std::numeric_limits<double>::infinity(); double minus_infinity = -std::numeric_limits<double>::infinity(); // and create a NaN (NotANumber) double NaN = +std::numeric_limits<double>::quiet_NaN (); double negated_NaN = (boost::math::changesign)(std::numeric_limits<double>::quiet_NaN ()); // Output the nonfinite values using the current (default C) locale. // The default representations differ from system to system, // for example, using Microsoft compilers, 1.#INF, -1.#INF, and 1.#QNAN. cout << "Using C locale" << endl; cout << "+std::numeric_limits<double>::infinity() = " << plus_infinity << endl; cout << "-std::numeric_limits<double>::infinity() = " << minus_infinity << endl; cout << "+std::numeric_limits<double>::quiet_NaN () = " << NaN << endl; // Display negated NaN. cout << "negated NaN " << negated_NaN << endl; // "-1.IND" // Create a new output locale, and add the nonfinite_num_put facet std::locale C99_out_locale (default_locale, new boost::math::nonfinite_num_put<char>); // and imbue the cout stream with the new locale. cout.imbue (C99_out_locale); // Or for the same effect more concisely: cout.imbue (locale(locale(), new boost::math::nonfinite_num_put<char>)); // Output using the new locale cout << "Using C99_out_locale " << endl; cout << "+std::numeric_limits<double>::infinity() = " << plus_infinity << endl; cout << "-std::numeric_limits<double>::infinity() = " << minus_infinity << endl; cout << "+std::numeric_limits<double>::quiet_NaN () = " << NaN << endl; // Display negated NaN. cout << "negated NaN " << negated_NaN << endl; // -nan // Create a string with the expected C99 representation of plus infinity. std::string inf = "inf"; { // Try to read an infinity value using the default C locale. // Create an input stream which will provide "inf" std::istringstream iss (inf); // Create a double ready to take the input, double infinity; // and read "inf" from the stringstream: iss >> infinity; // This will not work on all platforms! if (! iss) { // Reading infinity went wrong! std::cerr << "C locale input format error!" << std::endl; } } // Using default C locale. { // Now retry using C99 facets. // Create a new input locale and add the nonfinite_num_get facet. std::locale C99_in_locale (default_locale, new boost::math::nonfinite_num_get<char>); // Create an input stream which will provide "inf". std::istringstream iss (inf); // Imbue the stream with the C99 input locale. iss.imbue (C99_in_locale); // Create a double ready to take the input, double infinity; // and read from the stringstream: iss >> infinity; if (! iss) { // Reading infinity went wrong! std::cout << "C99 input format error!" << std::endl; } // Expect to get an infinity, which will display still using the C99 locale as "inf" cout << "infinity in C99 representation is " << infinity << endl; // To check, we can switch back to the default C locale. cout.imbue (default_locale); cout << "infinity in default C representation is " << infinity << endl; } // using C99 locale. { // A 'loop-back example, output to a stringstream, and reading it back in. // Create C99 input and output locales. std::locale C99_out_locale (default_locale, new boost::math::nonfinite_num_put<char>); std::locale C99_in_locale (default_locale, new boost::math::nonfinite_num_get<char>); std::ostringstream oss; oss.imbue(C99_out_locale); oss << plus_infinity; std::istringstream iss(oss.str()); // So stream contains "inf". iss.imbue (C99_in_locale); std::string s; iss >> s; cout.imbue(C99_out_locale); if (oss.str() != s) { cout << plus_infinity << " != " << s << " loopback failed!" << endl; } else { cout << plus_infinity << " == " << s << " as expected." << endl; } } // Example varying the width and position of the nonfinite representations. // With the nonfinite_num_put and _get facets, the width of the output is constant. #ifdef BOOST_NO_NUMERIC_LIMITS_LOWEST cout << "BOOST_NO_NUMERIC_LIMITS_LOWEST is defined, so no max_digits10 available." << endl; std::streamsize max_digits10 = 2 + std::numeric_limits<double>::digits * 30103UL / 100000UL; #else // Can use new C++0X max_digits10 (the maximum potentially significant digits). std::streamsize max_digits10 = std::numeric_limits<double>::max_digits10; #endif cout << "std::numeric_limits<double>::max_digits10 is " << max_digits10 << endl; cout.precision(max_digits10); double pi = 3.141592653589793238462643383279502884197169399375105820974944; // Expect 17 (probably) decimal digits (regardless of locale). // cout has the default locale. cout << "pi = " << pi << endl; // pi = 3.1415926535897931 cout.imbue (C99_out_locale); // Use cout with the C99 locale // (expect the same output for a double). cout << "pi = " << pi << endl; // pi = 3.1415926535897931 cout << "infinity in C99 representation is " << plus_infinity << endl; //int width = 2; // Check effect if width too small is OK. // (There was a disturbed layout on older MSVC?). int width = 20; // Similarly if we can switch back to the default C locale. cout.imbue (default_locale); cout << "infinity in default C representation is " << plus_infinity << endl; cout << "infinity in default C representation (setw(" << width << ") is |" << setw(width) << plus_infinity <<'|' << endl; cout << "infinity in default C representation (setw(" << width << ") is |" << left << setw(width) << plus_infinity <<'|' << endl; cout << "infinity in default C representation (setw(" << width << ") is |" << internal << setw(width) << plus_infinity <<'|' << endl; cout.imbue (C99_out_locale); cout << "infinity in C99 representation (setw(" << width << ") is |" << right << setw(width) << plus_infinity <<'|'<< endl; cout << "infinity in C99 representation (setw(" << width << ") is |" << left << setw(width) << plus_infinity <<'|'<< endl; cout << "infinity in C99 representation (setw(" << width << ") is |" << internal << setw(width) << plus_infinity <<'|'<< endl; return 0; } // int main()
// JAH 20160731 added this function in replacement to the separate // populate* functions that separately logged information tables // this calls the kmodel version for Actors and Scenarios and then handles // salience, capability, and dimensions tables void SMPModel::LogInfoTables() { // first call the KModel version to do the actors and scenarios tables Model::LogInfoTables(); // now do mine // assert tests for all tables here at the start assert(numDim == dimName.size()); // for efficiency sake, we'll do all tables in a single transaction // form insert commands string sqlD = string("INSERT INTO DimensionDescription (ScenarioId,Dim_k,\"Desc\") VALUES ('") + scenId + "', :dim_k, :desc)"; string sqlC = string("INSERT INTO SpatialCapability (ScenarioId, Turn_t, Act_i, Cap) VALUES ('") + scenId + "', :turn_t, :act_i, :cap)"; string sqlS = string("INSERT INTO SpatialSalience (ScenarioId, Turn_t, Act_i, Dim_k,Sal) VALUES ('") + scenId + "', :turn_t, :act_i, :dim_k, :sal)"; string sqlSc = string("UPDATE ScenarioDesc SET VotingRule = :vr, BigRAdjust = :br, " "BigRRange = :brr, ThirdPartyCommit = :tpc, InterVecBrgn = :ivb, BargnModel = :bm " " WHERE ScenarioId = '") + scenId + "'"; string sqlAcc = string("INSERT INTO Accommodation (ScenarioId, Act_i, Act_j, Affinity) VALUES ('") + scenId + "', :act_i, :act_j, :affinity)"; qtDB->transaction(); // Retrieve accommodation matrix auto st = dynamic_cast<SMPState *>(history.back()); assert(st != nullptr); auto accM = st->getAccomodate(); // Accomodation table to record affinities query.prepare(QString::fromStdString(sqlAcc)); assert((accM.numR() == numAct) && (accM.numC() == numAct)); for (unsigned int Act_i = 0; Act_i < numAct; ++Act_i) { for (unsigned int Act_j = 0; Act_j < numAct; ++Act_j) { //bind the data query.bindValue(":act_i", Act_i); query.bindValue(":act_j", Act_j); query.bindValue(":affinity", accM(Act_i, Act_j)); // record if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } } // Dimension Description Table query.prepare(QString::fromStdString(sqlD)); for (unsigned int k = 0; k < dimName.size(); k++) { // bind the data query.bindValue(":dim_k", k); query.bindValue(":desc", dimName[k].c_str()); // record if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } // Spatial Capability query.prepare(QString::fromStdString(sqlC)); // for each turn extract the information for (unsigned int t = 0; t < history.size(); t++) { auto st = history[t]; // get each actors capability value for each turn auto cp = (const SMPState*)history[t]; auto caps = cp->actrCaps(); for (unsigned int i = 0; i < numAct; i++) { // bind data query.bindValue(":turn_t", t); query.bindValue(":act_i", i); query.bindValue(":cap", caps(0, i)); // record if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } } // Spatial Salience query.prepare(QString::fromStdString(sqlS)); // for each turn extract the information for (unsigned int t = 0; t < history.size(); t++) { // Get the individual turn auto st = history[t]; // get the SMPState for turn auto cp = (const SMPState*)history[t]; // Extract information for each actor and dimension for (unsigned int i = 0; i < numAct; i++) { for (unsigned int k = 0; k < numDim; k++) { // Populate the actor auto ai = ((const SMPActor*)actrs[i]); // Get the Salience Value for each actor // double sal = ai->vSal(k, 0); //bind the data query.bindValue(":turn_t", t); query.bindValue(":act_i", i); query.bindValue(":dim_k", k); query.bindValue(":sal", ai->vSal(k, 0)); // record if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } } } query.prepare(QString::fromStdString(sqlSc)); //ScenarioDesc table query.bindValue(":vr", static_cast<int>(vrCltn)); query.bindValue(":br", static_cast<int>(bigRAdj)); query.bindValue(":brr", static_cast<int>(bigRRng)); query.bindValue(":tpc", static_cast<int>(tpCommit)); query.bindValue(":ivb", static_cast<int>(ivBrgn)); query.bindValue(":bm", static_cast<int>(brgnMod)); if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } // finish qtDB->commit(); return; }
void chomp_newline(char* str) { int len = strlen(str); if ( str[len-1] == '\n' ) str[len-1] = '\0'; }
// -------------------------------------------- void SMPState::updateBargnTable(const vector<vector<BargainSMP*>> & brgns, map<unsigned int, KBase::KMatrix> actorBargains, map<unsigned int, unsigned int> actorMaxBrgNdx) const { string sql = string("UPDATE Bargn SET Init_Prob = :init_prob, Init_Seld = :init_seld, " "Recd_Prob = :recd_prob, Recd_Seld = :recd_seld " "WHERE ('" + model->getScenarioID() + "' = ScenarioId) " "and (:turn_t = Turn_t) and (:bgnId = BargnId) " "and (:init_act_i = Init_Act_i) and (:recd_act_j = Recd_Act_j)"); QSqlQuery query = model->getQuery(); query.prepare(QString::fromStdString(sql)); auto updateBargn = [&query, this](int bargnID, int initActor, double initProb, int isInitSelected, int recvActor, double recvProb, int isRecvSelected) { query.bindValue(":init_prob", initProb); query.bindValue(":init_seld", isInitSelected); // For SQ cases, there would be no receiver if (initActor != recvActor) { query.bindValue(":recd_prob", recvProb); query.bindValue(":recd_seld", isRecvSelected); } else { // Pass NULL values for SQ cases query.bindValue(":recd_prob", QVariant::Double); query.bindValue(":recd_seld", QVariant::Int); } query.bindValue(":turn_t", turn); query.bindValue(":bgnId", bargnID); query.bindValue(":init_act_i", initActor); query.bindValue(":recd_act_j", recvActor); if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } return; }; // start for the transaction //model->beginDBTransaction(); // Update the bargain table for the bargain values for init actor and recd actor // along with the info whether a bargain got selected or not in the respective actor's queue for (unsigned int i = 0; i < brgns.size(); i++) { auto ai = ((const SMPActor*)(model->actrs[i])); double initProb = -0.1; int initSelected = -1; auto bargains_i = brgns[i]; int initBgnNdx = 0; auto initActr = -1; auto rcvrActr = -1; //uint64_t bgID = 0; // tag uninitialized value int countDown = 2; // Stop iterating if cases for i:i and i:j processed for (auto bg : bargains_i) { assert(nullptr != bg); if (bg->actInit == bg->actRcvr) { // For SQ case initActr = model->actrNdx(bg->actInit); rcvrActr = initActr; initProb = (actorBargains[initActr])(initBgnNdx, 0); initSelected = initBgnNdx == actorMaxBrgNdx[initActr] ? 1 : 0; updateBargn(bg->getID(), initActr, initProb, initSelected, rcvrActr, -1.0, 0); if (0 == --countDown) { break; } } else { if (ai == bg->actInit) { // this bargain is initiated by current actor initActr = model->actrNdx(bg->actInit); initProb = (actorBargains[initActr])(initBgnNdx, 0); initSelected = initBgnNdx == actorMaxBrgNdx[initActr] ? 1 : 0; rcvrActr = model->actrNdx(bg->actRcvr); // Get the bargains of receiver actor auto brgnRcvr = brgns[rcvrActr]; int rcvrBgNdx = 0; double rcvrProb = -1.0; int rcvrSelected = -1; for (auto bgRcv : brgnRcvr) { assert(nullptr != bgRcv); if (ai == bgRcv->actInit) { rcvrProb = (actorBargains[rcvrActr])(rcvrBgNdx, 0); // Check if it is the selected bargain for receiver actor rcvrSelected = actorMaxBrgNdx[rcvrActr] == rcvrBgNdx ? 1 : 0; --countDown; updateBargn(bg->getID(), initActr, initProb, initSelected, rcvrActr, rcvrProb, rcvrSelected); break; } ++rcvrBgNdx; } if (0 == countDown) { break; } } } ++initBgnNdx; } } //model->commitDBTransaction(); return; }
// Handle the reply from a scheduler // int CLIENT_STATE::handle_scheduler_reply( PROJECT* project, char* scheduler_url ) { SCHEDULER_REPLY sr; FILE* f; int retval; unsigned int i; bool signature_valid, update_global_prefs=false, update_project_prefs=false; char buf[1024], filename[256]; std::string old_gui_urls = project->gui_urls; PROJECT* p2; vector<RESULT*>new_results; project->last_rpc_time = now; if (work_fetch.requested_work()) { had_or_requested_work = true; } get_sched_reply_filename(*project, filename, sizeof(filename)); f = fopen(filename, "rb"); if (!f) return ERR_FOPEN; retval = sr.parse(f, project); fclose(f); if (retval) return retval; if (log_flags.sched_ops) { if (work_fetch.requested_work()) { snprintf(buf, sizeof(buf), ": got %d new tasks", (int)sr.results.size()); } else { safe_strcpy(buf, ""); } msg_printf(project, MSG_INFO, "Scheduler request completed%s", buf); } if (log_flags.sched_op_debug) { if (sr.scheduler_version) { msg_printf(project, MSG_INFO, "[sched_op] Server version %d", sr.scheduler_version ); } } // check that master URL is correct // if (strlen(sr.master_url)) { canonicalize_master_url(sr.master_url, sizeof(sr.master_url)); string url1 = sr.master_url; string url2 = project->master_url; downcase_string(url1); downcase_string(url2); if (url1 != url2) { p2 = lookup_project(sr.master_url); if (p2) { msg_printf(project, MSG_USER_ALERT, "You are attached to this project twice. Please remove projects named %s, then add %s", project->project_name, sr.master_url ); } else { msg_printf(project, MSG_USER_ALERT, _("This project is using an old URL. When convenient, remove the project, then add %s"), sr.master_url ); } } } // make sure we don't already have a project of same name // bool dup_name = false; for (i=0; i<projects.size(); i++) { p2 = projects[i]; if (project == p2) continue; if (!strcmp(p2->project_name, project->project_name)) { dup_name = true; break; } } if (dup_name) { msg_printf(project, MSG_INFO, "Already attached to a project named %s (possibly with wrong URL)", project->project_name ); msg_printf(project, MSG_INFO, "Consider detaching this project, then trying again" ); } // show messages from server // bool got_notice = false; for (i=0; i<sr.messages.size(); i++) { USER_MESSAGE& um = sr.messages[i]; int prio = MSG_INFO; if (!strcmp(um.priority.c_str(), "notice")) { prio = MSG_SCHEDULER_ALERT; got_notice = true; } msg_printf(project, prio, "%s", um.message.c_str()); } // if we requested work and didn't get notices, // clear scheduler notices from this project // if (work_fetch.requested_work() && !got_notice) { notices.remove_notices(project, REMOVE_SCHEDULER_MSG); } if (log_flags.sched_op_debug && sr.request_delay) { msg_printf(project, MSG_INFO, "Project requested delay of %.0f seconds", sr.request_delay ); } // if project is down, return error (so that we back off) // and don't do anything else // if (sr.project_is_down) { if (sr.request_delay) { double x = now + sr.request_delay; project->set_min_rpc_time(x, "project requested delay"); } return ERR_PROJECT_DOWN; } // if the scheduler reply includes global preferences, // insert extra elements, write to disk, and parse // if (sr.global_prefs_xml) { // skip this if we have host-specific prefs // and we're talking to an old scheduler // if (!global_prefs.host_specific || sr.scheduler_version >= 507) { retval = save_global_prefs( sr.global_prefs_xml, project->master_url, scheduler_url ); if (retval) { return retval; } update_global_prefs = true; } else { if (log_flags.sched_op_debug) { msg_printf(project, MSG_INFO, "ignoring prefs from old server; we have host-specific prefs" ); } } } // see if we have a new venue from this project // (this must go AFTER the above, since otherwise // global_prefs_source_project() is meaningless) // if (strcmp(project->host_venue, sr.host_venue)) { safe_strcpy(project->host_venue, sr.host_venue); msg_printf(project, MSG_INFO, "New computer location: %s", sr.host_venue); update_project_prefs = true; #ifdef USE_NET_PREFS if (project == global_prefs_source_project()) { safe_strcpy(main_host_venue, sr.host_venue); update_global_prefs = true; } #endif } if (update_global_prefs) { read_global_prefs(); } // deal with project preferences (should always be there) // If they've changed, write to account file, // then parse to get our venue, and pass to running apps // if (sr.project_prefs_xml) { if (strcmp(project->project_prefs.c_str(), sr.project_prefs_xml)) { project->project_prefs = string(sr.project_prefs_xml); update_project_prefs = true; } } // the account file has GUI URLs and project prefs. // rewrite if either of these has changed // if (project->gui_urls != old_gui_urls || update_project_prefs) { retval = project->write_account_file(); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't write account file: %s", boincerror(retval) ); return retval; } } if (update_project_prefs) { project->parse_account_file(); project->parse_preferences_for_user_files(); active_tasks.request_reread_prefs(project); } // show notice if we can't possibly get work from this project. // This must come after parsing project prefs // project->show_no_work_notice(); // if the scheduler reply includes a code-signing key, // accept it if we don't already have one from the project. // Otherwise verify its signature, using the key we already have. // if (sr.code_sign_key) { if (!strlen(project->code_sign_key)) { safe_strcpy(project->code_sign_key, sr.code_sign_key); } else { if (sr.code_sign_key_signature) { retval = check_string_signature2( sr.code_sign_key, sr.code_sign_key_signature, project->code_sign_key, signature_valid ); if (!retval && signature_valid) { safe_strcpy(project->code_sign_key, sr.code_sign_key); } else { msg_printf(project, MSG_INTERNAL_ERROR, "New code signing key doesn't validate" ); } } else { msg_printf(project, MSG_INTERNAL_ERROR, "Missing code sign key signature" ); } } } // copy new entities to client state // for (i=0; i<sr.apps.size(); i++) { APP* app = lookup_app(project, sr.apps[i].name); if (app) { // update app attributes; they may have changed on server // safe_strcpy(app->user_friendly_name, sr.apps[i].user_friendly_name); app->non_cpu_intensive = sr.apps[i].non_cpu_intensive; app->fraction_done_exact = sr.apps[i].fraction_done_exact; } else { app = new APP; *app = sr.apps[i]; retval = link_app(project, app); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle application %s in scheduler reply", app->name ); delete app; } else { apps.push_back(app); } } } FILE_INFO* fip; for (i=0; i<sr.file_infos.size(); i++) { fip = lookup_file_info(project, sr.file_infos[i].name); if (fip) { fip->merge_info(sr.file_infos[i]); } else { fip = new FILE_INFO; *fip = sr.file_infos[i]; if (fip->sticky_lifetime) { fip->sticky_expire_time = now + fip->sticky_lifetime; } retval = link_file_info(project, fip); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle file %s in scheduler reply", fip->name ); delete fip; } else { file_infos.push_back(fip); } } } for (i=0; i<sr.file_deletes.size(); i++) { fip = lookup_file_info(project, sr.file_deletes[i].c_str()); if (fip) { if (log_flags.file_xfer_debug) { msg_printf(project, MSG_INFO, "[file_xfer_debug] Got server request to delete file %s", fip->name ); } fip->sticky = false; } } for (i=0; i<sr.app_versions.size(); i++) { if (project->anonymous_platform) { msg_printf(project, MSG_INTERNAL_ERROR, "App version returned from anonymous platform project; ignoring" ); continue; } APP_VERSION& avpp = sr.app_versions[i]; if (strlen(avpp.platform) == 0) { safe_strcpy(avpp.platform, get_primary_platform()); } else { if (!is_supported_platform(avpp.platform)) { msg_printf(project, MSG_INTERNAL_ERROR, "App version has unsupported platform %s", avpp.platform ); continue; } } if (avpp.missing_coproc) { msg_printf(project, MSG_INTERNAL_ERROR, "App version uses non-existent %s GPU", avpp.missing_coproc_name ); } APP* app = lookup_app(project, avpp.app_name); if (!app) { msg_printf(project, MSG_INTERNAL_ERROR, "Missing app %s", avpp.app_name ); continue; } APP_VERSION* avp = lookup_app_version( app, avpp.platform, avpp.version_num, avpp.plan_class ); if (avp) { // update app version attributes in case they changed on server // avp->avg_ncpus = avpp.avg_ncpus; avp->max_ncpus = avpp.max_ncpus; avp->flops = avpp.flops; safe_strcpy(avp->cmdline, avpp.cmdline); avp->gpu_usage = avpp.gpu_usage; strlcpy(avp->api_version, avpp.api_version, sizeof(avp->api_version)); avp->dont_throttle = avpp.dont_throttle; avp->needs_network = avpp.needs_network; // if we had download failures, clear them // avp->clear_errors(); continue; } avp = new APP_VERSION; *avp = avpp; retval = link_app_version(project, avp); if (retval) { delete avp; continue; } app_versions.push_back(avp); } for (i=0; i<sr.workunits.size(); i++) { if (lookup_workunit(project, sr.workunits[i].name)) continue; WORKUNIT* wup = new WORKUNIT; *wup = sr.workunits[i]; wup->project = project; retval = link_workunit(project, wup); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle task %s in scheduler reply", wup->name ); delete wup; continue; } wup->clear_errors(); workunits.push_back(wup); } double est_rsc_runtime[MAX_RSC]; for (int j=0; j<coprocs.n_rsc; j++) { est_rsc_runtime[j] = 0; } for (i=0; i<sr.results.size(); i++) { RESULT* rp2 = lookup_result(project, sr.results[i].name); if (rp2) { // see if project wants to change the job's deadline // if (sr.results[i].report_deadline != rp2->report_deadline) { rp2->report_deadline = sr.results[i].report_deadline; } else { msg_printf(project, MSG_INTERNAL_ERROR, "Already have task %s\n", sr.results[i].name ); } continue; } RESULT* rp = new RESULT; *rp = sr.results[i]; retval = link_result(project, rp); if (retval) { msg_printf(project, MSG_INTERNAL_ERROR, "Can't handle task %s in scheduler reply", rp->name ); delete rp; continue; } if (strlen(rp->platform) == 0) { safe_strcpy(rp->platform, get_primary_platform()); rp->version_num = latest_version(rp->wup->app, rp->platform); } rp->avp = lookup_app_version( rp->wup->app, rp->platform, rp->version_num, rp->plan_class ); if (!rp->avp) { msg_printf(project, MSG_INTERNAL_ERROR, "No app version found for app %s platform %s ver %d class %s; discarding %s", rp->wup->app->name, rp->platform, rp->version_num, rp->plan_class, rp->name ); delete rp; continue; } if (rp->avp->missing_coproc) { msg_printf(project, MSG_INTERNAL_ERROR, "Missing coprocessor for task %s; aborting", rp->name ); rp->abort_inactive(EXIT_MISSING_COPROC); } else { rp->set_state(RESULT_NEW, "handle_scheduler_reply"); int rt = rp->avp->gpu_usage.rsc_type; if (rt > 0) { est_rsc_runtime[rt] += rp->estimated_runtime(); gpus_usable = true; // trigger a check of whether GPU is actually usable } else { est_rsc_runtime[0] += rp->estimated_runtime(); } } rp->wup->version_num = rp->version_num; rp->received_time = now; new_results.push_back(rp); results.push_back(rp); } sort_results(); if (log_flags.sched_op_debug) { if (sr.results.size()) { for (int j=0; j<coprocs.n_rsc; j++) { msg_printf(project, MSG_INFO, "[sched_op] estimated total %s task duration: %.0f seconds", rsc_name_long(j), est_rsc_runtime[j]/time_stats.availability_frac(j) ); } } } // update records for ack'ed results // for (i=0; i<sr.result_acks.size(); i++) { if (log_flags.sched_op_debug) { msg_printf(project, MSG_INFO, "[sched_op] handle_scheduler_reply(): got ack for task %s\n", sr.result_acks[i].name ); } RESULT* rp = lookup_result(project, sr.result_acks[i].name); if (rp) { rp->got_server_ack = true; } else { msg_printf(project, MSG_INTERNAL_ERROR, "Got ack for task %s, but can't find it", sr.result_acks[i].name ); } } // handle result abort requests // for (i=0; i<sr.result_abort.size(); i++) { RESULT* rp = lookup_result(project, sr.result_abort[i].name); if (rp) { ACTIVE_TASK* atp = lookup_active_task_by_result(rp); if (atp) { atp->abort_task(EXIT_ABORTED_BY_PROJECT, "aborted by project - no longer usable" ); } else { rp->abort_inactive(EXIT_ABORTED_BY_PROJECT); } } else { msg_printf(project, MSG_INTERNAL_ERROR, "Server requested abort of unknown task %s", sr.result_abort[i].name ); } } for (i=0; i<sr.result_abort_if_not_started.size(); i++) { RESULT* rp = lookup_result(project, sr.result_abort_if_not_started[i].name); if (!rp) { msg_printf(project, MSG_INTERNAL_ERROR, "Server requested conditional abort of unknown task %s", sr.result_abort_if_not_started[i].name ); continue; } if (rp->not_started) { rp->abort_inactive(EXIT_ABORTED_BY_PROJECT); } } // remove acked trickle files // if (sr.message_ack) { remove_trickle_files(project); } if (sr.send_full_workload) { project->send_full_workload = true; } project->dont_use_dcf = sr.dont_use_dcf; project->send_time_stats_log = sr.send_time_stats_log; project->send_job_log = sr.send_job_log; project->trickle_up_pending = false; // The project returns a hostid only if it has created a new host record. // In that case reset RPC seqno // if (sr.hostid) { if (project->hostid) { // if we already have a host ID for this project, // we must have sent it a stale seqno, // which usually means our state file was copied from another host. // So generate a new host CPID. // generate_new_host_cpid(); msg_printf(project, MSG_INFO, "Generated new computer cross-project ID: %s", host_info.host_cpid ); } //msg_printf(project, MSG_INFO, "Changing host ID from %d to %d", project->hostid, sr.hostid); project->hostid = sr.hostid; project->rpc_seqno = 0; } #ifdef ENABLE_AUTO_UPDATE if (sr.auto_update.present) { if (!sr.auto_update.validate_and_link(project)) { auto_update = sr.auto_update; } } #endif project->project_files = sr.project_files; project->link_project_files(); project->create_project_file_symlinks(); if (log_flags.state_debug) { msg_printf(project, MSG_INFO, "[state] handle_scheduler_reply(): State after handle_scheduler_reply():" ); print_summary(); } // the following must precede the backoff and request_delay checks, // since it overrides them // if (sr.next_rpc_delay) { project->next_rpc_time = now + sr.next_rpc_delay; } else { project->next_rpc_time = 0; } work_fetch.handle_reply(project, &sr, new_results); project->nrpc_failures = 0; project->min_rpc_time = 0; if (sr.request_delay) { double x = now + sr.request_delay; project->set_min_rpc_time(x, "requested by project"); } if (sr.got_rss_feeds) { handle_sr_feeds(sr.sr_feeds, project); } update_trickle_up_urls(project, sr.trickle_up_urls); // garbage collect in case the project sent us some irrelevant FILE_INFOs; // avoid starting transfers for them // gstate.garbage_collect_always(); // if the user provided app_config.xml for this project, // apply it to any app versions we just got // project->app_configs.config_app_versions(project, false); // make sure we don't set no_rsc_apps[] for all processor types // if (!project->anonymous_platform) { project->check_no_rsc_apps(); } return 0; }
void SMPState::recordProbEduChlg() const { size_t basePos = -1; size_t digCount = 0; size_t nextCommaPos = string::npos; auto nextActor = [&basePos, &nextCommaPos](string &actors) { basePos = nextCommaPos + 1; nextCommaPos = actors.find_first_of(",", basePos); size_t digCount = nextCommaPos - basePos; return actors.substr(basePos, digCount); }; QSqlQuery query = model->getQuery(); string qsql; qsql = string("INSERT INTO TPProbVictLoss " "(ScenarioId, Turn_t, Est_h, Init_i, ThrdP_k, Rcvr_j, Prob, Util_V, Util_L) " "VALUES (" "'") + model->getScenarioID() + "'," " :t, :h, :i, :thrdp_k, :j, :prob, :util_v, :util_l )"; query.prepare(QString::fromStdString(qsql)); //model->beginDBTransaction(); for (auto &tpv : tpvData) { auto thij = tpv.first; auto tpvArray = tpv.second; basePos = -1; digCount = 0; nextCommaPos = string::npos; auto t = std::stoi(nextActor(thij)); auto h = std::stoi(nextActor(thij)); auto i = std::stoi(nextActor(thij)); auto j = std::stoi(nextActor(thij)); query.bindValue(":t", t); query.bindValue(":h", h); query.bindValue(":i", i); query.bindValue(":j", j); const unsigned int na = model->numAct; for (int tpk = 0; tpk < na; tpk++) { // third party voter, tpk query.bindValue(":thrdp_k", tpk); // bind the data query.bindValue(":prob", tpvArray(tpk, 0)); query.bindValue(":util_v", tpvArray(tpk, 1)); query.bindValue(":util_l", tpvArray(tpk, 2)); // actually record it if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } } qsql = string("INSERT INTO ProbVict " "(ScenarioId, Turn_t, Est_h,Init_i,Rcvr_j,Prob) VALUES ('") + model->getScenarioID() + "', :t, :h, :i, :j, :phij)"; query.prepare(QString::fromStdString(qsql)); for (auto &phijVal : phijData) { auto thij = phijVal.first; auto phij = phijVal.second; basePos = -1; digCount = 0; nextCommaPos = string::npos; auto t = std::stoi(nextActor(thij)); auto h = std::stoi(nextActor(thij)); auto i = std::stoi(nextActor(thij)); auto j = std::stoi(nextActor(thij)); query.bindValue(":t", t); query.bindValue(":h", h); query.bindValue(":i", i); query.bindValue(":j", j); query.bindValue(":phij", phij); // actually record it if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } qsql = string("INSERT INTO UtilChlg " "(ScenarioId, Turn_t, Est_h,Aff_k,Init_i,Rcvr_j,Util_SQ,Util_Vict,Util_Cntst,Util_Chlg) VALUES ('") + model->getScenarioID() + "', :t, :h, :k, :i, :j, :euSQ, :euVict, :euCntst, :euChlg)"; query.prepare(QString::fromStdString(qsql)); for (auto &euVal : euData) { auto thkij = euVal.first; basePos = -1; digCount = 0; nextCommaPos = string::npos; auto t = std::stoi(nextActor(thkij)); auto h = std::stoi(nextActor(thkij)); auto k = std::stoi(nextActor(thkij)); auto i = std::stoi(nextActor(thkij)); auto j = std::stoi(nextActor(thkij)); auto eu = euVal.second; auto euSQ = eu[0]; auto euVict = eu[1]; auto euCntst = eu[2]; auto euChlg = eu[3]; query.bindValue(":t", t); query.bindValue(":h", h); query.bindValue(":k", k); query.bindValue(":i", i); query.bindValue(":j", j); query.bindValue(":euSQ", euSQ); query.bindValue(":euVict", euVict); query.bindValue(":euCntst", euCntst); query.bindValue(":euChlg", euChlg); // actually record it if (!query.exec()) { LOG(INFO) << query.lastError().text().toStdString(); assert(false); } } //model->commitDBTransaction(); return; }
int main() { ifstream archivo_notas("notas.dat", ios::in); if( !archivo_notas ) { cerr << "No se pudo abrir el archivo"; exit(1); } float nota1, nota2, nota3, codigo, promedio; int num = 0; char sep; string nombre; cout << left << setw(4) << "Cod" << left << setw(16) << "Nombre" << right << setw(8) << "Nota 1" << setw(8) << "Nota 2" << setw(8) << "Nota 3" << setw(10) << "Promedio" << endl; while(archivo_notas >> codigo >> nombre >> nota1 >> nota2 >> nota3) { promedio = (nota1 + nota2 + nota3) / 3; cout << left << setw(4) << codigo << setw(16) << nombre << right << setw(8) << fixed << setprecision(2) << nota1 << setw(8) << nota2 << setw(8) << nota3 << setw(10) << promedio << endl; ++num; } cout << endl << "Total notas procesadas: " << num << endl; return 0; }
inline typename boost::math::tools::promote_args<T>::type inv_cloglog(T x) { using std::exp; return exp(-exp(x)); }
EntitySystem::EntitySystem(EntitySystem&& other) : EntitySystem() { swap(*this, other); }
static int try_to_ul_wh(const string& orig_file_name) { directoryrec d = {}; int i1, i2, i4, key, ok = 0, dn = 0; uploadsrec u, u1; string file_name = orig_file_name; StringRemoveWhitespace(&file_name); if (!okfn(file_name)) { t2u_error(file_name, "Bad filename"); // bad filename return 1; } bout.cls(); bout.nl(3); bool done = false; if (session()->user()->IsRestrictionValidate() || session()->user()->IsRestrictionUpload() || (syscfg.sysconfig & sysconfig_all_sysop)) { dn = (syscfg.newuploads < session()->directories.size()) ? syscfg.newuploads : 0; } else { char temp[10]; // The hangup check is below so uploads get uploaded even on hangup done = false; while (!done) { if (hangup) { if (syscfg.newuploads < session()->directories.size()) { dn = syscfg.newuploads; } else { dn = 0; } done = true; } else { // The sleep_for used to be a wait_sec_or_hit( 1 ) sleep_for(milliseconds(500)); bout << "\r\nUpload " << file_name << " to which dir? <CR>=0 ?=List \r\n"; input(temp, 5, true); StringTrim(temp); if (temp[0] == '?') { dirlist(1); } else if (!temp[0]) { dn = 0; done = true; } else { int x = atoi(temp); if (session()->udir[x].subnum >= 0) { dliscan1(session()->udir[x].subnum); d = session()->directories[dn]; if ((d.mask & mask_no_uploads) && (!dcs())) { bout << "Can't upload there...\r\n"; pausescr(); } else { dn = session()->udir[x].subnum; done = true; } } } } } } dliscan1(dn); d = session()->directories[dn]; if (session()->numf >= d.maxfiles) { t2u_error(file_name, "This directory is currently full."); return 1; } if ((d.mask & mask_no_uploads) && (!dcs())) { t2u_error(file_name, "Uploads are not allowed to this directory."); return 1; } if (!is_uploadable(file_name.c_str())) { if (so()) { bout.nl(); bout << "|#5In filename database - add anyway? "; if (!yesno()) { t2u_error(file_name, "|#6File either already here or unwanted."); return 1; } } else { t2u_error(file_name, "|#6File either already here or unwanted."); return 1; } } string s = file_name; align(&s); if (contains(s, '?')) { t2u_error(file_name, "Contains wildcards"); return 1; } if (d.mask & mask_archive) { ok = 0; string s1; for (size_t i = 0; i < MAX_ARCS; i++) { if (session()->arcs[i].extension[0] && session()->arcs[i].extension[0] != ' ') { if (!s1.empty()) s1 += ", "; s1 += session()->arcs[i].extension; if (wwiv::strings::IsEquals(s.c_str() + 9, session()->arcs[i].extension)) { ok = 1; } } } if (!ok) { bout.nl(); bout << "Sorry, all uploads to this directory must be archived. Supported types are:\r\n"; bout << s1; bout.nl(2); t2u_error(file_name, "Unsupported archive"); return 1; } } strcpy(u.filename, s.c_str()); u.ownerusr = static_cast<uint16_t>(session()->usernum); u.ownersys = 0; u.numdloads = 0; u.unused_filetype = 0; u.mask = 0; const string unn = session()->names()->UserName(session()->usernum); strncpy(u.upby, unn.c_str(), sizeof(u.upby)); u.upby[36] = '\0'; strcpy(u.date, date()); if (File::Exists(StrCat(d.path, s))) { if (dcs()) { bout.nl(2); bout << "File already exists.\r\n|#5Add to database anyway? "; if (yesno() == 0) { t2u_error(file_name, "That file is already here."); return 1; } } else { t2u_error(file_name, "That file is already here."); return 1; } } if (ok && (!session()->HasConfigFlag(OP_FLAGS_FAST_SEARCH))) { bout.nl(); bout << "Checking for same file in other session()->directories...\r\n\n"; i2 = 0; for (size_t i = 0; (i < session()->directories.size()) && (session()->udir[i].subnum != -1); i++) { string s1 = StrCat("Scanning ", session()->directories[session()->udir[i].subnum].name); i4 = s1.size(); //s1 += string(i3 - i2, ' '); i2 = i4; bout << s1; bout.bputch('\r'); dliscan1(session()->udir[i].subnum); i1 = recno(u.filename); if (i1 >= 0) { bout.nl(); bout << "Same file found on " << session()->directories[session()->udir[i].subnum].name << wwiv::endl; if (dcs()) { bout.nl(); bout << "|#5Upload anyway? "; if (!yesno()) { t2u_error(file_name, "That file is already here."); return 1; } bout.nl(); } else { t2u_error(file_name, "That file is already here."); return 1; } } } bout << string(i2, ' ') << "\r"; dliscan1(dn); bout.nl(); } const string src = StrCat(session()->batch_directory(), file_name); const string dest = StrCat(d.path, file_name); if (File::Exists(dest)) { File::Remove(dest); } // s1 and s2 should remain set,they are used below movefile(src, dest, true); strcpy(u.description, "NO DESCRIPTION GIVEN"); bool file_id_avail = get_file_idz(&u, dn); done = false; while (!done && !hangup && !file_id_avail) { bool abort = false; bout.cls(); bout.nl(); bout << "|#1Upload going to |#7" << d.name << "\r\n\n"; bout << " |#1Filename |01: |#7" << file_name << wwiv::endl; bout << "|#2A|#7] |#1Description |01: |#7" << u.description << wwiv::endl; bout << "|#2B|#7] |#1Modify extended description\r\n\n"; print_extended(u.filename, &abort, 10, 0); bout << "|#2<|#7CR|#2> |#1to continue, |#7Q|#1 to abort upload: "; key = onek("\rQABC", true); switch (key) { case 'Q': bout << "Are you sure, file will be lost? "; if (yesno()) { t2u_error(file_name, "Changed mind"); // move file back to batch dir movefile(dest, src, true); return 1; } break; case 'A': bout.nl(); bout << "Please enter a one line description.\r\n:"; inputl(u.description, 58); break; case 'B': { bout.nl(); string ss = read_extended_description(u.filename); bout << "|#5Modify extended description? "; if (yesno()) { bout.nl(); if (!ss.empty()) { bout << "|#5Delete it? "; if (yesno()) { delete_extended_description(u.filename); u.mask &= ~mask_extended; } else { u.mask |= mask_extended; modify_extended_description(&ss, session()->directories[session()->current_user_dir().subnum].name); if (!ss.empty()) { delete_extended_description(u.filename); add_extended_description(u.filename, ss); } } } else { modify_extended_description(&ss, session()->directories[session()->current_user_dir().subnum].name); if (!ss.empty()) { add_extended_description(u.filename, ss); u.mask |= mask_extended; } else { u.mask &= ~mask_extended; } } } else if (!ss.empty()) { u.mask |= mask_extended; } else { u.mask &= ~mask_extended; } } break; case '\r': bout.nl(); done = true; } } bout.nl(3); File file(d.path, s); if (!file.Open(File::modeBinary | File::modeReadOnly)) { // dos error, file not found if (u.mask & mask_extended) { delete_extended_description(u.filename); } t2u_error(file_name, "DOS error - File not found."); return 1; } if (!syscfg.upload_cmd.empty()) { file.Close(); bout << "Please wait...\r\n"; if (!check_ul_event(dn, &u)) { if (u.mask & mask_extended) { delete_extended_description(u.filename); } t2u_error(file_name, "Failed upload event"); return 1; } else { file.Open(File::modeBinary | File::modeReadOnly); } } long lFileLength = file.GetLength(); u.numbytes = lFileLength; file.Close(); session()->user()->SetFilesUploaded(session()->user()->GetFilesUploaded() + 1); time_t tCurrentDate = time(nullptr); u.daten = static_cast<uint32_t>(tCurrentDate); File fileDownload(session()->download_filename_); fileDownload.Open(File::modeBinary | File::modeCreateFile | File::modeReadWrite); for (int i = session()->numf; i >= 1; i--) { FileAreaSetRecord(fileDownload, i); fileDownload.Read(&u1, sizeof(uploadsrec)); FileAreaSetRecord(fileDownload, i + 1); fileDownload.Write(&u1, sizeof(uploadsrec)); } FileAreaSetRecord(fileDownload, 1); fileDownload.Write(&u, sizeof(uploadsrec)); ++session()->numf; FileAreaSetRecord(fileDownload, 0); fileDownload.Read(&u1, sizeof(uploadsrec)); u1.numbytes = session()->numf; u1.daten = static_cast<uint32_t>(tCurrentDate); FileAreaSetRecord(fileDownload, 0); fileDownload.Write(&u1, sizeof(uploadsrec)); fileDownload.Close(); modify_database(u.filename, true); session()->user()->SetUploadK(session()->user()->GetUploadK() + bytes_to_k(u.numbytes)); WStatus *pStatus = session()->status_manager()->BeginTransaction(); pStatus->IncrementNumUploadsToday(); pStatus->IncrementFileChangedFlag(WStatus::fileChangeUpload); session()->status_manager()->CommitTransaction(pStatus); sysoplog() << StringPrintf("+ \"%s\" uploaded on %s", u.filename, session()->directories[dn].name); return 0; // This means success }