IQRouterBaseline::IQRouterBaseline( const Configuration& config, Module *parent, const string & name, int id, int inputs, int outputs ) : IQRouterBase( config, parent, name, id, inputs, outputs ) { string alloc_type; string arb_type; int iters; // Alloc allocators config.GetStr( "vc_allocator", alloc_type ); config.GetStr( "vc_alloc_arb_type", arb_type ); iters = config.GetInt( "vc_alloc_iters" ); if(iters == 0) iters = config.GetInt("alloc_iters"); _vc_allocator = Allocator::NewAllocator( this, "vc_allocator", alloc_type, _vcs*_inputs, _vcs*_outputs, iters, arb_type ); if ( !_vc_allocator ) { cout << "ERROR: Unknown vc_allocator type " << alloc_type << endl; exit(-1); } config.GetStr( "sw_allocator", alloc_type ); config.GetStr( "sw_alloc_arb_type", arb_type ); iters = config.GetInt("sw_alloc_iters"); if(iters == 0) iters = config.GetInt("alloc_iters"); _sw_allocator = Allocator::NewAllocator( this, "sw_allocator", alloc_type, _inputs*_input_speedup, _outputs*_output_speedup, iters, arb_type ); if ( !_sw_allocator ) { cout << "ERROR: Unknown sw_allocator type " << alloc_type << endl; exit(-1); } _speculative = config.GetInt( "speculative" ) ; if ( _speculative >= 2 ) { string filter_spec_grants; config.GetStr("filter_spec_grants", filter_spec_grants); if(filter_spec_grants == "any_nonspec_gnts") { _filter_spec_grants = 0; } else if(filter_spec_grants == "confl_nonspec_reqs") { _filter_spec_grants = 1; } else if(filter_spec_grants == "confl_nonspec_gnts") { _filter_spec_grants = 2; } else assert(false); _spec_sw_allocator = Allocator::NewAllocator( this, "spec_sw_allocator", alloc_type, _inputs*_input_speedup, _outputs*_output_speedup, iters, arb_type ); if ( !_spec_sw_allocator ) { cout << "ERROR: Unknown sw_allocator type " << alloc_type << endl; exit(-1); } } _sw_rr_offset.resize(_inputs*_input_speedup); }
bool ConfigurationHolder::saveBooleanToConfigFile(const Configuration & configObject) const { const WCHAR *boolValue = configObject.isTrue() ? L"1" : L"0"; BOOL ret = WritePrivateProfileString(CONFIG_FILE_SECTION_NAME, configObject.getName(), boolValue, configPath); return ret == TRUE; }
void testGetLocationUpdateInterval(Configuration& configuration, Logger& logger) { logger.info("Testing Configuration::getLocationUpdateInterval() method"); EXPECT_EQ(20, configuration.getLocationUpdateInterval()); }
/** * Get the default backend from config.xml, use UPnP to find it. * * Sets a string if there any connection problems */ bool MythContextPrivate::DefaultUPnP(QString &error) { Configuration *pConfig = new XmlConfiguration("config.xml"); QString loc = "MCP::DefaultUPnP() - "; QString localHostName = pConfig->GetValue(kDefaultBE + "LocalHostName", ""); QString PIN = pConfig->GetValue(kDefaultPIN, ""); QString USN = pConfig->GetValue(kDefaultUSN, ""); delete pConfig; if (USN.isEmpty()) { VERBOSE(VB_UPNP, loc + "No default UPnP backend"); return false; } VERBOSE(VB_UPNP, loc + "config.xml has default " + QString("PIN '%1' and host USN: %2") .arg(PIN).arg(USN)); // ---------------------------------------------------------------------- SSDP::Instance()->PerformSearch( gBackendURI ); // ---------------------------------------------------------------------- // We need to give the server time to respond... // ---------------------------------------------------------------------- DeviceLocation *pDevLoc = NULL; QTime timer; for (timer.start(); timer.elapsed() < 5000; usleep(25000)) { pDevLoc = SSDP::Instance()->Find( gBackendURI, USN ); if (pDevLoc) break; putchar('.'); } putchar('\n'); // ---------------------------------------------------------------------- if (!pDevLoc) { error = "Cannot find default UPnP backend"; return false; } if (UPnPconnect(pDevLoc, PIN)) { if (localHostName.length()) { m_DBparams.localHostName = localHostName; m_DBparams.localEnabled = true; gCoreContext->GetDB()->SetDatabaseParams(m_DBparams); } return true; } error = "Cannot connect to default backend via UPnP. Wrong saved PIN?"; return false; }
bool ConfigurationHolder::saveStringToConfigFile(const Configuration & configObject) const { BOOL ret = WritePrivateProfileString(CONFIG_FILE_SECTION_NAME, configObject.getName(), configObject.getString(), configPath); return ret == TRUE; }
AssistantDialog::AssistantDialog( const QStringList &playableFileTypes, bool saveSupported, Collections::CollectionLocationDelegate::OperationType operation, const QString &destCollectionName, const Configuration &prevConfiguration, QWidget *parent ) : KDialog( parent, Qt::Dialog ) , m_configuration( JUST_COPY ) , m_save( false ) , m_playableFileTypes( playableFileTypes ) { DEBUG_BLOCK Q_UNUSED( destCollectionName ) // keep it in signature, may be useful in future QWidget *uiBase = new QWidget( this ); setMainWidget( uiBase); ui.setupUi( uiBase ); setModal( true ); setWindowTitle( i18n( "Transcode Tracks" ) ); setMinimumSize( 590, 340 ); setMaximumWidth( 590 ); setSizePolicy( QSizePolicy::Preferred, QSizePolicy::MinimumExpanding ); setButtons( Ok|Cancel ); button( Ok )->setText( i18n( "Transc&ode" ) ); button( Ok )->setEnabled( false ); QString explanatoryText; KIcon justCopyIcon; QString justCopyText; QString justCopyDescription; switch( operation ) { case Collections::CollectionLocationDelegate::Copy: explanatoryText = i18n( "While copying, you can choose to transcode your music files into another " "format with an encoder (codec). This can be done to save space or to " "make your files readable by a portable music player or a particular " "software program." ); justCopyIcon = KIcon( "edit-copy" ); justCopyText = i18n( "&Copy" ); justCopyDescription = i18n( "Just copy the tracks without transcoding them." ); break; case Collections::CollectionLocationDelegate::Move: explanatoryText = i18n( "While moving, you can choose to transcode your music files into another " "format with an encoder (codec). This can be done to save space or to " "make your files readable by a portable music player or a particular " "software program. Only successfully transcoded files will be removed " "from their original location." ); justCopyIcon = KIcon( "go-jump" ); // Dolphin uses this icon for "move" justCopyText = i18n( "&Move" ); justCopyDescription = i18n( "Just move the tracks without transcoding them." ); break; } ui.explanatoryTextLabel->setText( explanatoryText ); ui.justCopyButton->setIcon( justCopyIcon ); ui.justCopyButton->setText( justCopyText ); ui.justCopyButton->setDescription( justCopyDescription ); ui.justCopyButton->setMinimumHeight( ui.justCopyButton->iconSize().height() + 2*10 ); //we make room for the pretty icon connect( ui.justCopyButton, SIGNAL(clicked()), this, SLOT(onJustCopyClicked()) ); //Let's set up the codecs page... populateFormatList(); connect( ui.formatListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(onFormatSelect(QListWidgetItem*)) ); ui.formatIconLabel->hide(); ui.formatNameLabel->hide(); connect( button( Ok ), SIGNAL(clicked()), this, SLOT(onTranscodeClicked()) ); ui.rememberCheckBox->setChecked( m_save ); ui.rememberCheckBox->setEnabled( saveSupported ); connect( ui.rememberCheckBox, SIGNAL(toggled(bool)), this, SLOT(onRememberToggled(bool)) ); switch( prevConfiguration.trackSelection() ) //restore the previously selected TrackSelection radio button { case Configuration::TranscodeUnlessSameType: ui.transcodeUnlessSameTypeRadioButton->setChecked( true ); break; case Configuration::TranscodeOnlyIfNeeded: ui.transcodeOnlyIfNeededRadioButton->setChecked( true ); break; case Configuration::TranscodeAll: ui.transcodeAllRadioButton->setChecked( true ); } ui.transcodeAllRadioButton->setEnabled( false ); ui.transcodeUnlessSameTypeRadioButton->setEnabled( false ); ui.transcodeOnlyIfNeededRadioButton->setEnabled( false ); }
string Logging::getLogDir(const Configuration& conf) { return conf.get("log_dir", ""); }
int main(int argc, char** argv) { GOOGLE_PROTOBUF_VERIFY_VERSION; Configurator configurator; // The following options are executable specific (e.g., since we // only have one instance of libprocess per execution, we only want // to advertise the port and ip option once, here). configurator.addOption<int>("port", 'p', "Port to listen on", 5050); configurator.addOption<string>("ip", "IP address to listen on"); #ifdef MESOS_WEBUI configurator.addOption<int>("webui_port", "Web UI port", 8080); #endif configurator.addOption<string>( "master", 'm', "May be one of:\n" " host:port\n" " zk://host1:port1,host2:port2,.../path\n" " zk://username:password@host1:port1,host2:port2,.../path\n" " file://path/to/file (where file contains one of the above)"); if (argc == 2 && string("--help") == argv[1]) { usage(argv[0], configurator); exit(1); } Configuration conf; try { conf = configurator.load(argc, argv); } catch (const ConfigurationException& e) { cerr << "Configuration error: " << e.what() << endl; exit(1); } // Initialize libprocess. process::initialize(); if (!conf.contains("master")) { cerr << "Missing required option --master (-m)" << endl; usage(argv[0], configurator); exit(1); } // TODO(vinod): Parse 'master' when we add ZooKeeper support. UPID master(conf["master"]); if (!master) { cerr << "Could not parse --master=" << conf["master"] << endl; usage(argv[0], configurator); exit(1); } if (!conf.contains("name")) { // TODO(benh): Need to add '--name' as an option. cerr << "Missing --name (-n)" << endl; usage(argv[0], configurator); exit(1); } LOG(INFO) << "Submitting scheduler ..."; Protocol<SubmitSchedulerRequest, SubmitSchedulerResponse> submit; SubmitSchedulerRequest request; request.set_name(conf["name"]); Future<SubmitSchedulerResponse> future = submit(master, request); future.await(5.0); if (future.isReady()) { if (future.get().okay()) { cout << "Scheduler submitted successfully" << endl; } else { cout << "Failed to submit scheduler" << endl; } } else { cout << "Timed out waiting for response from submitting scheduler" << endl; } return 0; }
//================================================================================================ // // Load() // // - Called by Main_OnInitDialog() // /// <summary> /// Attempts to load the config-file. Returns true if successful, false if not /// </summary> /// <remarks> /// If we're unsuccessful, the caller will assume this is the first time we've run the program /// and will run through the startup-wizard. /// </remarks> // bool Configuration::Load() { TRACEI("[Configuration] [Load] > Entering routine."); TiXmlDocument doc; const path pb=path::base_dir()/_T("peerblock.conf"); const path oldpb=path::base_dir()/_T("peerblock.conf.bak"); const path pg2=path::base_dir()/_T("pg2.conf"); vector<path> files; files.push_back(pb); files.push_back(oldpb); files.push_back(pg2); bool loaded = false; bool isDirty = false; for(vector<path>::iterator itr = files.begin(); itr != files.end() && !loaded; ++itr) { { HANDLE fp = NULL; HANDLE map = NULL; const void *view = NULL; if (!LoadFile((*itr).file_str().c_str(), &fp, &map, &view)) // first try to find a PeerBlock file { tstring strBuf = boost::str(tformat(_T("[Configuration] [Load] WARNING: Unable to load configuration file [%1%]")) % (*itr).file_str().c_str() ); TRACEBUFW(strBuf); continue; } tstring strBuf = boost::str(tformat(_T("[Configuration] [Load] Loaded configuration file [%1%]")) % (*itr).file_str().c_str() ); TRACEBUFI(strBuf); boost::shared_ptr<void> fp_safe(fp, CloseHandle); boost::shared_ptr<void> map_safe(map, CloseHandle); boost::shared_ptr<const void> view_safe(view, UnmapViewOfFile); doc.Parse((const char*)view); if(doc.Error()) { TRACEE("[Configuration] [Load] * ERROR: Can't parse xml document"); tstring strBuf = boost::str(tformat(_T("[Configuration] [Load] * - Error: [%1%] (\"%2%\") at row:[%3%] col:[%4%]")) % doc.ErrorId() % doc.ErrorDesc() % doc.ErrorRow() % doc.ErrorCol() ); TRACEBUFE(strBuf); // copy over to .failed path failedFile; failedFile = itr->file_str(); failedFile = failedFile.file_str() + L".failed"; path::copy(*itr, failedFile, true); strBuf = boost::str(tformat(_T("[Configuration] [Load] - Copied failed-parsing config-file to: [%1%]")) % failedFile.file_str() ); TRACEBUFE(strBuf); continue; } } if (*itr == pb) { TRACEI("[Configuration] [Load] found peerblock configuration file"); } else if (*itr == oldpb) { TRACEW("[Configuration] [Load] using last-known-good configuration file"); MessageBox(NULL, IDS_CONFERRTEXT, IDS_CONFERR, MB_ICONWARNING|MB_OK); g_config.Save(_T("peerblock.conf")); // save restored config to regular file } else if (*itr == pg2) { TRACEI("[Configuration] [Load] found old-style pg2 configuration file"); } else // can't find anything, return false so caller can run the startup-wizard { TRACEW("[Configuration] [Load] WARNING: No configuration file found."); return false; } loaded = true; } if (!loaded) { // can't find anything, return false so caller can run the startup-wizard TRACEW("[Configuration] [Load] ERROR: No configuration file loaded!"); return false; } TRACEI("[Configuration] [Load] parsing config root element"); const TiXmlElement *root=doc.RootElement(); if(!root || (strcmp(root->Value(), "PeerGuardian2") && strcmp(root->Value(), "PeerBlock"))) { TRACEI("[Configuration] [Load] ERROR: Not a valid configuration file!"); return false; } TRACEI("[Configuration] [Load] parsing config settings element"); if(const TiXmlElement *settings=root->FirstChildElement("Settings")) { GetChild(settings, "Block", this->Block); if (GetChild(settings, "BlockHttp", this->PortSet.AllowHttp)) this->PortSet.AllowHttp = !this->PortSet.AllowHttp; GetChild(settings, "AllowLocal", this->AllowLocal); GetChild(settings, "CacheCrc", this->CacheCrc); GetChild(settings, "BlinkOnBlock", this->BlinkOnBlock); GetChild(settings, "NotifyOnBlock", this->NotifyOnBlock); GetChild(settings, "LastVersionRun", this->LastVersionRun); // specially-treat RecentBlockWarntime since otherwise TinyXML will save it to the .conf as a hex value int i=(DWORD)RecentBlockWarntime; GetChild(settings, "RecentBlockWarntime", i); this->RecentBlockWarntime=(DWORD)i; GetChild(settings, "ListSanityChecking", this->EnableListSanityChecking); GetChild(settings, "WarningIconForHttpAllow", this->EnableWarningIconForHttpAllow); } TRACEI("[Configuration] [Load] parsing config logging element"); if(const TiXmlElement *logging=root->FirstChildElement("Logging")) { GetChild(logging, "LogSize", this->LogSize); GetChild(logging, "LogAllowed", this->LogAllowed); GetChild(logging, "LogBlocked", this->LogBlocked); GetChild(logging, "ShowAllowed", this->ShowAllowed); GetChild(logging, "Cleanup", this->CleanupType); if(const TiXmlElement *c=logging->FirstChildElement("Cleanup")) { int i=0; if(c->Attribute("Interval", &i)) this->CleanupInterval=(unsigned short)i; } tstring p; if(GetChild(logging, "ArchivePath", p)) this->ArchivePath=p; GetChild(logging, "MaxHistorySize", this->MaxHistorySize); GetChild(logging, "HistoryCheckInterval", this->HistoryCheckInterval); } TRACEI("[Configuration] [Load] parsing config tracelogging element"); if(const TiXmlElement *logging=root->FirstChildElement("TraceLog")) { GetChild(logging, "Enabled", this->TracelogEnabled); GetChild(logging, "Level", this->TracelogLevel); } TRACEI("[Configuration] [Load] parsing config colors element"); if(const TiXmlElement *colors=root->FirstChildElement("Colors")) { GetChild(colors, "ColorCode", this->ColorCode); GetChild(colors, "Blocked", this->BlockedColor); GetChild(colors, "Allowed", this->AllowedColor); GetChild(colors, "Http", this->HttpColor); } TRACEI("[Configuration] [Load] parsing config windowing element"); if(const TiXmlElement *windowing=root->FirstChildElement("Windowing")) { GetChild(windowing, "Main", this->WindowPos); GetChild(windowing, "Update", this->UpdateWindowPos); GetChild(windowing, "ListManager", this->ListManagerWindowPos); GetChild(windowing, "ListEditor", this->ListEditorWindowPos); GetChild(windowing, "History", this->HistoryWindowPos); GetChild(windowing, "StartMinimized", this->StartMinimized); GetChild(windowing, "ShowSplash", this->ShowSplash); GetChild(windowing, "StayHidden", this->StayHidden); GetChild(windowing, "HideOnClose", this->HideOnClose); GetChild(windowing, "HideMain", this->WindowHidden); GetChild(windowing, "AlwaysOnTop", this->AlwaysOnTop); GetChild(windowing, "HideTrayIcon", this->HideTrayIcon); if(const TiXmlElement *hcol=windowing->FirstChildElement("HistoryColumns")) { int cols[6]= {0}; GetChild(hcol, "Time", cols[0]); GetChild(hcol, "Range", cols[1]); GetChild(hcol, "Source", cols[2]); GetChild(hcol, "Destination", cols[3]); GetChild(hcol, "Protocol", cols[4]); GetChild(hcol, "Action", cols[5]); SaveListColumns(cols, this->HistoryColumns); } if(const TiXmlElement *lcol=windowing->FirstChildElement("LogColumns")) { int cols[6]= {0}; GetChild(lcol, "Time", cols[0]); GetChild(lcol, "Range", cols[1]); GetChild(lcol, "Source", cols[2]); GetChild(lcol, "Destination", cols[3]); GetChild(lcol, "Protocol", cols[4]); GetChild(lcol, "Action", cols[5]); SaveListColumns(cols, this->LogColumns); } if(const TiXmlElement *lcol=windowing->FirstChildElement("ListEditorColumns")) { int cols[3]= {0}; GetChild(lcol, "Range", cols[0]); GetChild(lcol, "StartingIp", cols[1]); GetChild(lcol, "EndingIp", cols[2]); SaveListColumns(cols, this->ListEditorColumns); } if(const TiXmlElement *lcol=windowing->FirstChildElement("ListManagerColumns")) { int cols[3]= {0}; GetChild(lcol, "File", cols[0]); GetChild(lcol, "Type", cols[1]); GetChild(lcol, "Description", cols[2]); SaveListColumns(cols, this->ListManagerColumns); } if(const TiXmlElement *ucol=windowing->FirstChildElement("UpdateColumns")) { int cols[3]= {0}; GetChild(ucol, "Description", cols[0]); GetChild(ucol, "Task", cols[1]); GetChild(ucol, "Status", cols[2]); SaveListColumns(cols, this->UpdateColumns); } } TRACEI("[Configuration] [Load] parsing config updates element"); if(const TiXmlElement *updates=root->FirstChildElement("Updates")) { string lastupdate; GetChild(updates, "UpdatePeerBlock", this->UpdatePeerBlock); GetChild(updates, "UpdateLists", this->UpdateLists); GetChild(updates, "UpdateAtStartup", this->UpdateAtStartup); GetChild(updates, "UpdateInterval", this->UpdateInterval); GetChild(updates, "UpdateCountdown", this->UpdateCountdown); GetChild(updates, "IgnoreListUpdateLimit", this->IgnoreListUpdateLimit); GetChild(updates, "UpdateProxy", this->UpdateProxy); if(const TiXmlElement *proxy=updates->FirstChildElement("UpdateProxy")) { const char *t=proxy->Attribute("Type"); this->UpdateProxyType=(t!=NULL && !strcmp(t, "http"))?CURLPROXY_HTTP:CURLPROXY_SOCKS5; } GetChild(updates, "LastUpdate", lastupdate); if(lastupdate.length()>0) { try { this->LastUpdate=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } GetChild(updates, "LastArchived", lastupdate); if(lastupdate.length()>0) { try { this->LastArchived=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } GetChild(updates, "LastStarted", lastupdate); if(lastupdate.length()>0) { try { this->LastStarted=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } GetChild(updates, "UniqueId", UniqueId); if (EnsureUniqueId()) { // we generated a new unique ID for this, so make sure we save it later on isDirty = true; } } TRACEI("[Configuration] [Load] parsing config messages element"); if(const TiXmlElement *messages=root->FirstChildElement("Messages")) { GetChild(messages, "FirstBlock", this->FirstBlock); GetChild(messages, "FirstHide", this->FirstHide); } TRACEI("[Configuration] [Load] parsing config ports element"); if (const TiXmlElement *portset = root->FirstChildElement("PortSet")) { GetChild(portset, "AllowHttp", this->PortSet.AllowHttp); GetChild(portset, "AllowFtp", this->PortSet.AllowFtp); GetChild(portset, "AllowSmtp", this->PortSet.AllowSmtp); GetChild(portset, "AllowPop3", this->PortSet.AllowPop3); if (const TiXmlElement *profiles = portset->FirstChildElement("Profiles")) { for (const TiXmlElement *profile = profiles->FirstChildElement("Profile"); profile != NULL; profile = profile->NextSiblingElement("Profile")) { PortProfile pf; GetChild(profile, "Name", pf.Name); GetChild(profile, "Enabled", pf.Enabled); GetChild(profile, "Type", pf.Type); if (const TiXmlElement *ports = profile->FirstChildElement("Ports")) { for (const TiXmlElement *range = ports->FirstChildElement("Range"); range != NULL; range = range->NextSiblingElement("Range")) { const char *start = range->Attribute("Start"); const char *end = range->Attribute("End"); if (start) { try { USHORT s = boost::lexical_cast<USHORT>(start); USHORT e = s; if (end) e = boost::lexical_cast<USHORT>(end); PortRange pr; pr.Start = s; pr.End = e; pf.Ports.push_back(pr); } catch (boost::bad_lexical_cast &) { // not valid number } } } } this->PortSet.Profiles.push_back(pf); } } } TRACEI("[Configuration] [Load] parsing config lists element"); if(const TiXmlElement *lists=root->FirstChildElement("Lists")) { for(const TiXmlElement *list=lists->FirstChildElement("List"); list!=NULL; list=list->NextSiblingElement("List")) { string file, url, type, description, lastupdate, lastdownload; bool enabled, failedupdate=false; GetChild(list, "File", file); GetChild(list, "Url", url); GetChild(list, "Type", type); GetChild(list, "Description", description); GetChild(list, "LastUpdate", lastupdate); GetChild(list, "LastDownload", lastdownload); GetChild(list, "FailedUpdate", failedupdate); if(!GetChild(list, "Enabled", enabled)) enabled=true; if(file.length()>0) { StaticList l; l.Type=(type=="allow")?List::Allow:List::Block; l.File=UTF8_TSTRING(file); l.Description=UTF8_TSTRING(description); l.Enabled=enabled; this->StaticLists.push_back(l); } else { DynamicList l; l.Type=(type=="allow")?List::Allow:List::Block; l.Url=UTF8_TSTRING(url); l.Description=UTF8_TSTRING(description); l.Enabled=enabled; l.FailedUpdate=failedupdate; if(lastupdate.length()>0) { try { l.LastUpdate=boost::lexical_cast<int>(lastupdate); } catch(...) { // keep going } } if(lastdownload.length()>0) { try { l.LastDownload=boost::lexical_cast<int>(lastdownload); } catch(...) { // keep going } } this->DynamicLists.push_back(l); } } } TRACEI("[Configuration] [Load] parsing I-Blocklist Subscription element"); if(const TiXmlElement *ibl=root->FirstChildElement("I-Blocklist")) { GetChild(ibl, "Username", this->IblUsername); GetChild(ibl, "PIN", this->IblPin); } if (isDirty) { TRACEI("[Configuration] [Load] config loaded dirty, saving"); Save(); } TRACEI("[Configuration] [Load] < Leaving routine."); return true; } // End of Load()
boolean StrategySettingsClass::init(){ Configuration cfg; if (cfg.loadFromFile(STRATEGY_CONFIG_FILE) == FILE_VALID){ valid = true; //Load track data trackData.trackLenght = cfg.getProperty(TRACK_LENGHT).asInt(); trackData.trackFinish = cfg.getProperty(TRACK_FINISH).asInt(); trackData.raceLaps = cfg.getProperty(RACE_LAPS).asInt(); trackData.raceTime = cfg.getProperty(RACE_TIME).asInt(); trackData.firstLapTime = cfg.getProperty(T_FIRST_LAP).asInt(); trackData.generalLapTime = cfg.getProperty(T_LAP).asInt(); trackData.lastLapTime = cfg.getProperty(T_LAST_LAP).asInt(); debugTrackSettings(); /* //Load first lap if (trackData.firstLapTime != 0){ loadLapProfile(STRATEGY_FIRSTLAP_FILE, firstLap, trackData.trackLenght + 1); consoleForm.println(F("First lap profile OK")); Log.i(STRAT_TAG) << F("First lap profile OK") << Endl; } else{ consoleForm.println(F("First lap profile SKIP")); Log.w(STRAT_TAG) << F("First lap profile SKIP") << Endl; valid = false; } //Load general lap if (trackData.generalLapTime != 0){ loadLapProfile(STRATEGY_FIRSTLAP_FILE, generalLap, trackData.trackLenght + 1); consoleForm.println(F("General lap profile OK")); Log.i(STRAT_TAG) << F("General lap profile OK") << Endl; } else{ consoleForm.println(F("General lap profile SKIP")); Log.w(STRAT_TAG) << F("General lap profile SKIP") << Endl; valid = false; } //Load last lap if (trackData.lastLapTime != 0){ loadLapProfile(STRATEGY_FIRSTLAP_FILE, lastLap, trackData.trackLenght + 1); consoleForm.println(F("Last lap profile OK")); Log.i(STRAT_TAG) << F("Last lap profile OK") << Endl; } else{ consoleForm.println(F("Last lap profile SKIP")); Log.w(STRAT_TAG) << F("Last lap profile SKIP") << Endl; valid = false; } */ if (loadLapProfile()){ consoleForm.println(F("Laps profiles loaded!")); Log.i(STRAT_TAG) << F("Laps profiles loaded!") << Endl; } else{ consoleForm.println(F("Failed to load laps profiles!")); Log.e(STRAT_TAG) << F("Failed to load laps profiles!") << Endl; valid = false; } } else{ consoleForm.println(cfg.getErrorMsg()); Log.e(STRAT_TAG) << cfg.getErrorMsg() << Endl; valid = false; } return valid; }
//The Main function of program int main(int argc, char *argv[]) { #ifdef _DEBUG //Handle the system signal. SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); #endif if (argc > 0) { std::shared_ptr<wchar_t> wPath(new wchar_t[MAX_PATH]()); //Path initialization and Winsock initialization. MultiByteToWideChar(CP_ACP, NULL, argv[0], MBSTOWCS_NULLTERMINATE, wPath.get(), MAX_PATH); if (FileInit(wPath.get()) == EXIT_FAILURE) return EXIT_FAILURE; wPath.reset(); //Windows Firewall Test in first start. if (argc > 1 && strlen(argv[1U]) == strlen("--FirstStart") && memcmp(argv[1], ("--FirstStart"), strlen("--FirstStart")) == 0) { if (FirewallTest(AF_INET6) == EXIT_FAILURE && FirewallTest(AF_INET) == EXIT_FAILURE) { PrintError(WINSOCK_ERROR, L"Windows Firewall Test error", NULL, nullptr, NULL); WSACleanup(); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } } else { return EXIT_FAILURE; } //Read configuration file and WinPcap initialization. if (Parameter.ReadParameter() == EXIT_FAILURE) { WSACleanup(); return EXIT_FAILURE; } std::thread CaptureInitializationThread(CaptureInit); CaptureInitializationThread.detach(); //Get Localhost DNS PTR Records. std::thread IPv6LocalAddressThread(LocalAddressToPTR, AF_INET6); std::thread IPv4LocalAddressThread(LocalAddressToPTR, AF_INET); IPv6LocalAddressThread.detach(); IPv4LocalAddressThread.detach(); //DNSCurve initialization if (Parameter.DNSCurve && DNSCurveParameter.Encryption) { randombytes_set_implementation(&randombytes_salsa20_implementation); DNSCurveInit(); } //Read IPFilter, start DNS Cache monitor(Timer type) and read Hosts. if (Parameter.FileRefreshTime > 0) { if (Parameter.OperationMode == LISTEN_CUSTOMMODE) { std::thread IPFilterThread(&Configuration::ReadIPFilter, std::ref(Parameter)); IPFilterThread.detach(); } if (Parameter.CacheType != 0) { std::thread DNSCacheTimerThread(DNSCacheTimerMonitor, Parameter.CacheType); DNSCacheTimerThread.detach(); } std::thread HostsThread(&Configuration::ReadHosts, std::ref(Parameter)); HostsThread.detach(); } //Service initialization and start service. SERVICE_TABLE_ENTRYW ServiceTable[] = {{LOCAL_SERVICENAME, (LPSERVICE_MAIN_FUNCTIONW)ServiceMain}, {nullptr, NULL}}; if (!StartServiceCtrlDispatcherW(ServiceTable)) { PrintError(SYSTEM_ERROR, L"Service start error", GetLastError(), nullptr, NULL); WSACleanup(); return EXIT_FAILURE; } WSACleanup(); return EXIT_SUCCESS; }
/** * Device signals that a specific property changed and reports the new value */ int CoreCallback::OnPropertyChanged(const MM::Device* device, const char* propName, const char* value) { if (core_->externalCallback_) { MMThreadGuard g(*pValueChangeLock_); char label[MM::MaxStrLength]; device->GetLabel(label); bool readOnly; device->GetPropertyReadOnly(propName, readOnly); const PropertySetting* ps = new PropertySetting(label, propName, value, readOnly); core_->stateCache_.addSetting(*ps); core_->externalCallback_->onPropertyChanged(label, propName, value); // find all configs that contain this property and callback to indicate // that the config group changed // TODO: assess whether performace is better by maintaining a map tying // property to configurations /* using namespace std; vector<string> configGroups = core_->getAvailableConfigGroups (); for (vector<string>::iterator it = configGroups.begin(); it!=configGroups.end(); ++it) { vector<string> configs = core_->getAvailableConfigs((*it).c_str()); bool found = false; for (vector<string>::iterator itc = configs.begin(); itc != configs.end() && !found; itc++) { Configuration config = core_->getConfigData((*it).c_str(), (*itc).c_str()); if (config.isPropertyIncluded(label, propName)) { found = true; // If we are part of this configuration, notify that it was changed // get the new config from cache rather than query the hardware string currentConfig = core_->getCurrentConfigFromCache( (*it).c_str() ); OnConfigGroupChanged((*it).c_str(), currentConfig.c_str()); } } } */ // Check if pixel size was potentially affected. If so, update from cache vector<string> pixelSizeConfigs = core_->getAvailablePixelSizeConfigs(); bool found = false; for (vector<string>::iterator itpsc = pixelSizeConfigs.begin(); itpsc != pixelSizeConfigs.end() && !found; itpsc++) { Configuration pixelSizeConfig = core_->getPixelSizeConfigData( (*itpsc).c_str()); if (pixelSizeConfig.isPropertyIncluded(label, propName)) { found = true; double pixSizeUm; try { // update pixel size from cache pixSizeUm = core_->getPixelSizeUm(true); } catch (CMMError ) { pixSizeUm = 0.0; } OnPixelSizeChanged(pixSizeUm); } } } return DEVICE_OK; }
CMeshX2::CMeshX2( const Configuration &config ) : Network( config ) { _subMesh[0] = new CMesh( config ); _subMesh[1] = new CMesh( config ); int k = config.GetInt( "k" ) ; int n = config.GetInt( "n" ) ; int c = config.GetInt( "c" ) ; gK = _k = k ; gN = _n = n ; gC = _c = c ; _sources = _c * powi( _k, _n); // Source nodes in network _dests = _c * powi( _k, _n); // Destination nodes in network _size = powi( _k, _n); // Number of routers in network _channels = 0; _f_read_history = new int[_sources]; _c_read_history = new int[_dests]; for (int i = 0; i < _size; i++) { _f_read_history[i] = 0; _c_read_history[i] = 0; } _subNetAssignment[Flit::READ_REQUEST] = config.GetInt( "read_request_subnet" ); assert( _subNetAssignment[Flit::READ_REQUEST] == 0 || _subNetAssignment[Flit::READ_REQUEST] == 1); _subNetAssignment[Flit::READ_REPLY] = config.GetInt( "read_reply_subnet" ); assert( _subNetAssignment[Flit::READ_REPLY] == 0 || _subNetAssignment[Flit::READ_REPLY] == 1 ); _subNetAssignment[Flit::WRITE_REQUEST] = config.GetInt( "write_request_subnet" ); assert( _subNetAssignment[Flit::WRITE_REQUEST] == 0 || _subNetAssignment[Flit::WRITE_REQUEST] == 1); _subNetAssignment[Flit::WRITE_REPLY] = config.GetInt( "write_reply_subnet" ); assert( _subNetAssignment[Flit::WRITE_REPLY] == 0 || _subNetAssignment[Flit::WRITE_REPLY] == 1 ); int cookie_0 = 0; int cookie_1 = 0; if ( _subNetAssignment[Flit::WRITE_REQUEST] == 0 || _subNetAssignment[Flit::READ_REPLY] == 0 ) cookie_0 = 1; if ( _subNetAssignment[Flit::WRITE_REQUEST] == 1 || _subNetAssignment[Flit::READ_REPLY] == 1 ) cookie_1 = 1; assert( cookie_0 == 1 || cookie_1 == 1 ); _subMesh[0]->SetChannelCookie(cookie_0); _subMesh[1]->SetChannelCookie(cookie_1); }
int Menu::DisplayMenu() { Display display; Configuration config; Functions func; string PanelHeaders[8] = {" MENU ", " DISPLAY ", " SERVER LIST ", " SET USERNAME ", " SETTINGS ", " ABOUT ", " QUIT ", " NEWS "}; string MenuList[MaxNo_Menu] = {" Server List ", " Set Username ", " Settings ", " About ", " Quit "}; int ypos[MaxNo_Menu] = { 12, 14, 16, 18, 20}; int xpos = 5; config.SetColour(MenuTitleColour); config.SetXYCoord(4, 10); cout << PanelHeaders[0]; config.SetColour(MenuTitleColour); config.SetXYCoord(42, 10); cout << PanelHeaders[1]; // Show Menu int i; config.SetColour(StandardColour); for (i=0; i< MaxNo_Menu; ++i) { config.SetXYCoord(xpos, ypos[i] ); config.SetColour(StandardColour); cout << MenuList[i]; } // Enable Menu i = 0; while(1) { config.SetXYCoord(xpos, ypos[i]); config.SetColour(HoverColour); cout << MenuList[i]; switch( _getch() ) { case 72: if(i>0) { config.SetXYCoord(xpos,ypos[i] ); config.SetColour(StandardColour); // Standard Going Down cout << MenuList[i]; i--; } break; case 80: if(i< MaxNo_Menu-1 ) { config.SetXYCoord(xpos,ypos[i] ); config.SetColour(StandardColour); // Standard Going Up cout << MenuList[i]; i++; } break; case 13: if(i==0) { func.ServerBrowser(PanelHeaders); } if(i==1) { func.SetUsername(PanelHeaders); } if(i==2) { func.Settings(PanelHeaders); } if(i==3) { func.DisplayAbout(PanelHeaders); } if(i==4) { // Exit display.RemoveText(); config.SetColour(MenuTitleColour), config.SetXYCoord(42, 10), cout << PanelHeaders[6]; config.SetColour(StandardColour); char Input; config.SetXYCoord(34,12); cout << "Are you sure you want to exit? [Y/N]: "; cin >> Input; if (toupper(Input) == 'N') { break; } else if (toupper(Input) == 'Y') { config.SetXYCoord(34,15); return 0; } else if (Input == ' ' || Input != toupper('Y') || Input != toupper('N')) { while(Input == ' ' || Input != toupper('Y') || Input != toupper('N')) { config.SetColour(ErrorColour); config.SetXYCoord(34,13),cout << "Error: Please Enter [Y/N]: "; config.SetColour(StandardColour), cin >> Input; if (toupper(Input) == 'N') { break; } else if (toupper(Input) == 'Y') { config.SetXYCoord(34,15); return 0; } } } } break; } }
Configuration::Configuration() { static Configuration config; config.readConfig(); }
void DBusAPIConfigurations::activate(QString config) { Configuration * c = Configurations::self()->configuration(config); if (c) { c->activate(); } }
void LeoCurriculumLearningExperiment::run() { std::ofstream ofs; // Store configuration with output if (!output_.empty()) { ofs.open(output_ + identity_ + ".yaml"); ofs << configurator()->root()->yaml(); ofs.close(); } for (size_t rr=0; rr < runs_; ++rr) { if (!output_.empty()) { std::ostringstream oss; oss << output_ << "-" << rr << identity_ << ".txt"; ofs.open(oss.str().c_str()); } // Load policy every run if (!load_file_.empty()) { std::string load_file = load_file_ + "-"; str_replace(load_file, "$run", std::to_string((int)rr)); // increment run if needed std::cout << "Loading policy: " << load_file << std::endl; Configuration loadconfig; loadconfig.set("action", "load"); loadconfig.set("file", load_file ); agent_->walk(loadconfig); } for (size_t ss=0, tt=0; (!trials_ || tt < trials_) && (!steps_ || ss < steps_); ++tt) { if ((ttdiv_) && (tt % ttdiv_ == 0)) reconfigureLeo(tt/trials_); if ((ssdiv_) && ((double)ss / ssdiv_ >= ssdiv_stepup_)) { reconfigureLeo((double)ss/steps_); ssdiv_stepup_++; } Observation obs; Action action; double reward, total_reward=0; int terminal; int test = (test_interval_ >= 0 && tt%(test_interval_+1) == test_interval_) * (rr+1); timer step_timer; Agent *agent = agent_; if (test) agent = test_agent_; environment_->start(test, &obs); CRAWL(obs); agent->start(obs, &action); state_->set(obs.v); action_->set(action.v); do { if (rate_) { double sleep_time = 1./rate_-step_timer.elapsed(); if (sleep_time > 0) usleep(1000000.*sleep_time); step_timer.restart(); } double tau = environment_->step(action, &obs, &reward, &terminal); CRAWL(action << " - " << reward << " -> " << obs); total_reward += reward; if (obs.size()) { if (terminal == 2) agent->end(tau, obs, reward); else agent->step(tau, obs, reward, &action); state_->set(obs.v); action_->set(action.v); if (!test) ss++; } } while (!terminal); if (test_interval_ >= 0) { if (test) { std::ostringstream oss; oss << std::setw(15) << tt+1-(tt+1)/(test_interval_+1) << std::setw(15) << ss << std::setw(15) << std::setprecision(3) << std::fixed << total_reward; agent->report(oss); environment_->report(oss); curve_->set(VectorConstructor(total_reward)); INFO(oss.str()); if (ofs.is_open()) ofs << oss.str() << std::endl; } } else { std::ostringstream oss; oss << std::setw(15) << tt << std::setw(15) << ss << std::setw(15) << std::setprecision(3) << std::fixed << total_reward; agent->report(oss); environment_->report(oss); curve_->set(VectorConstructor(total_reward)); INFO(oss.str()); if (ofs.is_open()) ofs << oss.str() << std::endl; } // Save policy every trial or every test trial if (((save_every_ == "trial") || (test && save_every_ == "test")) && !output_.empty() ) { std::ostringstream oss; oss << output_ << "-run" << rr << "-trial" << tt << "-"; Configuration saveconfig; saveconfig.set("action", "save"); saveconfig.set("file", oss.str().c_str()); agent_->walk(saveconfig); } } // Save policy every run if (save_every_ == "run" && !output_.empty()) { std::ostringstream oss; oss << output_ << "-run" << rr << "-"; Configuration saveconfig; saveconfig.set("action", "save"); saveconfig.set("file", oss.str().c_str()); agent_->walk(saveconfig); } if (ofs.is_open()) ofs.close(); if (rr < runs_ - 1) reset(); } }
BufferState::SharedBufferPolicy::SharedBufferPolicy(Configuration const & config, BufferState * parent, const string & name) : BufferPolicy(config, parent, name), _shared_buf_occupancy(0) { int const vcs = config.GetInt( "num_vcs" ); int num_private_bufs = config.GetInt("private_bufs"); if(num_private_bufs < 0) { num_private_bufs = vcs; } else if(num_private_bufs == 0) { num_private_bufs = 1; } _private_buf_occupancy.resize(num_private_bufs, 0); _buf_size = config.GetInt("buf_size"); if(_buf_size < 0) { _buf_size = vcs * config.GetInt("vc_buf_size"); } _private_buf_size = config.GetIntArray("private_buf_size"); if(_private_buf_size.empty()) { int const bs = config.GetInt("private_buf_size"); if(bs < 0) { _private_buf_size.push_back(_buf_size / num_private_bufs); } else { _private_buf_size.push_back(bs); } } _private_buf_size.resize(num_private_bufs, _private_buf_size.back()); vector<int> start_vc = config.GetIntArray("private_buf_start_vc"); if(start_vc.empty()) { int const sv = config.GetInt("private_buf_start_vc"); if(sv < 0) { start_vc.resize(num_private_bufs); for(int i = 0; i < num_private_bufs; ++i) { start_vc[i] = i * vcs / num_private_bufs; } } else { start_vc.push_back(sv); } } vector<int> end_vc = config.GetIntArray("private_buf_end_vc"); if(end_vc.empty()) { int const ev = config.GetInt("private_buf_end_vc"); if(ev < 0) { end_vc.resize(num_private_bufs); for(int i = 0; i < num_private_bufs; ++i) { end_vc[i] = (i + 1) * vcs / num_private_bufs - 1; } } else { end_vc.push_back(ev); } } _private_buf_vc_map.resize(vcs, -1); _shared_buf_size = _buf_size; for(int i = 0; i < num_private_bufs; ++i) { _shared_buf_size -= _private_buf_size[i]; assert(start_vc[i] <= end_vc[i]); for(int v = start_vc[i]; v <= end_vc[i]; ++v) { assert(_private_buf_vc_map[v] < 0); _private_buf_vc_map[v] = i; } } assert(_shared_buf_size >= 0); _reserved_slots.resize(vcs, 0); }
void MakeGenerator::emit( const std::shared_ptr<Directory> &d, const Configuration &conf, int argc, const char *argv[] ) { Directory curD; std::string makefn = d->makefilename( "Makefile" ); try { { std::ofstream f( makefn ); f << ".PHONY: all\n" ".ONESHELL:\n" ".SUFFIXES:\n" ".DEFAULT: all\n" ".NOTPARALLEL:\n" "\n" "TARGETS:=$(filter-out all,$(MAKECMDGOALS))\n" "MAKECMDGOALS:=\n" "MAKEFLAGS:=--no-print-directory\n" "all: Makefile.build\n\n" "\t@$(MAKE) -f Makefile.build $(TARGETS)\n\n" "Makefile.build: "; for ( const std::string &x: Lua::Engine::singleton().visitedFiles() ) f << ' ' << x; f << "\n\t@echo \"Regenerating build files...\"\n"; f << "\t@cd " << curD.fullpath() << " &&"; for ( int a = 0; a < argc; ++a ) f << ' ' << argv[a]; } TransformSet xform( d, conf.getSystem() ); Scope::root().transform( xform, conf ); std::ofstream rf( d->makefilename( "Makefile.build" ) ); rf << ".PHONY: default all install clean\n" ".SUFFIXES:\n" ".ONESHELL:\n" ".DEFAULT: all\n" "\n\ndefault: all\n"; std::vector<std::string> defTargs; int scopeCount = 0; emitScope( rf, defTargs, *d, xform, scopeCount ); rf << "all:"; for ( const std::string &a: defTargs ) rf << ' ' << a; rf << "\n\ninstall:\n\t@echo \"Installing...\"\n"; rf << "\n\nclean:"; for ( const std::string &a: defTargs ) rf << " clean-" << a; rf << "\n\n"; } catch ( std::exception &e ) { WARNING( "ERROR: " << e.what() ); ::unlink( makefn.c_str() ); if ( conf.isSkipOnError() ) { WARNING( "Configuration '" << conf.name() << "' had errors resolving build file, ignoring" ); } else throw; } catch ( ... ) { ::unlink( makefn.c_str() ); if ( conf.isSkipOnError() ) { WARNING( "Configuration '" << conf.name() << "' had errors resolving build file, ignoring" ); } else throw; } }
Power_Module::Power_Module(BSNetwork * n , TrafficManager* parent, const Configuration &config) : Module( 0, "power_module" ){ string pfile = config.GetStr("tech_file"); PowerConfig pconfig; pconfig.ParseFile(pfile); net = n; sim = parent; output_file_name = config.GetStr("power_output_file"); classes = config.GetInt("classes"); channel_width = (double)config.GetInt("channel_width"); channel_sweep = (double)config.GetInt("channel_sweep"); numVC = (double)config.GetInt("num_vcs"); depthVC = (double)config.GetInt("vc_buf_size"); //////////////////////////////////Constants///////////////////////////// //wire length in (mm) wire_length = pconfig.GetFloat("wire_length"); //////////Metal Parameters//////////// // Wire left/right coupling capacitance [ F/mm ] Cw_cpl = pconfig.GetFloat("Cw_cpl"); // Wire up/down groudn capacitance [ F/mm ] Cw_gnd = pconfig.GetFloat("Cw_gnd"); Cw = 2.0 * Cw_cpl + 2.0 * Cw_gnd ; Rw = pconfig.GetFloat("Rw"); // metal pitch [mm] MetalPitch = pconfig.GetFloat("MetalPitch"); //////////Device Parameters//////////// LAMBDA = pconfig.GetFloat("LAMBDA") ; // [um/LAMBDA] Cd = pconfig.GetFloat("Cd"); // [F/um] (for Delay) Cg = pconfig.GetFloat("Cg"); // [F/um] (for Delay) Cgdl = pconfig.GetFloat("Cgdl"); // [F/um] (for Delay) Cd_pwr = pconfig.GetFloat("Cd_pwr") ; // [F/um] (for Power) Cg_pwr = pconfig.GetFloat("Cg_pwr") ; // [F/um] (for Power) IoffN = pconfig.GetFloat("IoffN"); // [A/um] IoffP = pconfig.GetFloat("IoffP"); // [A/um] // Leakage from bitlines, two-port cell [A] IoffSRAM = pconfig.GetFloat("IoffSRAM"); // [Ohm] ( D1=1um Inverter) R = pconfig.GetFloat("R"); // [F] ( D1=1um Inverter - for Power ) Ci_delay = (1.0 + 2.0) * ( Cg + Cgdl ); // [F] ( D1=1um Inverter - for Power ) Co_delay = (1.0 + 2.0) * Cd ; Ci = (1.0 + 2.0) * Cg_pwr ; Co = (1.0 + 2.0) * Cd_pwr ; Vdd = pconfig.GetFloat("Vdd"); FO4 = R * ( 3.0 * Cd + 12 * Cg + 12 * Cgdl); tCLK = 20 * FO4; fCLK = 1.0 / tCLK; H_INVD2=(double)pconfig.GetInt("H_INVD2"); W_INVD2=(double)pconfig.GetInt("W_INVD2") ; H_DFQD1=(double)pconfig.GetInt("H_DFQD1"); W_DFQD1= (double)pconfig.GetInt("W_DFQD1"); H_ND2D1= (double)pconfig.GetInt("H_ND2D1"); W_ND2D1=(double)pconfig.GetInt("W_ND2D1"); H_SRAM=(double)pconfig.GetInt("H_SRAM"); W_SRAM=(double)pconfig.GetInt("W_SRAM"); ChannelPitch = 2.0 * MetalPitch ; CrossbarPitch = 2.0 * MetalPitch ; }
ChaosRouter::ChaosRouter( const Configuration& config, Module *parent, const string & name, int id, int inputs, int outputs ) : Router( config, parent, name, id, inputs, outputs ) { int i; if ( inputs != outputs ) { Error( "Chaos router must have equal number of input and output ports" ); } _buffer_size = config.GetInt( "const_flits_per_packet" ); _multi_queue_size = config.GetInt( "multi_queue_size" ); _cur_channel = 0; _read_stall = 0; // Routing _rf = GetRoutingFunction( config ); _input_route = new OutputSet * [_inputs]; _mq_route = new OutputSet * [_multi_queue_size]; for ( i = 0; i < _inputs; ++i ) { _input_route[i] = new OutputSet( _outputs ); } for ( i = 0; i < _multi_queue_size; ++i ) { _mq_route[i] = new OutputSet( _outputs ); } // Alloc pipelines (to simulate processing/transmission delays) _crossbar_pipe = new PipelineFIFO<Flit>( this, "crossbar_pipeline", _outputs, _st_prepare_delay + _st_final_delay ); // Input and output queues _input_frame = new queue<Flit *> [_inputs]; _output_frame = new queue<Flit *> [_outputs]; _multi_queue = new queue<Flit *> [_multi_queue_size]; _credit_queue = new queue<Credit *> [_inputs]; _input_state = new eQState [_inputs]; _input_output_match = new int [_inputs]; _input_mq_match = new int [_inputs]; _output_matched = new bool [_outputs]; _next_queue_cnt = new int [_outputs]; for ( i = 0; i < _inputs; ++i ) { _input_state[i] = empty; _input_output_match[i] = -1; _input_mq_match[i] = -1; } for ( i = 0; i < _outputs; ++i ) { _output_matched[i] = false; _next_queue_cnt[i] = 0; } _multi_match = new int [_multi_queue_size]; _mq_age = new int [_multi_queue_size]; _mq_matched = new bool [_multi_queue_size]; _multi_state = new eQState [_multi_queue_size]; for ( i = 0; i < _multi_queue_size; ++i ) { _multi_state[i] = empty; _multi_match[i] = -1; _mq_matched[i] = false; } }
void RunDialog::on_outputDirButton_clicked() { Configuration* pConfig = Configuration::getConfig(); QString dirName = QFileDialog::getExistingDirectory(this, tr("Choose the output directory"), QString().fromStdString(pConfig->getString("outputDirectory"))); ui->runName->setText(dirName); }
void BatchLearningExperiment::reconfigure(const Configuration &config) { config.get("rate", rate_); }
/** Load database and host settings from config.xml, or set some defaults. * \return true if config.xml was parsed */ bool MythContextPrivate::LoadDatabaseSettings(void) { // try new format first m_DBparams.LoadDefaults(); m_DBparams.localHostName = m_pConfig->GetValue("LocalHostName", ""); m_DBparams.dbHostPing = m_pConfig->GetValue(kDefaultDB + "PingHost", true); m_DBparams.dbHostName = m_pConfig->GetValue(kDefaultDB + "Host", ""); m_DBparams.dbUserName = m_pConfig->GetValue(kDefaultDB + "UserName", ""); m_DBparams.dbPassword = m_pConfig->GetValue(kDefaultDB + "Password", ""); m_DBparams.dbName = m_pConfig->GetValue(kDefaultDB + "DatabaseName", ""); m_DBparams.dbPort = m_pConfig->GetValue(kDefaultDB + "Port", 0); m_DBparams.wolEnabled = m_pConfig->GetValue(kDefaultWOL + "Enabled", false); m_DBparams.wolReconnect = m_pConfig->GetValue(kDefaultWOL + "SQLReconnectWaitTime", 0); m_DBparams.wolRetry = m_pConfig->GetValue(kDefaultWOL + "SQLConnectRetry", 5); m_DBparams.wolCommand = m_pConfig->GetValue(kDefaultWOL + "Command", ""); bool ok = m_DBparams.IsValid("config.xml"); if (!ok) // if new format fails, try legacy format { m_DBparams.LoadDefaults(); m_DBparams.dbHostName = m_pConfig->GetValue( kDefaultMFE + "DBHostName", ""); m_DBparams.dbUserName = m_pConfig->GetValue( kDefaultMFE + "DBUserName", ""); m_DBparams.dbPassword = m_pConfig->GetValue( kDefaultMFE + "DBPassword", ""); m_DBparams.dbName = m_pConfig->GetValue( kDefaultMFE + "DBName", ""); m_DBparams.dbPort = m_pConfig->GetValue( kDefaultMFE + "DBPort", 0); m_DBparams.forceSave = true; ok = m_DBparams.IsValid("config.xml"); } if (!ok) m_DBparams.LoadDefaults(); gCoreContext->GetDB()->SetDatabaseParams(m_DBparams); QString hostname = m_DBparams.localHostName; if (hostname.isEmpty() || hostname == "my-unique-identifier-goes-here") { char localhostname[1024]; if (gethostname(localhostname, 1024)) { LOG(VB_GENERAL, LOG_ALERT, "MCP: Error, could not determine host name." + ENO); localhostname[0] = '\0'; } hostname = localhostname; LOG(VB_GENERAL, LOG_NOTICE, "Empty LocalHostName."); } else { m_DBparams.localEnabled = true; } LOG(VB_GENERAL, LOG_INFO, QString("Using localhost value of %1") .arg(hostname)); gCoreContext->SetLocalHostname(hostname); return ok; }
bool ConfigurationHolder::readBooleanFromConfigFile(Configuration & configObject) { UINT val = GetPrivateProfileInt(CONFIG_FILE_SECTION_NAME, configObject.getName(), 0, configPath); configObject.setBool(val != 0); return true; }
bool MythContextPrivate::SaveDatabaseParams( const DatabaseParams ¶ms, bool force) { bool ret = true; // only rewrite file if it has changed if (params != m_DBparams || force) { m_pConfig->SetValue( "LocalHostName", params.localHostName); m_pConfig->SetValue( kDefaultDB + "PingHost", params.dbHostPing); m_pConfig->SetValue( kDefaultDB + "Host", params.dbHostName); m_pConfig->SetValue( kDefaultDB + "UserName", params.dbUserName); m_pConfig->SetValue( kDefaultDB + "Password", params.dbPassword); m_pConfig->SetValue( kDefaultDB + "DatabaseName", params.dbName); m_pConfig->SetValue( kDefaultDB + "Port", params.dbPort); m_pConfig->SetValue( kDefaultWOL + "Enabled", params.wolEnabled); m_pConfig->SetValue( kDefaultWOL + "SQLReconnectWaitTime", params.wolReconnect); m_pConfig->SetValue( kDefaultWOL + "SQLConnectRetry", params.wolRetry); m_pConfig->SetValue( kDefaultWOL + "Command", params.wolCommand); // clear out any legacy nodes.. m_pConfig->ClearValue(kDefaultMFE + "DBHostName"); m_pConfig->ClearValue(kDefaultMFE + "DBUserName"); m_pConfig->ClearValue(kDefaultMFE + "DBPassword"); m_pConfig->ClearValue(kDefaultMFE + "DBName"); m_pConfig->ClearValue(kDefaultMFE + "DBPort"); m_pConfig->ClearValue(kDefaultMFE + "DBHostPing"); // actually save the file m_pConfig->Save(); // Save the new settings: m_DBparams = params; gCoreContext->GetDB()->SetDatabaseParams(m_DBparams); // If database has changed, force its use: ResetDatabase(); } return ret; }
void testGetWirelessStateUpdateInterval(Configuration& configuration, Logger& logger) { logger.info("Testing Configuration::getWirelessStateUpdateInterval() method"); EXPECT_EQ(100, configuration.getWirelessStateUpdateInterval()); }
/** * Get the default backend from config.xml, use UPnP to find it. * * Sets a string if there any connection problems */ bool MythContextPrivate::DefaultUPnP(QString &error) { QString loc = "DefaultUPnP() - "; QString PIN = m_pConfig->GetValue(kDefaultPIN, ""); QString USN = m_pConfig->GetValue(kDefaultUSN, ""); if (USN.isEmpty()) { LOG(VB_UPNP, LOG_INFO, loc + "No default UPnP backend"); return false; } LOG(VB_UPNP, LOG_INFO, loc + "config.xml has default " + QString("PIN '%1' and host USN: %2") .arg(PIN).arg(USN)); // ---------------------------------------------------------------------- int timeout_ms = 2000; LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs") .arg(timeout_ms / 1000)); SSDP::Instance()->PerformSearch(gBackendURI, timeout_ms / 1000); // ---------------------------------------------------------------------- // We need to give the server time to respond... // ---------------------------------------------------------------------- DeviceLocation *pDevLoc = NULL; MythTimer totalTime; totalTime.start(); MythTimer searchTime; searchTime.start(); while (totalTime.elapsed() < timeout_ms) { pDevLoc = SSDP::Instance()->Find( gBackendURI, USN ); if (pDevLoc) break; usleep(25000); int ttl = timeout_ms - totalTime.elapsed(); if ((searchTime.elapsed() > 249) && (ttl > 1000)) { LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs") .arg(ttl / 1000)); SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000); searchTime.start(); } } // ---------------------------------------------------------------------- if (!pDevLoc) { error = "Cannot find default UPnP backend"; return false; } if (UPnPconnect(pDevLoc, PIN)) { pDevLoc->DecrRef(); return true; } pDevLoc->DecrRef(); error = "Cannot connect to default backend via UPnP. Wrong saved PIN?"; return false; }
//----- BroadcastEvent() ---------------------------------------------------- BOOL CFormChunkMergeView::BroadcastEvent(WORD event, void* pParameter) { switch (event) { case IBCE_CHANGED_SETTINGS: { // set settings from configuration Configuration* pConfig (Configuration::getInstance()); CComboBox* pCBox ((CComboBox*) GetDlgItem(IDC_CB_TEMPLATE)); set<string> tDirList(pConfig->getDirListTemplates()); CString tmpPath (pConfig->_cmDefaultTemplate.c_str()); //- templates LogMessageObject::LogMessage(NCU_MSG_TYPE_INFO, "Adding templates"); pCBox->ResetContent(); for (auto pIter(tDirList.begin()), pEnd(tDirList.end()); pIter != pEnd; ++pIter) { if (pIter->rfind(".nif") == string::npos) continue; pCBox->AddString(CString(pIter->c_str())); LogMessageObject::LogMessage(NCU_MSG_TYPE_SUB_INFO, "added: %s", pIter->c_str()); } pCBox->SelectString(-1, CString(tmpPath)); pCBox->GetWindowText(tmpPath); if (tmpPath.IsEmpty()) pCBox->SetCurSel(0); LogMessageObject::LogMessage(NCU_MSG_TYPE_INFO, "templates found: %d", tDirList.size()); //- materials pCBox = (CComboBox*) GetDlgItem(IDC_CB_MAT_SINGLE); map<string, NifUtlMaterial> matMap(NifUtlMaterialList::getInstance()->getMaterialMap()); short tIdx (0); short selIdx(0); // add materials to combo box for (auto pIter(matMap.begin()), pEnd(matMap.end()); pIter != pEnd; ++pIter, ++tIdx) { pCBox->InsertString (tIdx, CString(pIter->second._name.c_str())); pCBox->SetItemDataPtr(tIdx, (void*) (pIter->second._code)); if (pIter->second._code == pConfig->_cmMatSingleType) { selIdx = tIdx; } } pCBox->SetCurSel(selIdx); // material flags int selItem(pConfig->_cmMatHandling + IDC_RD_MAT_SINGLE); ((CButton*) GetDlgItem(IDC_RD_MAT_SINGLE)) ->SetCheck(selItem == IDC_RD_MAT_SINGLE); ((CButton*) GetDlgItem(IDC_RD_MAT_NITRISHAPE))->SetCheck(selItem == IDC_RD_MAT_NITRISHAPE); ((CButton*) GetDlgItem(IDC_RD_MAT_DEFINE)) ->SetCheck(selItem == IDC_RD_MAT_DEFINE); GetDlgItem(IDC_CB_MAT_SINGLE)->EnableWindow(selItem == IDC_RD_MAT_SINGLE); GetDlgItem(IDC_BT_MAT_DEFINE)->EnableWindow(selItem == IDC_RD_MAT_DEFINE); // collision flags selItem = pConfig->_cmCollHandling + IDC_RD_COLL_CDATA; ((CButton*) GetDlgItem(IDC_RD_COLL_CDATA))->SetCheck(selItem == IDC_RD_COLL_CDATA); ((CButton*) GetDlgItem(IDC_RD_COLL_FBACK))->SetCheck(selItem == IDC_RD_COLL_FBACK); ((CButton*) GetDlgItem(IDC_RD_COLL_MESH)) ->SetCheck(selItem == IDC_RD_COLL_MESH); // other flags ((CButton*) GetDlgItem(IDC_RD_COLL_LOCAL)) ->SetCheck(pConfig->_cmMergeColl ? BST_UNCHECKED : BST_CHECKED); ((CButton*) GetDlgItem(IDC_RD_COLL_GLOBAL)) ->SetCheck(pConfig->_cmMergeColl ? BST_CHECKED : BST_UNCHECKED); ((CButton*) GetDlgItem(IDC_CK_REORDER_TRIS))->SetCheck(pConfig->_cmReorderTris ? BST_CHECKED : BST_UNCHECKED); break; } case IBCE_SET_TOOLTIPP: { _toolTipCtrl.Activate(Configuration::getInstance()->_showToolTipps); break; } } // switch (event) return TRUE; }
FeS2Interface::FeS2Interface( const Configuration &config, const vector<Network *> & net) { //of.open("/home/andrew/booksim2-master/src/fes2.out"); of.open("fes2.out"); _trace_mode = config.GetInt("trace_mode"); if (_trace_mode == 1) { _trace = new TraceGenerator(); string trace_file_name; trace_file_name = config.GetStr("trace_file"); if (!_trace->openTraceFile( trace_file_name )) { cerr << "Trace file cannot be opened: " << trace_file_name << endl; } } _channel = NULL; _sources = net[0]->NumNodes( ); _dests = net[0]->NumNodes( ); _duplicate_networks = config.GetInt("subnets"); _concentrate = config.GetInt("fes2_concentrate") ? true : false; _host = config.GetStr( "fes2_host"); _port = config.GetInt("fes2_port"); _vcs = config.GetInt("num_vcs"); _subnets = config.GetInt("subnets"); _nodes = _sources; vector<int> mapping = config.GetIntArray("fes2_mapping"); for(unsigned int i = 0; i < mapping.size(); i++) { _node_map[i] = mapping[i]; } //initialize _request_buffer_flit _request_buffer_flit = new queue<FeS2RequestFlit *> * [_duplicate_networks]; for(int i=0; i < _duplicate_networks; i++){ _request_buffer_flit[i] = new queue<FeS2RequestFlit *> [_sources]; } //resize the _credits_* nested vectors _credits_from_noc_to_rtl.resize(_nodes); _credits_from_rtl_to_noc.resize(_nodes); for(int i = 0; i < _nodes; i++){ _credits_from_noc_to_rtl[i].resize(_subnets); _credits_from_rtl_to_noc[i].resize(_subnets); } for(int i = 0; i < _nodes; i++) for(int j = 0; j < _subnets; j++){ _credits_from_noc_to_rtl[i][j].resize(_vcs); _credits_from_rtl_to_noc[i][j].resize(_vcs); } //initialize current credits (we start with no credits buffered) for(int i = 0; i < _nodes; i++) for(int j = 0; j < _subnets; j++) for(int k = 0; k < _vcs; k++){ _credits_from_noc_to_rtl[i][j][k] = false; _credits_from_rtl_to_noc[i][j][k] = false; } }