// ========================================================= // Convenience method for reporting merged blocks by strand // ========================================================= void BedMerge::ReportStranded(string chrom, int start, int end, const vector<string> &names, const vector<string> &scores, int mergeCount, string strand) { // ARQ: removed to force all output to be zero-based, BED format, reagrdless of input type //if (_bed->isZeroBased == false) {start++;} printf("%s\t%d\t%d", chrom.c_str(), start, end); // just the merged intervals if (_numEntries == false && _reportNames == false && _reportScores == false) { printf("\t%s\n", strand.c_str()); } // merged intervals and counts else if (_numEntries == true && _reportNames == false && _reportScores == false) { printf("\t%d\t%s\n", mergeCount, strand.c_str()); } // merged intervals, counts, and scores else if (_numEntries == true && _reportNames == false && _reportScores == true) { printf("\t%d", mergeCount); ReportMergedScores(scores); printf("\t%s\n", strand.c_str()); } // merged intervals, counts, and names else if (_numEntries == true && _reportNames == true && _reportScores == false) { ReportMergedNames(names); printf("\t%d\t%s", mergeCount, strand.c_str()); printf("\n"); } // merged intervals, counts, names, and scores else if (_numEntries == true && _reportNames == true && _reportScores == true) { ReportMergedNames(names); ReportMergedScores(scores); printf("\t%s\t%d", strand.c_str(), mergeCount); printf("\n"); } // merged intervals and names else if (_numEntries == false && _reportNames == true && _reportScores == false) { ReportMergedNames(names); printf("\t%s\n", strand.c_str()); } // merged intervals and scores else if (_numEntries == false && _reportNames == false && _reportScores == true) { ReportMergedScores(scores); printf("\t%s\n", strand.c_str()); } // merged intervals, names, and scores else if (_numEntries == false && _reportNames == true && _reportScores == true) { ReportMergedNames(names); ReportMergedScores(scores); printf("\t%s\n", strand.c_str()); } }
/* You need to read the configuration file and extract the page size and number of pages * (these two parameter together define the maximum main memory you can use). * Values are in number of bytes. * You should read the names of the tables from the configuration file. * You can assume that the table data exists in a file named <table_name>.csv at the path * pointed by the config parameter PATH_FOR_DATA. ***************************************************************************************/ void DBSystem::readConfig(string configFilePath) { FILE *fd=fopen(configFilePath.c_str(),"rw+"); int count=0; char* temp=new char[100]; bool isBegin=false; bool isInTable=false; if(fd==NULL) cout<<"Config file not found"<<endl; fscanf (fd, "%s %d", temp, &pageSize); fscanf (fd, "%s %d", temp, &(numberOfPages)); fscanf (fd, "%s %s", temp, (pathForData)); fclose(fd); string sLine=""; ifstream infile; infile.open(configFilePath.c_str()); getline(infile, sLine); getline(infile, sLine); getline(infile, sLine); //cout<<sLine; //cout<<"Page size is : "<< pageSize << endl; //cout<<"Number of pages are : "<< numberOfPages <<endl; //cout<<"Path for table files is : "<< pathForData <<endl; string currentTableName; while(!infile.eof()) { string current(""); getline(infile, current); //cout << current<<endl; if( current.find("BEGIN") != -1 && !isBegin) { count=0; isBegin=true; continue; } else if( current.find("END") != -1 ) { if(count++==1) break; isBegin=false; isInTable=false; continue; } if(isBegin) { isInTable=true; isBegin=false; tableNames.push_back(current.substr(0,current.length())); currentTableName=current; tableNameToPrimaryKeys[currentTableName]=""; } else if(isInTable) { int index=current.find(','); string currentColumnName=current.substr(0,index); int len=current.length(); string currentDataType=current.substr(index+1,len); // cout<<currentDataType<<endl; currentColumnName=removeSpaces(currentColumnName); currentDataType=removeSpaces(currentDataType); if(currentDataType.find("varchar")!=string::npos || currentDataType.find("VARCHAR")!=string::npos) currentDataType="VARCHAR"; if(currentDataType=="integer") currentDataType="INT"; if(currentDataType=="float") currentDataType="FLOAT"; if(currentColumnName.compare("PRIMARY_KEY")==0){ // cout<<currentTableName<<" "<<currentDataType<<endl; tableNameToPrimaryKeys[currentTableName]=currentDataType; } else{ std::pair < string,string > bar = std::make_pair (currentColumnName,currentDataType); tableNameToColumnNames[currentTableName].push_back(bar); } } } }
bool DSMFactory::loadConfig(const string& conf_file_name, const string& conf_name, bool live_reload, DSMStateDiagramCollection* m_diags) { string script_name = conf_name.substr(0, conf_name.length()-5); // - .conf DBG("loading %s from %s ...\n", script_name.c_str(), conf_file_name.c_str()); AmConfigReader cfg; if(cfg.loadFile(conf_file_name)) return false; DSMScriptConfig script_config; script_config.RunInviteEvent = cfg.getParameter("run_invite_event")=="yes"; script_config.SetParamVariables = cfg.getParameter("set_param_variables")=="yes"; script_config.config_vars.insert(cfg.begin(), cfg.end()); if (live_reload) { INFO("live DSM config reload does NOT reload prompts and prompt sets!\n"); INFO("(see http://tracker.iptel.org/browse/SEMS-68)\n"); } else { if (!loadPrompts(cfg)) return false; if (!loadPromptSets(cfg)) return false; } DSMStateDiagramCollection* used_diags; if (m_diags != NULL) used_diags = m_diags; // got this from caller (main diags) else { // create a new set of diags used_diags = script_config.diags = new DSMStateDiagramCollection(); } if (!loadDiags(cfg, used_diags)) return false; vector<string> registered_apps; if (!registerApps(cfg, used_diags, registered_apps)) return false; ScriptConfigs_mut.lock(); try { Name2ScriptConfig[script_name] = script_config; // set ScriptConfig to this for all registered apps' names for (vector<string>::iterator reg_app_it= registered_apps.begin(); reg_app_it != registered_apps.end(); reg_app_it++) { string& app_name = *reg_app_it; // dispose of the old one, if it exists map<string, DSMScriptConfig>::iterator it=ScriptConfigs.find(app_name); if (it != ScriptConfigs.end()) { // may be in use by active call - don't delete but save to // old_diags for garbage collection (destructor) if (it->second.diags != NULL) old_diags.insert(it->second.diags); } // overwrite with new config ScriptConfigs[app_name] = script_config; } } catch(...) { ScriptConfigs_mut.unlock(); throw; } ScriptConfigs_mut.unlock(); bool res = true; vector<string> system_dsms = explode(cfg.getParameter("run_system_dsms"), ","); for (vector<string>::iterator it=system_dsms.begin(); it != system_dsms.end(); it++) { string status; if (createSystemDSM(script_name, *it, live_reload, status)) { } else { ERROR("creating system DSM '%s': '%s'\n", it->c_str(), status.c_str()); res = false; } } return res; }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); global_startstamp_ms = GetTickCount(); //LPWSTR *szArgList; LPSTR *szArgList; int nArgs; int i; //szArgList = CommandLineToArgvW(GetCommandLineW(), &nArgs); szArgList = CommandLineToArgvA(GetCommandLineA(), &nArgs); if( NULL == szArgList ) { //wprintf(L"CommandLineToArgvW failed\n"); return FALSE; } LPWSTR *szArgListW; int nArgsW; szArgListW = CommandLineToArgvW(GetCommandLineW(), &nArgsW); if( NULL == szArgListW ) { //wprintf(L"CommandLineToArgvW failed\n"); return FALSE; } global_audioinputdevicename="E-MU ASIO"; //"Wave (2- E-MU E-DSP Audio Proce" if(nArgs>1) { //global_filename = szArgList[1]; global_audioinputdevicename = szArgList[1]; } global_inputAudioChannelSelectors[0] = 0; // on emu patchmix ASIO device channel 1 (left) global_inputAudioChannelSelectors[1] = 1; // on emu patchmix ASIO device channel 2 (right) //global_inputAudioChannelSelectors[0] = 2; // on emu patchmix ASIO device channel 3 (left) //global_inputAudioChannelSelectors[1] = 3; // on emu patchmix ASIO device channel 4 (right) //global_inputAudioChannelSelectors[0] = 8; // on emu patchmix ASIO device channel 9 (left) //global_inputAudioChannelSelectors[1] = 9; // on emu patchmix ASIO device channel 10 (right) //global_inputAudioChannelSelectors[0] = 10; // on emu patchmix ASIO device channel 11 (left) //global_inputAudioChannelSelectors[1] = 11; // on emu patchmix ASIO device channel 12 (right) if(nArgs>2) { global_inputAudioChannelSelectors[0]=atoi((LPCSTR)(szArgList[2])); //0 for first asio channel (left) or 2, 4, 6, etc. } if(nArgs>3) { global_inputAudioChannelSelectors[1]=atoi((LPCSTR)(szArgList[3])); //1 for second asio channel (right) or 3, 5, 7, etc. } global_audiooutputdevicename="E-MU ASIO"; //"Wave (2- E-MU E-DSP Audio Proce" if(nArgs>4) { //global_filename = szArgList[1]; global_audiooutputdevicename = szArgList[4]; } global_outputAudioChannelSelectors[0] = 0; // on emu patchmix ASIO device channel 1 (left) global_outputAudioChannelSelectors[1] = 1; // on emu patchmix ASIO device channel 2 (right) //global_outputAudioChannelSelectors[0] = 2; // on emu patchmix ASIO device channel 3 (left) //global_outputAudioChannelSelectors[1] = 3; // on emu patchmix ASIO device channel 4 (right) //global_outputAudioChannelSelectors[0] = 8; // on emu patchmix ASIO device channel 9 (left) //global_outputAudioChannelSelectors[1] = 9; // on emu patchmix ASIO device channel 10 (right) //global_outputAudioChannelSelectors[0] = 10; // on emu patchmix ASIO device channel 11 (left) //global_outputAudioChannelSelectors[1] = 11; // on emu patchmix ASIO device channel 12 (right) if(nArgs>5) { global_outputAudioChannelSelectors[0]=atoi((LPCSTR)(szArgList[5])); //0 for first asio channel (left) or 2, 4, 6, etc. } if(nArgs>6) { global_outputAudioChannelSelectors[1]=atoi((LPCSTR)(szArgList[6])); //1 for second asio channel (right) or 3, 5, 7, etc. } if(nArgs>7) { global_cutfreq_hz = atof(szArgList[7]); } if(nArgs>8) { global_duration_sec = atof(szArgList[8]); } if(nArgs>9) { global_x = atoi(szArgList[9]); } if(nArgs>10) { global_y = atoi(szArgList[10]); } if(nArgs>11) { global_xwidth = atoi(szArgList[11]); } if(nArgs>12) { global_yheight = atoi(szArgList[12]); } if(nArgs>13) { global_alpha = atoi(szArgList[13]); } if(nArgs>14) { global_titlebardisplay = atoi(szArgList[14]); } if(nArgs>15) { global_menubardisplay = atoi(szArgList[15]); } if(nArgs>16) { global_acceleratoractive = atoi(szArgList[16]); } if(nArgs>17) { global_fontheight = atoi(szArgList[17]); } //new parameters if(nArgs>18) { global_statictextcolor_red = atoi(szArgList[18]); } if(nArgs>19) { global_statictextcolor_green = atoi(szArgList[19]); } if(nArgs>20) { global_statictextcolor_blue = atoi(szArgList[20]); } if(nArgs>21) { wcscpy(szWindowClass, szArgListW[21]); } if(nArgs>22) { wcscpy(szTitle, szArgListW[22]); } if(nArgs>23) { global_begin = szArgList[23]; } if(nArgs>24) { global_end = szArgList[24]; } global_statictextcolor=RGB(global_statictextcolor_red, global_statictextcolor_green, global_statictextcolor_blue); LocalFree(szArgList); LocalFree(szArgListW); int nShowCmd = false; //ShellExecuteA(NULL, "open", "begin.bat", "", NULL, nShowCmd); ShellExecuteA(NULL, "open", global_begin.c_str(), "", NULL, nCmdShow); ////////////////////////// //initialize random number ////////////////////////// srand((unsigned)time(0)); pFILE = fopen("devices.txt","w"); /////////////////////// //initialize port audio /////////////////////// global_err = Pa_Initialize(); if( global_err != paNoError ) { //MessageBox(0,"portaudio initialization failed",0,MB_ICONERROR); if(pFILE) fprintf(pFILE, "portaudio initialization failed.\n"); fclose(pFILE); return 1; } //////////////////////// //audio device selection //////////////////////// //SelectAudioInputDevice(); SelectAudioOutputDevice(); /* // Create an api map. std::map<int, std::string> apiMap; apiMap[RtAudio::MACOSX_CORE] = "OS-X Core Audio"; apiMap[RtAudio::WINDOWS_ASIO] = "Windows ASIO"; apiMap[RtAudio::WINDOWS_DS] = "Windows Direct Sound"; apiMap[RtAudio::UNIX_JACK] = "Jack Client"; apiMap[RtAudio::LINUX_ALSA] = "Linux ALSA"; apiMap[RtAudio::LINUX_OSS] = "Linux OSS"; apiMap[RtAudio::RTAUDIO_DUMMY] = "RtAudio Dummy"; std::vector< RtAudio::Api > apis; RtAudio::getCompiledApi(apis); fprintf(pFILE, "\nCompiled APIs:\n"); for (unsigned int i = 0; i<apis.size(); i++) fprintf(pFILE, " %s\n ", apiMap[apis[i]] ); fprintf(pFILE, "\nCurrent API: %s\n", apiMap[global_dac.getCurrentApi()]); unsigned int devices = global_dac.getDeviceCount(); fprintf(pFILE, "\nFound %i device(s) ...\n", devices); */ /* // Configure RtAudio global_rtParams.deviceId = global_dac.getDefaultOutputDevice(); global_rtParams.nChannels = NUM_CHANNELS; unsigned int sampleRate = SAMPLE_RATE; unsigned int bufferFrames = 512; // 512 sample frames */ // You don't necessarily have to do this - it will default to 44100 if not set. Tonic::setSampleRate(SAMPLE_RATE); //global_pSynth = new(StepSequencerExpSynth); //global_pSynth = new(EventsExpSynth); //global_pSynth = new(EventsExpBufferPlayerSynth); //global_pSynth = new(ControlSwitcherExpSynth); //global_pSynth = new(FMDroneExpSynth); //global_pSynth = new(SynthsAsGeneratorsExpSynth); //global_pSynth = new(FilteredNoiseSynth); //global_pSynth = new(StepSequencerBufferPlayerEffectExpSynth); //global_pSynth = new(StepSequencerBufferPlayerExpSynth); //global_pSynth = new(StepSequencerExpSynth); //global_pSynth = new(CompressorDuckingTestSynth); //global_pSynth = new(CompressorExpSynth); //global_pSynth = new(ControlSnapToScaleExpSynth); //global_pSynth = new(DelayExpSynth); //global_pSynth = new(FilterExpSynth); //global_pSynth = new(BandlimitedOscillatorExpSynth); //global_pSynth = new(BufferPlayerExpSynth); global_pSynth = new(SimpleStepSeqSynth); //global_pSynth = new(SimpleStepSequencerBufferPlayerSynth); //global_pSynth = new(LFNoiseTestSynth); //global_pSynth = new(ReverbTestSynth); //global_pSynth = new(SineSumSynth); //global_pSynth = new(XYSpeedSynth); //global_pSynth = new(StereoDelayTestSynth); VOROGUI_Init(global_pSynth); /* //would need something like this for vorogui vector<ControlParameter> params = global_pSynth->getParameters(); for (unsigned int i = 0; i < params.size(); i++) { TonicFloat min = params[i].getMin(); TonicFloat max = params[i].getMax(); TonicFloat value = params[i].getValue(); string mystring = params[i].getName(); } */ //global_pPOINTSET = VOROGUI_CreatePointset(); global_pPOINTSET = VOROGUI_ReadFromDisk(); ///////////////////// //init lowpass filter ///////////////////// /* SetLPF(global_cutfreq_hz, SAMPLE_RATE); */ /* global_DspParams[0] = SAMPLE_RATE; // sample rate global_DspParams[1] = global_cutfreq_hz; // cutoff frequency in Hz global_DspParams[2] = 1.25; // Q global_pDspFilter->setParams (global_DspParams); */ /* audioData[0] = new float[10000]; //usually, buffer is much smaller than 10000 audioData[1] = new float[10000]; */ ////////////// //setup stream ////////////// global_err = Pa_OpenStream( &global_stream, NULL, //NULL, //&global_inputParameters, &global_outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, 0, //paClipOff, // we won't output out of range samples so don't bother clipping them renderCallback, NULL ); //no callback userData if( global_err != paNoError ) { char errorbuf[2048]; sprintf(errorbuf, "Unable to open stream: %s\n", Pa_GetErrorText(global_err)); //MessageBox(0,errorbuf,0,MB_ICONERROR); if(pFILE) fprintf(pFILE, "%s\n", errorbuf); fclose(pFILE); return 1; } ////////////// //start stream ////////////// global_err = Pa_StartStream( global_stream ); if( global_err != paNoError ) { char errorbuf[2048]; sprintf(errorbuf, "Unable to start stream: %s\n", Pa_GetErrorText(global_err)); //MessageBox(0,errorbuf,0,MB_ICONERROR); if(pFILE) fprintf(pFILE, "%s\n", errorbuf); fclose(pFILE); return 1; } /* // open rtaudio stream try { global_dac.openStream(&global_rtParams, NULL, RTAUDIO_FLOAT32, sampleRate, &bufferFrames, &renderCallback, NULL, NULL); global_dac.startStream(); // hacky, yes, but let's just hang out for a while until someone presses a key //printf("\n\nPress Enter to stop\n\n"); //cin.get(); //dac.stopStream(); } catch (RtError& e) { std::cout << '\n' << e.getMessage() << '\n' << std::endl; exit(0); } */ /* fclose(pFILE); pFILE=NULL; */ MSG msg; HACCEL hAccelTable; // Initialize global strings //LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); //LoadString(hInstance, IDC_SPIWAVWIN32, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } if(global_acceleratoractive) { hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SPIWAVWIN32)); } else { hAccelTable = NULL; } // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; }
void TestSuite::menu_tests( string spec_file_path ) { ifstream fin; ofstream fout_tst, fout_ans; string tst_filename = "menu_test_"; string ans_filename = "menu_ans_"; string read; stringstream ss; int num_test_files = -1; double max, min = 0; int rand_int = 0; float rand_float = 0; srand (time(NULL)); system("mkdir -p tests"); char ans[128] = {'\0'}; while (strcmp(ans,"y") && strcmp(ans,"n") ) { for (int i = 0; i < 128; i++) ans[i] = '\0'; cout << "Would you like to generate files for testing menues? (y/n): " << endl; cin >> ans; } if (!strcmp(ans,"y") ) { // open .spec file check for success fin.open(spec_file_path.c_str()); if (!fin) return; fin.close(); //display menu for range, number of test cases while ( num_test_files < 0 || num_test_files > 100) { cout << "Enter number of test files to generate for menu testing (between 0 and 100): "; cin >> num_test_files; cout << endl; } cout << "\nWhat is the MINIMUM value you would like the randomly generated values to be?" << "\n Number between –2147483648 to 2147483646"<< endl; cin >> min; cout << "\nWhat is the MAXIMUM value you would like the randomly generated values to be?" << "\n Number between –2147483647 to 2147483647"<< endl; cin >> max; while(max <= min) { cout << "\n Maximum must be larger than mimimum." << endl; cout << "\nWhat is the MINIMUM value you would like the randomly generated values to be?" << "\n Number between –2147483648 to 2147483646"<< endl; cin >> min; cout << "\nWhat is the MAXIMUM value you would like the randomly generated values to be?" << "\n Number between –2147483647 to 2147483647"<< endl; cin >> max; } double range = max - min; //generate .tst files for (int i = 0; i < num_test_files;i++) { string test_filename = tst_filename; string answer_filename = ans_filename; //generate time stamp time_t rawTime; tm * timeInfo; char buffer [40]; string i_to_string = ""; ss.str(""); time (&rawTime); timeInfo = localtime (&rawTime); strftime (buffer,40,"%d_%m_%y_%H_%M_%S",timeInfo); string curr_time(buffer); ss << i+1; i_to_string = ss.str(); test_filename += i_to_string; answer_filename += i_to_string; test_filename = test_filename + "_" + curr_time + ".tst"; answer_filename = answer_filename + "_" + curr_time + ".ans"; fin.open(spec_file_path.c_str()); fout_ans.open(answer_filename.c_str()); fout_tst.open(test_filename.c_str()); //open .tst and .ans files for output while ( fin >> read ) { //atoi returns 0 if it is a string value, use in if stmts if (atoi(read.c_str())) fout_tst << read << endl; else if ( !atoi(read.c_str()) ) { if (read == "int") { rand_int = rand() % int(range)+(max-range+1); fout_tst << rand_int << endl; } else { rand_float = range * ((double)rand()/(double)RAND_MAX) + min; fout_tst << rand_float << endl; } } } fout_tst.close(); fin.close(); string s = goldencpp + " < " + test_filename; FILE *pfile = popen(s.c_str(), "r"); char buff[256]; while(fgets(buff, sizeof(buff), pfile) != 0) { string result(buff); fout_ans << result; } //closing out files //fout1.close(); fout_ans.close(); pclose(pfile); string command = "mv "; command += test_filename; command += " tests"; system (command.c_str()); command = "mv " + answer_filename + " tests"; system (command.c_str()); } }
void estimateSignalFitPerformance() { //open the ROOT efficiency file TFile ROOTFile(efficiencyFile.c_str()); if (!ROOTFile.IsOpen()) { cerr << "Error opening file " << efficiencyFile << ".\n"; return; } //get numBackgroundFail, numBackgroundPass, numSignalAll, and efficiency RooFitResult* fitResult = NULL; ROOTFile.GetObject("PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fitresults", fitResult); Double_t efficiency = 0.0; Double_t efficiencyError = 0.0; Double_t numBackgroundFail = 0.0; Double_t numBackgroundFailError = 0.0; Double_t numBackgroundPass = 0.0; Double_t numBackgroundPassError = 0.0; Double_t numSignalAll = 0.0; Double_t numSignalAllError = 0.0; if (fitResult != NULL) { RooRealVar* theEfficiency = (RooRealVar*)fitResult->floatParsFinal().find("efficiency"); efficiency = theEfficiency->getVal(); efficiencyError = theEfficiency->getError(); RooRealVar* theNumBackgroundFail = (RooRealVar*)fitResult->floatParsFinal().find("numBackgroundFail"); numBackgroundFail = theNumBackgroundFail->getVal(); numBackgroundFailError = theNumBackgroundFail->getError(); RooRealVar* theNumBackgroundPass = (RooRealVar*)fitResult->floatParsFinal().find("numBackgroundPass"); numBackgroundPass = theNumBackgroundPass->getVal(); numBackgroundPassError = theNumBackgroundPass->getError(); RooRealVar* theNumSignalAll = (RooRealVar*)fitResult->floatParsFinal().find("numSignalAll"); numSignalAll = theNumSignalAll->getVal(); numSignalAllError = theNumSignalAll->getError(); } else { cerr << "Error getting RooFitResult PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fitresults from file "; cerr << efficiencyFile << ".\n"; } //get integrals of tag-pass and tag-fail distributions TCanvas* fitCanvas = NULL; ROOTFile.GetObject("PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fit_canvas", fitCanvas); Double_t tagPassIntegral = 0; Double_t tagFailIntegral = 0; if (fitCanvas != NULL) { fitCanvas->cd(1); RooHist* tagPassDistribution = NULL; tagPassDistribution = (RooHist*)((TCanvas*)fitCanvas->GetPrimitive("fit_canvas_1"))->GetPrimitive("h_data"); fitCanvas->cd(2); RooHist* tagFailDistribution = NULL; tagFailDistribution = (RooHist*)((TCanvas*)fitCanvas->GetPrimitive("fit_canvas_2"))->GetPrimitive("h_data"); RooHist* blah = NULL; blah = (RooHist*)((TCanvas*)fitCanvas->GetPrimitive("fit_canvas_3"))->GetPrimitive("h_data"); cerr << blah->Integral() << endl; if ((tagPassDistribution != NULL) && (tagFailDistribution != NULL)) { tagPassIntegral = tagPassDistribution->Integral()*/*1.796*/1.844; tagFailIntegral = tagFailDistribution->Integral()*/*1.796*/1.844; } else cerr << "Error: could not get RooPlots.\n"; } else { cerr << "Error getting TCanvas PhotonToIDEB/unbinned/probe_eta_bin0__probe_nJets05_bin0__gaussPlusLinear/fit_canvas from file "; cerr << efficiencyFile << ".\n"; } //close file ROOTFile.Close(); //subtract fitted background from integral Double_t tagPassNumBkgSubtractedEvts = tagPassIntegral - numBackgroundPass; Double_t tagPassNumBkgSubtractedEvtsError = numBackgroundPassError; Double_t tagFailNumBkgSubtractedEvts = tagFailIntegral - numBackgroundFail; Double_t tagFailNumBkgSubtractedEvtsError = numBackgroundFailError; //calculate fitted signal Double_t tagPassNumFittedSignal = efficiency*numSignalAll; Double_t tagPassNumFittedSignalError = tagPassNumFittedSignal*sqrt(((efficiencyError*efficiencyError)/(efficiency*efficiency)) + ((numSignalAllError*numSignalAllError)/(numSignalAll*numSignalAll))); Double_t tagFailNumFittedSignal = (1.0 - efficiency)*numSignalAll; Double_t tagFailNumFittedSignalError = tagFailNumFittedSignal* sqrt(((efficiencyError*efficiencyError)/((1.0 - efficiency)*(1.0 - efficiency))) + ((numSignalAllError*numSignalAllError)/(numSignalAll*numSignalAll))); //calculate difference between signal fit result and background subtracted integral Double_t tagPassDifference = tagPassNumBkgSubtractedEvts - tagPassNumFittedSignal; Double_t tagPassDifferenceError = sqrt(tagPassNumBkgSubtractedEvtsError*tagPassNumBkgSubtractedEvtsError + tagPassNumFittedSignalError*tagPassNumFittedSignalError); Double_t tagFailDifference = tagFailNumBkgSubtractedEvts - tagFailNumFittedSignal; Double_t tagFailDifferenceError = sqrt(tagFailNumBkgSubtractedEvtsError*tagFailNumBkgSubtractedEvtsError + tagFailNumFittedSignalError*tagFailNumFittedSignalError); //compare signal fit result to background subtracted integral cout << "Tag pass signal fit: " << tagPassNumFittedSignal << " +/- " << tagPassNumFittedSignalError << endl; cout << "Tag pass background subtracted integral: " << tagPassNumBkgSubtractedEvts << " +/- " << tagPassNumBkgSubtractedEvtsError; cout << endl; cout << "Difference: " << tagPassDifference << " +/- " << tagPassDifferenceError << endl; cout << "Tag fail signal fit: " << tagFailNumFittedSignal << " +/- " << tagFailNumFittedSignalError << endl; cout << "Tag fail background subtracted integral: " << tagFailNumBkgSubtractedEvts << " +/- " << tagFailNumBkgSubtractedEvtsError; cout << endl; cout << "Difference: " << tagFailDifference << " +/- " << tagFailDifferenceError << endl; }
//Uses stat to check if the specified file exists static bool exists(string p) { struct stat DirInfo; int err = stat(p.c_str(), &DirInfo); return (err == 0); }
/******************************************************************************* * For each run, the input filename and restart information (if needed) must * * be given on the command line. For non-restarted case, command line is: * * * * executable <input file name> * * * * For restarted run, command line is: * * * * executable <input file name> <restart directory> <restart number> * * * *******************************************************************************/ int main(int argc, char* argv[]) { // Initialize libMesh, PETSc, MPI, and SAMRAI. LibMeshInit init(argc, argv); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); { // cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, initialize the restart database (if this is a restarted run), // and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Setup user-defined kernel function. LEInteractor::s_kernel_fcn = &kernel; LEInteractor::s_kernel_fcn_stencil_size = 8; // Get various standard options set in the input file. const bool dump_viz_data = app_initializer->dumpVizData(); const int viz_dump_interval = app_initializer->getVizDumpInterval(); const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter(); const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty(); const string exodus_filename = app_initializer->getExodusIIFilename(); const bool dump_restart_data = app_initializer->dumpRestartData(); const int restart_dump_interval = app_initializer->getRestartDumpInterval(); const string restart_dump_dirname = app_initializer->getRestartDumpDirectory(); const bool dump_postproc_data = app_initializer->dumpPostProcessingData(); const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval(); const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory(); if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty()) { Utilities::recursiveMkdir(postproc_data_dump_dirname); } const bool dump_timer_data = app_initializer->dumpTimerData(); const int timer_dump_interval = app_initializer->getTimerDumpInterval(); // Create a simple FE mesh. Mesh solid_mesh(NDIM); const double dx = input_db->getDouble("DX"); const double ds = input_db->getDouble("MFAC") * dx; string elem_type = input_db->getString("ELEM_TYPE"); const double R = 0.5; if (NDIM == 2 && (elem_type == "TRI3" || elem_type == "TRI6")) { const int num_circum_nodes = ceil(2.0 * M_PI * R / ds); for (int k = 0; k < num_circum_nodes; ++k) { const double theta = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes); solid_mesh.add_point(libMesh::Point(R * cos(theta), R * sin(theta))); } TriangleInterface triangle(solid_mesh); triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL; triangle.elem_type() = Utility::string_to_enum<ElemType>(elem_type); triangle.desired_area() = 1.5 * sqrt(3.0) / 4.0 * ds * ds; triangle.insert_extra_points() = true; triangle.smooth_after_generating() = true; triangle.triangulate(); } else { // NOTE: number of segments along boundary is 4*2^r. const double num_circum_segments = 2.0 * M_PI * R / ds; const int r = log2(0.25 * num_circum_segments); MeshTools::Generation::build_sphere(solid_mesh, R, r, Utility::string_to_enum<ElemType>(elem_type)); } // Ensure nodes on the surface are on the analytic boundary. MeshBase::element_iterator el_end = solid_mesh.elements_end(); for (MeshBase::element_iterator el = solid_mesh.elements_begin(); el != el_end; ++el) { Elem* const elem = *el; for (unsigned int side = 0; side < elem->n_sides(); ++side) { const bool at_mesh_bdry = !elem->neighbor(side); if (!at_mesh_bdry) continue; for (unsigned int k = 0; k < elem->n_nodes(); ++k) { if (!elem->is_node_on_side(k, side)) continue; Node& n = *elem->get_node(k); n = R * n.unit(); } } } solid_mesh.prepare_for_use(); BoundaryMesh boundary_mesh(solid_mesh.comm(), solid_mesh.mesh_dimension() - 1); solid_mesh.boundary_info->sync(boundary_mesh); boundary_mesh.prepare_for_use(); bool use_boundary_mesh = input_db->getBoolWithDefault("USE_BOUNDARY_MESH", false); Mesh& mesh = use_boundary_mesh ? boundary_mesh : solid_mesh; kappa_s = input_db->getDouble("KAPPA_S"); eta_s = input_db->getDouble("ETA_S"); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database // and, if this is a restarted run, from the restart database. Pointer<INSHierarchyIntegrator> navier_stokes_integrator; const string solver_type = app_initializer->getComponentDatabase("Main")->getString("solver_type"); if (solver_type == "STAGGERED") { navier_stokes_integrator = new INSStaggeredHierarchyIntegrator( "INSStaggeredHierarchyIntegrator", app_initializer->getComponentDatabase("INSStaggeredHierarchyIntegrator")); } else if (solver_type == "COLLOCATED") { navier_stokes_integrator = new INSCollocatedHierarchyIntegrator( "INSCollocatedHierarchyIntegrator", app_initializer->getComponentDatabase("INSCollocatedHierarchyIntegrator")); } else { TBOX_ERROR("Unsupported solver type: " << solver_type << "\n" << "Valid options are: COLLOCATED, STAGGERED"); } Pointer<IBFEMethod> ib_method_ops = new IBFEMethod("IBFEMethod", app_initializer->getComponentDatabase("IBFEMethod"), &mesh, app_initializer->getComponentDatabase("GriddingAlgorithm")->getInteger("max_levels")); Pointer<IBHierarchyIntegrator> time_integrator = new IBExplicitHierarchyIntegrator("IBHierarchyIntegrator", app_initializer->getComponentDatabase("IBHierarchyIntegrator"), ib_method_ops, navier_stokes_integrator); Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>("PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>("StandardTagAndInitialize", time_integrator, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>("LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>("GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Configure the IBFE solver. ib_method_ops->registerLagBodyForceFunction(tether_force_function); EquationSystems* equation_systems = ib_method_ops->getFEDataManager()->getEquationSystems(); // Create Eulerian initial condition specification objects. if (input_db->keyExists("VelocityInitialConditions")) { Pointer<CartGridFunction> u_init = new muParserCartGridFunction( "u_init", app_initializer->getComponentDatabase("VelocityInitialConditions"), grid_geometry); navier_stokes_integrator->registerVelocityInitialConditions(u_init); } if (input_db->keyExists("PressureInitialConditions")) { Pointer<CartGridFunction> p_init = new muParserCartGridFunction( "p_init", app_initializer->getComponentDatabase("PressureInitialConditions"), grid_geometry); navier_stokes_integrator->registerPressureInitialConditions(p_init); } // Create Eulerian boundary condition specification objects (when necessary). const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift(); vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM); if (periodic_shift.min() > 0) { for (unsigned int d = 0; d < NDIM; ++d) { u_bc_coefs[d] = NULL; } } else { for (unsigned int d = 0; d < NDIM; ++d) { ostringstream bc_coefs_name_stream; bc_coefs_name_stream << "u_bc_coefs_" << d; const string bc_coefs_name = bc_coefs_name_stream.str(); ostringstream bc_coefs_db_name_stream; bc_coefs_db_name_stream << "VelocityBcCoefs_" << d; const string bc_coefs_db_name = bc_coefs_db_name_stream.str(); u_bc_coefs[d] = new muParserRobinBcCoefs( bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry); } navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs); } // Create Eulerian body force function specification objects. if (input_db->keyExists("ForcingFunction")) { Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction( "f_fcn", app_initializer->getComponentDatabase("ForcingFunction"), grid_geometry); time_integrator->registerBodyForceFunction(f_fcn); } // Set up visualization plot file writers. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); if (uses_visit) { time_integrator->registerVisItDataWriter(visit_data_writer); } AutoPtr<ExodusII_IO> exodus_io(uses_exodus ? new ExodusII_IO(mesh) : NULL); // Initialize hierarchy configuration and data on all patches. ib_method_ops->initializeFEData(); time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm); // Deallocate initialization objects. app_initializer.setNull(); // Print the input database contents to the log file. plog << "Input database:\n"; input_db->printClassData(plog); // Write out initial visualization data. int iteration_num = time_integrator->getIntegratorStep(); double loop_time = time_integrator->getIntegratorTime(); if (dump_viz_data) { pout << "\n\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { exodus_io->write_timestep( exodus_filename, *equation_systems, iteration_num / viz_dump_interval + 1, loop_time); } } // Open streams to save lift and drag coefficients and the norms of the // velocity. if (SAMRAI_MPI::getRank() == 0) { drag_stream.open("C_D.curve", ios_base::out | ios_base::trunc); lift_stream.open("C_L.curve", ios_base::out | ios_base::trunc); U_L1_norm_stream.open("U_L1.curve", ios_base::out | ios_base::trunc); U_L2_norm_stream.open("U_L2.curve", ios_base::out | ios_base::trunc); U_max_norm_stream.open("U_max.curve", ios_base::out | ios_base::trunc); drag_stream.precision(10); lift_stream.precision(10); U_L1_norm_stream.precision(10); U_L2_norm_stream.precision(10); U_max_norm_stream.precision(10); } // Main time step loop. double loop_time_end = time_integrator->getEndTime(); double dt = 0.0; while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining()) { iteration_num = time_integrator->getIntegratorStep(); loop_time = time_integrator->getIntegratorTime(); pout << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "At beginning of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; System& U_system = equation_systems->get_system<System>(IBFEMethod::VELOCITY_SYSTEM_NAME); AutoPtr<NumericVector<double> > U_vec = U_system.current_local_solution->clone(); *U_vec = *U_system.solution; U_vec->close(); DofMap& U_dof_map = U_system.get_dof_map(); vector<unsigned int> vars(NDIM); for (unsigned int d = 0; d < NDIM; ++d) { vars[d] = d; } U_fcn = new MeshFunction(*equation_systems, *U_vec, U_dof_map, vars); U_fcn->init(); dt = time_integrator->getMaximumTimeStepSize(); time_integrator->advanceHierarchy(dt); loop_time += dt; delete U_fcn; pout << "\n"; pout << "At end of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "\n"; // At specified intervals, write visualization and restart files, // print out timer data, and store hierarchy data for post // processing. iteration_num += 1; const bool last_step = !time_integrator->stepsRemaining(); if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step)) { pout << "\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { exodus_io->write_timestep( exodus_filename, *equation_systems, iteration_num / viz_dump_interval + 1, loop_time); } } if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step)) { pout << "\nWriting restart files...\n\n"; RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num); } if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step)) { pout << "\nWriting timer data...\n\n"; TimerManager::getManager()->print(plog); } if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step)) { postprocess_data(patch_hierarchy, navier_stokes_integrator, mesh, equation_systems, iteration_num, loop_time, postproc_data_dump_dirname); } } // Close the logging streams. if (SAMRAI_MPI::getRank() == 0) { drag_stream.close(); lift_stream.close(); U_L1_norm_stream.close(); U_L2_norm_stream.close(); U_max_norm_stream.close(); } // Cleanup Eulerian boundary condition specification objects (when // necessary). for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d]; } // cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); return 0; } // main
void CWeaponDefHandler::ParseWeapon(const LuaTable& wdTable, WeaponDef& wd) { //bool twophase; bool manualBombSettings; //Allow the user to manually specify the burst and burstrate for his AircraftBomb int color; int color2; //bool turret; //bool smokeTrail; //string modelName; wd.tdfId = wdTable.GetInt("id", 0); wd.filename = wdTable.GetString("filename", "unknown"); wd.description = wdTable.GetString("name", "Weapon"); wd.cegTag = wdTable.GetString("cegTag", ""); wd.avoidFriendly = wdTable.GetBool("avoidFriendly", true); wd.avoidFeature = wdTable.GetBool("avoidFeature", true); wd.avoidNeutral = wdTable.GetBool("avoidNeutral", true); wd.collisionFlags = 0; const bool collideFriendly = wdTable.GetBool("collideFriendly", true); const bool collideFeature = wdTable.GetBool("collideFeature", true); const bool collideNeutral = wdTable.GetBool("collideNeutral", true); if (!collideFriendly) { wd.collisionFlags |= COLLISION_NOFRIENDLY; } if (!collideFeature) { wd.collisionFlags |= COLLISION_NOFEATURE; } if (!collideNeutral) { wd.collisionFlags |= COLLISION_NONEUTRAL; } wd.minIntensity = wdTable.GetFloat("minIntensity", 0.0f); wd.dropped = wdTable.GetBool("dropped", false); //FIXME: unused in the engine? manualBombSettings = wdTable.GetBool("manualBombSettings", false); wd.turret = wdTable.GetBool("turret", false); wd.highTrajectory = wdTable.GetInt("highTrajectory", 2); wd.noSelfDamage = wdTable.GetBool("noSelfDamage", false); wd.impactOnly = wdTable.GetBool("impactOnly", false); wd.waterweapon = wdTable.GetBool("waterWeapon", false); wd.fireSubmersed = wdTable.GetBool("fireSubmersed", wd.waterweapon); wd.submissile = wdTable.GetBool("submissile", false); wd.tracks = wdTable.GetBool("tracks", false); wd.fixedLauncher = wdTable.GetBool("fixedLauncher", false); wd.noExplode = wdTable.GetBool("noExplode", false); wd.isShield = wdTable.GetBool("isShield", false); wd.maxvelocity = wdTable.GetFloat("weaponVelocity", 0.0f); wd.beamtime = wdTable.GetFloat("beamTime", 1.0f); wd.beamburst = wdTable.GetBool("beamburst", false); wd.waterBounce = wdTable.GetBool("waterBounce", false); wd.groundBounce = wdTable.GetBool("groundBounce", false); wd.bounceSlip = wdTable.GetFloat("bounceSlip", 1.0f); wd.bounceRebound = wdTable.GetFloat("bounceRebound", 1.0f); wd.numBounce = wdTable.GetInt("numBounce", -1); wd.thickness = wdTable.GetFloat("thickness", 2.0f); wd.corethickness = wdTable.GetFloat("coreThickness", 0.25f); wd.laserflaresize = wdTable.GetFloat("laserFlareSize", 15.0f); wd.intensity = wdTable.GetFloat("intensity", 0.9f); wd.duration = wdTable.GetFloat("duration", 0.05f); wd.falloffRate = wdTable.GetFloat("fallOffRate", 0.5f); wd.lodDistance = wdTable.GetInt("lodDistance", 1000); wd.visuals.modelName = wdTable.GetString("model", ""); wd.visuals.smokeTrail = wdTable.GetBool("smokeTrail", false); wd.visuals.alwaysVisible = wdTable.GetBool("alwaysVisible", false); wd.visuals.sizeDecay = wdTable.GetFloat("sizeDecay", 0.0f); wd.visuals.alphaDecay = wdTable.GetFloat("alphaDecay", 1.0f); wd.visuals.separation = wdTable.GetFloat("separation", 1.0f); wd.visuals.noGap = wdTable.GetBool("noGap", true); wd.visuals.stages = wdTable.GetInt("stages", 5); wd.gravityAffected = wdTable.GetBool("gravityAffected", wd.dropped); wd.type = wdTable.GetString("weaponType", "Cannon"); // logOutput.Print("%s as %s",weaponname.c_str(),wd.type.c_str()); const bool melee = (wd.type == "Melee"); wd.targetBorder = wdTable.GetFloat("targetBorder", melee ? 1.0f : 0.0f); if (wd.targetBorder > 1.0f) { logOutput.Print("warning: targetBorder truncated to 1 (was %f)", wd.targetBorder); wd.targetBorder = 1.0f; } else if (wd.targetBorder < -1.0f) { logOutput.Print("warning: targetBorder truncated to -1 (was %f)", wd.targetBorder); wd.targetBorder = -1.0f; } wd.cylinderTargetting = wdTable.GetFloat("cylinderTargetting", melee ? 1.0f : 0.0f); wd.range = wdTable.GetFloat("range", 10.0f); const float accuracy = wdTable.GetFloat("accuracy", 0.0f); const float sprayAngle = wdTable.GetFloat("sprayAngle", 0.0f); const float movingAccuracy = wdTable.GetFloat("movingAccuracy", accuracy); // should really be tan but TA seem to cap it somehow // should also be 7fff or ffff theoretically but neither seems good wd.accuracy = sin((accuracy) * PI / 0xafff); wd.sprayAngle = sin((sprayAngle) * PI / 0xafff); wd.movingAccuracy = sin((movingAccuracy) * PI / 0xafff); wd.targetMoveError = wdTable.GetFloat("targetMoveError", 0.0f); wd.leadLimit = wdTable.GetFloat("leadLimit", -1.0f); wd.leadBonus = wdTable.GetFloat("leadBonus", 0.0f); // setup the default damages const LuaTable dmgTable = wdTable.SubTable("damage"); float defDamage = dmgTable.GetFloat("default", 0.0f); if (defDamage == 0.0f) { defDamage = 1.0f; //avoid division by zeroes } for (int a = 0; a < damageArrayHandler->GetNumTypes(); ++a) { wd.damages[a] = defDamage; } map<string, float> damages; dmgTable.GetMap(damages); map<string, float>::const_iterator di; for (di = damages.begin(); di != damages.end(); ++di) { const int type = damageArrayHandler->GetTypeFromName(di->first); if (type != 0) { float dmg = di->second; if (dmg != 0.0f) { wd.damages[type] = dmg; } else { wd.damages[type] = 1.0f; } } } wd.damages.impulseFactor = wdTable.GetFloat("impulseFactor", 1.0f); wd.damages.impulseBoost = wdTable.GetFloat("impulseBoost", 0.0f); wd.damages.craterMult = wdTable.GetFloat("craterMult", wd.damages.impulseFactor); wd.damages.craterBoost = wdTable.GetFloat("craterBoost", 0.0f); wd.areaOfEffect = wdTable.GetFloat("areaOfEffect", 8.0f) * 0.5f; wd.edgeEffectiveness = wdTable.GetFloat("edgeEffectiveness", 0.0f); // prevent 0/0 division in CGameHelper::Explosion if (wd.edgeEffectiveness > 0.999f) { wd.edgeEffectiveness = 0.999f; } wd.projectilespeed = wdTable.GetFloat("weaponVelocity", 0.0f) / GAME_SPEED; wd.startvelocity = max(0.01f, wdTable.GetFloat("startVelocity", 0.0f) / GAME_SPEED); wd.weaponacceleration = wdTable.GetFloat("weaponAcceleration", 0.0f) / GAME_SPEED / GAME_SPEED; wd.reload = wdTable.GetFloat("reloadTime", 1.0f); wd.salvodelay = wdTable.GetFloat("burstRate", 0.1f); wd.salvosize = wdTable.GetInt("burst", 1); wd.projectilespershot = wdTable.GetInt("projectiles", 1); wd.maxAngle = wdTable.GetFloat("tolerance", 3000.0f) * 180.0f / 0x7fff; wd.restTime = 0.0f; wd.metalcost = wdTable.GetFloat("metalPerShot", 0.0f); wd.energycost = wdTable.GetFloat("energyPerShot", 0.0f); wd.selfExplode = wdTable.GetBool("burnblow", false); wd.predictBoost = wdTable.GetFloat("predictBoost", wd.selfExplode ? 0.5f : 0.0f); wd.sweepFire = wdTable.GetBool("sweepfire", false); wd.canAttackGround = wdTable.GetBool("canAttackGround", true); wd.myGravity = wdTable.GetFloat("myGravity", 0.0f); wd.fireStarter = wdTable.GetFloat("fireStarter", 0.0f) * 0.01f; wd.paralyzer = wdTable.GetBool("paralyzer", false); if (wd.paralyzer) { wd.damages.paralyzeDamageTime = max(0, wdTable.GetInt("paralyzeTime", 10)); } else { wd.damages.paralyzeDamageTime = 0; } const float defShake = wd.paralyzer ? 0.0f : wd.damages.GetDefaultDamage(); wd.cameraShake = wdTable.GetFloat("cameraShake", defShake); wd.cameraShake = max(0.0f, wd.cameraShake); wd.soundTrigger = wdTable.GetBool("soundTrigger", false); //sunparser->GetDef(wd.highTrajectory, "0", weaponname + "minbarrelangle"); wd.stockpile = wdTable.GetBool("stockpile", false); wd.stockpileTime = wdTable.GetFloat("stockpileTime", wd.reload); wd.interceptor = wdTable.GetInt("interceptor", 0); wd.targetable = wdTable.GetInt("targetable", 0); wd.manualfire = wdTable.GetBool("commandfire", false); wd.coverageRange = wdTable.GetFloat("coverage", 0.0f); // FIXME -- remove the old style ? LuaTable shTable = wdTable.SubTable("shield"); const float3 shieldBadColor (1.0f, 0.5f, 0.5f); const float3 shieldGoodColor(0.5f, 0.5f, 1.0f); if (shTable.IsValid()) { wd.shieldRepulser = shTable.GetBool("repulser", false); wd.smartShield = shTable.GetBool("smart", false); wd.exteriorShield = shTable.GetBool("exterior", false); wd.visibleShield = shTable.GetBool("visible", false); wd.visibleShieldRepulse = shTable.GetBool("visibleRepulse", false); wd.visibleShieldHitFrames = shTable.GetInt("visibleHitFrames", 0); wd.shieldEnergyUse = shTable.GetFloat("energyUse", 0.0f); wd.shieldForce = shTable.GetFloat("force", 0.0f); wd.shieldRadius = shTable.GetFloat("radius", 0.0f); wd.shieldMaxSpeed = shTable.GetFloat("maxSpeed", 0.0f); wd.shieldPower = shTable.GetFloat("power", 0.0f); wd.shieldPowerRegen = shTable.GetFloat("powerRegen", 0.0f); wd.shieldPowerRegenEnergy = shTable.GetFloat("powerRegenEnergy", 0.0f); wd.shieldRechargeDelay = (int)(shTable.GetFloat("rechargeDelay", 0) * GAME_SPEED); wd.shieldStartingPower = shTable.GetFloat("startingPower", 0.0f); wd.shieldInterceptType = shTable.GetInt("interceptType", 0); wd.shieldBadColor = shTable.GetFloat3("badColor", shieldBadColor); wd.shieldGoodColor = shTable.GetFloat3("goodColor", shieldGoodColor); wd.shieldAlpha = shTable.GetFloat("alpha", 0.2f); } else { wd.shieldRepulser = wdTable.GetBool("shieldRepulser", false); wd.smartShield = wdTable.GetBool("smartShield", false); wd.exteriorShield = wdTable.GetBool("exteriorShield", false); wd.visibleShield = wdTable.GetBool("visibleShield", false); wd.visibleShieldRepulse = wdTable.GetBool("visibleShieldRepulse", false); wd.visibleShieldHitFrames = wdTable.GetInt("visibleShieldHitFrames", 0); wd.shieldEnergyUse = wdTable.GetFloat("shieldEnergyUse", 0.0f); wd.shieldForce = wdTable.GetFloat("shieldForce", 0.0f); wd.shieldRadius = wdTable.GetFloat("shieldRadius", 0.0f); wd.shieldMaxSpeed = wdTable.GetFloat("shieldMaxSpeed", 0.0f); wd.shieldPower = wdTable.GetFloat("shieldPower", 0.0f); wd.shieldPowerRegen = wdTable.GetFloat("shieldPowerRegen", 0.0f); wd.shieldPowerRegenEnergy = wdTable.GetFloat("shieldPowerRegenEnergy", 0.0f); wd.shieldRechargeDelay = (int)(wdTable.GetFloat("shieldRechargeDelay", 0) * GAME_SPEED); wd.shieldStartingPower = wdTable.GetFloat("shieldStartingPower", 0.0f); wd.shieldInterceptType = wdTable.GetInt("shieldInterceptType", 0); wd.shieldBadColor = wdTable.GetFloat3("shieldBadColor", shieldBadColor); wd.shieldGoodColor = wdTable.GetFloat3("shieldGoodColor", shieldGoodColor); wd.shieldAlpha = wdTable.GetFloat("shieldAlpha", 0.2f); } int defInterceptType = 0; if (wd.type == "Cannon") { defInterceptType = 1; } else if ((wd.type == "LaserCannon") || (wd.type == "BeamLaser")) { defInterceptType = 2; } else if ((wd.type == "StarburstLauncher") || (wd.type == "MissileLauncher")) { defInterceptType = 4; } wd.interceptedByShieldType = wdTable.GetInt("interceptedByShieldType", defInterceptType); wd.wobble = wdTable.GetFloat("wobble", 0.0f) * PI / 0x7fff / 30.0f; wd.dance = wdTable.GetFloat("dance", 0.0f) / GAME_SPEED; wd.trajectoryHeight = wdTable.GetFloat("trajectoryHeight", 0.0f); wd.noAutoTarget = (wd.manualfire || wd.interceptor || wd.isShield); wd.onlyTargetCategory = 0xffffffff; if (wdTable.GetBool("toAirWeapon", false)) { // fix if we sometime call aircrafts otherwise wd.onlyTargetCategory = CCategoryHandler::Instance()->GetCategories("VTOL"); //logOutput.Print("air only weapon %s %i",weaponname.c_str(),wd.onlyTargetCategory); } wd.largeBeamLaser = wdTable.GetBool("largeBeamLaser", false); wd.visuals.tilelength = wdTable.GetFloat("tileLength", 200.0f); wd.visuals.scrollspeed = wdTable.GetFloat("scrollSpeed", 5.0f); wd.visuals.pulseSpeed = wdTable.GetFloat("pulseSpeed", 1.0f); wd.visuals.beamdecay = wdTable.GetFloat("beamDecay", 1.0f); wd.visuals.beamttl = wdTable.GetInt("beamTTL", 0); if (wd.type == "Cannon") { wd.heightmod = wdTable.GetFloat("heightMod", 0.8f); } else if (wd.type == "BeamLaser") { wd.heightmod = wdTable.GetFloat("heightMod", 1.0f); } else { wd.heightmod = wdTable.GetFloat("heightMod", 0.2f); } wd.supplycost = 0.0f; wd.onlyForward = !wd.turret && (wd.type != "StarburstLauncher"); color = wdTable.GetInt("color", 0); color2 = wdTable.GetInt("color2", 0); const float3 rgbcol = hs2rgb(color / float(255), color2 / float(255)); wd.visuals.color = wdTable.GetFloat3("rgbColor", rgbcol); wd.visuals.color2 = wdTable.GetFloat3("rgbColor2", float3(1.0f, 1.0f, 1.0f)); wd.uptime = wdTable.GetFloat("weaponTimer", 0.0f); wd.flighttime = wdTable.GetInt("flightTime", 0) * 32; wd.turnrate = wdTable.GetFloat("turnRate", 0.0f) * PI / 0x7fff / 30.0f; if ((wd.type == "AircraftBomb") && !manualBombSettings) { if (wd.reload < 0.5f) { wd.salvodelay = min(0.2f, wd.reload); wd.salvosize = (int)(1 / wd.salvodelay) + 1; wd.reload = 5; } else { wd.salvodelay = min(0.4f, wd.reload); wd.salvosize = 2; } } //if(!wd.turret && (wd.type != "TorpedoLauncher")) { // wd.maxAngle*=0.4f; //} //2+min(damages[0]*0.0025f,weaponDef->areaOfEffect*0.1f) const float tempsize = 2.0f + min(wd.damages[0] * 0.0025f, wd.areaOfEffect * 0.1f); wd.size = wdTable.GetFloat("size", tempsize); wd.sizeGrowth = wdTable.GetFloat("sizeGrowth", 0.2f); wd.collisionSize = wdTable.GetFloat("collisionSize", 0.05f); wd.visuals.colorMap = 0; const string colormap = wdTable.GetString("colormap", ""); if (colormap != "") { wd.visuals.colorMap = CColorMap::LoadFromDefString(colormap); } wd.heightBoostFactor = wdTable.GetFloat("heightBoostFactor", -1.0f); wd.proximityPriority = wdTable.GetFloat("proximityPriority", 1.0f); // get some weapon specific defaults if (wd.type == "Cannon") { // CExplosiveProjectile wd.visuals.texture1 = &ph->plasmatex; wd.visuals.color = wdTable.GetFloat3("rgbColor", float3(1.0f,0.5f,0.0f)); wd.intensity = wdTable.GetFloat("intensity", 0.2f); } else if (wd.type == "Rifle") { // ... } else if (wd.type == "Melee") { // ... } else if (wd.type == "AircraftBomb") { // CExplosiveProjectile or CTorpedoProjectile wd.visuals.texture1 = &ph->plasmatex; } else if (wd.type == "Shield") { wd.visuals.texture1 = &ph->perlintex; } else if (wd.type == "Flame") { // CFlameProjectile wd.visuals.texture1 = &ph->flametex; wd.size = wdTable.GetFloat("size", tempsize); wd.sizeGrowth = wdTable.GetFloat("sizeGrowth", 0.5f); wd.collisionSize = wdTable.GetFloat("collisionSize", 0.5f); wd.duration = wdTable.GetFloat("flameGfxTime", 1.2f); if (wd.visuals.colorMap == 0) { wd.visuals.colorMap = CColorMap::Load12f(1.000f, 1.000f, 1.000f, 0.100f, 0.025f, 0.025f, 0.025f, 0.100f, 0.000f, 0.000f, 0.000f, 0.000f); } } else if (wd.type == "MissileLauncher") { // CMissileProjectile wd.visuals.texture1 = &ph->missileflaretex; wd.visuals.texture2 = &ph->missiletrailtex; } else if (wd.type == "TorpedoLauncher") { // CExplosiveProjectile or CTorpedoProjectile wd.visuals.texture1 = &ph->plasmatex; } else if (wd.type == "LaserCannon") { // CLaserProjectile wd.visuals.texture1 = &ph->laserfallofftex; wd.visuals.texture2 = &ph->laserendtex; wd.visuals.hardStop = wdTable.GetBool("hardstop", false); wd.collisionSize = wdTable.GetFloat("collisionSize", 0.5f); } else if (wd.type == "BeamLaser") { if (wd.largeBeamLaser) { wd.visuals.texture1 = ph->textureAtlas->GetTexturePtr("largebeam"); wd.visuals.texture2 = &ph->laserendtex; wd.visuals.texture3 = ph->textureAtlas->GetTexturePtr("muzzleside"); wd.visuals.texture4 = &ph->beamlaserflaretex; } else { wd.visuals.texture1 = &ph->laserfallofftex; wd.visuals.texture2 = &ph->laserendtex; wd.visuals.texture3 = &ph->beamlaserflaretex; } } else if (wd.type == "LightingCannon") { wd.visuals.texture1 = &ph->laserfallofftex; wd.thickness = wdTable.GetFloat("thickness", 0.8f); } else if (wd.type == "EmgCannon") { // CEmgProjectile wd.visuals.texture1 = &ph->plasmatex; wd.visuals.color = wdTable.GetFloat3("rgbColor", float3(0.9f,0.9f,0.2f)); wd.size = wdTable.GetFloat("size", 3.0f); } else if (wd.type == "DGun") { // CFireBallProjectile wd.collisionSize = wdTable.GetFloat("collisionSize", 10.0f); } else if (wd.type == "StarburstLauncher") { // CStarburstProjectile wd.visuals.texture1 = &ph->sbflaretex; wd.visuals.texture2 = &ph->sbtrailtex; wd.visuals.texture3 = &ph->explotex; } else { wd.visuals.texture1 = &ph->plasmatex; wd.visuals.texture2 = &ph->plasmatex; } // FIXME -- remove the 'textureN' format? LuaTable texTable = wdTable.SubTable("textures"); string texName; texName = wdTable.GetString("texture1", ""); texName = texTable.GetString(1, texName); if (texName != "") { wd.visuals.texture1 = ph->textureAtlas->GetTexturePtr(texName); } texName = wdTable.GetString("texture2", ""); texName = texTable.GetString(2, texName); if (texName != "") { wd.visuals.texture2 = ph->textureAtlas->GetTexturePtr(texName); } texName = wdTable.GetString("texture3", ""); texName = texTable.GetString(3, texName); if (texName != "") { wd.visuals.texture3 = ph->textureAtlas->GetTexturePtr(texName); } texName = wdTable.GetString("texture4", ""); texName = texTable.GetString(4, texName); if (texName != "") { wd.visuals.texture4 = ph->textureAtlas->GetTexturePtr(texName); } const string expGenTag = wdTable.GetString("explosionGenerator", ""); if (expGenTag.empty()) { wd.explosionGenerator = NULL; } else { wd.explosionGenerator = explGenHandler->LoadGenerator(expGenTag); } const string bounceExpGenTag = wdTable.GetString("bounceExplosionGenerator", ""); if (bounceExpGenTag.empty()) { wd.bounceExplosionGenerator = NULL; } else { wd.bounceExplosionGenerator = explGenHandler->LoadGenerator(bounceExpGenTag); } const float gd = max(30.0f, wd.damages[0] / 20.0f); const float defExpSpeed = (8.0f + (gd * 2.5f)) / (9.0f + (sqrt(gd) * 0.7f)) * 0.5f; wd.explosionSpeed = wdTable.GetFloat("explosionSpeed", defExpSpeed); // Dynamic Damage wd.dynDamageInverted = wdTable.GetBool("dynDamageInverted", false); wd.dynDamageExp = wdTable.GetFloat("dynDamageExp", 0.0f); wd.dynDamageMin = wdTable.GetFloat("dynDamageMin", 0.0f); wd.dynDamageRange = wdTable.GetFloat("dynDamageRange", 0.0f); LoadSound(wdTable, wd.firesound, "start"); LoadSound(wdTable, wd.soundhit, "hit"); if ((wd.firesound.getVolume(0) == -1.0f) || (wd.soundhit.getVolume(0) == -1.0f)) { // no volume (-1.0f) read from weapon definition, set it dynamically here if (wd.damages[0] <= 50.0f) { wd.soundhit.setVolume(0, 5.0f); wd.firesound.setVolume(0, 5.0f); } else { float soundVolume = sqrt(wd.damages[0] * 0.5f); if (wd.type == "LaserCannon") { soundVolume *= 0.5f; } float hitSoundVolume = soundVolume; if ((soundVolume > 100.0f) && ((wd.type == "MissileLauncher") || (wd.type == "StarburstLauncher"))) { soundVolume = 10.0f * sqrt(soundVolume); } if (wd.firesound.getVolume(0) == -1.0f) { wd.firesound.setVolume(0, soundVolume); } soundVolume = hitSoundVolume; if (wd.areaOfEffect > 8.0f) { soundVolume *= 2.0f; } if (wd.type == "DGun") { soundVolume *= 0.15f; } if (wd.soundhit.getVolume(0) == -1.0f) { wd.soundhit.setVolume(0, soundVolume); } } } // custom parameters table wdTable.SubTable("customParams").GetMap(wd.customParams); }
bool check_size( const string& s, size_t sz ) { return s.size( ) > sz; }
const char * getApkPath() { return g_apkPath.c_str(); }
auto check_size_( const int& n, const string& s ) { return to_string( n ).size( ) > s.size( ); }
bool isNumber(string s) { if (s.empty()) return false; int i = 0; while(isspace(s[i])) { i++; } if (s[i] == '+' || s[i] == '-') { i++; } bool eAppear = false; bool dotAppear = false; bool firstPart = false; bool secondPart = false; bool spaceAppear = false; while(s[i] != '\0') { if (s[i] == '.') { if (dotAppear || eAppear || spaceAppear) { return false; } else { dotAppear = true; } } else if (s[i] == 'e' || s[i] == 'E') { if (eAppear || !firstPart || spaceAppear) { return false; } else { eAppear = true; } } else if (isdigit(s[i])) { if (spaceAppear) { return false; } if (!eAppear) { firstPart = true; } else { secondPart = true; } } else if (s[i] == '+' || s[i] == '-') { if (spaceAppear) { return false; } if (!eAppear || !(s[i - 1] == 'e' || s[i - 1] == 'E')) { return false; } } else if (isspace(s[i])) { spaceAppear = true; } else { return false; } i++; } if (!firstPart) { return false; } else if (eAppear && !secondPart) { return false; } else { return true; } }
/* * Apply delta */ bool CReferenceBuilder::updateReference(std::vector<TUpdateList>& updateList, const CTimestamp& baseTimestamp, const CTimestamp& endTimestamp, const string& refRootPath, const string& refPath, volatile bool* stopAsked) { if (updateList.empty()) return true; uint i, j; for (i=0; i<updateList.size(); ++i) { const TUpdateList& tableList = updateList[i]; if (tableList.empty()) continue; CTableBuffer tableBuffer; tableBuffer.init(i, refRootPath, refPath); if (!tableBuffer.openAllRefFilesWrite()) { nlwarning("CReferenceBuilder::updateReference(): failed to preopen all reference files for table '%d' in reference '%s'", i, refPath.c_str()); return false; } for (j=0; j<tableList.size(); ++j) { const CUpdateFile& update = tableList[j]; if (update.EndTime < baseTimestamp || update.StartTime >= endTimestamp) continue; if (!tableBuffer.applyDeltaChanges(update.Filename)) { nlwarning("CReferenceBuilder::updateReference(): failed to apply delta file '%s'", update.Filename.c_str()); return false; } PDS_LOG_DEBUG(1)("CReferenceBuilder::updateReference(): updated reference with file '%s'", update.Filename.c_str()); } } return true; }
FragSpectrumScanDatabase::FragSpectrumScanDatabase(string id_par) : scan2rt(0) { if(id_par.empty()) id = "no_id"; else id = id_par; }
static void init_files(CursesWindow* window, const string& bbsdir) { window->SetColor(SchemeId::PROMPT); window->Puts("Creating Data Files.\n"); window->SetColor(SchemeId::NORMAL); memset(&syscfg, 0, sizeof(configrec)); strcpy(syscfg.systempw, "SYSOP"); sprintf(syscfg.msgsdir, "%smsgs%c", bbsdir.c_str(), File::pathSeparatorChar); sprintf(syscfg.gfilesdir, "%sgfiles%c", bbsdir.c_str(), File::pathSeparatorChar); sprintf(syscfg.datadir, "%sdata%c", bbsdir.c_str(), File::pathSeparatorChar); sprintf(syscfg.dloadsdir, "%sdloads%c", bbsdir.c_str(), File::pathSeparatorChar); sprintf(syscfg.tempdir, "%stemp1%c", bbsdir.c_str(), File::pathSeparatorChar); sprintf(syscfg.menudir, "%sgfiles%cmenus%c", bbsdir.c_str(), File::pathSeparatorChar, File::pathSeparatorChar); strcpy(syscfg.systemname, "My WWIV BBS"); strcpy(syscfg.systemphone, " - - "); strcpy(syscfg.sysopname, "The New Sysop"); syscfg.newusersl = 10; syscfg.newuserdsl = 0; syscfg.maxwaiting = 50; // Always use 1 for the primary port. syscfg.primaryport = 1; syscfg.newuploads = 0; syscfg.maxusers = 500; syscfg.newuser_restrict = restrict_validate; syscfg.req_ratio = 0.0; syscfg.newusergold = 100.0; valrec v; v.ar = 0; v.dar = 0; v.restrict = 0; v.sl = 10; v.dsl = 0; for (int i = 0; i < 10; i++) { syscfg.autoval[i] = v; } for (int i = 0; i < 256; i++) { slrec sl; sl.time_per_logon = static_cast<uint16_t>((i / 10) * 10); sl.time_per_day = static_cast<uint16_t>(((float)sl.time_per_logon) * 2.5); sl.messages_read = static_cast<uint16_t>((i / 10) * 100); if (i < 10) { sl.emails = 0; } else if (i <= 19) { sl.emails = 5; } else { sl.emails = 20; } if (i <= 10) { sl.posts = 10; } else if (i <= 25) { sl.posts = 10; } else if (i <= 39) { sl.posts = 4; } else if (i <= 79) { sl.posts = 10; } else { sl.posts = 25; } sl.ability = 0; if (i >= 150) { sl.ability |= ability_cosysop; } if (i >= 100) { sl.ability |= ability_limited_cosysop; } if (i >= 90) { sl.ability |= ability_read_email_anony; } if (i >= 80) { sl.ability |= ability_read_post_anony; } if (i >= 70) { sl.ability |= ability_email_anony; } if (i >= 60) { sl.ability |= ability_post_anony; } if (i == 255) { sl.time_per_logon = 255; sl.time_per_day = 255; sl.posts = 255; sl.emails = 255; } syscfg.sl[i] = sl; } syscfg.userreclen = sizeof(userrec); syscfg.waitingoffset = offsetof(userrec, waiting); syscfg.inactoffset = offsetof(userrec, inact); syscfg.sysstatusoffset = offsetof(userrec, sysstatus); syscfg.fuoffset = offsetof(userrec, forwardusr); syscfg.fsoffset = offsetof(userrec, forwardsys); syscfg.fnoffset = offsetof(userrec, net_num); syscfg.max_subs = 64; syscfg.max_dirs = 64; syscfg.qscn_len = 4 * (1 + syscfg.max_subs + ((syscfg.max_subs + 31) / 32) + ((syscfg.max_dirs + 31) / 32)); syscfg.post_call_ratio = 0.0; save_config(); create_arcs(out->window()); memset(&statusrec, 0, sizeof(statusrec_t)); string now(date()); strcpy(statusrec.date1, now.c_str()); strcpy(statusrec.date2, "00/00/00"); strcpy(statusrec.date3, "00/00/00"); strcpy(statusrec.log1, "000000.LOG"); strcpy(statusrec.log2, "000000.LOG"); strcpy(statusrec.gfiledate, now.c_str()); statusrec.callernum = 65535; statusrec.qscanptr = 2; statusrec.net_bias = 0.001f; statusrec.net_req_free = 3.0; qsc = (uint32_t *)malloc(syscfg.qscn_len); memset(qsc, 0, syscfg.qscn_len); save_status(); userrec u = {}; memset(&u, 0, sizeof(u)); write_user(0, &u); write_qscn(0, qsc); u.inact = inact_deleted; // Note: this is where init makes a user record #1 that is deleted for new installs. write_user(1, &u); write_qscn(1, qsc); { File namesfile(StrCat("data/", NAMES_LST)); namesfile.Open(File::modeBinary|File::modeReadWrite|File::modeCreateFile); } { subboard_t r = {}; r.name = "General"; r.filename = "GENERAL"; r.readsl = 10; r.postsl = 20; r.maxmsgs = 50; r.storage_type = 2; Subs subs("data/", {}); subs.insert(0, r); // TODO(rushfan): Check for error. subs.Save(); } { directoryrec d1; memset(&d1, 0, sizeof(directoryrec)); strcpy(d1.name, "Sysop"); strcpy(d1.filename, "SYSOP"); sprintf(d1.path, "dloads%csysop%c", File::pathSeparatorChar, File::pathSeparatorChar); File::mkdir(d1.path); d1.dsl = 100; d1.maxfiles = 50; d1.type = 65535; File dirsfile(StrCat("data/", DIRS_DAT)); dirsfile.Open(File::modeBinary|File::modeCreateFile|File::modeReadWrite); dirsfile.Write(&d1, sizeof(directoryrec)); memset(&d1, 0, sizeof(directoryrec)); strcpy(d1.name, "Miscellaneous"); strcpy(d1.filename, "misc"); sprintf(d1.path, "dloads%cmisc%c", File::pathSeparatorChar, File::pathSeparatorChar); File::mkdir(d1.path); d1.dsl = 10; d1.age = 0; d1.dar = 0; d1.maxfiles = 50; d1.mask = 0; d1.type = 0; dirsfile.Write(&d1, sizeof(directoryrec)); dirsfile.Close(); } window->Printf(".\n"); //////////////////////////////////////////////////////////////////////////// window->SetColor(SchemeId::PROMPT); window->Puts("Copying String and Miscellaneous files.\n"); window->SetColor(SchemeId::NORMAL); File::Rename("wwivini.510", WWIV_INI); File::Rename("menucmds.dat", StringPrintf("data%cmenucmds.dat", File::pathSeparatorChar)); File::Rename("regions.dat", StringPrintf("data%cregions.dat", File::pathSeparatorChar)); File::Rename("wfc.dat", StringPrintf("data%cwfc.dat", File::pathSeparatorChar)); // Create the sample files. create_text("welcome.msg"); create_text("newuser.msg"); create_text("feedback.msg"); create_text("system.msg"); create_text("logon.msg"); create_text("logoff.msg"); create_text("logoff.mtr"); create_text("comment.txt"); window->Printf(".\n"); //////////////////////////////////////////////////////////////////////////// window->SetColor(SchemeId::PROMPT); window->Puts("Decompressing archives. Please wait"); window->SetColor(SchemeId::NORMAL); if (File::Exists("en-menus.zip")) { system("unzip -qq -o en-menus.zip -dgfiles "); File::Rename("en-menus.zip", StringPrintf("dloads%csysop%cen-menus.zip", File::pathSeparatorChar, File::pathSeparatorChar)); } if (File::Exists("regions.zip")) { system("unzip -qq -o regions.zip -ddata"); const string destination = StringPrintf("dloads%csysop%cregions.zip", File::pathSeparatorChar, File::pathSeparatorChar); File::Rename("regions.zip", destination); } if (File::Exists("zip-city.zip")) { system("unzip -qq -o zip-city.zip -ddata"); const string destination = StringPrintf("dloads%csysop%czip-city.zip", File::pathSeparatorChar, File::pathSeparatorChar); File::Rename("zip-city.zip", destination); } window->SetColor(SchemeId::NORMAL); }
void AndroidWrapper::log(string tag, string message){ __android_log_write(ANDROID_LOG_INFO, tag.c_str(), message.c_str()); }
//___________________________________________________________________ static LREThreadBuffer * DataSplit(LinesReader ** lrIRScript, const string & stProgName, HANDLE mutex, const string & stSampleFolder, const string & stThreadID, const int iMaxAnonymsNum, const vector<FeatureSet*> & vAuthors, const int iAuthorsNumber, const map<string,FeatureInfo,LexComp> & lexicon) { const string stLogsFolder = ResourceBox::Get()->getStringValue("LogsFolder"); LREThreadBuffer * buffer = NULL; int i; string stLine(75,'\0'); fprintf(stderr,"Alloc LRE Thread buffer\n"); fflush(stderr); buffer = new LREThreadBuffer(mutex,NULL,iMaxAnonymsNum+1,iAuthorsNumber); if (buffer == NULL) { fprintf(stderr,"Alloc Thread Buffer failed\n"); fflush(stderr); return NULL; } buffer->vAuthors = &vAuthors; fprintf(stderr,"Alloc LRE IR Aux buffer\n"); fflush(stderr); LREAuxBuffer * irAuxBuffer=NULL; if (stProgName.compare("LRE") == 0) { const bool bIsClosedSet = (ResourceBox::Get()->getIntValue("ClosedAuthorSet") > 0); const bool bIsNoAuthorSet = (ResourceBox::Get()->getIntValue("IsNoAuthor") > 0); if (bIsClosedSet) irAuxBuffer = new LREAuxBuffer(); else if (!bIsNoAuthorSet) irAuxBuffer = new LREOpenSet(&lexicon); else irAuxBuffer = new LRENoAuthor(); } else if (stProgName.compare("LREClassify") == 0) { irAuxBuffer = new LREClassify(); } else abort_err(string("Unknown program name in LRE: name=")+stProgName); if (irAuxBuffer == NULL) abort_err(string("Failed to alloc LREAuxBuffer. name=")+stProgName); buffer->irAuxBuffer=irAuxBuffer; SimilarityMeasure * simMatch = NULL; const string stSimFuncType = ResourceBox::Get()->getStringValue("SimilarityMeasure"); if (stSimFuncType.compare("cos") == 0) simMatch = new CosineMatch; else if (stSimFuncType.compare("dist") == 0) simMatch = new DistanceMatch; else if (stSimFuncType.compare("mmx") == 0) simMatch = new MinMaxMatch; else abort_err(string("Illegal SimilarityMeasure: ")+stSimFuncType); if (simMatch == NULL) abort_err(string("Failed to alloc SimilarityMeasure. name=")+stSimFuncType); buffer->simMatch = simMatch; buffer->lexicon = &lexicon; buffer->iAnonymIndex=0; buffer->stThreadID = stThreadID; buffer->stIRScriptFile = stSampleFolder+"IRScript_"+stThreadID+".txt"; buffer->stIRQueryLog = stLogsFolder+"IR_"+stThreadID+".txt"; buffer->stDebugLog = stLogsFolder+"debug_"+stThreadID+".txt"; fprintf(stderr,"open the script file: %s\n",buffer->stIRScriptFile.c_str()); fflush(stderr); FILE * fIRScript = open_file(buffer->stIRScriptFile,"DataSplit","w"); i=0; const string stScriptFile = stSampleFolder+"anonyms.txt"; fprintf(stderr,"Alloc Lines Reader: %s\n",stScriptFile.c_str()); fflush(stderr); if (lrIRScript == NULL) {fprintf(stderr,"NULL lines reader buffer\n"); fflush(stderr); exit(0);} if (*lrIRScript == NULL) *lrIRScript = new LinesReader(stScriptFile,512); if (*lrIRScript == NULL) {fprintf(stderr,"Failed to alloc lines reader object\n"); fflush(stderr); exit(0);} while ((i++<iMaxAnonymsNum) && (*lrIRScript)->bMoreToRead()) { (*lrIRScript)->voGetLine(stLine); fprintf(fIRScript,"%s\n",stLine.c_str()); fflush(fIRScript); } fclose(fIRScript); fprintf(stderr,"Create Thread\n"); fflush(stderr); // Create the batch audio mutex. DWORD tiLREThread; buffer->tid = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)LREProcess,(void*)buffer,0,&tiLREThread); if (buffer->tid == NULL) abort_err("Failed to create LRE thread"); return buffer; }
void mime_head::build_head(string& out, bool clean) { if (clean) out.clear(); if (m_headers) { std::list<HEADER*>::const_iterator cit = m_headers->begin(); for (; cit != m_headers->end(); ++cit) { out.format_append("%s: %s\r\n", (*cit)->name, (*cit)->value); } } char buf[64]; rfc822 rfc; rfc.mkdate_cst(time(NULL), buf, sizeof(buf)); out.format_append("Date: %s\r\n", buf); if (m_from) out.format_append("From: %s\r\n", m_from->c_str()); if (m_replyto) out.format_append("Reply-To: %s\r\n", m_replyto->c_str()); if (m_returnpath) out.format_append("Return-Path: %s\r\n", m_returnpath->c_str()); if (m_tos) append_recipients(out, "To", *m_tos); if (m_ccs) append_recipients(out, "Cc", *m_ccs); if (m_bccs) append_recipients(out, "Bcc", *m_bccs); if (m_subject) out.format_append("Subject: %s\r\n", m_subject->c_str()); out.append("MIME-Version: 1.0\r\n"); out.format_append("Content-Type: %s/%s", get_ctype(), get_stype()); if (m_boundary) out.format_append(";\r\n\tboundary=\"%s\"\r\n", m_boundary->c_str()); else out.append("\r\n"); out.append("\r\n"); }
//___________________________________________________________________ void LRE(const string & stProgName) { Timer tiLRE; tiLRE.reset(); tiLRE.start(); const string stLogsFolder = ResourceBox::Get()->getStringValue("LogsFolder"); const string stSampleFolder = ResourceBox::Get()->getStringValue("SampleFolder"); const string stFeaturePool = stSampleFolder+"FeaturePool.txt"; const int iIRLoops = ResourceBox::Get()->getIntValue("IRLoops"); map<string,FeatureInfo,LexComp> lexicon; HANDLE mutex; fprintf(stderr,"Main Thread - Start\n"); fflush(stderr); mutex = CreateMutex(NULL,FALSE,NULL); if (mutex == NULL) abort_err("Create mutex failed in LRE"); fprintf(stderr,"Load Feature Pool\n"); fflush(stderr); LoadFeatureSet(lexicon,NULL,stFeaturePool,NULL); LinesReader * lrSamples=NULL; fprintf(stderr,"Load Authors Set - Start\n"); fflush(stderr); const string stAuthorSuffix = string("Author") + ((stProgName.compare("LREClassify") == 0)?"\\":"\\Ftrs\\"); const string stAuthorsList = stSampleFolder + "authors.txt"; const int iMaxCandsNum = ScriptSize(stAuthorsList); vector<FeatureSet*> vAuthors(iMaxCandsNum+1); const int iAuthorsNumber = LoadCandidates(vAuthors,stSampleFolder+stAuthorSuffix,stAuthorsList,&lexicon); fprintf(stderr,"Load Authors Set - End (#Authors=%d)\n",iAuthorsNumber); fflush(stderr); FILE * fIRQueryLog = open_file(stLogsFolder+"IR_All.txt","LRE","w"); const int iMaxAnonymsNum = ScriptSize(stSampleFolder+"anonyms.txt"); const int iMultiProcDegree = ResourceBox::Get()->getIntValue("MultiProcessingDegree"); const int iAnonymSegment = iMaxAnonymsNum/iMultiProcDegree + iMaxAnonymsNum%iMultiProcDegree; int i; list<LREThreadBuffer*> threadsList; LREThreadBuffer * buffer=NULL; char thread_id[50]; string stLine(75,'\0'); fprintf(stderr,"#MaxAnonyms=%d; Segment: %d + %d = %d\n",iMaxAnonymsNum,iMaxAnonymsNum/iMultiProcDegree,iMaxAnonymsNum%iMultiProcDegree,iAnonymSegment); fflush(stderr); fprintf(stderr,"Alloc Threads\n"); fflush(stderr); for (i=0;i<iMultiProcDegree;i++) { sprintf(thread_id,"tid%d",i); buffer = DataSplit(&lrSamples, stProgName, mutex, stSampleFolder, thread_id, iAnonymSegment, vAuthors, iAuthorsNumber, lexicon); threadsList.push_back(buffer); } fprintf(stderr,"Join Threads\n"); fflush(stderr); list<LREThreadBuffer*>::iterator threadsIter = threadsList.begin(); int iAnonymsNumber=0; while (threadsIter != threadsList.end()) { fprintf(stderr,"Wait for thread end\n"); fflush(stderr); LREThreadBuffer * ltbTemp = *threadsIter; fprintf(stderr,"Call Join\n"); fflush(stderr); // Wait for the LRE thread end. WaitForSingleObject(ltbTemp->tid,INFINITE); CloseHandle(ltbTemp->tid); threadsIter++; fprintf(stderr,"Consolidate the IR queries log. tid=%s, #Anonyms=%d\nIRLog=%s\n", ltbTemp->stThreadID.c_str(),ltbTemp->iAnonymIndex,ltbTemp->stIRQueryLog.c_str()); fflush(stderr); ConsolidateLogs(fIRQueryLog,ltbTemp->stIRQueryLog); iAnonymsNumber += ltbTemp->iAnonymIndex; fprintf(stderr,"Del Buffer\n"); fflush(stderr); delete ltbTemp; fprintf(stderr,"End Join iteration\n"); fflush(stderr); } fprintf(stderr,"#Anonyms=%d\n",iAnonymsNumber); fflush(stderr); ClearItems(vAuthors,iAuthorsNumber); tiLRE.stop(); fprintf(stderr,"Total LRE Time: %d\n",tiLRE.iGetTime()); fflush(stderr); fprintf(fIRQueryLog,"#Total LRE Time: %d\n",tiLRE.iGetTime()); fflush(fIRQueryLog); fclose(fIRQueryLog); if (CloseHandle(mutex) == 0) abort_err("Destroy mutex failed"); }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; HGDIOBJ hOldBrush; HGDIOBJ hOldPen; int iOldMixMode; COLORREF crOldBkColor; COLORREF crOldTextColor; int iOldBkMode; HFONT hOldFont, hFont; TEXTMETRIC myTEXTMETRIC; switch (message) { case WM_CREATE: { /* HWND hStatic = CreateWindowEx(WS_EX_TRANSPARENT, L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_CENTER, 0, 100, 100, 100, hWnd, (HMENU)IDC_MAIN_STATIC, GetModuleHandle(NULL), NULL); */ HWND hStatic = CreateWindowEx(WS_EX_TRANSPARENT, L"STATIC", L"", WS_CHILD | WS_VISIBLE | global_staticalignment, 0, 100, 100, 100, hWnd, (HMENU)IDC_MAIN_STATIC, GetModuleHandle(NULL), NULL); if(hStatic == NULL) MessageBox(hWnd, L"Could not create static text.", L"Error", MB_OK | MB_ICONERROR); SendMessage(hStatic, WM_SETFONT, (WPARAM)global_hFont, MAKELPARAM(FALSE, 0)); } break; case WM_SIZE: { RECT rcClient; GetClientRect(hWnd, &rcClient); HWND hStatic = GetDlgItem(hWnd, IDC_MAIN_STATIC); global_staticwidth = rcClient.right - 0; //global_staticheight = rcClient.bottom-(rcClient.bottom/2); global_staticheight = rcClient.bottom-0; //spi, begin global_imagewidth = rcClient.right - 0; global_imageheight = rcClient.bottom - 0; WavSetLib_Initialize(global_hwnd, IDC_MAIN_STATIC, global_staticwidth, global_staticheight, global_fontwidth, global_fontheight, global_staticalignment); //spi, end //SetWindowPos(hStatic, NULL, 0, rcClient.bottom/2, global_staticwidth, global_staticheight, SWP_NOZORDER); SetWindowPos(hStatic, NULL, 0, 0, global_staticwidth, global_staticheight, SWP_NOZORDER); } break; case WM_CTLCOLOREDIT: { SetBkMode((HDC)wParam, TRANSPARENT); SetTextColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF)); return (INT_PTR)::GetStockObject(NULL_PEN); } break; case WM_CTLCOLORSTATIC: { SetBkMode((HDC)wParam, TRANSPARENT); //SetTextColor((HDC)wParam, RGB(0xFF, 0xFF, 0xFF)); SetTextColor((HDC)wParam, global_statictextcolor); return (INT_PTR)::GetStockObject(NULL_PEN); } break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... SetStretchBltMode(hdc, COLORONCOLOR); //spi, begin /* StretchDIBits(hdc, 0, 0, global_xwidth, global_yheight, 0, 0, FreeImage_GetWidth(global_dib), FreeImage_GetHeight(global_dib), FreeImage_GetBits(global_dib), FreeImage_GetInfo(global_dib), DIB_RGB_COLORS, SRCCOPY); */ StretchDIBits(hdc, 0, 0, global_imagewidth, global_imageheight, 0, 0, FreeImage_GetWidth(global_dib), FreeImage_GetHeight(global_dib), FreeImage_GetBits(global_dib), FreeImage_GetInfo(global_dib), DIB_RGB_COLORS, SRCCOPY); //spi, end hOldBrush = SelectObject(hdc, (HBRUSH)GetStockObject(GRAY_BRUSH)); //hOldPen = SelectObject(hdc, (HPEN)GetStockObject(WHITE_PEN)); //original hOldPen = SelectObject(hdc, (HPEN)GetStockObject(WHITE_PEN)); //spi //iOldMixMode = SetROP2(hdc, R2_MASKPEN); iOldMixMode = SetROP2(hdc, R2_MERGEPEN); //original //iOldMixMode = SetROP2(hdc, R2_MERGEPENNOT); //spi //iOldMixMode = SetROP2(hdc, R2_MERGENOTPEN); //spi //Rectangle(hdc, 100, 100, 200, 200); //crOldBkColor = SetBkColor(hdc, RGB(0xFF, 0x00, 0x00)); //original crOldBkColor = SetBkColor(hdc, RGB(0x00, 0x00, 0x00)); //spi crOldTextColor = SetTextColor(hdc, RGB(0xFF, 0xFF, 0xFF)); iOldBkMode = SetBkMode(hdc, TRANSPARENT); //hFont=CreateFontW(70,0,0,0,FW_BOLD,0,0,0,0,0,0,2,0,L"SYSTEM_FIXED_FONT"); //hOldFont=(HFONT)SelectObject(hdc,global_hFont); hOldFont = (HFONT)SelectObject(hdc, global_hFont); GetTextMetrics(hdc, &myTEXTMETRIC); global_fontwidth = myTEXTMETRIC.tmAveCharWidth; //TextOutW(hdc, 100, 100, L"test string", 11); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HDC tempHdc = CreateCompatibleDC(hdc); // create a bitmap of a size you need, let's say it 100x100 HBITMAP canvas = CreateCompatibleBitmap(hdc, global_imagewidth, global_imageheight); // select new bitmap into context, don't forget to save old bitmap handle HBITMAP oldBmp = (HBITMAP)SelectObject(tempHdc, canvas); //BLENDFUNCTION blend = { AC_SRC_OVER, 0, 127, AC_SRC_ALPHA }; BLENDFUNCTION blend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA }; //BLENDFUNCTION blend = { AC_SRC_OVER, 0, 64, AC_SRC_ALPHA }; //BLENDFUNCTION blend = { AC_SRC_OVER, 0, 32, AC_SRC_ALPHA }; //SetDCPenColor(tempHdc, RGB(255, 0, 0)); //SetDCBrushColor(tempHdc, RGB(255, 0, 0)); //Rectangle(tempHdc, dim.left, dim.top, dim.right, dim.bottom); if (global_pPOINTSET) VOROGUI_DrawPointset(global_pPOINTSET, tempHdc); bool res = AlphaBlend(hdc, 0, 0, global_imagewidth, global_imageheight, tempHdc, 0, 0, global_imagewidth, global_imageheight, blend); // reset the old bitmap SelectObject(tempHdc, oldBmp); // canvas is no longer needed and should be deleted to avoid GDI leaks DeleteObject(canvas); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SelectObject(hdc, hOldBrush); SelectObject(hdc, hOldPen); SetROP2(hdc, iOldMixMode); SetBkColor(hdc, crOldBkColor); SetTextColor(hdc, crOldTextColor); SetBkMode(hdc, iOldBkMode); SelectObject(hdc, hOldFont); //DeleteObject(hFont); EndPaint(hWnd, &ps); } break; case WM_LBUTTONDOWN: { VOROGUI_OnLButtonDown(global_pPOINTSET, hWnd, wParam, lParam); } break; case WM_LBUTTONUP: { VOROGUI_OnLButtonUp(global_pPOINTSET, hWnd, wParam, lParam); } break; case WM_RBUTTONUP: { VOROGUI_OnRButtonUp(global_pPOINTSET, hWnd, wParam, lParam); } break; case WM_KEYDOWN: { if (wParam == 'S') { VOROGUI_WriteToDisk(global_pPOINTSET); } } break; case WM_DESTROY: { if (global_timer) timeKillEvent(global_timer); global_abort=true; //Sleep(2000); //should be the same as the sleep time in the StartGlobalProcess() callback function WavSetLib_Terminate(); FreeImage_Unload(global_dib); DeleteObject(global_hFont); //if(global_pFILE) fclose(global_pFILE); global_ifstream.close(); if (pFILE) fclose(pFILE); //added by spi /* delete global_pDspFilter; */ /* delete[] audioData[0]; delete[] audioData[1]; */ /* global_dac.stopStream(); */ if (global_pSynth) delete global_pSynth; VOROGUI_DestroyPointset(global_pPOINTSET); //int nShowCmd = false; //ShellExecuteA(NULL, "open", "end.bat", "", NULL, nShowCmd); ShellExecuteA(NULL, "open", global_end.c_str(), "", NULL, 0); PostQuitMessage(0); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
void read_conf() { read_file(file_conf); vector<string> conf_line = split(file_content.c_str(), '\n'); conf_file_dir = conf_line[0]; conf_port = atoi(conf_line[1].c_str()); }
//Function to run c++ souce with redirected input/output int TestSuite::run_code( string test_file_path, string test_file_name ){ //bool TestSuite::run_code( string test_file_path, string test_file_name ) { //This instruction will run the test program with test_file_path piped in. //The output will be piped to test_out.klein and also a file in the //timestamped output file directory. The klein file is used for comparing //the output to the expected value. int wait_pid, childpid; int time_limit = 10; bool time_limit_exceeded = false; bool inf_loop = false; int fpt1, fpt2; int status; int timer = 0; char path[512] = ""; getcwd(path, sizeof(path)); string dir_path = path; int i = testProgram.rfind('/'); string run_instruction = "./" + testProgram.substr(i + 1, testProgram.length()) + " < "; run_instruction += dir_path + test_file_path.substr(1, test_file_path.length()); run_instruction += " > " + dir_path + "/test_out.klein"; childpid = fork(); if (childpid == 0) { fpt1 = open(test_file_path.c_str(), O_RDONLY); fpt2 = creat("dummy.out", 0644); fpt2 = creat("test_out.klein", 0644); close(0); dup(fpt1); close(fpt1); close(1); dup(fpt2); close(fpt2); execvp(testProgram.c_str() ,NULL); while (true) { sleep(10); timer++; wait_pid = waitpid(childpid, &status,WNOHANG); if (wait_pid != 0) break; if (timer > time_limit) { //insert failed code because of infinite loop time_limit_exceeded = true; inf_loop = true; kill(childpid, 9); } } } if (inf_loop) { //do stuff for failing because of inifinite loop return 0; } else { chdir((testProgram.substr(0, i )).c_str()); system( run_instruction.c_str() ); chdir(path); return 1; } }
int main(int argc, char ** argv) { initFeatures(); initClassifiers(); initDataProviders(); initNonMaximumSuppressors(); const string commandLineKeys = "{h|help|false|show help and exit}" "{c|config||.xml or .yml file containing detector " "configuration parameters, i.e. features to used " "and thier parameters, classifier type " "and params of the training algorithm, " "general detection parameters}" "{|pos||path to annotation with positive examples}" "{|posname|annotation|name of the positive annotation file node to read from}" "{|neg||path to annotation with negative examples}" "{|negname|annotation|name of the negative annotation file node to read from}" "{|dump||prefix of files to save dataset to}" "{|rand|50|number of random samples to draw from each negative image}" "{|bi|3|number of bootstrap iterations}" "{|samples|0|number of samples to draw from all false detections at each iteration. All false positives are used by default}" "{|mirror|true|use horizontaly flip positives for training}" "{|mem|0|preallocate memory for specified " "number of samples in the dataset. " "If more samples are needed dataset resize " "is performed that may lead to additional memory usage}" "{|seed||seed to initialize RNG}"; CommandLineParser cmdParser(argc, argv, commandLineKeys.c_str()); if (cmdParser.get<bool>("help")) { cmdParser.printParams(); return 0; } if (cmdParser.get<string>("seed") == "") { theRNG() = RNG(time(0)); } else { theRNG() = RNG(cmdParser.get<uint64>("seed")); } cout << "rng state: " << theRNG().state << endl; FileStorage config(cmdParser.get<string>("config"), FileStorage::READ); CV_Assert(config.isOpened()); // read detection parameters DetectionParams detectorParams; FileNode detectorParamsFn = config["detector_params"]; if (detectorParamsFn.empty()) { cout << "Error. detection_params tag is missed in cofig file" << endl; return 2; } cout << "reading general detector parameters..." << flush; detectorParamsFn >> detectorParams; cout << "done" << endl; // configure feature descriptors Features features; FileNode featuresFn = config["features"]; for (FileNodeIterator i = featuresFn.begin(); i != featuresFn.end(); ++i) { FileNode featureType = (*i)["name"]; CV_Assert(!featureType.empty()); string featureName; featureType >> featureName; Ptr<Feature> feature = Algorithm::create<Feature>(featureName); feature->read(*i); features.featuresSet.push_back(feature); cout << featureName << " feature is used" << endl; } // configure classifier FileNode classifierFn = config["classifier"]; FileNode classifierType = classifierFn["name"]; CV_Assert(!classifierType.empty()); string classifierName; classifierType >> classifierName; Ptr<Classifier> classifier = Algorithm::create<Classifier>(classifierName); classifier->read(classifierFn); cout << classifierName << " classifier is used" << endl; string classifierModelFile = classifierFn["modelFileName"]; string classifierModelName = classifierFn["modelName"]; // configure nonmaximum suppressor FileNode nmsFn = config["nonmaximum_suppressor"]; Ptr<NonMaximumSuppressor> nms = 0; if (!nmsFn.empty()) { FileNode nmsType = nmsFn["name"]; CV_Assert(!nmsType.empty()); string nmsName; nmsType >> nmsName; nms = Algorithm::create<NonMaximumSuppressor>(nmsName); nms->read(nmsFn); cout << nmsName << " nonmaximum suppressor is used" << endl; }
void DBSystem::insertRecord(string tableName, string record) { //printCurrentMemory(); int pageId = getLastPageForTable(tableName); struct Page * newPage; //cout<<record; if(pageId<0){ cout<<"Such a page doesn't exist\n"; return; } string path(pathForData); path +="/"+tableName +".csv"; FILE *fd=fopen(path.c_str(),"ra+"); if(fd==NULL){ cout<<"table file not found "<<endl;return;} fseek ( fd, 0, SEEK_END ); fprintf (fd, "%s\n",record.c_str()); fclose(fd); int sizeofPage = pageIdToSizeHash[pageId]; if((sizeofPage + record.size()) <= pageSize) { if((sizeofPage + record.size()) == pageSize) ifAddNewlineToTable[tableName] = 1; else ifAddNewlineToTable[tableName] = 0; //We can append the record to this page if(pageMemoryHash[pageId] == NULL){ //cout<<"MISS "; pageToRecordMap[pageId].second +=1; newPage = createNewPage(tableName, pageId); lruPageReplace(pageId,newPage); pageMemoryHash[pageId] = newPage; } else{ //cout<<"HIT\n"; pageToRecordMap[pageId].second +=1; newPage = pageMemoryHash[pageId]; newPage->pageRecords->push_back(record); placePageInFront(newPage); } pageIdToSizeHash[pageId] += record.size(); //Increment the end record id of the page } else{ int newPageId = getNewPageIdForTable(tableName,record);//this function def needs to change newPage = createNewPage(tableName, newPageId); lruPageReplace(newPageId,newPage); pageMemoryHash[newPageId] = newPage; if(ifAddNewlineToTable[tableName] == 1){ pageIdToSizeHash[newPageId]++; ifAddNewlineToTable[tableName] = 0; } //cout<<"MISS "<<newPageId<<endl; } /******************** Adding to unique attrib's list********************************/ vector< string > temp; std::istringstream ss(record); std::string token; while(std::getline(ss, token, ',')) { temp.push_back(token); } int si=temp.size(); for(int m=0;m<si;m++) { if(uniqueAttribs[tableName].size()==0) { std::set<string> t; t.insert(temp[m]); uniqueAttribs[tableName].push_back(t); } else { uniqueAttribs[tableName][m].insert(temp[m]); //cout<<attribs[tableNames[i]][m].size()<<endl;l } } //printCurrentMemory(); //printAllPages(tableName); }
//##EDIT## Function for 2 void two(string name) { //Decided not to touch this. I mean no harm, but it's very stringy and clustered and would give me a headach to sort. It's okay tho. //SOme of my older projects are much much muuuuchhhhh worse :p cout << "Very vise, as you vell remember, probably, ze skillet ees \n" << "an excellent tool for eencapeetation" << "congrats. Een ze next room you see a dancing flamingo \n" << "Suddenly you find a book in your hands and ze flamingo bows its head "; int response2 = 0; do { cout << "Vot action do you take?\n" << " 1) Bash ze dancing Famingo, it vos shaking its boom at me!\n" << " 2) Read ze contents of ze book to ze flamingo\n" << " 3) Nutink \n"; cin >> response2; } while (response2 < 1 || response2 > 3); if (response2 == 2) { cout << "Maybe you do not know " << name.c_str() << "zat flamingos *hate* books\n" << "If you attempt to read to zem they vill attempt to keek you\n" << "in a most unfortunate area. Zen, ven you are bent over\n" << "zey keek you een head. I vonce saw zis happen to a\n" << "highly experienced Shakeyspearean dude \n" << "I teenk he tought zat ze flameengo vos dissing Shakeyspeare\n" << "So he read even louder to ze flameengo, I vill not \n" << "divoolge any further details.\nGame Over.\n\n."; return; } else if (response2 == 3) { cout << "I vouldn't call you naive " << name.c_str() << "but zis parteekular\n" << "flameengo vos carrying a highly dangerous veapon called a \n" << "florpenskook, zis veapon causes high pitched screaming from peekles\n" << "eef I remember correktly, you vere turned into a peekle vonce\n" << "so, vhile you might not emit screams, you vill feel like\n" << "suptink is eating your head. Zis ees because ze florpenskook\n" << "makes ze victim feel like a peeckle, vich ees vy ze peekles scream\n" << "zey know of their impendeeng doom, your head repreesents ze part \n" << "of ze peekle getting eaten. Vell? Do you feel it?\n" << "You probably don't because I vos making dat all up.\n" << "Game Over.\n\n"; return; } else // Remember to enclose each 'else' statement (}) at the //*end* of the program { cout << "Vonce again you have proven you breelliance to ze vorld\n" << "Yes, ze folks are like " << name.c_str() << "ees smaaaaaart.\n" << "Of course I already knew zat, by now you're probably vondering\n" << "eef I am a vampire, ze answer is, sort of, I vonce vos a minion to ze\n" << "great vampire Kenchman, I vos his dentist, he vos a smaaaart person.\n" << "Von day ven I vos attendink to his teeth, he bit me\n" << "and he vos like 'Oh, I vasn't trying to do that, let me make it up to you.'\n" << "So he took me to thees poob, but eenside, he vos attacked by a moonchking\n" << "Ze moonchkin knocked all his toothys out, and mine. So, after ze brawl\n" << "He said, 'My leetle feedly beets grow back, here, have my teeth.'\n" << "Me, being Kenchmans Frenchman Henchman, could not refuse sooch an offer\n" << "So, zat ees how I got zees lurverly toothys. I digress, in our next room\n" << "ve have JahJa Bingz, Opi Van Kenobi, and Padme Amidala, each in danger\n"; int response3 = 0; do { cout << "So? Who do ve save?\n\n" << "1) JarJarBinx\n" << "2) Podme Amydaly\n" << "3) Obi Van Kenopi\n"; cin >> response3; } while (response3 < 1 || response3 > 3); if (response3 == 2) { cout << "You have just proven that you tink Jarjar's ears \n" << "Make his boot look fat. And zat you like skinnybooted people\n" << "Don't hate on ze fatbooted people.\n" << "Game Over.\n."; return; } else if (response3 == 3) { cout << "Now really, do you tink zat a Jeddy vould need help\n" << "From eescapeeng from a deadly trap? Opi Van Kenopi ees probably\n" << "telling ze Jeddy couceel zat " << name.c_str() << " ees a beeg goon\n" << "Game Over. "; return; } else { cout << "Very good, ze goongan vould need a lot of help.\n" << "zat ees because everyone loves ze preencess, and hates on ze goongans\n" << "Without your help hees life vould have been meeserable\n" << "Speaking of vich, my vonderful vampire client, who ees a very smaaaart\n" << "person, has eexsperience on sooch a matter. Vonce he vos playing a piano\n" << "een ze vampire equeevalent of Carnegie Hall, vith hees toes mind you, ven\n" << "Jane Ulkovitz, ze lead tenor of ze poonk rock band 'Ze Dirty, Oogly, Nasty Hariballs\n" << "Valked up and gave heem a teacup full of peat moss. And he vos like 'Oh, vy tank\n" << "Jane Ulkvotiz, for dees lurverly teacup, even zough you make eet a point to make\n" << "My life miserable. So zen he put ze teacup on ze piano he vos playing,\n" << "and continued. Zat vos ven ze teacup started doing joomping jacks\n" << "on ze piano, zen he vos like 'oh, Jane ulkovits of ze dirty,oogly\n" << "hairballs. you are making my life meeserable, you should go avay'.\n" << "But enough of ze hair-raising anecdotes of Kenchman ze lurverly vampire\n" << "Ze next Question concerns teacups. Eef you saw a Tanzanian een a vig\n" << "drinking geenger ale een a teacup vile een ze ookefenooke svamp,"; int response4 = 0; do { cout << "Vot do you do? Do you...\n" << "1) Say, 'Howdy Tanzanian guy een a vig drinking ginger ale!'?\n" << "2) Sneak oop vith a boombox and start playing ze dirty oogly nasty hairballs?\n" << "3) Geev heem a two-liter bottle of orange soda?\n"; cin >> response4; } while (response4 < 1 || response4 > 3); if (response4 == 1) { cout << "My dear " << name.c_str() << " Eesn't eet obvious\n" << "Zat ze guy ees a Tanzanian een a vig etc.? I mean \n" << "I said zat, didn't I? Eef you said sumptink zat painfooly obvious\n" << "I tink he vould heet you vith a peekle.\n" << "Ah peeckles, zey are so lurverly for heeting people vith\n" << "Especially eef zeir really beeg vones, vouldn't you be happy\n" << "Heeting a person saying obvious tings like 'Zis ees a Tanzanian een\n" << "A vig drinking ginger ale in a teacoop, een a svamp'?\n" << "Game Over.\n"; return; } else if (response4 == 2) { cout << "Eeven eef zis vos ze correct answer, I vould not avard it too you\n" << "eef you remember, it vos zat band who gave ze teacoop to ze great\n" << "and very smaaaaaart vampire, Kenchman. Besides, ze Tanzanian vould\n" << "be a beet occupied drinking ginger ale een a teacup, vouldn't he?\n" << "Game Over."; return; } else { cout << "Zat ees ze correct answer, nutink is more refreshing from\n" << "drinking ginger ale in a teacup zen a two liter bottel of orange soda\n" << "besides, I'm obsesses vith oranges, so zat vould be ze correct answer anyvay\n" << "Deed you not notice zat? Do you know vy vampires are so hard to find?\n" << "It ees because ve don't look een ze right places. For Example\n" << "ze great vampire Kenchman has a blog, and an biography\n" << "Ze blog ees at vvv.Kenchman.komm, ze biog ees a Vikipedia.\n" << "See? If people thought like zem zey woulf find a lot more\n" << "but enough about ze vampires. Let us move to ze fascinating soobject\n" << "of Tarzan.\n\n"; int response5 = 0; do { cout << "Ven Tarzan vos een his prime vich of zese vos he?\n" << "1) A park ranger?\n" << "2) An electrician?\n" << "3) An ice cream man?\n"; cin >> response5; } while (response5 < 1 || response5 > 3); if (response5 == 1) { cout << "Vhile it is true zar he vos a park ranger, it vos not vhile een his prime\n" << "He became a park ranger at ze age of 12, but vhen he vos een hees 'prime'\n" << "he vos sumptink else. Sorry.\n\n"; return; } else if (response5 == 3) { cout << "Now vere de heg do you tink that Tarzan vould get an ice cream truck\n" << "Ze local joongle icecream repo store? Of course not!!!!!!\n" << "Dear " << name.c_str() << " zere is no icecream repo store.\n" << "zat vould never fly een ze joongle, vy not? Because it doesn't have vings\n" << "Vot vere you tinking I vould say? Honh?\n\n"; return; } else { cout << "Congratulations, you have completed our test vith admirable results.\n" << "Zat ees eef you didn't have to keep restarting.\n" << "Eef zat vos ze result, vell, maybe you should talk to ze kung fu baboon.\n" << "Yes, Tarzan vos an electrician een hees prime, but since zer vos no\n" << "electricity een ze joongle he vos unemployed."; cout << "Would you like to play again?\n"; int responsel = 0; do { cout << "1) for Yes,\n" << " 2) for No"; cin >> responsel; } while (responsel < 1 || responsel > 2); if (responsel == 1) { cout << "Very well\n"; return; } else { cout << "Farewell " << name.c_str() << "."; } } } } } }
#include "unpackhash.hpp" #include <iostream> #include "print_dir.hpp" using namespace std; using namespace Spread; typedef Hash::DirMap HMap; string D1 = "hey\n"; string D2 = "yo man\n"; Hash H1(D1.c_str(), D1.size()); Hash H2(D2.c_str(), D2.size()); int main() { UnpackHash unp; UnpackHash::makeIndex("test1.zip", unp.index, "_unp_test2"); printDir(unp.index); unp.addInput(Hash(), "test1.zip"); unp.addOutput(H2, "_unp_test1/file2.txt"); unp.addOutput(H2, "_unp_test1/file2_copy.txt"); unp.addOutput(H1, "_unp_test1/dir/to/file1.txt"); unp.addOutput(H2, "_unp_test1/file2_again.txt"); unp.run(); printDir("_unp_test1"); printDir("_unp_test2");
// 짝수 단어 #include <iostream> #include <string> using namespace std; string str; int size; void input() { cin >> str; size = str.size(); for (char &c : str) c -= 'a'; } void solve() { long long r = 0; for (int from = 0; from < size; from++) { int ok = 0; for (int to = from+1; to < size; to+=2) { ok ^= 1 << str[to-1]; ok ^= 1 << str[to]; if (ok == 0) r++; } } cout << r << endl; } int main() { int t; cin >> t; while (t--) { input(); solve(); }
void DSMFactory::runMonitorAppSelect(const AmSipRequest& req, string& start_diag, map<string, string>& vars) { #define FALLBACK_OR_EXCEPTION(code, reason) \ if (MonSelectFallback.empty()) { \ throw AmSession::Exception(code, reason); \ } else { \ DBG("falling back to '%s'\n", MonSelectFallback.c_str()); \ start_diag = MonSelectFallback; \ return; \ } #ifdef USE_MONITORING if (NULL == MONITORING_GLOBAL_INTERFACE) { ERROR("using $(mon_select) but monitoring not loaded\n"); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } AmArg di_args, ret; if (MonSelectCaller != MonSelect_NONE) { AmUriParser from_parser; if (MonSelectCaller == MonSelect_FROM) from_parser.uri = req.from_uri; else { size_t end; string pai = getHeader(req.hdrs, SIP_HDR_P_ASSERTED_IDENTITY, true); if (!from_parser.parse_contact(pai, 0, end)) { WARN("Failed to parse " SIP_HDR_P_ASSERTED_IDENTITY " '%s'\n", pai.c_str()); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } } if (!from_parser.parse_uri()) { DBG("failed to parse caller uri '%s'\n", from_parser.uri.c_str()); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } AmArg caller_filter; caller_filter.push("caller"); caller_filter.push(from_parser.uri_user); DBG(" && looking for caller=='%s'\n", from_parser.uri_user.c_str()); di_args.push(caller_filter); } if (MonSelectCallee != MonSelect_NONE) { AmArg callee_filter; callee_filter.push("callee"); if (MonSelectCallee == MonSelect_RURI) callee_filter.push(req.user); else { AmUriParser to_parser; size_t end; if (!to_parser.parse_contact(req.to, 0, end)) { ERROR("Failed to parse To '%s'\n", req.to.c_str()); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } if (!to_parser.parse_uri()) { DBG("failed to parse callee uri '%s'\n", to_parser.uri.c_str()); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } callee_filter.push(to_parser.uri_user); } DBG(" && looking for callee=='%s'\n", req.user.c_str()); di_args.push(callee_filter); } // apply additional filters if (MonSelectFilters.size()) { string app_params = getHeader(req.hdrs, PARAM_HDR); for (vector<string>::iterator it = MonSelectFilters.begin(); it != MonSelectFilters.end(); it++) { AmArg filter; filter.push(*it); // avp name string app_param_val = get_header_keyvalue(app_params, *it); filter.push(app_param_val); di_args.push(filter); DBG(" && looking for %s=='%s'\n", it->c_str(), app_param_val.c_str()); } } MONITORING_GLOBAL_INTERFACE->invoke("listByFilter",di_args,ret); if ((ret.getType()!=AmArg::Array)|| !ret.size()) { DBG("call info not found. caller uri %s, r-uri %s\n", req.from_uri.c_str(), req.r_uri.c_str()); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } AmArg sess_id, sess_params; if (ret.size()>1) { DBG("multiple call info found - picking the first one\n"); } const char* session_id = ret.get(0).asCStr(); sess_id.push(session_id); MONITORING_GLOBAL_INTERFACE->invoke("get",sess_id,sess_params); if ((sess_params.getType()!=AmArg::Array)|| !sess_params.size() || sess_params.get(0).getType() != AmArg::Struct) { INFO("call parameters not found. caller uri %s, r-uri %s, id %s\n", req.from_uri.c_str(), req.r_uri.c_str(), ret.get(0).asCStr()); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } AmArg& sess_dict = sess_params.get(0); if (sess_dict.hasMember("app")) { start_diag = sess_dict["app"].asCStr(); DBG("selected application '%s' for session\n", start_diag.c_str()); } else { ERROR("selected session params don't contain 'app'\n"); FALLBACK_OR_EXCEPTION(500, "Internal Server Error"); } AmArg2DSMStrMap(sess_dict["appParams"], vars); vars["mon_session_record"] = session_id; #else ERROR("using $(mon_select) for dsm application, " "but compiled without monitoring support!\n"); throw AmSession::Exception(500, "Internal Server Error"); #endif #undef FALLBACK_OR_EXCEPTION }
Onceref<Triead> App::findTriead(TrieadOwner *to, const string &tname, bool immed) { pw::lockmutex lm(mutex_); assertNotAbortedL(); // reference guarantees that it won't disappear when sleeping Autoref<TrieadUpd> selfupd = assertTrieadOwnerL(to); // A special short-circuit for the self-reference, a thread can // find itself even if it's not fully constructed. if (to->get()->getName() == tname) return to->get(); if (selfupd->waitFor_ != NULL) throw Exception::fTrace("In Triceps application '%s' thread '%s' owner object must not be used from 2 OS threads.", name_.c_str(), to->get()->getName().c_str()); TrieadUpdMap::iterator it = threads_.find(tname); if (it == threads_.end()) throw Exception::fTrace("In Triceps application '%s' thread '%s' is referring to a non-existing thread '%s'.", name_.c_str(), to->get()->getName().c_str(), tname.c_str()); Autoref <TrieadUpd> upd = it->second; if (upd->dispose_) // disposed is the same as non-existing throw Exception::fTrace("In Triceps application '%s' thread '%s' is referring to a non-existing thread '%s'.", name_.c_str(), to->get()->getName().c_str(), tname.c_str()); Triead *t = upd->t_; if (t != NULL && (immed || t->isConstructed())) return t; if (immed) throw Exception::fTrace("In Triceps application '%s' thread '%s' did an immediate find of a declared but undefined thread '%s'.", name_.c_str(), to->get()->getName().c_str(), tname.c_str()); // Make sure that won't deadlock: go through the dependency // chain and ensure that it doesn't return back to our thread. // Doing it once up front is enough, because afterwards the responsibility // of the deadlock detection will be on the new sleepers. for (TrieadUpd *p = upd; p != NULL; p = p->waitFor_) { if (p == selfupd.get()) { // print the list of dependencies, it repeats the same loop Erref deps; for (TrieadUpd *pp = upd; pp != selfupd.get(); pp = pp->waitFor_) deps.f("%s waits for %s", pp->t_->getName().c_str(), pp->waitFor_->t_->getName().c_str()); throw Exception::fTrace(deps, "In Triceps application '%s' thread '%s' waiting for thread '%s' would cause a deadlock:", name_.c_str(), to->get()->getName().c_str(), tname.c_str()); } } selfupd->waitFor_ = upd; try { do { upd->waitL(name_, tname, deadline_); // will throw on timeout t = upd->t_; } while (!isAbortedL() && (t == NULL || !t->isConstructed())); selfupd->waitFor_ = NULL; } catch (...) { selfupd->waitFor_ = NULL; throw; } assertNotAbortedL(); return t; }