int main(int argc, char *argv[]) { msg_error_t res = MSG_OK; #ifdef _MSC_VER unsigned int prev_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT); #endif MSG_init(&argc, argv); if (argc < 3) { printf("Usage: %s platform_file deployment_file\n", argv[0]); printf("example: %s msg_platform.xml msg_deployment.xml\n", argv[0]); exit(1); } res = test_all(argv[1], argv[2]); #ifdef _MSC_VER _set_output_format(prev_exponent_format); #endif if (res == MSG_OK) return 0; else return 1; }
bool ThermoFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv) { OBMol* pmol = dynamic_cast<OBMol*>(pOb); string title(pmol->GetTitle()); OBNasaThermoData* pND = static_cast<OBNasaThermoData*>(pmol->GetData(ThermoData)); if(!pND) { obErrorLog.ThrowError(__FUNCTION__,"No thermo data in " + title, obWarning); return false; } ostream &ofs = *pConv->GetOutStream(); unsigned int i; #ifdef _MSC_VER unsigned oldf = _set_output_format(_TWO_DIGIT_EXPONENT); #endif string formula = pmol->GetSpacedFormula(); vector<string> toks; tokenize(toks,formula); ofs << left << setw(24) << title.substr(0,24); //Check that atom numbers are less than 999 bool toobig=toks.size()>8; for(i=0;i<toks.size() && !toobig ;i+=2) if(atoi(toks[i+1].c_str())>999) toobig =true; if(toobig) //Reaction Design extension ofs << string(20,' '); else { toks.resize(8); for(i=0;i<8;i+=2) ofs << left << setw(2) << toks[i] << right << setw(3) << toks[i+1]; } ofs << right << pND->GetPhase() << fixed << setprecision(3) << setw(10) << pND->GetLoT(); ofs << setw(10) << pND->GetHiT() << setw(9) << pND->GetMidT() << " 01"; if(toobig) ofs << "&\n" << formula << '\n'; else ofs << '\n'; ofs << scientific << setprecision(7); for(i=0;i<5;++i) ofs << setw(15) << pND->GetCoeff(i); ofs << " 2\n"; for(i=5;i<10;++i) ofs << setw(15) << pND->GetCoeff(i); ofs << " 3\n"; for(i=10;i<14;++i) ofs << setw(15) << pND->GetCoeff(i); ofs << " 4\n"; #ifdef _MSC_VER _set_output_format(oldf); #endif return true; }
using namespace tecplot::___3933; namespace tecplot { namespace teciompi { DataSetWriterMPI::DataSetWriterMPI( ___37* ___36, ___3501 vars, ___3501 ___4671, ___1844 const& maxIJKSubzoneSize, ___2090::ItemOffset_t maxFESubzoneSize, MPI_Comm communicator, int mainProcess, int localProcess, bool flushToDisk ) : DataSetWriter(___36, vars, ___4671, maxIJKSubzoneSize, maxFESubzoneSize, flushToDisk) , m_communicator(communicator) , m_mainProcess(mainProcess) , m_localProcess(localProcess) {} DataSetWriterMPI::~DataSetWriterMPI() {} ___372 DataSetWriterMPI::writeDataSet( FileWriterInterface& szpltFile, ___1392& szpltZoneHeaderFileLocs) { REQUIRE(szpltFile.___2041()); if (!___2337->___896()) return ___4226; ___372 ___2039 = ___4226; #if defined _WIN32 && _MSC_FULL_VER < 190022816 unsigned int oldOutputFormat = _set_output_format(_TWO_DIGIT_EXPONENT); #endif try { ZoneWriterFactoryMPI ___4710(___2680, *___2337, m_communicator, m_mainProcess); boost::unordered_map<___4636, boost::shared_ptr<___4709> > zoneWriterMap; boost::unordered_map<___4636, ___1393> zoneFileLocMap; if (m_localProcess == m_mainProcess) { ___1393 fileLoc = szpltFile.fileLoc(); MPICommunicator communicator(m_communicator); m_zoneIter->reset(); ___4636 const ___341 = m_zoneIter->baseItem(); while (___2039 && m_zoneIter->hasNext()) { ___4636 const ___904 = m_zoneIter->next(); ___4636 const fileZone = ___904 - ___341; if (!___2337->___4638(___904 + 1)) continue; uint64_t zoneFileSize; if (___2337->zoneIsPartitioned(___904 + 1) || ___2337->zoneGetOwnerProcess(___904 + 1) == m_localProcess) { zoneFileLocMap[fileZone] = fileLoc; std::vector<___372> ___4564; ___372 ___4499; getZoneSharing(___4564, ___4499, ___904, ___341, szpltFile.___844()); zoneWriterMap[fileZone] = ___4710.___4708(*m_varIter, ___904, ___341, ___4564, ___4499); zoneFileSize = zoneWriterMap[fileZone]->zoneFileSize(szpltFile.___2002() == ___4226); } else { int zoneOwner = ___2337->zoneGetOwnerProcess(___904 + 1); communicator.sendScalar(fileLoc, zoneOwner, TecioMPI::ZONE_FILE_LOC); communicator.receiveScalar(zoneFileSize, zoneOwner, TecioMPI::ZONE_FILE_SIZE); } fileLoc += zoneFileSize; } } else { MPINonBlockingCommunicationCollection communicationCollection(m_communicator); m_zoneIter->reset(); ___4636 const ___341 = m_zoneIter->baseItem(); while (___2039 && m_zoneIter->hasNext()) { ___4636 const ___904 = m_zoneIter->next(); ___4636 const fileZone = ___904 - ___341; if (!___2337->___4638(___904 + 1)) continue; if (___2337->zoneIsPartitioned(___904 + 1) || ___2337->zoneGetOwnerProcess(___904 + 1) == m_localProcess) { std::vector<___372> ___4564; ___372 ___4499; getZoneSharing(___4564, ___4499, ___904, ___341, szpltFile.___844()); zoneWriterMap[fileZone] = ___4710.___4708(*m_varIter, ___904, ___341, ___4564, ___4499); uint64_t zoneSize = zoneWriterMap[fileZone]->zoneFileSize(szpltFile.___2002() == ___4226); if (!___2337->zoneIsPartitioned(___904 + 1)) { communicationCollection.sendScalarCopy(zoneSize, m_mainProcess, TecioMPI::ZONE_FILE_SIZE); communicationCollection.receiveScalar(zoneFileLocMap[fileZone], m_mainProcess, TecioMPI::ZONE_FILE_LOC); } } } communicationCollection.___4446(); } m_zoneIter->reset(); ___4636 const ___341 = m_zoneIter->baseItem(); while (___2039 && m_zoneIter->hasNext()) { ___4636 const ___904 = m_zoneIter->next(); ___4636 const fileZone = ___904 - ___341; if (!___2337->___4638(___904 + 1)) continue; if (___2337->zoneIsPartitioned(___904 + 1) || ___2337->zoneGetOwnerProcess(___904 + 1) == m_localProcess) { ___2039 = zoneWriterMap[fileZone]->writeZone(szpltFile, zoneFileLocMap[fileZone]); if (m_localProcess == m_mainProcess) { szpltZoneHeaderFileLocs[fileZone] = zoneWriterMap[fileZone]->getZoneHeaderFilePosition(); m_varIter->reset(); ___4352 const baseVar = m_varIter->baseItem(); while (m_varIter->hasNext()) { ___4352 const datasetVar = m_varIter->next(); ___4352 const fileVar = datasetVar - baseVar; m_zoneVarMetadata->m_vzMinMaxes[fileVar][fileZone] = zoneWriterMap[fileZone]->varMinMax(datasetVar); } } else if (!___2337->zoneIsPartitioned(___904 + 1)) { MPINonBlockingCommunicationCollection communicationCollection(m_communicator); ___1393 headerFileLoc = zoneWriterMap[fileZone]->getZoneHeaderFilePosition(); communicationCollection.sendScalarCopy(headerFileLoc, m_mainProcess, TecioMPI::HEADER_FILE_LOC); std::vector<double> minValues; std::vector<double> maxValues; m_varIter->reset(); while (m_varIter->hasNext()) { ___4352 const ___4336 = m_varIter->next(); ___2479 varMinMax = zoneWriterMap[fileZone]->varMinMax(___4336); minValues.push_back(varMinMax.minValue()); maxValues.push_back(varMinMax.maxValue()); } communicationCollection.sendVectorCopy(minValues, m_mainProcess, TecioMPI::VAR_MIN_VALUES_SIZE, TecioMPI::VAR_MIN_VALUES_VEC); communicationCollection.sendVectorCopy(maxValues, m_mainProcess, TecioMPI::VAR_MAX_VALUES_SIZE, TecioMPI::VAR_MAX_VALUES_VEC); communicationCollection.___4446(); } } else if (m_localProcess == m_mainProcess) { int zoneOwner = ___2337->zoneGetOwnerProcess(___904 + 1); MPICommunicator communicator(m_communicator); communicator.receiveScalar(szpltZoneHeaderFileLocs[fileZone], zoneOwner, TecioMPI::HEADER_FILE_LOC); SimpleVector<double> minValues; SimpleVector<double> maxValues; communicator.receiveVector(minValues, zoneOwner, TecioMPI::VAR_MIN_VALUES_SIZE, TecioMPI::VAR_MIN_VALUES_VEC); communicator.receiveVector(maxValues, zoneOwner, TecioMPI::VAR_MAX_VALUES_SIZE, TecioMPI::VAR_MAX_VALUES_VEC); ___478(minValues.size() == m_varIter->___2812()); ___478(maxValues.size() == m_varIter->___2812()); m_varIter->reset(); ___4352 const baseVar = m_varIter->baseItem(); while (m_varIter->hasNext()) { ___4352 const fileVar = m_varIter->next() - baseVar; m_zoneVarMetadata->m_vzMinMaxes[fileVar][fileZone] = ___2479(minValues[fileVar], maxValues[fileVar]); } } if (szpltFile.___844() == ___845) ___2680.remove(___904); } if (!___2039) { ___2680.clear(); } } catch(std::exception const& e) { ___2039 = ___1186(e.what()); } #if defined _WIN32 _set_output_format(oldOutputFormat); #endif return ___2039; } }}
static String formatNumber(double number, const char* suffix, unsigned suffixLength) { #if OS(WIN) && _MSC_VER < 1900 unsigned oldFormat = _set_output_format(_TWO_DIGIT_EXPONENT); #endif String result = String::format("%.6g", number); #if OS(WIN) && _MSC_VER < 1900 _set_output_format(oldFormat); #endif result.append(suffix, suffixLength); return result; }
/// Default constructor FrameworkManagerImpl::FrameworkManagerImpl() #ifdef MPI_BUILD : m_mpi_environment() #endif { // Mantid only understands English... setGlobalLocaleToAscii(); // Setup memory allocation scheme Kernel::MemoryOptions::initAllocatorOptions(); #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #endif #ifdef _MSC_VER // This causes the exponent to consist of two digits (Windows Visual Studio normally 3, Linux default 2), where two digits are not sufficient I presume it uses more _set_output_format(_TWO_DIGIT_EXPONENT); #endif g_log.notice() << Mantid::welcomeMessage() << std::endl; loadAllPlugins(); disableNexusOutput(); setNumOMPThreadsToConfigValue(); #ifdef MPI_BUILD g_log.notice() << "This MPI process is rank: " << boost::mpi::communicator().rank() << std::endl; #endif g_log.debug() << "FrameworkManager created." << std::endl; }
/*--------------------------------------------------------------------------*/ void set_xxprintf(FILE *fp,XXPRINTF *xxprintf,FLUSH *flush,char **target) { /* Force Windows display to have two-digit exponent. */ #ifdef _MSC_VER _set_output_format(_TWO_DIGIT_EXPONENT); #endif /* re-initialize value of sprintf_buffer */ strcpy(sprintf_buffer, ""); if (fp == (FILE *) 0) { /* sprintf */ *target = sprintf_buffer; *flush = voidflush; *xxprintf = (XXPRINTF) sprintf; } else if ( fp == stdout ) { /* sciprint2 */ *target = (char *) 0; *flush = fflush; *xxprintf = (XXPRINTF) local_sciprint; } else { /* fprintf */ *target = (char *) fp; *flush = fflush; *xxprintf = (XXPRINTF) fprintf; } }
void TestEnforceConstantTimeStep() throw(Exception) { TimeStepper stepper(0.0, 1.0, 0.3); // timestep does not divide, but no checking TS_ASSERT_THROWS_THIS( TimeStepper bad_const_dt_stepper(0.0, 1.0, 0.3, true), "TimeStepper estimates non-constant timesteps will need to be used: " "check timestep divides (end_time-start_time) (or divides printing timestep). " "[End time=1; start=0; dt=0.3; error=0.1]"); #ifdef _MSC_VER _set_output_format(_TWO_DIGIT_EXPONENT); #endif TS_ASSERT_THROWS_THIS( TimeStepper bad_const_dt_stepper2(0.0, 1.0, 0.99999999, true), "TimeStepper estimates non-constant timesteps will need to be used: " "check timestep divides (end_time-start_time) (or divides printing timestep). " "[End time=1; start=0; dt=1; error=1e-08]"); TimeStepper const_dt_stepper(0.0, 1.0, 0.1, true); unsigned counter = 0; while (!const_dt_stepper.IsTimeAtEnd()) { counter++; TS_ASSERT_DELTA(const_dt_stepper.GetNextTimeStep(), 0.1, 1e-15); TS_ASSERT_EQUALS(const_dt_stepper.GetIdealTimeStep(), 0.1); const_dt_stepper.AdvanceOneTimeStep(); if (const_dt_stepper.IsTimeAtEnd()) { TS_ASSERT_EQUALS(const_dt_stepper.GetNextTimeStep(), 0.0); } else { TS_ASSERT_DELTA(const_dt_stepper.GetNextTimeStep(), 0.1, 1e-15); } } TS_ASSERT_EQUALS(counter,10u); }
static void xbt_preinit(void) { unsigned int seed = 2147483647; #ifdef _WIN32 SYSTEM_INFO si; GetSystemInfo(&si); xbt_pagesize = si.dwPageSize; #elif HAVE_SYSCONF xbt_pagesize = sysconf(_SC_PAGESIZE); #else #error Cannot get page size. #endif xbt_pagebits = 0; int x = xbt_pagesize; while(x >>= 1) { ++xbt_pagebits; } #ifdef _TWO_DIGIT_EXPONENT /* Even printf behaves differently on Windows... */ _set_output_format(_TWO_DIGIT_EXPONENT); #endif xbt_log_preinit(); xbt_backtrace_preinit(); xbt_os_thread_mod_preinit(); xbt_fifo_preinit(); xbt_dict_preinit(); srand(seed); #ifndef _WIN32 srand48(seed); #endif atexit(xbt_postexit); }
inline std::string DebugString(double const number, int const precision) { char result[50]; #if OS_WIN && PRINCIPIA_COMPILER_MSVC && (_MSC_VER < 1900) unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT); int const size = sprintf_s(result, ("%+." + std::to_string(precision) + "e").c_str(), number); _set_output_format(old_exponent_format); #else int const size = snprintf(result, sizeof(result), ("%+." + std::to_string(precision) + "e").c_str(), number); #endif CHECK_LE(0, size); return std::string(result, size); }
void RDOKernel::init() { #ifdef COMPILER_VISUAL_STUDIO _set_output_format(_TWO_DIGIT_EXPONENT); #endif new RDOKernel(); }
void gla::PrivateManager::translateTopToBottom() { #ifdef _WIN32 unsigned int oldFormat = _set_output_format(_TWO_DIGIT_EXPONENT); #endif runLLVMOptimizations1(); #ifdef _WIN32 _set_output_format(oldFormat); #endif int innerAoS, outerSoA; backEnd->getRegisterForm(outerSoA, innerAoS); if (outerSoA != 1) UnsupportedFunctionality("SoA in middle end: ", outerSoA); if (innerAoS != 4 && innerAoS != 1) UnsupportedFunctionality("AoS other than size 4 or 1 in middle end: ", innerAoS); }
/** Main function */ int main(int argc, char *argv[]) { msg_error_t res = MSG_OK; #ifdef _MSC_VER unsigned int prev_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT); #endif MSG_init(&argc, argv); if (argc != 3) { XBT_CRITICAL("Usage: %s platform_file deployment_file <model>\n", argv[0]); XBT_CRITICAL ("example: %s msg_platform.xml msg_deployment.xml KCCFLN05_Vegas\n", argv[0]); exit(1); } /* Options for the workstation/model: KCCFLN05 => for maxmin KCCFLN05_proportional => for proportional (Vegas) KCCFLN05_Vegas => for TCP Vegas KCCFLN05_Reno => for TCP Reno */ //MSG_config("workstation/model", argv[3]); res = test_all(argv[1], argv[2]); XBT_INFO("Total simulation time: %le", MSG_get_clock()); #ifdef _MSC_VER _set_output_format(prev_exponent_format); #endif if (res == MSG_OK) return 0; else return 1; } /* end_of_main */
void init() { hSleepEvent = CreateEvent(NULL, TRUE, FALSE, FALSE); #ifdef __MINGW32__ putenv("PRINTF_EXPONENT_DIGITS=2"); #else #if defined(_MSC_VER) && _MSC_VER >= 1900 #else _set_output_format(_TWO_DIGIT_EXPONENT); #endif #endif }
bool initFPU() { #ifdef _WIN64 // int old_cw = ld_initfpu(_RC_NEAR); int old_cw = ld_initfpu(0x300 /*_PC_64 | _RC_NEAR*/, // #defines NOT identical to CPU FPU control word! 0xF00 /*_MCW_PC | _MCW_RC*/); #else int old_cw = _control87(_MCW_EM | _PC_64 | _RC_NEAR, _MCW_EM | _MCW_PC | _MCW_RC); #endif _set_output_format(_TWO_DIGIT_EXPONENT); return true; }
/* this just calls scs_init, scs_solve, and scs_finish */ idxint scs(Data * d, Cone * k, Sol * sol, Info * info) { #if ( defined _WIN32 || defined _WIN64 ) && !defined MATLAB_MEX_FILE && !defined PYTHON /* sets width of exponent for floating point numbers to 2 instead of 3 */ unsigned int old_output_format = _set_output_format(_TWO_DIGIT_EXPONENT); #endif Work * w = scs_init(d, k, info); #ifdef EXTRAVERBOSE scs_printf("size of idxint = %lu, size of pfloat = %lu\n", sizeof(idxint), sizeof(pfloat)); #endif if (!w) { return failureDefaultReturn(d, NULL, sol, info, "could not initialize work"); } scs_solve(w, d, k, sol, info); scs_finish(d, w); return info->statusVal; }
int sc_main( int, char*[] ) { #if defined(_MSC_VER) && _MSC_VER < 1900 _set_output_format(_TWO_DIGIT_EXPONENT); #endif test_print(); test_constructors(); test_assignment(); test_conversion(); test_relational(); test_arithmetic(); test_SC_ZERO_TIME(); return 0; }
/// Default constructor FrameworkManagerImpl::FrameworkManagerImpl() #ifdef MPI_BUILD : m_mpi_environment() #endif { // Mantid only understands English... setGlobalLocaleToAscii(); // Setup memory allocation scheme Kernel::MemoryOptions::initAllocatorOptions(); #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #endif #ifdef _MSC_VER // This causes the exponent to consist of two digits (Windows Visual Studio normally 3, Linux default 2), where two digits are not sufficient I presume it uses more _set_output_format(_TWO_DIGIT_EXPONENT); #endif g_log.notice() << Mantid::welcomeMessage() << std::endl; loadPluginsUsingKey(PLUGINS_DIR_KEY); disableNexusOutput(); setNumOMPThreadsToConfigValue(); #ifdef MPI_BUILD g_log.notice() << "This MPI process is rank: " << boost::mpi::communicator().rank() << std::endl; #endif g_log.debug() << "FrameworkManager created." << std::endl; int updateInstrumentDefinitions = 0; int reVal = Kernel::ConfigService::Instance().getValue("UpdateInstrumentDefinitions.OnStartup",updateInstrumentDefinitions); if ((reVal == 1) && (updateInstrumentDefinitions == 1)) { UpdateInstrumentDefinitions(); } else { g_log.information() << "Instrument updates disabled - cannot update instrument definitions." << std::endl; } }
/* Maybe set up some platform specific issues */ static void nbSpecialSetup() { mwDisableErrorBoxes(); #if ENABLE_CRLIBM /* Try to handle inconsistencies with x87. We shouldn't use * this. This helps, but there can still be some problems for some * values. Sticking with SSE2 is the way to go. */ crlibm_init(); #endif #ifdef _MSC_VER /* FIXME: Also for mingw, but seems to be missing */ /* Make windows printing be more consistent. For some reason it * defaults to printing 3 digits in the exponent. There are still * issues where the rounding of the last digit by printf on * windows in a small number of cases. */ _set_output_format(_TWO_DIGIT_EXPONENT); #endif /* _WIN32 */ }
/// Default constructor FrameworkManagerImpl::FrameworkManagerImpl() #ifdef MPI_BUILD : m_mpi_environment() #endif { // Mantid only understands English... setGlobalLocaleToAscii(); // Setup memory allocation scheme Kernel::MemoryOptions::initAllocatorOptions(); #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); #endif #if defined(_MSC_VER) && _MSC_VER < 1900 // This causes the exponent to consist of two digits. // VC++ >=1900 use standards conforming behaviour and only // uses the number of digits required _set_output_format(_TWO_DIGIT_EXPONENT); #endif g_log.notice() << Mantid::welcomeMessage() << std::endl; loadPluginsUsingKey(PLUGINS_DIR_KEY); disableNexusOutput(); setNumOMPThreadsToConfigValue(); #ifdef MPI_BUILD g_log.notice() << "This MPI process is rank: " << boost::mpi::communicator().rank() << std::endl; #endif g_log.debug() << "FrameworkManager created." << std::endl; AsynchronousStartupTasks(); }
int main(int argc, char **av) { char *prog = *av; opt *set = NULL; int i, grpdebug = 0, debug = 0, setlen = 0, listing = 0; str err = MAL_SUCCEED; char prmodpath[FILENAME_MAX]; const char *modpath = NULL; char *binpath = NULL; str *monet_script; char *dbpath = NULL; char *dbextra = NULL; int verbosity = 0; static struct option long_options[] = { { "config", required_argument, NULL, 'c' }, { "dbpath", required_argument, NULL, 0 }, { "dbextra", required_argument, NULL, 0 }, { "daemon", required_argument, NULL, 0 }, { "debug", optional_argument, NULL, 'd' }, { "help", no_argument, NULL, '?' }, { "version", no_argument, NULL, 0 }, { "verbose", optional_argument, NULL, 'v' }, { "readonly", no_argument, NULL, 'r' }, { "single-user", no_argument, NULL, 0 }, { "set", required_argument, NULL, 's' }, { "threads", no_argument, NULL, 0 }, { "memory", no_argument, NULL, 0 }, { "properties", no_argument, NULL, 0 }, { "io", no_argument, NULL, 0 }, { "transactions", no_argument, NULL, 0 }, { "trace", optional_argument, NULL, 't' }, { "modules", no_argument, NULL, 0 }, { "algorithms", no_argument, NULL, 0 }, { "optimizers", no_argument, NULL, 0 }, { "performance", no_argument, NULL, 0 }, { "forcemito", no_argument, NULL, 0 }, { "heaps", no_argument, NULL, 0 }, { NULL, 0, NULL, 0 } }; #if defined(_MSC_VER) && defined(__cplusplus) set_terminate(mserver_abort); #endif #ifdef _MSC_VER _CrtSetReportMode(_CRT_ERROR, 0); _CrtSetReportMode(_CRT_ASSERT, 0); _set_invalid_parameter_handler(mserver_invalid_parameter_handler); #ifdef _TWO_DIGIT_EXPONENT _set_output_format(_TWO_DIGIT_EXPONENT); #endif #endif if (setlocale(LC_CTYPE, "") == NULL) { fprintf(stderr, "cannot set locale\n"); exit(1); } if (getcwd(monet_cwd, FILENAME_MAX - 1) == NULL) { perror("pwd"); fprintf(stderr,"monet_init: could not determine current directory\n"); exit(-1); } /* retrieve binpath early (before monet_init) because some * implementations require the working directory when the binary was * called */ binpath = get_bin_path(); if (!(setlen = mo_builtin_settings(&set))) usage(prog, -1); for (;;) { int option_index = 0; int c = getopt_long(argc, av, "c:d::rs:t::v::?", long_options, &option_index); if (c == -1) break; switch (c) { case 0: if (strcmp(long_options[option_index].name, "dbpath") == 0) { size_t optarglen = strlen(optarg); /* remove trailing directory separator */ while (optarglen > 0 && (optarg[optarglen - 1] == '/' || optarg[optarglen - 1] == '\\')) optarg[--optarglen] = '\0'; dbpath = absolute_path(optarg); if( dbpath == NULL) fprintf(stderr, "#error: can not allocate memory for dbpath\n"); else setlen = mo_add_option(&set, setlen, opt_cmdline, "gdk_dbpath", dbpath); break; } if (strcmp(long_options[option_index].name, "dbextra") == 0) { if (dbextra) fprintf(stderr, "#warning: ignoring multiple --dbextra arguments\n"); else dbextra = optarg; break; } #ifdef HAVE_CONSOLE if (strcmp(long_options[option_index].name, "daemon") == 0) { setlen = mo_add_option(&set, setlen, opt_cmdline, "monet_daemon", optarg); break; } #endif if (strcmp(long_options[option_index].name, "single-user") == 0) { setlen = mo_add_option(&set, setlen, opt_cmdline, "gdk_single_user", "yes"); break; } if (strcmp(long_options[option_index].name, "version") == 0) { monet_version(); exit(0); } /* debugging options */ if (strcmp(long_options[option_index].name, "properties") == 0) { grpdebug |= GRPproperties; break; } if (strcmp(long_options[option_index].name, "algorithms") == 0) { grpdebug |= GRPalgorithms; break; } if (strcmp(long_options[option_index].name, "optimizers") == 0) { grpdebug |= GRPoptimizers; break; } if (strcmp(long_options[option_index].name, "forcemito") == 0) { grpdebug |= GRPforcemito; break; } if (strcmp(long_options[option_index].name, "performance") == 0) { grpdebug |= GRPperformance; break; } if (strcmp(long_options[option_index].name, "io") == 0) { grpdebug |= GRPio; break; } if (strcmp(long_options[option_index].name, "memory") == 0) { grpdebug |= GRPmemory; break; } if (strcmp(long_options[option_index].name, "modules") == 0) { grpdebug |= GRPmodules; break; } if (strcmp(long_options[option_index].name, "transactions") == 0) { grpdebug |= GRPtransactions; break; } if (strcmp(long_options[option_index].name, "threads") == 0) { grpdebug |= GRPthreads; break; } if (strcmp(long_options[option_index].name, "trace") == 0) { mal_trace = 1; break; } if (strcmp(long_options[option_index].name, "heaps") == 0) { grpdebug |= GRPheaps; break; } usage(prog, -1); /* not reached */ case 'c': /* coverity[var_deref_model] */ setlen = mo_add_option(&set, setlen, opt_cmdline, "config", optarg); break; case 'd': if (optarg) { char *endarg; debug |= strtol(optarg, &endarg, 10); if (*endarg != '\0') { fprintf(stderr, "ERROR: wrong format for --debug=%s\n", optarg); usage(prog, -1); } } else { debug |= 1; } break; case 'r': setlen = mo_add_option(&set, setlen, opt_cmdline, "gdk_readonly", "yes"); break; case 's': { /* should add option to a list */ /* coverity[var_deref_model] */ char *tmp = strchr(optarg, '='); if (tmp) { *tmp = '\0'; setlen = mo_add_option(&set, setlen, opt_cmdline, optarg, tmp + 1); } else fprintf(stderr, "ERROR: wrong format %s\n", optarg); } break; case 't': mal_trace = 1; break; case 'v': if (optarg) { char *endarg; verbosity = (int) strtol(optarg, &endarg, 10); if (*endarg != '\0') { fprintf(stderr, "ERROR: wrong format for --verbose=%s\n", optarg); usage(prog, -1); } } else { verbosity++; } break; case '?': /* a bit of a hack: look at the option that the current `c' is based on and see if we recognize it: if -? or --help, exit with 0, else with -1 */ usage(prog, strcmp(av[optind - 1], "-?") == 0 || strcmp(av[optind - 1], "--help") == 0 ? 0 : -1); default: fprintf(stderr, "ERROR: getopt returned character " "code '%c' 0%o\n", c, (uint8_t) c); usage(prog, -1); } } if (!(setlen = mo_system_config(&set, setlen))) usage(prog, -1); GDKsetdebug(debug | grpdebug); /* add the algorithm tracers */ if (debug) mo_print_options(set, setlen); GDKsetverbose(verbosity); monet_script = (str *) malloc(sizeof(str) * (argc + 1)); if (monet_script == NULL) { fprintf(stderr, "!ERROR: cannot allocate memory for script \n"); exit(1); } i = 0; while (optind < argc) { monet_script[i] = absolute_path(av[optind]); if (monet_script[i] == NULL) { fprintf(stderr, "!ERROR: cannot allocate memory for script \n"); exit(1); } i++; optind++; } monet_script[i] = NULL; if (!dbpath) { dbpath = absolute_path(mo_find_option(set, setlen, "gdk_dbpath")); if (!dbpath) { fprintf(stderr, "!ERROR: cannot allocate memory for database directory \n"); exit(1); } } if (BBPaddfarm(dbpath, 1 << PERSISTENT) != GDK_SUCCEED || BBPaddfarm(dbextra ? dbextra : dbpath, 1 << TRANSIENT) != GDK_SUCCEED) { fprintf(stderr, "!ERROR: cannot add farm\n"); exit(1); } if (GDKcreatedir(dbpath) != GDK_SUCCEED) { fprintf(stderr, "!ERROR: cannot create directory for %s\n", dbpath); exit(1); } GDKfree(dbpath); if (monet_init(set, setlen) == 0) { mo_free_options(set, setlen); if (GDKerrbuf && *GDKerrbuf) fprintf(stderr, "%s\n", GDKerrbuf); exit(1); } mo_free_options(set, setlen); if (GDKsetenv("monet_version", GDKversion()) != GDK_SUCCEED || GDKsetenv("monet_release", #ifdef MONETDB_RELEASE MONETDB_RELEASE #else "unreleased" #endif ) != GDK_SUCCEED) { fprintf(stderr, "!ERROR: GDKsetenv failed\n"); exit(1); } if ((modpath = GDKgetenv("monet_mod_path")) == NULL) { /* start probing based on some heuristics given the binary * location: * bin/mserver5 -> ../ * libX/monetdb5/lib/ * probe libX = lib, lib32, lib64, lib/64 */ size_t pref; /* "remove" common prefix of configured BIN and LIB * directories from LIBDIR */ for (pref = 0; LIBDIR[pref] != 0 && BINDIR[pref] == LIBDIR[pref]; pref++) ; const char *libdirs[] = { &LIBDIR[pref], "lib", "lib64", "lib/64", "lib32", NULL, }; struct stat sb; if (binpath != NULL) { char *p = strrchr(binpath, DIR_SEP); if (p != NULL) *p = '\0'; p = strrchr(binpath, DIR_SEP); if (p != NULL) { *p = '\0'; for (i = 0; libdirs[i] != NULL; i++) { int len = snprintf(prmodpath, sizeof(prmodpath), "%s%c%s%cmonetdb5", binpath, DIR_SEP, libdirs[i], DIR_SEP); if (len == -1 || len >= FILENAME_MAX) continue; if (stat(prmodpath, &sb) == 0) { modpath = prmodpath; break; } } } else { printf("#warning: unusable binary location, " "please use --set monet_mod_path=/path/to/... to " "allow finding modules\n"); fflush(NULL); } } else { printf("#warning: unable to determine binary location, " "please use --set monet_mod_path=/path/to/... to " "allow finding modules\n"); fflush(NULL); } if (modpath != NULL && GDKsetenv("monet_mod_path", modpath) != GDK_SUCCEED) { fprintf(stderr, "!ERROR: GDKsetenv failed\n"); exit(1); } } /* configure sabaoth to use the right dbpath and active database */ msab_dbpathinit(GDKgetenv("gdk_dbpath")); /* wipe out all cruft, if left over */ if ((err = msab_wildRetreat()) != NULL) { /* just swallow the error */ free(err); } /* From this point, the server should exit cleanly. Discussion: * even earlier? Sabaoth here registers the server is starting up. */ if ((err = msab_registerStarting()) != NULL) { /* throw the error at the user, but don't die */ fprintf(stderr, "!%s\n", err); free(err); } #ifdef HAVE_SIGACTION { struct sigaction sa; (void) sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handler; if (sigaction(SIGINT, &sa, NULL) == -1 || sigaction(SIGQUIT, &sa, NULL) == -1 || sigaction(SIGTERM, &sa, NULL) == -1) { fprintf(stderr, "!unable to create signal handlers\n"); } } #else #ifdef _MSC_VER if (!SetConsoleCtrlHandler(winhandler, TRUE)) fprintf(stderr, "!unable to create console control handler\n"); #else if(signal(SIGINT, handler) == SIG_ERR) fprintf(stderr, "!unable to create signal handlers\n"); #ifdef SIGQUIT if(signal(SIGQUIT, handler) == SIG_ERR) fprintf(stderr, "!unable to create signal handlers\n"); #endif if(signal(SIGTERM, handler) == SIG_ERR) fprintf(stderr, "!unable to create signal handlers\n"); #endif #endif { str lang = "mal"; /* we inited mal before, so publish its existence */ if ((err = msab_marchScenario(lang)) != NULL) { /* throw the error at the user, but don't die */ fprintf(stderr, "!%s\n", err); free(err); } } { /* unlock the vault, first see if we can find the file which * holds the secret */ char secret[1024]; char *secretp = secret; FILE *secretf; size_t len; if (GDKgetenv("monet_vault_key") == NULL) { /* use a default (hard coded, non safe) key */ snprintf(secret, sizeof(secret), "%s", "Xas632jsi2whjds8"); } else { if ((secretf = fopen(GDKgetenv("monet_vault_key"), "r")) == NULL) { fprintf(stderr, "unable to open vault_key_file %s: %s\n", GDKgetenv("monet_vault_key"), strerror(errno)); /* don't show this as a crash */ msab_registerStop(); exit(1); } len = fread(secret, 1, sizeof(secret), secretf); secret[len] = '\0'; len = strlen(secret); /* secret can contain null-bytes */ if (len == 0) { fprintf(stderr, "vault key has zero-length!\n"); /* don't show this as a crash */ msab_registerStop(); exit(1); } else if (len < 5) { fprintf(stderr, "#warning: your vault key is too short " "(%zu), enlarge your vault key!\n", len); } fclose(secretf); } if ((err = AUTHunlockVault(secretp)) != MAL_SUCCEED) { /* don't show this as a crash */ msab_registerStop(); fprintf(stderr, "%s\n", err); freeException(err); exit(1); } } /* make sure the authorisation BATs are loaded */ if ((err = AUTHinitTables(NULL)) != MAL_SUCCEED) { /* don't show this as a crash */ msab_registerStop(); fprintf(stderr, "%s\n", err); freeException(err); exit(1); } if (mal_init()) { /* don't show this as a crash */ msab_registerStop(); return 0; } if((err = MSinitClientPrg(mal_clients, "user", "main")) != MAL_SUCCEED) { msab_registerStop(); fprintf(stderr, "%s\n", err); freeException(err); exit(1); } emergencyBreakpoint(); for (i = 0; monet_script[i]; i++) { str msg = evalFile(monet_script[i], listing); /* check for internal exception message to terminate */ if (msg) { if (strcmp(msg, "MALException:client.quit:Server stopped.") == 0) mal_exit(0); fprintf(stderr, "#%s: %s\n", monet_script[i], msg); freeException(msg); } GDKfree(monet_script[i]); monet_script[i] = 0; } free(monet_script); if ((err = msab_registerStarted()) != NULL) { /* throw the error at the user, but don't die */ fprintf(stderr, "!%s\n", err); free(err); } #ifdef HAVE_CONSOLE if (!monet_daemon) { MSserveClient(mal_clients); } else #endif while (!interrupted && !GDKexiting()) { MT_sleep_ms(100); } /* mal_exit calls exit, so statements after this call will * never get reached */ mal_exit(0); return 0; }
int unitTests() { int nfailed = 0; # ifdef _MSC_VER // floats are printed with three digit exponents on windows, which messes // up the tests. Turn this off for consistency: _set_output_format(_TWO_DIGIT_EXPONENT); # endif // Test various basic format specs against results of sprintf CHECK_EQUAL(tfm::format("%s", "asdf"), "asdf"); CHECK_EQUAL(tfm::format("%d", 1234), "1234"); CHECK_EQUAL(tfm::format("%i", -5678), "-5678"); CHECK_EQUAL(tfm::format("%o", 012), "12"); CHECK_EQUAL(tfm::format("%u", 123456u), "123456"); CHECK_EQUAL(tfm::format("%x", 0xdeadbeef), "deadbeef"); CHECK_EQUAL(tfm::format("%X", 0xDEADBEEF), "DEADBEEF"); CHECK_EQUAL(tfm::format("%e", 1.23456e10), "1.234560e+10"); CHECK_EQUAL(tfm::format("%E", -1.23456E10), "-1.234560E+10"); CHECK_EQUAL(tfm::format("%f", -9.8765), "-9.876500"); CHECK_EQUAL(tfm::format("%F", 9.8765), "9.876500"); CHECK_EQUAL(tfm::format("%g", 10), "10"); CHECK_EQUAL(tfm::format("%G", 100), "100"); CHECK_EQUAL(tfm::format("%c", 65), "A"); CHECK_EQUAL(tfm::format("%hc", (short)65), "A"); CHECK_EQUAL(tfm::format("%lc", (long)65), "A"); CHECK_EQUAL(tfm::format("%s", "asdf_123098"), "asdf_123098"); // Note: All tests printing pointers are different on windows, since // there's no standard numerical representation. // Representation also differs between 32-bit and 64-bit windows. # ifdef _MSC_VER # ifdef _WIN64 CHECK_EQUAL(tfm::format("%p", (void*)0x12345), "0000000000012345"); # else CHECK_EQUAL(tfm::format("%p", (void*)0x12345), "00012345"); # endif // _WIN64 # else CHECK_EQUAL(tfm::format("%p", (void*)0x12345), "0x12345"); # endif // _MSC_VER CHECK_EQUAL(tfm::format("%%%s", "asdf"), "%asdf"); // note: plain "%%" format gives warning with gcc // chars with int format specs are printed as ints: CHECK_EQUAL(tfm::format("%hhd", (char)65), "65"); CHECK_EQUAL(tfm::format("%hhu", (unsigned char)65), "65"); CHECK_EQUAL(tfm::format("%hhd", (signed char)65), "65"); # ifdef _MSC_VER # ifdef _WIN64 CHECK_EQUAL(tfm::format("%p", (const char*)0x10), "0000000000000010"); # else CHECK_EQUAL(tfm::format("%p", (const char*)0x10), "00000010"); # endif // _WIN64 # else CHECK_EQUAL(tfm::format("%p", (const char*)0x10), "0x10"); // should print address, not string. # endif // _MSC_VER // bools with string format spec are printed as "true" or "false" CHECK_EQUAL(tfm::format("%s", true), "true"); CHECK_EQUAL(tfm::format("%d", true), "1"); // Test precision & width CHECK_EQUAL(tfm::format("%10d", -10), " -10"); CHECK_EQUAL(tfm::format("%.4d", 10), "0010"); CHECK_EQUAL(tfm::format("%10.4f", 1234.1234567890), " 1234.1235"); CHECK_EQUAL(tfm::format("%.f", 10.1), "10"); CHECK_EQUAL(tfm::format("%.2s", "asdf"), "as"); // strings truncate to precision CHECK_EQUAL(tfm::format("%.2s", std::string("asdf")), "as"); // // Test variable precision & width CHECK_EQUAL(tfm::format("%*.4f", 10, 1234.1234567890), " 1234.1235"); CHECK_EQUAL(tfm::format("%10.*f", 4, 1234.1234567890), " 1234.1235"); CHECK_EQUAL(tfm::format("%*.*f", 10, 4, 1234.1234567890), " 1234.1235"); CHECK_EQUAL(tfm::format("%*.*f", -10, 4, 1234.1234567890), "1234.1235 "); // Test flags CHECK_EQUAL(tfm::format("%#x", 0x271828), "0x271828"); CHECK_EQUAL(tfm::format("%#o", 0x271828), "011614050"); CHECK_EQUAL(tfm::format("%#f", 3.0), "3.000000"); CHECK_EQUAL(tfm::format("%+d", 3), "+3"); CHECK_EQUAL(tfm::format("%+d", 0), "+0"); CHECK_EQUAL(tfm::format("%+d", -3), "-3"); CHECK_EQUAL(tfm::format("%010d", 100), "0000000100"); CHECK_EQUAL(tfm::format("%010d", -10), "-000000010"); // sign should extend CHECK_EQUAL(tfm::format("%#010X", 0xBEEF), "0X0000BEEF"); CHECK_EQUAL(tfm::format("% d", 10), " 10"); CHECK_EQUAL(tfm::format("% d", -10), "-10"); // Test flags with variable precision & width CHECK_EQUAL(tfm::format("%+.2d", 3), "+03"); CHECK_EQUAL(tfm::format("%+.2d", -3), "-03"); // flag override precedence CHECK_EQUAL(tfm::format("%+ d", 10), "+10"); // '+' overrides ' ' CHECK_EQUAL(tfm::format("% +d", 10), "+10"); CHECK_EQUAL(tfm::format("%-010d", 10), "10 "); // '-' overrides '0' CHECK_EQUAL(tfm::format("%0-10d", 10), "10 "); // Check that length modifiers are ignored CHECK_EQUAL(tfm::format("%hd", (short)1000), "1000"); CHECK_EQUAL(tfm::format("%ld", (long)100000), "100000"); CHECK_EQUAL(tfm::format("%lld", (long long)100000), "100000"); CHECK_EQUAL(tfm::format("%zd", (size_t)100000), "100000"); CHECK_EQUAL(tfm::format("%td", (ptrdiff_t)100000), "100000"); CHECK_EQUAL(tfm::format("%jd", 100000), "100000"); // Check that 0-argument formatting is printf-compatible CHECK_EQUAL(tfm::format("100%%"), "100%"); // printf incompatibilities: // compareSprintf("%6.4x", 10); // precision & width can't be supported independently // compareSprintf("%.4d", -10); // negative numbers + precision don't quite work. // General "complicated" format spec test CHECK_EQUAL(tfm::format("%0.10f:%04d:%+g:%s:%#X:%c:%%:%%asdf", 1.234, 42, 3.13, "str", 0XDEAD, (int)'X'), "1.2340000000:0042:+3.13:str:0XDEAD:X:%:%asdf"); // Test wrong number of args EXPECT_ERROR( tfm::format("%d", 5, 10) ) EXPECT_ERROR( tfm::format("%d %d", 1) ) // Unterminated format spec EXPECT_ERROR( tfm::format("%123", 10) ) // Types used to specify variable width/precision must be convertible to int. EXPECT_ERROR( tfm::format("%0*d", "thing that can't convert to int", 42) ) EXPECT_ERROR( tfm::format("%0.*d", "thing that can't convert to int", 42) ) // Error required if not enough args for variable width/precision EXPECT_ERROR( tfm::format("%*d", 1) ) EXPECT_ERROR( tfm::format("%.*d", 1) ) EXPECT_ERROR( tfm::format("%*.*d", 1, 2) ) // Unhandled C99 format spec EXPECT_ERROR( tfm::format("%n", 10) ) EXPECT_ERROR( tfm::format("%a", 10) ) EXPECT_ERROR( tfm::format("%A", 10) ) #ifdef TEST_WCHAR_T_COMPILE // Test wchar_t handling - should fail to compile! tfm::format("%ls", L"blah"); #endif // Test that formatting is independent of underlying stream state. std::ostringstream oss; oss.width(20); oss.precision(10); oss.fill('*'); oss.setf(std::ios::scientific); tfm::format(oss, "%f", 10.1234123412341234); CHECK_EQUAL(oss.str(), "10.123412"); // Test formatting a custom object MyInt myobj(42); CHECK_EQUAL(tfm::format("myobj: %s", myobj), "myobj: 42"); // Test that interface wrapping works correctly TestWrap wrap; CHECK_EQUAL(wrap.error(10, "someformat %s:%d:%d", "asdf", 2, 4), "10: someformat asdf:2:4"); TestExceptionDef ex("blah %d", 100); CHECK_EQUAL(ex.what(), std::string("blah 100")); // Test tfm::printf by swapping the std::cout stream buffer to capture data // which would noramlly go to the stdout std::ostringstream coutCapture; std::streambuf* coutBuf = std::cout.rdbuf(coutCapture.rdbuf()); tfm::printf("%s %s %d\n", "printf", "test", "1"); tfm::printfln("%s %s %d", "printfln", "test", "1"); std::cout.rdbuf(coutBuf); // restore buffer CHECK_EQUAL(coutCapture.str(), "printf test 1\nprintfln test 1\n"); return nfailed; }
jbool fm::initKernel(fastiva_ModuleInfo* pAppModule) { Kernel::g_pAtExitProcQ = ADDR_ZERO; memset(&kernelData, 0, sizeof(kernelData)); jlonglong currTimeMillis = -1; //fastiva_Task* pGCTask = Kernel::g_pSystemTask = (fastiva_Task*)fox_kernel_createTaskContext(); fox_task_create_ex(gc_task, ADDR_ZERO, 0, Kernel::g_pSystemTask, 0); kernelData.g_aPackageSlot = (fastiva_PackageSlot*)sys_heap_virtualAlloc(NULL, sizeof(fastiva_PackageSlot)*1024); // WARNING!!! the initializing order is very important !!! // v3 KASSERT(java_lang_Object_T$::g_context$.context.m_pSuperContext == ADDR_ZERO); // java_lang_Thread_p pSystemThread = fm::attachNativeTask(Kernel::g_pSystemTask); // pSystemThread->m_priority = (5); fox_mutex_init(kernelData.g_pLock); kernelData.g_ivtableLock = fox_semaphore_create(); #if (JPP_JNI_EXPORT_LEVEL > 0) fox_mutex_init(kernelData.g_pContextIDLock); //fox_mutex_init(kernelData.g_pPackageListLock); kernelData.stringPool.init(); kernelData.g_interpreterModule.m_hDLL = (void*)-1; #endif #if FASTIVA_SUPPORTS_EXTERNAL_PACKAGE_LOADER fastiva_Runtime* pFastivaRuntime = pModule->m_pRuntime; if (pFastivaRuntime != ADDR_ZERO) { initThunk(pFastivaRuntime); } #endif #ifdef _WIN32 // 1.0+ddE // 두자리수 exponent 표현 선택. #ifndef UNDER_CE _set_output_format(_TWO_DIGIT_EXPONENT); #endif #endif FASTIVA_BEGIN_MANAGED_SECTION(0); TRY$ { fm::initClassLoader(); java_lang_Object_C$::initStatic$(); fm::initPrimitiveClasses(); //_asm int 3; /* fastiva_Package* pPackage = FASTIVA_GET_FIRST_PACKAGE(); fastiva_Package* pEndPackage = FASTIVA_GET_ENDOF_PACKAGE(); while (pPackage < pEndPackage) { fm::registerComponent(pPackage, ADDR_ZERO); #ifdef __GNUC__ pPackage = (fastiva_Package*)((char*)pPackage + 0x40); #else pPackage = (fastiva_Package*)((char*)pPackage + 0x28); #endif } */ // String class 를 초기화한다. // PreloadableClass 중에 StringConstant 를 가진 class 의 경우, // 해당 field assign 시 global publishing 이 발생한다. // 그 전에 String class의 m_pVTable 이 초기화되어야하만다. java_lang_String_C$::importClass$(); g_pLibcoreModule->initStringPool(); g_pLibcoreModule->linkPreloadableClasses(true); /** java_lang_String은 linkClass 도중 String-Contant를 생성하기 위해 필요하다. 예외처리가 필요하다. */ java_lang_Class_C$::importClass$(); g_pLibcoreModule->internStringPool(); /* java_lang_String_p aInitInternBuffer[MAX_INIT_INTERN]; kernelData.g_aInitInternBuffer = aInitInternBuffer; java_lang_String_T$ tStr; java_lang_String_T$::getRawContext$()->m_pClass->obj.vtable$ = *(void**)&tStr; fm::linkClass(java_lang_String_T$::getRawContext$()->m_pClass); */ Kernel::g_pSysEvent = FASTIVA_NEW(java_lang_Object)(); fm::initSystemException(); java_lang_Class_C$::importClass$(); java_lang_Thread_C$::importClass$(); java_lang_System_C$* pSystemC = java_lang_System_C$::importClass$(); java_lang_StringBuffer_C$::importClass$(); java_util_Hashtable_C$::importClass$(); java_lang_ClassLoader_C$::importClass$(); fastiva_lockGlobalRef(Kernel::g_pSysEvent); // fastiva_lockGlobalRef(pSystemThread); fastiva_lockGlobalRef(kernelData.g_pInternedString); #ifdef _WIN32 #if JPP_JDK_VERSION >= JPP_JDK_CDC java_io_FileDescriptor_C$* pStatic = java_io_FileDescriptor_C$::importClass$(); pStatic->g_in->m_descriptor = (int)fox_file_getStandardHandle(FOX_STANDARD_INPUT); pStatic->g_out->m_descriptor = (int)fox_file_getStandardHandle(FOX_STANDARD_OUTPUT); pStatic->g_err->m_descriptor = (int)fox_file_getStandardHandle(FOX_STANDARD_ERROR); #else java_io_FileOutputStream_p out = FASTIVA_NEW(java_io_FileOutputStream)((int)fox_file_getStandardHandle(FOX_STANDARD_OUTPUT)); //java_io_FileOutputStream_p out = FASTIVA_NEW(java_io_FileOutputStream)((int)fox_file_getStandardHandle(FOX_STANDARD_OUTPUT)); pSystemC->set__props(FASTIVA_NEW(java_util_Properties)()); pSystemC->set__out(FASTIVA_NEW(java_io_PrintStream)(out)); pSystemC->set__err(FASTIVA_NEW(java_io_PrintStream)(out)); //(int)fox_file_getStandardHandle(FOX_STANDARD_OUTPUT); #endif #endif fm::initMainThread(); { /* 2011.10.25 * ClassCache 사용방식이 변경되어 bootstrap 단계에서 ClassCache 가 초기화되지 않는 문제가 있다. * ClassCache.initStatic() 내의 LangAccess.setInstance() 가 수행되도록 하여야 한다. */ java_lang_ClassCache_C$::importClass$(); } if (pAppModule != NULL) { ((fastiva_Module*)pAppModule)->initExteranlModule(); } #if defined(FASTIVA_J2SE) || defined(FASTIVA_CDC) // Z-TEMP 2007.09 java_lang_System_C$::getRawStatic$()->initializeSystemClass(); /* { g_pLibcoreModule->linkPreloadableClasses(); } if (pAppModule != ADDR_ZERO) { ((fastiva_Module*)pAppModule)->init(); } */ java_lang_Boolean_C$::importClass$(); java_lang_Byte_C$::importClass$(); java_lang_Character_C$::importClass$(); java_lang_Short_C$::importClass$(); java_lang_Integer_C$::importClass$(); java_lang_Long_C$::importClass$(); java_lang_Float_C$::importClass$(); java_lang_Double_C$::importClass$(); java_lang_Number_C$::importClass$(); #ifndef FASTIVA_CLDC //J131 Library에서 .exe로 Link가 되지 않아 forName에서 ClassNotFoundException이 //발생하므로 임시로 여기에서 import한다. main 함수가 있는 곳으로 이동되어야 한다. //sun_io_Converters_C$::importClass$(); #ifdef FASTIVA_J2SE javax_swing_text_html_parser_ParserDelegator_C$::importClass$(); #endif // Z-TEMP 2007.09 sun_net_www_protocol_file_Handler_C$::importClass$(); // Z-TEMP 2007.09 sun_net_www_protocol_jar_Handler_C$::importClass$(); #endif //findNativeMethod_MD에서 java_lang_ClassLoader::findNative0$를 이용하여 //Native를 찾기 위해서 ClassLoader가 import되어야 한다. java_lang_Class_p pClassLoader = (java_lang_Class_p)java_lang_ClassLoader_C$::importClass$(); java_lang_ClassLoader_C$::getRawStatic$()->getSystemClassLoader(); #if !JPP_JDK_IS_ANDROID() java_util_Properties_p props = FASTIVA_NEW(java_util_Properties)(); java_lang_System_C$::getRawStatic$()->initProperties(props); java_lang_System_C$::getRawStatic$()->set__props(props); #endif //sun_awt_NativeLibLoader::loadLibraries()에서 awt.dll을 Loading하기 때문에 //우선적으로 Loading한다. java_awt_XXX가 import된 후에 sun_awt_NativeLibLoader::loadLibraries()가 //불리기 때문에 여기서 미리 Loading을 한다. //sun_awt_NativeLibLoader_C$::importClass$(); //sun_awt_NativeLibLoader::loadLibraries(); //java_lang_System::loadLibrary(fastiva.createString("jpeg")); #endif #if (JPP_JNI_EXPORT_LEVEL > 0) int idx = kernelData.g_utfHashTable.addRefName("<init>"); KASSERT(idx == JPP_REF_NAME_ID::init$$); idx = kernelData.g_utfHashTable.addRefName("<cinit>"); KASSERT(idx == JPP_REF_NAME_ID::initStatic$$); idx = kernelData.g_utfHashTable.addRefName("main"); KASSERT(idx == JPP_REF_NAME_ID::main$); #endif #if FASTIVA_SUPPORTS_JAVASCRIPT fm::initJScript(); #endif //fox_task_startScheduler(); } CATCH_ANY$ { return false; } FASTIVA_END_MANAGED_SECTION(); gg: return true; }
rt_public void eif_rtinit(int argc, EIF_NATIVE_CHAR **argv, EIF_NATIVE_CHAR **envp) { char *eif_timeout; /* Retrieve root argument if any and update `argc' accordingly. */ eif_retrieve_root(&argc, argv); #ifdef EIF_WINDOWS set_windows_exception_filter(); #if defined(_MSC_VER) && _MSC_VER >= 1400 /* version 14.0+ (MSVC 8.0+) */ /* Ensures consistent behavior across all our platforms where we * get 2-digit exponent up to 99 and then 3-digit exponent for 100 and * above. */ (void) _set_output_format(_TWO_DIGIT_EXPONENT); #endif #endif #ifdef BOEHM_GC GC_register_displacement (OVERHEAD); #endif ieee_init(); starting_working_directory = (char *) eif_malloc (PATH_MAX + 1); /* Initialize directory to an empty string by default. */ starting_working_directory [0] = '\0'; ufill(); /* Get urgent memory chunks */ #if defined(DEBUG) && (EIF_OS != EIF_OS_VXWORKS) && !defined(EIF_WINDOWS) /* The following install signal handlers for signals USR1 and USR2. Both * raise an immediate scanning of memory and dumping of the free list usage * and other statistics. The difference is that USR1 also performrs a full * GC cycle before runnning the diagnosis. If memck() is programmed to * panic when inconsistencies are detected, this may raise a system failure * due to race condition. There is nothing the user can do about it, except * pray--RAM. */ esignal(SIGUSR1, mem_diagnose); esignal(SIGUSR2, mem_diagnose); #endif /* Check if the user wants to override the default timeout value * for interprocess communications (IPC). This new value is specified in * the ISE_TIMEOUT environment variable */ eif_timeout = getenv("ISE_TIMEOUT"); if ((eif_timeout != NULL) && (strlen(eif_timeout) > 0)) { /* Environment variable set */ TIMEOUT = (unsigned) atoi(eif_timeout); } else { TIMEOUT = 30; } eoption = egc_foption; #ifdef WORKBENCH xinitint(); /* Interpreter initialization */ esystem = egc_fsystem; eif_par_table = egc_partab; eif_par_table_size = egc_partab_size; eorg_table = egc_forg_table; pattern = egc_fpattern; debug_initialize(); /* Initialize debug information (breakpoints ...) */ /* In workbench mode, we have a slight problem: when we link ewb in * workbench mode, since ewb is a child from ised, the run-time will * assume, wrongly, that the executable is started in debug mode. Therefore, * we need a special run-time, with no debugging hooks involved. */ #ifndef NOHOOK winit(); /* Did we start under ewb control? */ #endif /* Initialize dynamically computed variables (i.e. system dependent) * Then we may call update. Eventually, when debugging the * application, the values loaded from the update file will be overridden * by the workbench (via winit). */ egc_einit(); /* Various static initializations */ fcount = scount; { char temp = 0; int i; for (i=1;i<argc;i++) { if (0 == rt_nstrcmp (argv[i], rt_nmakestr("-ignore_updt"))) { temp = (char) 1; break; } } update(temp, argv[0]); } /* Read melted information * Note: the `update' function takes * care of the initialization of the * temporary descriptor structures */ create_desc(); /* Create descriptor (call) tables */ #else /* * Initialize the finalized system with the static data structures. */ esystem = egc_fsystem; eif_par_table = egc_partab; eif_par_table_size = egc_partab_size; eif_gen_conf_init (eif_par_table_size); nbref = egc_fnbref; esize = egc_fsize; #endif #if !defined CUSTOM || defined NEED_UMAIN_H umain(argc, argv, envp); /* User's initializations */ #endif #if !defined CUSTOM || defined NEED_ARGV_H rt_arg_init(argc, argv); /* Save copy for class ARGUMENTS */ #endif eif_environ = envp; /* Save pointer to environment variable storage */ once_init(); #if defined(EIF_THREADS) && defined(WORKBENCH) notify_root_thread(); #endif initprf(); /* Initialize profiler. */ init_emnger(); /* Initialize ISE_EXCEPTION_MANAGER */ init_scp_manager(); /* Initialize ISE_SCOOP_MANAGER */ /* Initialize our root class. */ eif_init_root(); }
~ScientificNotationExponentOutputNormalizer() { _set_output_format(m_old_format); }
ScientificNotationExponentOutputNormalizer() : m_old_format(_set_output_format(_TWO_DIGIT_EXPONENT)) {}
// from crm_vector_tokenize.c int main(void) { char input[1024]; char arg[8192]; char opts[1024]; int i, j; int ret; int k; crmhash_t feavec[2048]; uint32_t feamult[2048]; uint32_t feaord[2048]; ARGPARSE_BLOCK apb = { 0 }; VT_USERDEF_TOKENIZER tokenizer = { 0 }; VT_USERDEF_COEFF_MATRIX our_coeff = { 0 }; int use_default_re_and_coeff = USE_DEFAULT_RE_AND_COEFF; char my_regex[256]; static const int coeff[] = { 1, 3, 0, 0, 0, 1, 0, 5, 0, 0, 1, 0, 0, 11, 0, 1, 0, 0, 0, 23 }; init_stdin_out_err_as_os_handles(); #if 0 setvbuf(stdout, stdout_buf, _IOFBF, sizeof(stdout_buf)); setvbuf(stderr, stderr_buf, _IOFBF, sizeof(stderr_buf)); #endif #if (defined(WIN32) || defined(_WIN32) || defined(_WIN64) || defined(WIN64)) && defined(_DEBUG) /* * Hook in our client-defined reporting function. * Every time a _CrtDbgReport is called to generate * a debug report, our function will get called first. */ _CrtSetReportHook(crm_dbg_report_function); /* * Define the report destination(s) for each type of report * we are going to generate. In this case, we are going to * generate a report for every report type: _CRT_WARN, * _CRT_ERROR, and _CRT_ASSERT. * The destination(s) is defined by specifying the report mode(s) * and report file for each report type. */ _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); // Store a memory checkpoint in the s1 memory-state structure _CrtMemCheckpoint(&crm_memdbg_state_snapshot1); atexit(crm_report_mem_analysis); // Get the current bits i = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Set the debug-heap flag so that freed blocks are kept on the // linked list, to catch any inadvertent use of freed memory #if 0 i |= _CRTDBG_DELAY_FREE_MEM_DF; #endif // Set the debug-heap flag so that memory leaks are reported when // the process terminates. Then, exit. //i |= _CRTDBG_LEAK_CHECK_DF; // Clear the upper 16 bits and OR in the desired freqency //i = (i & 0x0000FFFF) | _CRTDBG_CHECK_EVERY_16_DF; i |= _CRTDBG_CHECK_ALWAYS_DF; // Set the new bits _CrtSetDbgFlag(i); // // set a malloc marker we can use it in the leak dump at the end of the program: // (void)_calloc_dbg(1, 1, _CLIENT_BLOCK, __FILE__, __LINE__); #endif // fprintf(stderr, " args: %d \n", argc); // for (i = 0; i < argc; i++) // fprintf(stderr, " argi: %d, argv: %s \n", i, argv[i]); atexit(crm_final_cleanup); #if defined(HAVE__SET_OUTPUT_FORMAT) _set_output_format(_TWO_DIGIT_EXPONENT); // force MSVC (& others?) to produce floating point %f with 2 digits for power component instead of 3 for easier comparison with 'knowngood'. #endif // force MSwin/Win32 console I/O into binary mode: treat \r\n and \n as completely different - like it is on *NIX boxes! #if defined(HAVE__SETMODE) && defined(HAVE__FILENO) && defined(O_BINARY) (void)_setmode(_fileno(crm_stdin), O_BINARY); (void)_setmode(_fileno(crm_stdout), O_BINARY); (void)_setmode(_fileno(crm_stderr), O_BINARY); #endif user_trace = 1; internal_trace = 1; do { strcpy(my_regex, "[[:alpha:]]+"); memset(&tokenizer, 0, sizeof(tokenizer)); memset(&our_coeff, 0, sizeof(our_coeff)); fprintf(stdout, "Enter a test string: "); fgets(input, sizeof(input), stdin); input[sizeof(input) - 1] = 0; fprintf(stdout, "Input = '%s'\n", input); // fscanf(stdin, "%1023s", input); // fprintf(stdout, "Input = '%s'\n", input); fprintf(stdout, "Enter optional 'vector: ...' arg (don't forget the 'vector: prefix in there!): "); fgets(arg, sizeof(arg), stdin); arg[sizeof(arg) - 1] = 0; fprintf(stdout, "Args = '%s'\n", arg); apb.s1start = my_regex; apb.s1len = (int)strlen(my_regex); apb.s2start = arg; apb.s2len = (int)strlen(arg); apb.sflags = CRM_MARKOVIAN | CRM_UNIQUE; fprintf(stdout, "Optional OSBF style token globbing: type integer values for max_token_size and count (must specify both!): "); fgets(opts, sizeof(opts), stdin); opts[sizeof(opts) - 1] = 0; k = sscanf(opts, "%d %d", &i, &j); if (k == 2) { fprintf(stdout, "using max_token_size %d and count %d.\n", i, j); tokenizer.max_token_length = i; tokenizer.max_big_token_count = j; } tokenizer.regex = my_regex; tokenizer.regexlen = (int)strlen(my_regex); if (strlen(arg) < 3) { CRM_VERIFY(transfer_matrix_to_VT(&our_coeff, coeff, 5, 4, 1)); } memset(feavec, 0, sizeof(feavec)); memset(feamult, 0, sizeof(feamult)); memset(feaord, 0, sizeof(feaord)); tokenizer.input_next_offset = 0; ret = crm_vector_tokenize_selector(&apb, vht, tdw, input, (int)strlen(input), 0, (use_default_re_and_coeff ? NULL : &tokenizer), (use_default_re_and_coeff ? NULL : &our_coeff), feavec, WIDTHOF(feavec), feamult, feaord, &j); for (k = 0; k < j; k++) { fprintf(stdout, "feature[%4d] = %12lu (%08lX) / mul: %d, order: %d\n", k, (unsigned long int)feavec[k], (unsigned long int)feavec[k], feamult[k], feaord[k]); } fprintf(stdout, "... and next_offset is %d\n", tokenizer.input_next_offset); tokenizer.input_next_offset = 0; memset(feavec, 0, sizeof(feavec)); ret = crm_vector_tokenize_selector_old(&apb, input, 0, (int)strlen(input), (use_default_re_and_coeff ? NULL : my_regex), (use_default_re_and_coeff ? 0 : (int)strlen(my_regex)), (use_default_re_and_coeff ? NULL : coeff), (use_default_re_and_coeff ? 0 : 5), (use_default_re_and_coeff ? 0 : 4), feavec, WIDTHOF(feavec), &j, &tokenizer.input_next_offset); for (k = 0; k < j; k++) { fprintf(stdout, "feature[%4d] = %12lu (%08lX)\n", k, (unsigned long int)feavec[k], (unsigned long int)feavec[k]); } fprintf(stdout, "... and next_offset is %d\n", tokenizer.input_next_offset); fprintf(stdout, "Another round? (enter 'y' for yes): "); fgets(input, sizeof(input), stdin); input[sizeof(input) - 1] = 0; } while (input[0] == 'y'); return ret >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; }
int main (int argc, char *argv[]) { Filesystem::convert_native_arguments (argc, (const char **)argv); getargs (argc, argv); if (! quiet) std::cout << "Comparing \"" << filenames[0] << "\" and \"" << filenames[1] << "\"\n"; // Create a private ImageCache so we can customize its cache size // and instruct it store everything internally as floats. ImageCache *imagecache = ImageCache::create (true); imagecache->attribute ("forcefloat", 1); if (sizeof(void *) == 4) // 32 bit or 64? imagecache->attribute ("max_memory_MB", 512.0); else imagecache->attribute ("max_memory_MB", 2048.0); imagecache->attribute ("autotile", 256); // force a full diff, even for files tagged with the same // fingerprint, just in case some mistake has been made. imagecache->attribute ("deduplicate", 0); ImageBuf img0, img1; if (! read_input (filenames[0], img0, imagecache) || ! read_input (filenames[1], img1, imagecache)) return ErrFile; // ImageSpec spec0 = img0.spec(); // stash it int ret = ErrOK; for (int subimage = 0; subimage < img0.nsubimages(); ++subimage) { if (subimage > 0 && !compareall) break; if (subimage >= img1.nsubimages()) break; if (! read_input (filenames[0], img0, imagecache, subimage) || ! read_input (filenames[1], img1, imagecache, subimage)) { std::cerr << "Failed to read subimage " << subimage << "\n"; return ErrFile; } if (img0.nmiplevels() != img1.nmiplevels()) { if (! quiet) std::cout << "Files do not match in their number of MIPmap levels\n"; } for (int m = 0; m < img0.nmiplevels(); ++m) { if (m > 0 && !compareall) break; if (m > 0 && img0.nmiplevels() != img1.nmiplevels()) { std::cerr << "Files do not match in their number of MIPmap levels\n"; ret = ErrDifferentSize; break; } if (! read_input (filenames[0], img0, imagecache, subimage, m) || ! read_input (filenames[1], img1, imagecache, subimage, m)) return ErrFile; if (img0.deep() != img1.deep()) { std::cerr << "One image contains deep data, the other does not\n"; ret = ErrDifferentSize; break; } int npels = img0.spec().width * img0.spec().height * img0.spec().depth; if (npels == 0) npels = 1; // Avoid divide by zero for 0x0 images ASSERT (img0.spec().format == TypeDesc::FLOAT); // Compare the two images. // ImageBufAlgo::CompareResults cr; ImageBufAlgo::compare (img0, img1, failthresh, warnthresh, cr); int yee_failures = 0; if (perceptual && ! img0.deep()) { ImageBufAlgo::CompareResults cr; yee_failures = ImageBufAlgo::compare_Yee (img0, img1, cr); } if (cr.nfail > (failpercent/100.0 * npels) || cr.maxerror > hardfail || yee_failures > (failpercent/100.0 * npels)) { ret = ErrFail; } else if (cr.nwarn > (warnpercent/100.0 * npels) || cr.maxerror > hardwarn) { if (ret != ErrFail) ret = ErrWarn; } // Print the report // if (verbose || (ret != ErrOK && !quiet)) { if (compareall) print_subimage (img0, subimage, m); std::cout << " Mean error = "; safe_double_print (cr.meanerror); std::cout << " RMS error = "; safe_double_print (cr.rms_error); std::cout << " Peak SNR = "; safe_double_print (cr.PSNR); std::cout << " Max error = " << cr.maxerror; if (cr.maxerror != 0) { std::cout << " @ (" << cr.maxx << ", " << cr.maxy; if (img0.spec().depth > 1) std::cout << ", " << cr.maxz; if (cr.maxc < (int)img0.spec().channelnames.size()) std::cout << ", " << img0.spec().channelnames[cr.maxc] << ')'; else if (cr.maxc < (int)img1.spec().channelnames.size()) std::cout << ", " << img1.spec().channelnames[cr.maxc] << ')'; else std::cout << ", channel " << cr.maxc << ')'; } std::cout << "\n"; // when Visual Studio is used float values in scientific foramt are // printed with three digit exponent. We change this behaviour to fit // Linux way #ifdef _MSC_VER _set_output_format(_TWO_DIGIT_EXPONENT); #endif std::streamsize precis = std::cout.precision(); std::cout << " " << cr.nwarn << " pixels (" << std::setprecision(3) << (100.0*cr.nwarn / npels) << std::setprecision(precis) << "%) over " << warnthresh << "\n"; std::cout << " " << cr.nfail << " pixels (" << std::setprecision(3) << (100.0*cr.nfail / npels) << std::setprecision(precis) << "%) over " << failthresh << "\n"; if (perceptual) std::cout << " " << yee_failures << " pixels (" << std::setprecision(3) << (100.0*yee_failures / npels) << std::setprecision(precis) << "%) failed the perceptual test\n"; } // If the user requested that a difference image be output, // do that. N.B. we only do this for the first subimage // right now, because ImageBuf doesn't really know how to // write subimages. if (diffimage.size() && (cr.maxerror != 0 || !outdiffonly)) { ImageBuf diff; if (diffabs) ImageBufAlgo::absdiff (diff, img0, img1); else ImageBufAlgo::sub (diff, img0, img1); if (diffscale != 1.0f) ImageBufAlgo::mul (diff, diff, diffscale); diff.write (diffimage); // Clear diff image name so we only save the first // non-matching subimage. diffimage = ""; } } } if (compareall && img0.nsubimages() != img1.nsubimages()) { if (! quiet) std::cerr << "Images had differing numbers of subimages (" << img0.nsubimages() << " vs " << img1.nsubimages() << ")\n"; ret = ErrFail; } if (!compareall && (img0.nsubimages() > 1 || img1.nsubimages() > 1)) { if (! quiet) std::cout << "Only compared the first subimage (of " << img0.nsubimages() << " and " << img1.nsubimages() << ", respectively)\n"; } if (ret == ErrOK) { if (! quiet) std::cout << "PASS\n"; } else if (ret == ErrWarn) { if (! quiet) std::cout << "WARNING\n"; } else if (ret) { if (quiet) std::cerr << "FAILURE\n"; else std::cout << "FAILURE\n"; } imagecache->invalidate_all (true); ImageCache::destroy (imagecache); return ret; }
void erl_start(int argc, char **argv) { int i = 1; char* arg=NULL; int have_break_handler = 1; char envbuf[21]; /* enough for any 64-bit integer */ size_t envbufsz; int ncpu = early_init(&argc, argv); int proc_tab_sz = ERTS_DEFAULT_MAX_PROCESSES; int port_tab_sz = ERTS_DEFAULT_MAX_PORTS; int port_tab_sz_ignore_files = 0; envbufsz = sizeof(envbuf); if (erts_sys_getenv_raw(ERL_MAX_ETS_TABLES_ENV, envbuf, &envbufsz) == 0) user_requested_db_max_tabs = atoi(envbuf); else user_requested_db_max_tabs = 0; envbufsz = sizeof(envbuf); if (erts_sys_getenv_raw("ERL_FULLSWEEP_AFTER", envbuf, &envbufsz) == 0) { Uint16 max_gen_gcs = atoi(envbuf); erts_smp_atomic32_set_nob(&erts_max_gen_gcs, (erts_aint32_t) max_gen_gcs); } #if (defined(__APPLE__) && defined(__MACH__)) || defined(__DARWIN__) /* * The default stack size on MacOS X is too small for pcre. */ erts_sched_thread_suggested_stack_size = 256; #endif #ifdef DEBUG verbose = DEBUG_DEFAULT; #endif erts_error_logger_warnings = am_error; while (i < argc) { if (argv[i][0] != '-') { erts_usage(); } if (strcmp(argv[i], "--") == 0) { /* end of emulator options */ i++; break; } switch (argv[i][1]) { /* * NOTE: -M flags are handled (and removed from argv) by * erts_alloc_init(). * * The -d, -m, -S, -t, and -T flags was removed in * Erlang 5.3/OTP R9C. * * -S, and -T has been reused in Erlang 5.5/OTP R11B. * * -d has been reused in a patch R12B-4. */ case '#' : arg = get_arg(argv[i]+2, argv[i+1], &i); if ((display_items = atoi(arg)) == 0) { erts_fprintf(stderr, "bad display items%s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("using display items %d\n",display_items)); break; case 'f': if (!strncmp(argv[i],"-fn",3)) { int warning_type = ERL_FILENAME_WARNING_WARNING; arg = get_arg(argv[i]+3, argv[i+1], &i); switch (*arg) { case 'u': switch (*(argv[i]+4)) { case 'w': case 0: break; case 'i': warning_type = ERL_FILENAME_WARNING_IGNORE; break; case 'e': warning_type = ERL_FILENAME_WARNING_ERROR; break; default: erts_fprintf(stderr, "bad type of warnings for " "wrongly coded filename: %s\n", argv[i]+4); erts_usage(); } erts_set_user_requested_filename_encoding ( ERL_FILENAME_UTF8, warning_type ); break; case 'l': erts_set_user_requested_filename_encoding ( ERL_FILENAME_LATIN1, warning_type ); break; case 'a': switch (*(argv[i]+4)) { case 'w': case 0: break; case 'i': warning_type = ERL_FILENAME_WARNING_IGNORE; break; case 'e': warning_type = ERL_FILENAME_WARNING_ERROR; break; default: erts_fprintf(stderr, "bad type of warnings for " "wrongly coded filename: %s\n", argv[i]+4); erts_usage(); } erts_set_user_requested_filename_encoding ( ERL_FILENAME_UNKNOWN, warning_type ); break; default: erts_fprintf(stderr, "bad filename encoding %s, can be " "(l,u or a, optionally followed by w, " "i or e)\n", arg); erts_usage(); } break; } else { erts_fprintf(stderr, "%s unknown flag %s\n", argv[0], argv[i]); erts_usage(); } case 'L': erts_no_line_info = 1; break; case 'v': #ifdef DEBUG if (argv[i][2] == '\0') { verbose |= DEBUG_SYSTEM; } else { char *ch; for (ch = argv[i]+2; *ch != '\0'; ch++) { switch (*ch) { case 's': verbose |= DEBUG_SYSTEM; break; case 'g': verbose |= DEBUG_PRIVATE_GC; break; case 'M': verbose |= DEBUG_MEMORY; break; case 'a': verbose |= DEBUG_ALLOCATION; break; case 't': verbose |= DEBUG_THREADS; break; case 'p': verbose |= DEBUG_PROCESSES; break; case 'm': verbose |= DEBUG_MESSAGES; break; default : erts_fprintf(stderr,"Unknown verbose option: %c\n",*ch); } } } erts_printf("Verbose level: "); if (verbose & DEBUG_SYSTEM) erts_printf("SYSTEM "); if (verbose & DEBUG_PRIVATE_GC) erts_printf("PRIVATE_GC "); if (verbose & DEBUG_MEMORY) erts_printf("PARANOID_MEMORY "); if (verbose & DEBUG_ALLOCATION) erts_printf("ALLOCATION "); if (verbose & DEBUG_THREADS) erts_printf("THREADS "); if (verbose & DEBUG_PROCESSES) erts_printf("PROCESSES "); if (verbose & DEBUG_MESSAGES) erts_printf("MESSAGES "); erts_printf("\n"); #else erts_fprintf(stderr, "warning: -v (only in debug compiled code)\n"); #endif break; case 'V' : { char tmp[256]; tmp[0] = tmp[1] = '\0'; #ifdef DEBUG strcat(tmp, ",DEBUG"); #endif #ifdef ERTS_SMP strcat(tmp, ",SMP"); #endif #ifdef USE_THREADS strcat(tmp, ",ASYNC_THREADS"); #endif #ifdef HIPE strcat(tmp, ",HIPE"); #endif erts_fprintf(stderr, "Erlang "); if (tmp[1]) { erts_fprintf(stderr, "(%s) ", tmp+1); } erts_fprintf(stderr, "(" EMULATOR ") emulator version " ERLANG_VERSION "\n"); erl_exit(0, ""); } break; case 'H': /* undocumented */ fprintf(stderr, "The undocumented +H option has been removed (R10B-6).\n\n"); break; case 'h': { char *sub_param = argv[i]+2; /* set default heap size * * h|ms - min_heap_size * h|mbs - min_bin_vheap_size * */ if (has_prefix("mbs", sub_param)) { arg = get_arg(sub_param+3, argv[i+1], &i); if ((BIN_VH_MIN_SIZE = atoi(arg)) <= 0) { erts_fprintf(stderr, "bad heap size %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("using minimum binary virtual heap size %d\n", BIN_VH_MIN_SIZE)); } else if (has_prefix("ms", sub_param)) { arg = get_arg(sub_param+2, argv[i+1], &i); if ((H_MIN_SIZE = atoi(arg)) <= 0) { erts_fprintf(stderr, "bad heap size %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("using minimum heap size %d\n", H_MIN_SIZE)); } else { /* backward compatibility */ arg = get_arg(argv[i]+2, argv[i+1], &i); if ((H_MIN_SIZE = atoi(arg)) <= 0) { erts_fprintf(stderr, "bad heap size %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("using minimum heap size %d\n", H_MIN_SIZE)); } break; } case 'd': /* * Never produce crash dumps for internally detected * errors; only produce a core dump. (Generation of * crash dumps is destructive and makes it impossible * to inspect the contents of process heaps in the * core dump.) */ erts_no_crash_dump = 1; break; case 'e': if (sys_strcmp("c", argv[i]+2) == 0) { erts_ets_always_compress = 1; } else { /* set maximum number of ets tables */ arg = get_arg(argv[i]+2, argv[i+1], &i); if (( user_requested_db_max_tabs = atoi(arg) ) < 0) { erts_fprintf(stderr, "bad maximum number of ets tables %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("using maximum number of ets tables %d\n", user_requested_db_max_tabs)); } break; case 'i': /* define name of module for initial function */ init = get_arg(argv[i]+2, argv[i+1], &i); break; case 'b': /* define name of initial function */ boot = get_arg(argv[i]+2, argv[i+1], &i); break; case 'B': if (argv[i][2] == 'i') /* +Bi */ ignore_break = 1; else if (argv[i][2] == 'c') /* +Bc */ replace_intr = 1; else if (argv[i][2] == 'd') /* +Bd */ have_break_handler = 0; else if (argv[i+1][0] == 'i') { /* +B i */ get_arg(argv[i]+2, argv[i+1], &i); ignore_break = 1; } else if (argv[i+1][0] == 'c') { /* +B c */ get_arg(argv[i]+2, argv[i+1], &i); replace_intr = 1; } else if (argv[i+1][0] == 'd') { /* +B d */ get_arg(argv[i]+2, argv[i+1], &i); have_break_handler = 0; } else /* +B */ have_break_handler = 0; break; case 'K': /* If kernel poll support is present, erl_sys_args() will remove the K parameter and value */ get_arg(argv[i]+2, argv[i+1], &i); erts_fprintf(stderr, "kernel-poll not supported; \"K\" parameter ignored\n", arg); break; case 'n': arg = get_arg(argv[i]+2, argv[i+1], &i); switch (arg[0]) { case 's': /* synchronous */ erts_port_synchronous_ops = 1; erts_port_schedule_all_ops = 0; break; case 'a': /* asynchronous */ erts_port_synchronous_ops = 0; erts_port_schedule_all_ops = 1; break; case 'd': /* Default - schedule on conflict (asynchronous) */ erts_port_synchronous_ops = 0; erts_port_schedule_all_ops = 0; break; default: bad_n_option: erts_fprintf(stderr, "bad -n option %s\n", arg); erts_usage(); } if (arg[1] != '\0') goto bad_n_option; break; case 'P': /* set maximum number of processes */ arg = get_arg(argv[i]+2, argv[i+1], &i); errno = 0; proc_tab_sz = strtol(arg, NULL, 10); if (errno != 0 || proc_tab_sz < ERTS_MIN_PROCESSES || ERTS_MAX_PROCESSES < proc_tab_sz) { erts_fprintf(stderr, "bad number of processes %s\n", arg); erts_usage(); } break; case 'Q': /* set maximum number of ports */ arg = get_arg(argv[i]+2, argv[i+1], &i); errno = 0; port_tab_sz = strtol(arg, NULL, 10); if (errno != 0 || port_tab_sz < ERTS_MIN_PROCESSES || ERTS_MAX_PROCESSES < port_tab_sz) { erts_fprintf(stderr, "bad number of ports %s\n", arg); erts_usage(); } port_tab_sz_ignore_files = 1; break; case 'S' : /* Was handled in early_init() just read past it */ (void) get_arg(argv[i]+2, argv[i+1], &i); break; case 's' : { char *estr; int res; char *sub_param = argv[i]+2; if (has_prefix("bt", sub_param)) { arg = get_arg(sub_param+2, argv[i+1], &i); res = erts_init_scheduler_bind_type_string(arg); if (res != ERTS_INIT_SCHED_BIND_TYPE_SUCCESS) { switch (res) { case ERTS_INIT_SCHED_BIND_TYPE_NOT_SUPPORTED: estr = "not supported"; break; case ERTS_INIT_SCHED_BIND_TYPE_ERROR_NO_CPU_TOPOLOGY: estr = "no cpu topology available"; break; case ERTS_INIT_SCHED_BIND_TYPE_ERROR_BAD_TYPE: estr = "invalid type"; break; default: estr = "undefined error"; break; } erts_fprintf(stderr, "setting scheduler bind type '%s' failed: %s\n", arg, estr); erts_usage(); } } else if (has_prefix("bwt", sub_param)) { arg = get_arg(sub_param+3, argv[i+1], &i); if (erts_sched_set_busy_wait_threshold(arg) != 0) { erts_fprintf(stderr, "bad scheduler busy wait threshold: %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("scheduler wakup threshold: %s\n", arg)); } else if (has_prefix("cl", sub_param)) { arg = get_arg(sub_param+2, argv[i+1], &i); if (sys_strcmp("true", arg) == 0) erts_sched_compact_load = 1; else if (sys_strcmp("false", arg) == 0) erts_sched_compact_load = 0; else { erts_fprintf(stderr, "bad scheduler compact load value '%s'\n", arg); erts_usage(); } } else if (has_prefix("ct", sub_param)) { arg = get_arg(sub_param+2, argv[i+1], &i); res = erts_init_cpu_topology_string(arg); if (res != ERTS_INIT_CPU_TOPOLOGY_OK) { switch (res) { case ERTS_INIT_CPU_TOPOLOGY_INVALID_ID: estr = "invalid identifier"; break; case ERTS_INIT_CPU_TOPOLOGY_INVALID_ID_RANGE: estr = "invalid identifier range"; break; case ERTS_INIT_CPU_TOPOLOGY_INVALID_HIERARCHY: estr = "invalid hierarchy"; break; case ERTS_INIT_CPU_TOPOLOGY_INVALID_ID_TYPE: estr = "invalid identifier type"; break; case ERTS_INIT_CPU_TOPOLOGY_INVALID_NODES: estr = "invalid nodes declaration"; break; case ERTS_INIT_CPU_TOPOLOGY_MISSING_LID: estr = "missing logical identifier"; break; case ERTS_INIT_CPU_TOPOLOGY_NOT_UNIQUE_LIDS: estr = "not unique logical identifiers"; break; case ERTS_INIT_CPU_TOPOLOGY_NOT_UNIQUE_ENTITIES: estr = "not unique entities"; break; case ERTS_INIT_CPU_TOPOLOGY_MISSING: estr = "missing cpu topology"; break; default: estr = "undefined error"; break; } erts_fprintf(stderr, "bad cpu topology '%s': %s\n", arg, estr); erts_usage(); } } else if (has_prefix("pp", sub_param)) { arg = get_arg(sub_param+2, argv[i+1], &i); if (sys_strcmp(arg, "true") == 0) erts_port_parallelism = 1; else if (sys_strcmp(arg, "false") == 0) erts_port_parallelism = 0; else { erts_fprintf(stderr, "bad port parallelism scheduling hint %s\n", arg); erts_usage(); } } else if (sys_strcmp("nsp", sub_param) == 0) erts_use_sender_punish = 0; else if (has_prefix("tbt", sub_param)) { arg = get_arg(sub_param+3, argv[i+1], &i); res = erts_init_scheduler_bind_type_string(arg); if (res == ERTS_INIT_SCHED_BIND_TYPE_ERROR_BAD_TYPE) { erts_fprintf(stderr, "setting scheduler bind type '%s' failed: invalid type\n", arg); erts_usage(); } } else if (sys_strcmp("wt", sub_param) == 0) { arg = get_arg(sub_param+2, argv[i+1], &i); if (erts_sched_set_wakeup_other_thresold(arg) != 0) { erts_fprintf(stderr, "scheduler wakeup threshold: %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("scheduler wakeup threshold: %s\n", arg)); } else if (sys_strcmp("ws", sub_param) == 0) { arg = get_arg(sub_param+2, argv[i+1], &i); if (erts_sched_set_wakeup_other_type(arg) != 0) { erts_fprintf(stderr, "scheduler wakeup strategy: %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("scheduler wakeup threshold: %s\n", arg)); } else if (has_prefix("ss", sub_param)) { /* suggested stack size (Kilo Words) for scheduler threads */ arg = get_arg(sub_param+2, argv[i+1], &i); erts_sched_thread_suggested_stack_size = atoi(arg); if ((erts_sched_thread_suggested_stack_size < ERTS_SCHED_THREAD_MIN_STACK_SIZE) || (erts_sched_thread_suggested_stack_size > ERTS_SCHED_THREAD_MAX_STACK_SIZE)) { erts_fprintf(stderr, "bad stack size for scheduler threads %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("suggested scheduler thread stack size %d kilo words\n", erts_sched_thread_suggested_stack_size)); } else { erts_fprintf(stderr, "bad scheduling option %s\n", argv[i]); erts_usage(); } break; } case 't': /* set atom table size */ arg = get_arg(argv[i]+2, argv[i+1], &i); errno = 0; erts_atom_table_size = strtol(arg, NULL, 10); if (errno != 0 || erts_atom_table_size < MIN_ATOM_TABLE_SIZE || erts_atom_table_size > MAX_ATOM_TABLE_SIZE) { erts_fprintf(stderr, "bad atom table size %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("setting maximum number of atoms to %d\n", erts_atom_table_size)); break; case 'T' : arg = get_arg(argv[i]+2, argv[i+1], &i); errno = 0; erts_modified_timing_level = atoi(arg); if ((erts_modified_timing_level == 0 && errno != 0) || erts_modified_timing_level < 0 || erts_modified_timing_level >= ERTS_MODIFIED_TIMING_LEVELS) { erts_fprintf(stderr, "bad modified timing level %s\n", arg); erts_usage(); } else { VERBOSE(DEBUG_SYSTEM, ("using modified timing level %d\n", erts_modified_timing_level)); } break; case 'R': { /* set compatibility release */ int this_rel; arg = get_arg(argv[i]+2, argv[i+1], &i); erts_compat_rel = atoi(arg); this_rel = this_rel_num(); if (erts_compat_rel < this_rel - 2 || this_rel < erts_compat_rel) { erts_fprintf(stderr, "bad compatibility release number %s\n", arg); erts_usage(); } switch (erts_compat_rel) { /* Currently no compat features... */ default: break; } break; } case 'A': /* Was handled in early init just read past it */ (void) get_arg(argv[i]+2, argv[i+1], &i); break; case 'a': /* suggested stack size (Kilo Words) for threads in thread pool */ arg = get_arg(argv[i]+2, argv[i+1], &i); erts_async_thread_suggested_stack_size = atoi(arg); if ((erts_async_thread_suggested_stack_size < ERTS_ASYNC_THREAD_MIN_STACK_SIZE) || (erts_async_thread_suggested_stack_size > ERTS_ASYNC_THREAD_MAX_STACK_SIZE)) { erts_fprintf(stderr, "bad stack size for async threads %s\n", arg); erts_usage(); } VERBOSE(DEBUG_SYSTEM, ("suggested async-thread stack size %d kilo words\n", erts_async_thread_suggested_stack_size)); break; case 'r': { char *sub_param = argv[i]+2; if (has_prefix("g", sub_param)) { get_arg(sub_param+1, argv[i+1], &i); /* already handled */ } else { erts_ets_realloc_always_moves = 1; } break; } case 'c': if (argv[i][2] == 0) { /* -c: documented option */ erts_disable_tolerant_timeofday = 1; } #ifdef ERTS_OPCODE_COUNTER_SUPPORT else if (argv[i][2] == 'i') { /* -ci: undcoumented option*/ count_instructions = 1; } #endif break; case 'W': arg = get_arg(argv[i]+2, argv[i+1], &i); switch (arg[0]) { case 'i': erts_error_logger_warnings = am_info; break; case 'w': erts_error_logger_warnings = am_warning; break; case 'e': /* The default */ erts_error_logger_warnings = am_error; default: erts_fprintf(stderr, "unrecognized warning_map option %s\n", arg); erts_usage(); } break; case 'z': { char *sub_param = argv[i]+2; int new_limit; if (has_prefix("dbbl", sub_param)) { arg = get_arg(sub_param+4, argv[i+1], &i); new_limit = atoi(arg); if (new_limit < 1 || INT_MAX/1024 < new_limit) { erts_fprintf(stderr, "Invalid dbbl limit: %d\n", new_limit); erts_usage(); } else { erts_dist_buf_busy_limit = new_limit*1024; } } else { erts_fprintf(stderr, "bad -z option %s\n", argv[i]); erts_usage(); } break; } default: erts_fprintf(stderr, "%s unknown flag %s\n", argv[0], argv[i]); erts_usage(); } i++; } /* Output format on windows for sprintf defaults to three exponents. * We use two-exponent to mimic normal sprintf behaviour. */ #if defined(__WIN32__) && defined(_TWO_DIGIT_EXPONENT) _set_output_format(_TWO_DIGIT_EXPONENT); #endif /* Restart will not reinstall the break handler */ #ifdef __WIN32__ if (ignore_break) erts_set_ignore_break(); else if (replace_intr) erts_replace_intr(); else init_break_handler(); #else if (ignore_break) erts_set_ignore_break(); else if (have_break_handler) init_break_handler(); if (replace_intr) erts_replace_intr(); #endif boot_argc = argc - i; /* Number of arguments to init */ boot_argv = &argv[i]; erl_init(ncpu, proc_tab_sz, port_tab_sz, port_tab_sz_ignore_files); load_preloaded(); erts_end_staging_code_ix(); erts_commit_staging_code_ix(); erts_initialized = 1; erl_first_process_otp("otp_ring0", NULL, 0, boot_argc, boot_argv); #ifdef ERTS_SMP erts_start_schedulers(); /* Let system specific code decide what to do with the main thread... */ erts_sys_main_thread(); /* May or may not return! */ #else erts_thr_set_main_status(1, 1); #if ERTS_USE_ASYNC_READY_Q erts_get_scheduler_data()->aux_work_data.async_ready.queue = erts_get_async_ready_queue(1); #endif set_main_stack_size(); process_main(); #endif }
int main(int argc, char* argv[]) { #if defined(WIN32) //Required as windows default is 3 digit exponent. _set_output_format(_TWO_DIGIT_EXPONENT); #endif // Convert the args to a list vector<string> args; for(int i = 1; i < argc; i++) { args.push_back(argv[1]); } magphys::CommandLine commandLine; if(!commandLine.loadArguments(args)) { return 1; } // Load the filters we are using magphys::ModelData modelData {commandLine.redshift()}; if(!modelData.loadFilters(commandLine.filtersFile())) { return 1; } // Load the observations if(!modelData.loadObservations(commandLine.observationsFile())) { return 1; } // Load the IR Model if(!modelData.loadModelInfrared(commandLine.modelInfraredFile())) { return 1; } // Load the Optical Model if(!modelData.loadModelOptical(commandLine.modelOpticalFile())) { return 1; } magphys::Fit fit {modelData.redshift()}; fit.initialise(); // For each observation vector<magphys::ObservationLine>& observationLines = *modelData.observationLines(); for(size_t i = 0; i < observationLines.size(); i++) { magphys::ObservationLine& observationLine = observationLines[i]; // Check we have enough fluxes to work on int numberFluxes = 0; for(auto& observation : observationLine.observations__) { if(observation.flux_obs__ > 0) { numberFluxes++; } } // If we haven't enough fluxes ignore std::cout << "number fluxes = " << numberFluxes << std::endl; if(numberFluxes < 4) { continue; } // Correct the fluxes for this observation modelData.convertToLnu(fit.dist(), observationLine); } return 0; }
int main(int argc, char **argv) { char string1[1000]; int counth, countv, maxcounthv, start, Nbpms,i, j, bpmCounter, columnCounter, horizontalBpmCounter, verticalBpmCounter, flag, loopcounter=0; std::ofstream linxFile, linyFile, noiseFile, spectrumFile; std::ifstream driveInputFile, drivingTermsFile, dataFile; std::string temp_str, dataFilePath, bpmFileName, workingDirectoryPath, sussixInputFilePath, driveInputFilePath, drivingTermsFilePath, noiseFilePath, linxFilePath, linyFilePath, spectrumFilePath; #ifdef _WIN32 /*Changes minor formatting difference in windows regarding the output of a number in scientific notation.*/ _set_output_format(_TWO_DIGIT_EXPONENT); #endif omp_set_dynamic(0); //To output scientific notation std::cout << std::setiosflags (std::ios::scientific); get_and_check_file_paths(&workingDirectoryPath, &drivingTermsFilePath, &driveInputFilePath, &sussixInputFilePath, argv[1]); std::cout << "READ THIS:" << workingDirectoryPath << std::endl; /* set all options to defaults, it could happen that they are not included in the file (tbach) */ InpData.init_input_values(); //Reads input data from Drive.inp into global InpData class get_inp_data(driveInputFilePath); //Checks tune_x/y, kcase, kick, labelrun, pickend, and pickend check_inp_data(); drivingTermsFile.open(drivingTermsFilePath.c_str()); if(cannotOpenFile(drivingTermsFilePath,'i')){ std::cout << "Leaving drive due to error" << std::endl; exit(EXIT_FAILURE); } /* From drivingTermsFilePath assign dataFilePath, assign turns. */ while (readDrivingTerms(drivingTermsFile, &(InpData.turns), &dataFilePath)) { /* set all values to be calculated to default values */ CalcData.init_calc_values(); dataFile.open(dataFilePath.c_str()); /* Check the file dataFilePath */ if(cannotOpenFile(dataFilePath,'i')) continue; loopcounter++; std::cout << "Data file: " << dataFilePath << std::endl; bpmFileName = dataFilePath.substr(dataFilePath.rfind('/',dataFilePath.size()-2)); std::cout << "bpmFileName: " << bpmFileName << std::endl; noiseFilePath = workingDirectoryPath+'/'+bpmFileName+"_noise"; linxFilePath = workingDirectoryPath+'/'+bpmFileName+"_linx"; linyFilePath = workingDirectoryPath+'/'+bpmFileName+"_liny"; bpmFileName +="_bpm"; linxFile.open(linxFilePath.c_str()); linyFile.open(linyFilePath.c_str()); if (InpData.labelrun == 1) { noiseFilePath = workingDirectoryPath+'/'+bpmFileName+"_noise"; noiseFile.open(noiseFilePath.c_str()); if(cannotOpenFile(noiseFilePath,'o')){ std::cerr << "Leaving drive due to error" << std::endl; exit(EXIT_FAILURE); } } if(cannotOpenFile(linxFilePath,'o') || cannotOpenFile(linyFilePath,'o')){ std::cerr << "Leaving drive due to error" << std::endl; exit(EXIT_FAILURE); } linxFile << "* NAME S BINDEX SLABEL TUNEX MUX AMPX NOISE PK2PK AMP01 PHASE01 CO CORMS AMP_20 PHASE_20 AMP02 PHASE02 AMP_30 PHASE_30 AMP_1_1 PHASE_1_1 AMP2_2 PHASE2_2 AMP0_2 PHASE0_2 NATTUNEX NATAMPX\n"; linxFile << std::scientific << "$ %s %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le\n"; linyFile << "* NAME S BINDEX SLABEL TUNEY MUY AMPY NOISE PK2PK AMP10 PHASE10 CO CORMS AMP_1_1 PHASE_1_1 AMP_20 PHASE_20 AMP1_1 PHASE1_1 AMP0_2 PHASE0_2 AMP0_3 PHASE0_3 NATTUNEY NATAMPY\n"; linyFile << std::scientific << "$ %s %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le %le\n"; flag = 0; for (i = 0; i < MAXPICK; i++) BPMs[i].pickedup = false; /* start data file reading, puts the tbt data each BPM struct into with all the data from the pick-ups */ bpmCounter = 0; columnCounter = 0; horizontalBpmCounter = -1; verticalBpmCounter = MAXPICK / 2 - 1; i = 0; string1[0] = (char)dataFile.get(); while (string1[0] == '#') { /* then it is a comment line (tbach) */ while (dataFile.get() != '\n'); /* read until the end of the line (tbach) */ string1[0] = (char)dataFile.get(); /* read the first char of the new line (tbach) */ } /* after this, we have skipped all the comment lines, and s[0] is the first character of a new line which is not a "#" (tbach) */ if (LOG_INFO) printf("BPM file content:\n"); while (string1[0] != EOF) { if (string1[0] == '\n') { ++bpmCounter; if (LOG_INFO) printf("\n"); columnCounter = 0; } if (isspace((int)string1[0]) && flag == 1) flag = 0; if (!isspace((int)string1[0]) && flag == 0) { while (!isspace((int)string1[i]) && string1[i] != EOF) { ++i; string1[i] = (char)dataFile.get(); if (i > 100) { string1[i + 1] = '\0'; fprintf(stderr, "Found a value which has more than 100 characters, exit parsing.\n" "This is most probably a malformatted file. bpmCounter=%d columnCounter=%d string1=%s\n", bpmCounter, columnCounter, string1); exit(EXIT_FAILURE); } } string1[i + 1] = string1[i]; string1[i] = '\0'; if (LOG_INFO) printf("%s ", string1); if (columnCounter >= MAXTURNS) { fprintf(stderr, "Found >= %d Turns, this turn size is not supported. Reduce amount of turns. bpmCounter:%d\n", MAXTURNS - 3, bpmCounter); /* 0,1,2 is plane, name and location (tbach) */ exit(EXIT_FAILURE); } if (bpmCounter >= MAXPICK) { fprintf(stderr, "Found >= %d BPMs, this size is not supported. Reduce amount of BPMs. columnCounter:%d\n", MAXPICK, columnCounter); exit(EXIT_FAILURE); } if (columnCounter == 0) { /*plane (tbach) */ BPMs[bpmCounter].plane = atoi(string1); if (BPMs[bpmCounter].plane == 0) /* 0 is horizontal, 1 is vertical (tbach) */ ++horizontalBpmCounter; else ++verticalBpmCounter; } else if (columnCounter == 1) { /*bpm name (tbach) */ if (BPMs[bpmCounter].plane == 0) { if (horizontalBpmCounter < 0) /* Branch prediction will cry, but well lets have security (tbach) */ { fprintf(stderr, "horizontalBpmCounter < 0. Should not happen. Probably malformatted input file?\n"); exit(EXIT_FAILURE); } BPMs[horizontalBpmCounter].bpmname = string1; BPMs[horizontalBpmCounter].pickedup = true; } else { BPMs[verticalBpmCounter].bpmname = string1; BPMs[verticalBpmCounter].pickedup = true; } } else if (columnCounter == 2) { /*bpm location (tbach) */ if (BPMs[bpmCounter].plane == 0) { if (horizontalBpmCounter < 0) /* Branch prediction will cry, but well lets have security (tbach) */ { fprintf(stderr, "horizontalBpmCounter < 0. Should not happen. Probably malformatted input file?\n"); exit(EXIT_FAILURE); } BPMs[horizontalBpmCounter].bpmpos = atof(string1); } else BPMs[verticalBpmCounter].bpmpos = atof(string1); } else { /*bpm data (tbach) */ if (BPMs[bpmCounter].plane == 0) BPMs[horizontalBpmCounter].tbtdata[columnCounter - 3] = atof(string1); else BPMs[verticalBpmCounter].tbtdata[columnCounter - 3] = atof(string1); Nturns = columnCounter - 3 + 1; /* If the last line is an empty line, then we can get the number of turns only from here. First 3 are plane, name and location. Plus 1 for index start at 0 (tbach) */ } ++columnCounter; flag = 1; string1[0] = string1[i + 1]; i = 0; } if (flag == 0) string1[0] = (char)dataFile.get(); } dataFile.close(); Nbpms = bpmCounter; counth = horizontalBpmCounter + 1; countv = verticalBpmCounter + 1; /* now redefine turns as the minimum of the Nturns read and the DrivingTerms data card */ /* NB assumes all BPMs have the same number of turns as the last one read is used */ if (InpData.turns > Nturns) InpData.turns = Nturns; /* Some statistics and checks */ printf("Total number of pick-ups: %d Last turn number: %d, turns to run: %d\n", Nbpms, Nturns, InpData.turns); printf("Horizontal pick-ups: %d Vertical pick-ups: %d\n", counth, -MAXPICK / 2 + countv); printf("name of BPM[0]: %s, pos: %f, first turn: %f, second turn: %f, last turn: %f, last turn to run: %f \n", BPMs[0].bpmname.c_str(), BPMs[0].bpmpos, BPMs[0].tbtdata[0], BPMs[0].tbtdata[1], BPMs[0].tbtdata[Nturns - 1], BPMs[0].tbtdata[InpData.turns - 1]); /* end of data file reading */ printf("kick: %d \n", InpData.kick); /* searching for two working adjacent pick-ups */ /* after the Q-kickers for finding the kick */ if (InpData.kick < 0) { start = -(InpData.kcase - 1) * MAXPICK / 2 + 2; while (BPMs[start].pickedup == false || BPMs[start + 2].pickedup == false) { start = start + 2; } printf("looking for kick in pick-up:%d\n", start + 1); /* Find kick here and get kick */ for (columnCounter = 1; (InpData.kick < 0) && (columnCounter < InpData.turns); ++columnCounter) { if (fabs(BPMs[start].tbtdata[columnCounter] - BPMs[start].tbtdata[columnCounter - 1]) > InpData.kper) { InpData.kick = columnCounter; } } if (InpData.kick < 0) { fprintf(stderr, "NO KICK FOUND\n"); exit(EXIT_FAILURE); } else printf("Found kick in turn:%d\n", InpData.kick + 1); /*Natural count */ } if (InpData.kick > 0) { for (i = 0; i < MAXPICK; i++) { if (BPMs[i].pickedup == true) { for (j = InpData.kick; j < InpData.turns; j++) BPMs[i].tbtdata[j - InpData.kick] = BPMs[i].tbtdata[j]; } } InpData.turns -= InpData.kick; } printf("Turns to be processed after kick offset: %d BPMs[0].tbtdata[0]: %f \n", InpData.turns, BPMs[0].tbtdata[0]); /* First part of the analysis: Determine phase of all pick-ups and noise */ writeSussixInput(sussixInputFilePath, InpData.turns, InpData.istun, InpData.tunex, InpData.tuney); if (counth >= (countv - MAXPICK / 2)) maxcounthv = counth; else maxcounthv = -MAXPICK / 2 + countv; if (maxcounthv > InpData.pickend) maxcounthv = InpData.pickend; if (maxcounthv >= MAXPICK) { fprintf(stderr, "\nNot enough Pick-up mexmory\n"); exit(EXIT_FAILURE); } printf("BPMs in loop: %d, pickstart: %d, resulting loop length: %d\n", maxcounthv, InpData.pickstart, maxcounthv - InpData.pickstart); #pragma omp parallel for private(i, horizontalBpmCounter, verticalBpmCounter, j, maxamp, calculatednattunex, calculatednattuney, calculatednatampx, calculatednatampy) for (i = InpData.pickstart; i < maxcounthv; ++i) { horizontalBpmCounter = i; verticalBpmCounter = i + MAXPICK / 2; if (verticalBpmCounter >= countv) verticalBpmCounter = countv - 1; if (horizontalBpmCounter >= counth) horizontalBpmCounter = counth - 1; if (horizontalBpmCounter < 0 || verticalBpmCounter < 0) { fprintf(stderr, "horizontal or vertical BpmCounter < 0. Should not happen.\n"); exit(EXIT_FAILURE); } for (j = 0; j < MAXTURNS; ++j) { doubleToSend[j] = BPMs[horizontalBpmCounter].tbtdata[j]; doubleToSend[j + MAXTURNS] = BPMs[verticalBpmCounter].tbtdata[j]; doubleToSend[j + 2 * MAXTURNS] = 0.0; doubleToSend[j + 3 * MAXTURNS] = 0.0; } /* This calls the external Fortran code (tbach)-Different name depending on OS (asherman)*/ #ifdef _WIN32 SUSSIX4DRIVENOISE (&doubleToSend[0], &tune[0], &litude[0], &phase[0], &allfreqsx[0], &allampsx[0], &allfreqsy[0], &allampsy[0], (char *)sussixInputFilePath.c_str()); #else sussix4drivenoise_(&doubleToSend[0], &tune[0], &litude[0], &phase[0], &allfreqsx[0], &allampsx[0], &allfreqsy[0], &allampsy[0], (char *)sussixInputFilePath.c_str()); #endif /* Let's look for natural tunes in the istun range if natural tunes input is given*/ maxamp = 0; calculatednattunex = NATTUNE_DEFAULT; if (InpData.nattunex > NATTUNE_DEFAULT) { for (j = 0; j < 300; ++j) { if ((InpData.nattunex - InpData.istun < allfreqsx[j] && allfreqsx[j] < InpData.nattunex + InpData.istun) && (maxamp < allampsx[j])) { maxamp = allampsx[j]; calculatednattunex = allfreqsx[j]; calculatednatampx = maxamp; } } } maxamp = 0; calculatednattuney = NATTUNE_DEFAULT; if (InpData.nattuney > NATTUNE_DEFAULT) { for (j = 0; j < 300; ++j) { if ((InpData.nattuney - InpData.istun < allfreqsy[j] && allfreqsy[j] < InpData.nattuney + InpData.istun) && (maxamp < allampsy[j])) { maxamp = allampsy[j]; calculatednattuney = allfreqsy[j]; calculatednatampy = maxamp; } } } #pragma omp critical { BPMs[horizontalBpmCounter].pickedup = BPMstatus(1, InpData.turns); /*Always returns true*/ if (InpData.labelrun == 1) noiseFile << std::scientific << "1 " << horizontalBpmCounter << " " << noise1 << ' ' << noiseAve << ' ' << maxpeak << ' ' << maxfreq << ' ' << maxmin << ' ' << nslines << ' ' << BPMs[i].pickedup << ' ' << phase[0] / 360. << std::endl; /* PRINT LINEAR FILE */ if (amplitude[0] > 0 && BPMs[i].pickedup == true && horizontalBpmCounter == i) { linxFile << std::scientific << '"' << BPMs[horizontalBpmCounter].bpmname << "\" " << BPMs[horizontalBpmCounter].bpmpos << ' ' << horizontalBpmCounter << ' ' << BPMs[horizontalBpmCounter].pickedup << ' ' << tune[0] << ' ' << phase[0] / 360. << ' ' << amplitude[0] << ' ' << noise1 << ' ' << maxmin << ' ' << amplitude[2] / amplitude[0] << ' ' << phase[2] / 360. << ' ' << co << ' ' << co2 << ' ' << amplitude[1] / amplitude[0] << ' ' << phase[1] / 360. << ' ' << amplitude[12] / amplitude[0] << ' ' << phase[12] / 360. << ' ' << amplitude[6] / amplitude[0] << ' ' << phase[6] / 360. << ' ' << amplitude[14] / amplitude[0] << ' ' << phase[14] / 360. << ' ' << amplitude[16] / amplitude[0] << ' ' << phase[16] / 360. << ' ' << amplitude[18] / amplitude[0] << ' ' << phase[18] / 360. << ' ' << calculatednattunex << ' ' << calculatednatampx << std::endl; ++CalcData.tunecountx; CalcData.tunesumx += tune[0]; CalcData.tune2sumx += tune[0] * tune[0]; if (calculatednattunex > NATTUNE_DEFAULT) { /* Initialized to -100. Condition true if nat tune found */ ++CalcData.nattunexcount; CalcData.nattunexsum += calculatednattunex; CalcData.nattunex2sum += calculatednattunex * calculatednattunex; } /* Horizontal Spectrum output */ if (i < 10) { spectrumFilePath = workingDirectoryPath+'/'+BPMs[i].bpmname+".x"; spectrumFile.open(spectrumFilePath.c_str()); if(cannotOpenFile(spectrumFilePath,'o')){ std::cout << "Leaving drive due to error" << std::endl; exit(EXIT_FAILURE); } spectrumFile << "* FREQ AMP\n$ %le %le\n"; for (j = 0; j < 300; ++j) spectrumFile << std::scientific << allfreqsx[j] << ' ' << allampsx[j] << std::endl; spectrumFile.close(); } } BPMs[verticalBpmCounter].pickedup = BPMstatus(2, InpData.turns); /*Always returns true*/ if (InpData.labelrun == 1) noiseFile << std::scientific << "2 " << verticalBpmCounter << " " << noise1 << ' ' << noiseAve << ' ' << maxpeak << ' ' << maxfreq << ' ' << maxmin << ' ' << nslines << ' ' << BPMs[verticalBpmCounter].pickedup << ' ' << phase[3] / 360. << std::endl; if (amplitude[3] > 0 && BPMs[verticalBpmCounter].pickedup == true && verticalBpmCounter == i + MAXPICK / 2) { linyFile << std::scientific << '"' << BPMs[verticalBpmCounter].bpmname << "\" " << BPMs[verticalBpmCounter].bpmpos << ' ' << verticalBpmCounter << ' ' << BPMs[verticalBpmCounter].pickedup << ' ' << tune[1] << ' ' << phase[3] / 360. << ' ' << amplitude[3] << ' ' << noise1 << ' ' << maxmin << ' ' << amplitude[5] / amplitude[3] << ' ' << phase[5] / 360. << ' ' << co << ' ' << co2 << ' ' << amplitude[13] / amplitude[3] << ' ' << phase[13] / 360. << ' ' << amplitude[15] / amplitude[3] << ' ' << phase[15] / 360. << ' ' << amplitude[17] / amplitude[3] << ' ' << phase[17] / 360. << ' ' << amplitude[4] / amplitude[3] << ' ' << phase[4] / 360. << ' ' << amplitude[11] / amplitude[3] << ' ' << phase[11] / 360. << ' ' << calculatednattuney << ' ' << calculatednatampy << std::endl; ++CalcData.tunecounty; CalcData.tunesumy += tune[1]; CalcData.tune2sumy += tune[1] * tune[1]; if (calculatednattuney > NATTUNE_DEFAULT) { /* Initialized to -100. Condition true if nat tune found */ ++CalcData.nattuneycount; CalcData.nattuneysum += calculatednattuney; CalcData.nattuney2sum += calculatednattuney * calculatednattuney; } if (verticalBpmCounter < MAXPICK / 2 + 10) { spectrumFilePath = workingDirectoryPath+'/'+BPMs[i].bpmname+".y"; spectrumFile.open(spectrumFilePath.c_str()); if(cannotOpenFile(spectrumFilePath,'o')){ std::cout << "Leaving drive due to error" << std::endl; exit(EXIT_FAILURE); } spectrumFile << "* FREQ AMP\n$ %le %le\n"; for (j = 0; j < 300; ++j) spectrumFile << std::scientific << allfreqsy[j] << ' ' << allampsy[j] << std::endl; spectrumFile.close(); } } } /* end of omp critical section */ } /* end of parallel for */ linxFile.close(); linyFile.close(); if (InpData.labelrun == 1) noiseFile.close(); /* Sort and move the "@..." lines to the top of the _linx/y files */ formatLinFile(linxFilePath, CalcData.tunecountx, CalcData.tunesumx, CalcData.tune2sumx, CalcData.nattunexcount, CalcData.nattunexsum, CalcData.nattunex2sum, 1); formatLinFile(linyFilePath, CalcData.tunecounty, CalcData.tunesumy, CalcData.tune2sumy, CalcData.nattuneycount, CalcData.nattuneysum, CalcData.nattuney2sum, 2); } /* end of while loop over all files to analyse */ drivingTermsFile.close(); if (loopcounter == 0) std::cout << "Drivingterms file has bad input, no data ever read\n"; return EXIT_SUCCESS; }