int run(const char* filename) { FILE *fp = fopen(filename, "r"); if (fp == NULL) { return -1; } command_line_list = list_create(); char line[256]; while (!feof(fp)) { memset_zero(line); fgets(line, sizeof(line), fp); line_number ++; command_line* cmd_line = validate_command_line(line); if (cmd_line == NULL) { continue; } list_push_back(command_line_list, cmd_line); // create pipe for piping pipe(cmd_line->pipe_filedes); } fclose(fp); // run commands line by line for (int i = 0; i < command_line_list->num_of_elements; i++) { command_line* cmd_line = (command_line*)command_line_list->elements[i]; process_command_line(cmd_line); } // wait until all child processes are exited while (1) { int status; pid_t pid = wait(&status); if (pid == -1 && errno == EINTR) { continue; } // but if exited command's action type is respwan, re-run that command for (int i = 0; i < command_line_list->num_of_elements; i++) { command_line* cmd_line = (command_line*)command_line_list->elements[i]; if (cmd_line->pid == pid && equal_str(cmd_line->action, "respawn")) { process_command_line(cmd_line); break; } } } return 0; }
//------------------------------------------------------------------------------ // Main function to generate module files in current directory //------------------------------------------------------------------------------ int main(int argc, char* argv[]){ // Strings for command line options std::string namespace_name=""; std::string author=""; std::string email=""; // determine namespace name, author and email from command line process_command_line(argc, argv, namespace_name, author, email); // create file header std::string file_header = create_file_header(author, email); // Generate data.cpp create_data(file_header, namespace_name); // Generate interface.cpp create_interface(file_header, namespace_name); // Generate initialise.cpp create_initialise(file_header, namespace_name); // Generate internal.hpp create_internal(file_header, namespace_name); // Generate internal.hpp create_module(file_header, namespace_name); // Generate makefile create_makefile(file_header, namespace_name); return EXIT_SUCCESS; }
static void do_reload(void) { int e = 0; drivers_unload_all(); /* Close all drivers */ config_clear(); clear_settings(); /* Reread command line*/ CHAIN(e, process_command_line(stored_argc, stored_argv)); /* Reread config file */ if (strcmp(configfile, UNSET_STR)==0) strncpy(configfile, DEFAULT_CONFIGFILE, sizeof(configfile)); CHAIN(e, process_configfile(configfile)); /* Set default values */ CHAIN(e, (set_default_settings(), 0)); /* Set reporting values */ CHAIN(e, set_reporting("LCDd", report_level, report_dest)); CHAIN(e, (report(RPT_INFO, "Set report level to %d, output to %s", report_level, ((report_dest == RPT_DEST_SYSLOG) ? "syslog" : "stderr")), 0)); /* And restart the drivers */ CHAIN(e, init_drivers()); CHAIN_END(e, "Critical error while reloading, abort."); }
int main(int argc, char* argv[]) { // コマンドラインパース auto const command_line = process_command_line(argc, argv); // グラフファイルを開いてgraph_dataに導入 std::ifstream ifs_graph(command_line.network); std::string const graph_data{std::istreambuf_iterator<char>(ifs_graph), std::istreambuf_iterator<char>()}; ifs_graph.close(); std::cout << "Loaded Graph: Length = " << graph_data.size() << std::endl; // graph_dataよりグラフパース bn::graph_t graph; bn::database_t data; std::tie(graph, data) = bn::serializer::bif().parse(graph_data.cbegin(), graph_data.cend()); std::cout << "Parsed Graph: Num of Node = " << graph.vertex_list().size() << std::endl; // リンクファイルがあるなら,そのリンク状態にする if(command_line.link_info) { // 全てのリンクを削除 graph.erase_all_edge(); // リンクファイル読み込み std::ifstream ifs(command_line.link_info.get()); bn::serializer::csv().load(ifs, graph); ifs.close(); } // 書出 std::ofstream ofs(command_line.output); bn::serializer::dot().write(ofs, graph, data); ofs.close(); }
void signal_handler(int signo) { if (signo == SIGINT) { will_dead = 1; broadcasting_signal(signo); fprintf(stderr, "terminated by SIGNAL(%d)\n", SIGINT); exit(1); } else if (signo == SIGCHLD) { if (will_dead) { return; } int state; pid_t pid_child = waitpid(-1, &state, WNOHANG); for (int i = 0; i < command_line_list->num_of_elements; i++) { command_line* cmd_line = (command_line*)command_line_list->elements[i]; if (cmd_line->pid == pid_child && equal_str(cmd_line->action, "respawn")) { process_command_line(cmd_line); break; } } } else if (signo == SIGTERM) { will_dead = 1; broadcasting_signal(signo); fprintf(stderr, "terminated by SIGNAL(%d)\n", SIGTERM); exit(1); } }
int main() { std::cout << std::setprecision(10); std::string input; while (std::cout << "# ", std::getline(std::cin, input)) { if (input.length() && input[0] == '/') { process_command_line(input); continue; } try { Parser p(input); auto result = p.parse(); std::cout << "-> " << result->eval() << "\n\n"; } catch (const ParserException& e) { std::cout << "Invalid input: " << e.what() << "\n\n"; } input.clear(); } }
int main (int argc, char **argv) { int pcl_return; union { int (*func)(); void *func_void; } unifunc; #ifdef HAVE_SETLOCALE setlocale (LC_ALL, ""); #endif pcl_return = process_command_line (argc, argv); if (pcl_return != 99) { return pcl_return; } if (strlen (argv[1]) > 31) { fprintf (stderr, "Invalid PROGRAM name\n"); return 1; } cob_init (argc - 1, &argv[1]); unifunc.func_void = cob_resolve (argv[1]); if (unifunc.func_void == NULL) { cob_call_error (); } cob_stop_run ( unifunc.func() ); }
int localedef_main (int argc, char *argv[]) { ProgramOptions opts; if (!process_command_line (&opts, argc, argv)) return EXIT_OK; if (opts.gen) { // create the locale databases as specified in generation list generate_locales (opts.map_file, opts.alias_file, opts.charmap_dir.c_str (), opts.src_dir.c_str (), opts.output_dir.c_str (), opts.use_ucs, opts.no_position, opts.link_aliases); } else { assert (0 != opts.locale_name); // C++ locale name requested std::string std_locale (opts.locale_name); // retrieve the output directory if any std::string std_outdir (""); if (std_locale.rfind (_RWSTD_PATH_SEP) != std::string::npos) { std_outdir = std_locale.substr ( 0, std_locale.rfind (_RWSTD_PATH_SEP) + 1); std_locale = std_locale.substr (std_locale.rfind (_RWSTD_PATH_SEP) + 1, std_locale.size ()); } // create the locale database create_locale (opts.source_name, opts.charmap_name, std_outdir, std_locale, opts.force_output, opts.use_ucs, opts.no_position, opts.link_aliases); } return EXIT_OK; }
int main(int argc, char* argv[]) { FILE* outputFile; FILE* gridFile; FILE* listFile; process_command_line(argc, argv); /* printf("%d %s %s %s\n", sort, outputFileName, gridFileName, listFileName); */ /* Make sure we can open all the files - exit if we don't. */ /* Note that exiting will close any open files, we do not have to close ** them explicitly. */ gridFile = open_file(gridFileName, "r"); listFile = open_file(listFileName, "r"); outputFile = open_file(outputFileName, "w"); read_grid(gridFile); process_list(listFile, outputFile); return 0; }
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if(fdwReason == DLL_PROCESS_ATTACH) { process_command_line(); void * module_base = reinterpret_cast<void *>(hinstDLL); if(verbose) write_line("Module base: " + ail::hex_string_32(reinterpret_cast<unsigned>(hinstDLL))); initialise_dll_vector(); anti_debugging(); if(! ( hide_module(module_base) && apply_hot_patches() && install_exception_handler() && process_main_thread() && python::initialise_python() ) ) { console_output = true; write_line("A fatal error occured, the program is not going to continue, please close this window."); while(true) Sleep(0); } if(prompt_mode) initialise_console(); LoadLibrary("D2Client.dll"); } return TRUE; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd) { DWORD tmp; BOOL fActivated; _hAppInstance = hInstance; if (FAILED(ActivatePreviousInstance(_szAppName, _szTitle, &fActivated)) || fActivated) { // Exit immediately if previous instance exists return 0; } process_command_line(lpCmdLine); if (_WindowSystem && _argc == 1) { int eembc = 0, hello = 0, mixed = 1, done = 0; init_gui(hInstance, hPrevInstance, nShowCmd); if (!done && MessageBox(NULL, TEXT("EEMBC (mixed)?"), TEXT("Pick a program"), MB_YESNO) == IDYES) { done = 1; eembc = 1; } if (!done && MessageBox(NULL, TEXT("EEMBC (int)?"), TEXT("Pick a program"), MB_YESNO) == IDYES) { done = 1; eembc = 1; mixed = 0; } if (!done && MessageBox(NULL, TEXT("HelloWorld (mixed)?"), TEXT("Pick a program"), MB_YESNO) == IDYES) { done = 1; hello = 1; } if (!done && MessageBox(NULL, TEXT("HelloWorld (int)?"), TEXT("Pick a program"), MB_YESNO) == IDYES) { done = 1; hello = 1; mixed = 0; } if (!done) { exit(0); } //_argv[_argc++] = "=HeapMin1500K"; //_argv[_argc++] = "=HeapCapacity1500K"; if (!mixed) { _argv[_argc++] = "-int"; } if (eembc) { _argv[_argc++] = "-cp"; _argv[_argc++] = "/eembcBM.jar"; _argv[_argc++] = "com.sun.mep.bench.main"; } if (hello) { _argv[_argc++] = "-cp"; _argv[_argc++] = "/HelloWorld.jar"; _argv[_argc++] = "HelloWorld"; } } SetForegroundWindow((HWND)(((DWORD)_hwndMain) | 0x01)); HANDLE vm_thread_handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&vm_thread_routine, 0, 0, &tmp); // Handle events until we're done if (_WindowSystem) { MSG msg; while (GetMessage(&msg, NULL, 0,0) == TRUE) { TranslateMessage (&msg); DispatchMessage(&msg); } } else { if (vm_thread_handle != NULL) { WaitForSingleObject(vm_thread_handle, INFINITE); } } CloseHandle(vm_thread_handle); if (_log_file) { fclose(_log_file); _log_file = NULL; } TerminateProcess(GetCurrentProcess(), 0); return 0; }
int main(int argc, char const* argv[]) { client_options const options = process_command_line( argc, argv ); if( options.show_version ) { uint8_t major, minor, patch; zmqpp::zmq_version(major, minor, patch); std::cout << BUILD_CLIENT_NAME << " version " << BUILD_VERSION << std::endl; std::cout << " built against 0mq version " << static_cast<int>(major) << "." << static_cast<int>(minor) << "." << static_cast<int>(patch) << std::endl; return EXIT_FAILURE; } if( options.show_usage || options.show_help ) { show_usage( std::cout, BUILD_CLIENT_NAME ); if( options.show_help ) { std::cout << std::endl << show_help( std::cout ); } return EXIT_FAILURE; } bool can_send = false, can_recv = false, toggles = false; switch( options.type ) { case zmqpp::socket_type::push: can_send = true; break; case zmqpp::socket_type::pull: can_recv = true; break; case zmqpp::socket_type::publish: can_send = true; break; case zmqpp::socket_type::subscribe: can_recv = true; break; case zmqpp::socket_type::request: can_send = true; toggles = true; break; case zmqpp::socket_type::reply: can_recv = true, toggles = true; break; default: std::cerr << "Unsupported socket type" << std::endl; return EXIT_FAILURE; } int standardin = -1; // If we can send / toggle then we need stdin if( can_send || toggles ) { if( options.verbose ) { std::cerr << "Connecting to stdin" << std::endl; } standardin = fileno(stdin); if ( standardin < 0 ) // really? { std::cerr << "Unable to get standard input, this might be an OS thing, sorry." << std::endl; return EXIT_FAILURE; } } zmqpp::context context; zmqpp::socket socket( context, options.type ); // TODO: allow subscriptions on command line if( zmqpp::socket_type::subscribe == options.type ) { socket.subscribe( "" ); } if( !options.binds.empty() ) { for(size_t i = 0; i < options.binds.size(); ++i) { if( options.verbose ) { std::cerr << "binding to " << options.binds[i] << std::endl; } try { socket.bind( options.binds[i] ); } catch(zmqpp::zmq_internal_exception& e) { std::cerr << "failed to bind to endpoint " << options.binds[i] << ": " << e.what() << std::endl; return EXIT_FAILURE; } } } if( !options.connects.empty() ) { for(size_t i = 0; i < options.connects.size(); ++i) { if( options.verbose ) { std::cerr << "connecting to " << options.connects[i] << std::endl; } try { socket.connect( options.connects[i] ); } catch(zmqpp::zmq_internal_exception& e) { std::cerr << "failed to bind to endpoint " << options.connects[i] << ": " << e.what() << std::endl; return EXIT_FAILURE; } } } zmqpp::poller poller; poller.add(socket); if( standardin >= 0 ) { poller.add( standardin ); } if( options.verbose && ( can_send || toggles ) ) { std::cerr << "While sending packets is allowed data entered on standard in will be sent to the 0mq socket." << std::endl; if( options.singlepart ) { std::cerr << "messages will be considered terminated by newline." << std::endl; } else { std::cerr << "Message parts will be considered terminated by newline." << std::endl; std::cerr << "Messages will be considered terminated by an empty part." << std::endl; std::cerr << "The empty part itself will not be included." << std::endl; } std::cerr << std::endl; if ( toggles && !can_send ) { std::cerr << "Sending starts as disabled for this socket type." << std::endl; std::cerr << std::endl; } } if( options.detailed ) { if( standardin >= 0 ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "reading from stdin is enabled." << std::endl; } if( can_send ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "sending via socket is enabled." << std::endl; } if( can_recv ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "receiving via socket is enabled." << std::endl; } if( toggles ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "socket will flip between send/recv." << std::endl; } if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Warning - Detailed logging is enabled." << std::endl; } zmqpp::message message; while(true) { poller.check_for(socket, (can_recv) ? zmqpp::poller::poll_in : zmqpp::poller::poll_none); if( standardin >= 0 ) { poller.check_for(standardin, (can_send) ? zmqpp::poller::poll_in : zmqpp::poller::poll_none); } if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Polling for incomming message data." << std::endl; } if( poller.poll() ) { if (poller.has_input(socket)) { assert(can_recv); if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Message on socket." << std::endl; } do { std::string message; socket.receive(message); if( options.annotate ) { std::cout << "<<: "; } std::cout << message << std::endl; } while(socket.has_more_parts()); if( options.annotate ) { std::cout << " --- " << std::endl; } else { std::cout << std::endl; } if (toggles) { can_recv = false; can_send = true; if( options.detailed ) { if( options.annotate ) { std::cerr << "**: " << std::endl; } std::cerr << "Toggling to sending enabled" << std::endl; } } } if( (standardin >= 0) && poller.has_input( standardin ) ) { assert(can_send); if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Data on stdin." << std::endl; } // TODO: handle cases where we actually read a mb of data from standard in and still don't have the terminator std::array<char, 1048576> buffer; size_t length = 0; char* result = fgets( buffer.data(), buffer.size(), stdin ); if( !result ) { if( options.annotate ) { std::cerr << "!!: "; } std::cerr << "Error in standard input" << std::endl; return EXIT_FAILURE; } assert(message.parts() == 0); while( result && (length = strlen( buffer.data() ) - 1) > 0 ) // trim newline from gets { buffer[length] = 0; message.add( buffer.data(), length ); if( options.singlepart ) { break; } result = fgets(buffer.data(), buffer.size(), stdin); } if( message.parts() > 0 ) { if( options.verbose ) { for( size_t i = 0; i < message.parts(); ++i ) { if( options.annotate ) { std::cout << ">>: "; } std::cout << message.get(i) << std::endl; } if( options.annotate ) { std::cout << " --- " << std::endl; } else { std::cout << std::endl; } } if( !socket.send( message, true ) ) { if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Output blocking, waiting to send" << std::endl; } if( !socket.send( message ) ) { if( options.annotate ) { std::cerr << "!!: "; } std::cerr << "Send failed, socket would have blocked" << std::endl; zmqpp::message tmp; std::swap( tmp, message ); } } if (toggles) { can_recv = true; can_send = false; if( options.detailed ) { if( options.annotate ) { std::cerr << "**: " << std::endl; } std::cerr << "Toggling to receive enabled" << std::endl; } } } } else if( (standardin >= 0) && can_send && !can_recv ) { if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "No data on stdin, exiting reader." << std::endl; } break; } } else if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Poller returned with no data, possibly an interrupt." << std::endl; } } if( options.detailed ) { if( options.annotate ) { std::cerr << "**: "; } std::cerr << "Exited reader, shutting down." << std::endl; } return EXIT_SUCCESS; }
int main(int argc, char*argv[]) { unsigned int old_cw; fpu_fix_start(&old_cw); Teuchos::Time timer("total"); timer.start(); Teuchos::GlobalMPISession mpisess(&argc,&argv,&std::cout); Tpetra::DefaultPlatform::DefaultPlatformType& platform = Tpetra::DefaultPlatform::getDefaultPlatform(); Teuchos::RCP<const Teuchos::Comm<int> > comm = platform.getComm(); typedef dd_real Scalar; typedef int LO; //LocalOrdinal typedef int GO; //GlobalOrdinal typedef Tpetra::DefaultPlatform::DefaultPlatformType::NodeType Node; typedef Tpetra::MultiVector<Scalar,LO,GO,Node> TMV; typedef Tpetra::Operator<Scalar,LO,GO,Node> TOP; typedef Belos::LinearProblem<Scalar,TMV,TOP> BLinProb; typedef Belos::SolverManager<Scalar,TMV,TOP> BSolverMgr; //Just get one parameter from the command-line: the name of an xml file //to get parameters from. std::string xml_file("calore1_mm.xml"); process_command_line(argc, argv, xml_file); //Read the contents of the xml file into a ParameterList. That parameter list //should specify a matrix-file and optionally which Belos solver to use, and //which Ifpack2 preconditioner to use, etc. If there are sublists of parameters //for Belos and Ifpack2, those will be passed to the respective destinations //from within the build_problem and build_solver functions. std::cout << "Every proc reading parameters from xml_file: " << xml_file << std::endl; Teuchos::ParameterList test_params = Teuchos::ParameterXMLFileReader(xml_file).getParameters(); //The build_problem function is located in build_problem.hpp. //Note that build_problem calls build_precond and sets a preconditioner on the //linear-problem, if a preconditioner is specified. Teuchos::RCP<BLinProb> problem = build_problem<Scalar,LO,GO,Node>(test_params, comm); //The build_solver function is located in build_solver.hpp: Teuchos::RCP<BSolverMgr> solver = build_solver<Scalar,TMV,TOP>(test_params, problem); Belos::ReturnType ret = solver->solve(); if (comm->getRank() == 0) { std::cout << "Converged in " << solver->getNumIters() << " iterations." << std::endl; } //Next compute residual vector and then 2-norm of residual: Teuchos::RCP<TMV> R = Teuchos::rcp(new TMV(*problem->getRHS())); problem->computeCurrResVec(&*R, &*problem->getLHS(), &*problem->getRHS()); Teuchos::Array<Teuchos::ScalarTraits<Scalar>::magnitudeType> norms(R->getNumVectors()); R->norm2(norms); if (norms.size() < 1) { throw std::runtime_error("ERROR: norms.size()==0 indicates R->getNumVectors()==0."); } if (comm->getRank() == 0) { std::cout << "2-Norm of 0th residual vec: " << norms[0] << std::endl; } //If the xml file specified a number of iterations to expect, then we will //use that as a test pass/fail criteria. if (test_params.isParameter("expectNumIters")) { int expected_iters = 0; Ifpack2::getParameter(test_params, "expectNumIters", expected_iters); int actual_iters = solver->getNumIters(); if (ret == Belos::Converged && actual_iters <= expected_iters && norms[0] < 1.e-7) { if (comm->getRank() == 0) { std::cout << "End Result: TEST PASSED" << std::endl; } } else { if (comm->getRank() == 0) { std::cout << "Actual iters("<<actual_iters <<") != expected number of iterations (" <<expected_iters<<"), or resid-norm(" << norms[0] << ") >= 1.e-7"<<std::endl; } } } fpu_fix_end(&old_cw); timer.stop(); if (comm->getRank() == 0) { std::cout << "proc 0 total program time: " << timer.totalElapsedTime() << std::endl; } return 0; }
int main(int argc, char **argv) { int e = 0; pid_t parent_pid = 0; stored_argc = argc; stored_argv = argv; /* * Settings in order of preference: * * 1: Settings specified in command line options... * 2: Settings specified in configuration file... * 3: Default settings * * Because of this, and because one option (-c) specifies where * the configuration file is, things are done in this order: * * 1. Read and set options. * 2. Read configuration file; if option is read in configuration * file and not already set, then set it. * 3. Having read configuration file, if parameter is not set, * set it to the default value. * * It is for this reason that the default values are **NOT** set * in the variable declaration... */ /* Report that server is starting (report will be delayed) */ report(RPT_NOTICE, "LCDd version %s starting", version); report(RPT_INFO, "Built on %s, protocol version %s, API version %s", build_date, protocol_version, api_version); clear_settings(); /* Read command line*/ CHAIN(e, process_command_line(argc, argv)); /* Read config file * If config file was not given on command line use default */ if (strcmp(configfile, UNSET_STR) == 0) strncpy(configfile, DEFAULT_CONFIGFILE, sizeof(configfile)); CHAIN(e, process_configfile(configfile)); /* Set default values*/ set_default_settings(); /* Set reporting settings (will also flush delayed reports) */ set_reporting("LCDd", report_level, report_dest); report(RPT_INFO, "Set report level to %d, output to %s", report_level, ((report_dest == RPT_DEST_SYSLOG) ? "syslog" : "stderr")); CHAIN_END(e, "Critical error while processing settings, abort."); /* Now, go into daemon mode (if we should)... * We wait for the child to report it is running OK. This mechanism * is used because forking after starting the drivers causes the * child to loose the (LPT) port access. */ if (!foreground_mode) { report(RPT_INFO, "Server forking to background"); CHAIN(e, parent_pid = daemonize()); } else { output_GPL_notice(); report(RPT_INFO, "Server running in foreground"); } install_signal_handlers(!foreground_mode); /* Only catch SIGHUP if not in foreground mode */ /* Startup the subparts of the server */ CHAIN(e, sock_init(bind_addr, bind_port)); CHAIN(e, screenlist_init()); CHAIN(e, init_drivers()); CHAIN(e, clients_init()); CHAIN(e, input_init()); CHAIN(e, menuscreens_init()); CHAIN(e, server_screen_init()); CHAIN_END(e, "Critical error while initializing, abort."); if (!foreground_mode) { /* Tell to parent that startup went OK. */ wave_to_parent(parent_pid); } drop_privs(user); /* This can't be done before, because sending a signal to a process of a different user will fail */ do_mainloop(); /* This loop never stops; we'll get out only with a signal...*/ return 0; }
int main(int argc, char *argv[]) { struct arg_str *cblOpt = arg_str1("c", "cable", "nero:<VID>:<PID> | xil3 | dusb", "cable driver to use"); struct arg_lit *scanOpt = arg_lit0("s", "scan", " scan the JTAG chain"); struct arg_file *bitOpt = arg_file0("b", "bitfile", "<fileName>", " bit file to load"); struct arg_uint *devOpt = arg_uint0("d", "device", "<device>", " target device (default \"1\")"); struct arg_lit *helpOpt = arg_lit0("h", "help", " print this help and exit\n"); struct arg_end *endOpt = arg_end(20); void* argTable[] = {cblOpt, scanOpt, bitOpt, devOpt, helpOpt, endOpt}; const char *progName = "xilprg"; uint32 exitCode = 0; int numErrors; const char *cable, *bitFile; uint32 devNum; char line[1024]; char configFileName[4097]; // TODO: Fix, somehow. if ( arg_nullcheck(argTable) != 0 ) { fprintf(stderr, "%s: insufficient memory\n", progName); fail(1); } numErrors = arg_parse(argc, argv, argTable); if ( helpOpt->count > 0 ) { printf("Xilinx Programmer 0.6 Copyright (C) 2006-2011 Zoltan Csizmadia & Chris McClelland\n\nUsage: %s", progName); arg_print_syntax(stdout, argTable, "\n"); printf("\nProgram a Xilinx FPGA.\n\n"); arg_print_glossary(stdout, argTable," %-10s %s\n"); fail(0); } if ( numErrors > 0 ) { arg_print_errors(stdout, endOpt, progName); fprintf(stderr, "Try '%s --help' for more information.\n", progName); fail(2); } if ( (scanOpt->count == 0 && bitOpt->count == 0) || (scanOpt->count != 0 && bitOpt->count != 0) ) { fprintf(stderr, "%s: you must specify either -s|--scan or -b|--bitfile, but not both\n", progName); fprintf(stderr, "Try '%s --help' for more information.\n", progName); fail(3); } cable = cblOpt->sval[0]; bitFile = bitOpt->count ? bitOpt->filename[0] : NULL; devNum = devOpt->count ? devOpt->ival[0] : 1; if ( initialize() ) { fprintf(stderr, "%s failed to initialize!\n", progName); fail(4); } if ( getConfigFullPath("xilprg.conf", configFileName, sizeof(configFileName)) ) { fprintf(stderr, "%s failed to determine the location of its config file!\n", progName); fail(5); } if ( load_config_file(configFileName) ) { fprintf(stderr, "%s failed to load its config file from %s!\n", progName, configFileName); fail(6); } try { sprintf(line, "cable %s", cable); process_command_line(line); if ( scanOpt->count ) { process_command_line("detect"); } else { sprintf(line, "program %lu \"%s\"", devNum, bitFile); process_command_line(line); } } catch ( const std::exception &ex ) { fprintf(stderr, "%s failed: %s!\n", progName, ex.what()); fail(7); } cleanup: uninitialize(); arg_freetable(argTable, sizeof(argTable)/sizeof(argTable[0])); return exitCode; }
int main( int argc, char *argv[] ) { /* resulting name for ops file */ char ops_file[MAX_LENGTH] = ""; /* same for fct file */ char fct_file[MAX_LENGTH] = ""; /* for calls to outside programs, eg zchaff. */ char command[MAX_LENGTH]; char command2[MAX_LENGTH]; /* for trying another path */ /* for getting their answer. */ char command3[MAX_LENGTH]; FILE *SATRES; /* sat solver data. */ int sat; float sat_rtime; int nractions = -1; struct tms start, end; RPGlayer *t, *tpp; Bool goalreached; char c; int linecount; /* int time; */ times ( &lstart ); printf("\n\n"); system("rm CNF"); system("rm SATRES"); printf("\n\n"); fflush(stdout); /* command line treatment */ if ( argc == 1 || ( argc == 2 && *++argv[0] == '?' ) ) { ff_usage(); exit( 1 ); } if ( !process_command_line( argc, argv ) ) { ff_usage(); exit( 1 ); } /* make file names */ /* one input name missing */ if ( !gcmd_line.ops_file_name || !gcmd_line.fct_file_name ) { fprintf(stdout, "\nff: two input files needed\n\n"); ff_usage(); exit( 1 ); } /* add path info, complete file names will be stored in * ops_file and fct_file */ sprintf(ops_file, "%s%s", gcmd_line.path, gcmd_line.ops_file_name); sprintf(fct_file, "%s%s", gcmd_line.path, gcmd_line.fct_file_name); /* parse the input files */ /* start parse & instantiation timing */ times( &start ); /* domain file (ops) */ if ( gcmd_line.display_info >= 1 ) { printf("\nff: parsing domain file"); } /* it is important for the pddl language to define the domain before * reading the problem */ load_ops_file( ops_file ); /* problem file (facts) */ if ( gcmd_line.display_info >= 1 ) { printf(" ... done.\nff: parsing problem file"); } sprintf(command3, "python addons/removeconstraints.py %s",fct_file); system(command3); sprintf(command3, "python addons/parseconstraints.py"); system(command3); load_fct_file( fct_file ); if ( gcmd_line.display_info >= 1 ) { printf(" ... done.\n\n"); } /* Load token of mutex2ignore */ if( gcmd_line.mutex2ignore_file_name[0] != '\0' ) load_mutex2ignore_file( gcmd_line.mutex2ignore_file_name ); /* This is needed to get all types. */ build_orig_constant_list(); /* last step of parsing: see if it's an ADL domain! */ if ( !make_adl_domain() ) { printf("\nff: this is not an ADL problem!"); printf("\n can't be handled by this version.\n\n"); exit( 1 ); } /* now instantiate operators; */ /************************** * first do PREPROCESSING * **************************/ /* start by collecting all strings and thereby encoding * the domain in integers. */ encode_domain_in_integers(); /* inertia preprocessing, first step: * - collect inertia information * - split initial state into * - arrays for individual predicates * - arrays for all static relations * - array containing non - static relations */ do_inertia_preprocessing_step_1(); /* normalize all PL1 formulae in domain description: * (goal, preconds and effect conditions) * - simplify formula * - expand quantifiers * - NOTs down */ normalize_all_wffs(); /* translate negative preconds: introduce symmetric new predicate * NOT-p(..) (e.g., not-in(?ob) in briefcaseworld) */ translate_negative_preconds(); /* split domain in easy (disjunction of conjunctive preconds) * and hard (non DNF preconds) part, to apply * different instantiation algorithms */ split_domain(); /*********************************************** * PREPROCESSING FINISHED * * * * NOW MULTIPLY PARAMETERS IN EFFECTIVE MANNER * ***********************************************/ build_easy_action_templates(); build_hard_action_templates(); times( &end ); TIME( gtempl_time ); times( &start ); /* perform reachability analysis in terms of relaxed * fixpoint */ perform_reachability_analysis(); times( &end ); TIME( greach_time ); times( &start ); /* collect the relevant facts and build final domain * and problem representations. */ collect_relevant_facts_and_fluents(); times( &end ); TIME( grelev_time ); /* for num2sat, SKIP LNF AND, WITH THAT, GCONN STRUCTURES!!! * * reason: LNF is not needed for the CNF encodings, and the RPG is * built only once so optimizations are not time critical. * * LNF introduces a huge overhead, and creates many variables * (e.g. n^2 vs n for pre-LNF, in jugs) which would have to be * filtered for the input ones, anyway. * * RPG sets off on these data structures: * extern Action *gactions; * extern int gnum_actions; * extern State ginitial_state; * extern int *glogic_goal; * extern int gnum_logic_goal; * extern Comparator *gnumeric_goal_comp; * extern ExpNode_pointer *gnumeric_goal_lh, *gnumeric_goal_rh; * extern int gnum_numeric_goal; */ /* instead, do some additional pre-processing to collect all different * constraints, and all different conjunctions psi of constraints. * needed to get a natural implementation of collecting value tuples * for all such constructs. */ collect_relevant_constraints_and_psis(); /* that is done. let's go. * * NOTE that keeping track of the RPG layers in here * isn't just a coincidence. It's made so that we can use these same * functions to build another RPG if we want to, eg. one that's * modified to greedily estimate the variable domains instead of * enumerating them completely. */ /* separating CNF and Hybrid CNF methods completely, * though they got a large overlap. * reason: looks nicer, and mayb at some point * we're gonna use a different RPG for hybrid. */ /* just to avoid "might be used uninitialized" message */ tpp = NULL; if ( gcmd_line.CNFencoding == 0 || gcmd_line.CNFencoding == 1 ) { /* propositional CNF! */ times( &start ); gRPG = new_RPGlayer(); t = RPG_initialize(gRPG); times( &end ); TIME( gRPG_time ); TIMECHECK; if ( gcmd_line.display_info ) { RPG_PV_statistics(t); fflush(stdout); } times( &start ); gCNF = new_CNF(); gCNFend = gCNF; gCNFnumvars = 0; gCNFnumclauses = 0; CNF_initialize(t, &gCNFend, &gCNFnumvars, &gCNFnumclauses); times( &end ); TIME( gCNF_time ); TIMECHECK; if ( gcmd_line.display_info ) { CNF_statistics(t, gCNF, gCNFnumvars, gCNFnumclauses); fflush(stdout); } /* ########################################################################################## ########################################################################################## ########################################################################################## ########################################################################################## ########################################################################################## ########################################################################################## */ system("rm auxiliar.txt"); goalreached = FALSE; while ( TRUE ) { times( &start ); tpp = RPG_extend(t); times( &end ); TIME( gRPG_time ); TIMECHECK; if ( gcmd_line.display_info ) { RPG_AE_statistics(t); RPG_PV_statistics(tpp); fflush(stdout); } times( &start ); CNF_extend(t, &gCNFend, &gCNFnumvars, &gCNFnumclauses); times( &end ); TIME( gCNF_time ); TIMECHECK; if ( gcmd_line.display_info ) { CNF_statistics(tpp, gCNF, gCNFnumvars, gCNFnumclauses); fflush(stdout); } if ( !goalreached && !RPG_satisfiesgoal(tpp) ) { t = tpp; continue; } if ( !goalreached ) { if ( gcmd_line.display_info ) { printf("\nGoal reached at %d!", tpp->t); fflush(stdout); } goalreached = TRUE; } CNF_get_goal(tpp, &gCNFend, &gCNFnumclauses); CNF_output(gCNF, gCNFnumvars, gCNFnumclauses, tpp->t); TIMECHECK; CNF_print_act_table(gRPG, "action-table"); sprintf(command, "python %s/addons/addconstraints.py CNF action-table", here); system(command); if ( gcmd_line.debug && gcmd_line.dCNF ) { CNF_print(gRPG, gCNF, gCNFnumvars, gCNFnumclauses); printf("\n\n"); /* exit( 0 ); */ } if ( gcmd_line.CNFsolver == 0 ) { sprintf(command, "%s/solvers/minisat/MiniSat_v1.14/minisat CNF", num2satpath); sprintf(command2, "%s/solvers/minisat/MiniSat_v1.14/minisat CNF", here); } if ( gcmd_line.CNFsolver == 1 ) { sprintf(command, "%s/solvers/zchaff/zchaff CNF", num2satpath); sprintf(command2, "%s/solvers/zchaff/zchaff CNF", here); } if ( gcmd_line.CNFsolver == 2 ) { /* OJO: que no hagan falta dos comandos: -m y -s 2 */ /* minisat */ CNF_print_act_table(gRPG, "action-table"); sprintf(command, "%s/solvers/minisat+mutex.py CNF action-table %s m", num2satpath, gcmd_line.mutex2ignore_file_name ); sprintf(command2, "%s/solvers/minisat+mutex.py CNF action-table %s m", here, gcmd_line.mutex2ignore_file_name ); } if ( gcmd_line.CNFsolver == 3 ) { /* zchaff */ CNF_print_act_table(gRPG, "action-table"); sprintf(command, "%s/solvers/minisat+mutex.py CNF action-table %s z", num2satpath, gcmd_line.mutex2ignore_file_name ); sprintf(command2, "%s/solvers/minisat+mutex.py CNF action-table %s z", here, gcmd_line.mutex2ignore_file_name ); } if ( gcmd_line.display_info ) { printf("\nInvoking SAT solver, command:"); printf("\n%s", command); printf("\n"); fflush(stdout); } if( system( command ) ) { printf("failed with path %s, trying with %s\n", num2satpath, here); printf("\nInvoking SAT solver, command:"); printf("\n%s", command2); printf("\n"); fflush(stdout); system( command2 ); } if ( (SATRES = fopen( "SATRES", "r" )) == NULL ) { printf("\nSATRES file not present. Failure!\n\n"); exit( 0 ); } fscanf(SATRES, "%d %f\n", &sat, &sat_rtime); gSAT_time += sat_rtime; TIMECHECK; if ( sat ) { break; } fclose(SATRES); /* system("rm CNF"); */ /* system("rm SATRES"); */ CNF_retract_goal(tpp, &gCNFend, &gCNFnumclauses); t = tpp; } /* endwhile main planning loop */ if ( gcmd_line.display_info ) { nractions = CNF_output_plan(SATRES, gRPG, gCNFnumvars); fflush(stdout); } fclose(SATRES); /* system("rm CNF"); */ /* system("rm SATRES"); */ } /* endif propositional CNF requested */ if ( gcmd_line.CNFencoding == 2 || gcmd_line.CNFencoding == 3 ) { /* Hybrid CNF! */ times( &start ); gRPG = new_RPGlayer(); t = RPG_initialize(gRPG); times( &end ); TIME( gRPG_time ); TIMECHECK; if ( gcmd_line.display_info ) { RPG_PV_statistics(t); fflush(stdout); } times( &start ); gHCNF = new_HCNF(); gHCNFend = gHCNF; gHCNFnumvars = 0; gHCNFnumclauses = 0; HCNF_initialize(t, &gHCNFend, &gHCNFnumvars, &gHCNFnumclauses); times( &end ); TIME( gCNF_time ); TIMECHECK; if ( gcmd_line.display_info ) { HCNF_statistics(t, gHCNF, gHCNFnumvars, gHCNFnumclauses); fflush(stdout); } goalreached = FALSE; while ( TRUE ) { times( &start ); tpp = RPG_extend(t); times( &end ); TIME( gRPG_time ); TIMECHECK; if ( gcmd_line.display_info ) { RPG_AE_statistics(t); RPG_PV_statistics(tpp); fflush(stdout); } times( &start ); HCNF_extend(t, &gHCNFend, &gHCNFnumvars, &gHCNFnumclauses); times( &end ); TIME( gCNF_time ); TIMECHECK; if ( gcmd_line.display_info ) { HCNF_statistics(tpp, gHCNF, gHCNFnumvars, gHCNFnumclauses); fflush(stdout); } if ( !goalreached && !RPG_satisfiesgoal(tpp) ) { t = tpp; continue; } if ( !goalreached ) { if ( gcmd_line.display_info ) { printf("\nGoal reached at %d!", tpp->t); fflush(stdout); } goalreached = TRUE; } HCNF_get_goal(tpp, &gHCNFend, &gHCNFnumclauses); HCNF_output(gRPG, gHCNF, gHCNFnumvars, gHCNFnumclauses, tpp->t); TIMECHECK; if ( gcmd_line.debug && gcmd_line.dHCNF ) { HCNF_print(gRPG, gHCNF, gHCNFnumvars, gHCNFnumclauses); printf("\n\n"); exit( 0 ); } sprintf(command, "%s/solvers/mathsat/mathsat-3.3.1/mathsat CNF > SATRES", num2satpath); sprintf(command2, "%s/solvers/mathsat/mathsat-3.3.1/mathsat CNF > SATRES", here); if ( gcmd_line.display_info ) { printf("\nInvoking MATHSAT solver, command:"); printf("\n%s", command); printf("\n"); fflush(stdout); } if( system( command ) ) { printf("failed with path %s, trying with %s\n", num2satpath, here); system( command2 ); } if ( (SATRES = fopen( "SATRES", "r" )) == NULL ) { printf("\nSATRES file not present. Failure!\n\n"); exit( 0 ); } /* read in MATHSAT's output. looks like: * Result = 1 * TSTP Exit Status: SAT * * # ------------------------------------------------- * # User time : 0.020 s * # System time : 0.019 s * # Total time : 0.039 s */ fscanf(SATRES, "Result = %d\n", &sat); linecount = 0; while ( TRUE ) { c = fgetc(SATRES); if ( c == '\n') { linecount++; if ( linecount == 5 ) { break; } } } fscanf(SATRES, "# Total time : %f s\n", &sat_rtime); gSAT_time += sat_rtime; TIMECHECK; if ( sat ) { if ( gcmd_line.display_info ) { printf("\nSAT! %f sec. Plan found.", sat_rtime); fflush(stdout); } break; } else { if ( gcmd_line.display_info ) { printf("\nUNSAT! %f sec. Iterate.", sat_rtime); fflush(stdout); } } fclose(SATRES); system("rm CNF"); system("rm SATRES"); HCNF_retract_goal(tpp, &gHCNFend, &gHCNFnumclauses); t = tpp; } /* endwhile main planning loop */ fclose(SATRES); system("rm CNF"); system("rm SATRES"); } /* endif hybrid CNF requested */ if ( !tpp ) { printf("\ntpp NULL at plan info output?\n\n"); exit( 1 ); } if ( gcmd_line.display_info ) { output_planner_info(gRPG, nractions); } sprintf(command3, "python addons/timemachine.py %s",fct_file); system(command3); printf("\n\n"); exit( 0 ); }
int main (int argc, char* argv[]) { Teuchos::GlobalMPISession mpisess(&argc, &argv); bool success = true; Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); try { Teuchos::Time timer("total"); timer.start(); Tpetra::DefaultPlatform::DefaultPlatformType& platform = Tpetra::DefaultPlatform::getDefaultPlatform(); Teuchos::RCP<const Teuchos::Comm<int> > comm = platform.getComm(); typedef double Scalar; typedef Tpetra::Map<>::local_ordinal_type LO; typedef Tpetra::Map<>::global_ordinal_type GO; typedef Tpetra::DefaultPlatform::DefaultPlatformType::NodeType Node; typedef Tpetra::MultiVector<Scalar,LO,GO,Node> TMV; typedef Tpetra::Operator<Scalar,LO,GO,Node> TOP; typedef Belos::LinearProblem<Scalar,TMV,TOP> BLinProb; typedef Belos::SolverManager<Scalar,TMV,TOP> BSolverMgr; //Just get one parameter from the command-line: the name of an xml file //to get parameters from. std::string xml_file("calore1_mm.xml"); { bool printedHelp = false; process_command_line (printedHelp, xml_file, argc, argv); if (printedHelp) { return EXIT_SUCCESS; } } //Read the contents of the xml file into a ParameterList. That parameter list //should specify a matrix-file and optionally which Belos solver to use, and //which Ifpack2 preconditioner to use, etc. If there are sublists of parameters //for Belos and Ifpack2, those will be passed to the respective destinations //from within the build_problem and build_solver functions. *out << "Every proc reading parameters from xml_file: " << xml_file << std::endl; Teuchos::ParameterList test_params = Teuchos::ParameterXMLFileReader(xml_file).getParameters(); //The build_problem function is located in build_problem.hpp. //Note that build_problem calls build_precond and sets a preconditioner on the //linear-problem, if a preconditioner is specified. Teuchos::RCP<BLinProb> problem = build_problem<Scalar,LO,GO,Node>(test_params, comm); //The build_solver function is located in build_solver.hpp: Teuchos::RCP<BSolverMgr> solver = build_solver<Scalar,TMV,TOP>(test_params, problem); Belos::ReturnType ret = solver->solve(); *out << "Converged in " << solver->getNumIters() << " iterations." << std::endl; Teuchos::RCP<TMV> R = Teuchos::rcp(new TMV(*problem->getRHS())); problem->computeCurrResVec(&*R, &*problem->getLHS(), &*problem->getRHS()); Teuchos::Array<Teuchos::ScalarTraits<Scalar>::magnitudeType> norms(R->getNumVectors()); R->norm2(norms); if (norms.size() < 1) { throw std::runtime_error("ERROR: norms.size()==0 indicates R->getNumVectors()==0."); } *out << "2-Norm of 0th residual vec: " << norms[0] << std::endl; //If the xml file specified a number of iterations to expect, then we will //use that as a test pass/fail criteria. if (test_params.isParameter("expectNumIters")) { int expected_iters = 0; Ifpack2::getParameter(test_params, "expectNumIters", expected_iters); int actual_iters = solver->getNumIters(); if (ret == Belos::Converged && actual_iters <= expected_iters && norms[0] < 1.e-7) { } else { success = false; *out << "Actual iters("<<actual_iters <<") > expected number of iterations (" <<expected_iters<<"), or resid-norm(" << norms[0] << ") >= 1.e-7"<<std::endl; } } timer.stop(); *out << "proc 0 total program time: " << timer.totalElapsedTime() << std::endl; } TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success) if (success) { *out << "End Result: TEST PASSED\n"; } else { *out << "End Result: TEST FAILED\n"; } return ( success ? 0 : 1 ); }
int main( int argc, char *argv[] ) { /* resulting name for ops file */ char ops_file[MAX_LENGTH] = ""; /* same for fct file */ char fct_file[MAX_LENGTH] = ""; struct tms start, end; State current_start, current_end; int i, j; Bool found_plan; times ( &lstart ); /* command line treatment */ if ( argc == 1 || ( argc == 2 && *++argv[0] == '?' ) ) { ff_usage(); exit( 1 ); } if ( !process_command_line( argc, argv ) ) { ff_usage(); exit( 1 ); } /* make file names */ /* one input name missing */ if ( !gcmd_line.ops_file_name || !gcmd_line.fct_file_name ) { fprintf(stdout, "\nff: two input files needed\n\n"); ff_usage(); exit( 1 ); } /* add path info, complete file names will be stored in * ops_file and fct_file */ sprintf(ops_file, "%s%s", gcmd_line.path, gcmd_line.ops_file_name); sprintf(fct_file, "%s%s", gcmd_line.path, gcmd_line.fct_file_name); /* parse the input files */ /* start parse & instantiation timing */ times( &start ); /* domain file (ops) */ if ( gcmd_line.display_info >= 1 ) { printf("\nff: parsing domain file"); } /* it is important for the pddl language to define the domain before * reading the problem */ load_ops_file( ops_file ); /* problem file (facts) */ if ( gcmd_line.display_info >= 1 ) { printf(" ... done.\nff: parsing problem file"); } load_fct_file( fct_file ); if ( gcmd_line.display_info >= 1 ) { printf(" ... done.\n\n"); } /* This is needed to get all types. */ build_orig_constant_list(); /* last step of parsing: see if it's an ADL domain! */ if ( !make_adl_domain() ) { printf("\nff: this is not an ADL problem!"); printf("\n can't be handled by this version.\n\n"); exit( 1 ); } /* now instantiate operators; */ /************************** * first do PREPROCESSING * **************************/ /* start by collecting all strings and thereby encoding * the domain in integers. */ encode_domain_in_integers(); /* inertia preprocessing, first step: * - collect inertia information * - split initial state into * _ arrays for individual predicates * - arrays for all static relations * - array containing non - static relations */ do_inertia_preprocessing_step_1(); /* normalize all PL1 formulae in domain description: * (goal, preconds and effect conditions) * - simplify formula * - expand quantifiers * - NOTs down */ normalize_all_wffs(); /* translate negative preconds: introduce symmetric new predicate * NOT-p(..) (e.g., not-in(?ob) in briefcaseworld) */ translate_negative_preconds(); /* split domain in easy (disjunction of conjunctive preconds) * and hard (non DNF preconds) part, to apply * different instantiation algorithms */ split_domain(); /*********************************************** * PREPROCESSING FINISHED * * * * NOW MULTIPLY PARAMETERS IN EFFECTIVE MANNER * ***********************************************/ build_easy_action_templates(); build_hard_action_templates(); times( &end ); TIME( gtempl_time ); times( &start ); /* perform reachability analysis in terms of relaxed * fixpoint */ perform_reachability_analysis(); times( &end ); TIME( greach_time ); times( &start ); /* collect the relevant facts and build final domain * and problem representations. */ collect_relevant_facts(); times( &end ); TIME( grelev_time ); times( &start ); /* now build globally accessable connectivity graph */ build_connectivity_graph(); times( &end ); TIME( gconn_time ); /*********************************************************** * we are finally through with preprocessing and can worry * * bout finding a plan instead. * ***********************************************************/ times( &start ); /* another quick preprocess: approximate goal orderings and split * goal set into sequence of smaller sets, the goal agenda */ compute_goal_agenda(); /* make space in plan states info, and relax */ for ( i = 0; i < MAX_PLAN_LENGTH + 1; i++ ) { make_state( &(gplan_states[i]), gnum_ft_conn ); gplan_states[i].max_F = gnum_ft_conn; } make_state( ¤t_start, gnum_ft_conn ); current_start.max_F = gnum_ft_conn; make_state( ¤t_end, gnum_ft_conn ); current_end.max_F = gnum_ft_conn; initialize_relax(); source_to_dest( &(gplan_states[0]), &ginitial_state ); source_to_dest( ¤t_start, &ginitial_state ); source_to_dest( ¤t_end, &(ggoal_agenda[0]) ); for ( i = 0; i < gnum_goal_agenda; i++ ) { if ( !do_enforced_hill_climbing( ¤t_start, ¤t_end ) ) { break; } source_to_dest( ¤t_start, &(gplan_states[gnum_plan_ops]) ); if ( i < gnum_goal_agenda - 1 ) { for ( j = 0; j < ggoal_agenda[i+1].num_F; j++ ) { current_end.F[current_end.num_F++] = ggoal_agenda[i+1].F[j]; } } } found_plan = ( i == gnum_goal_agenda ) ? TRUE : FALSE; if ( !found_plan ) { printf("\n\nEnforced Hill-climbing failed !"); printf("\nswitching to Best-first Search now.\n"); found_plan = do_best_first_search(); } times( &end ); TIME( gsearch_time ); if ( found_plan ) { print_plan(); } output_planner_info(); printf("\n\n"); exit( 0 ); }
int main (int argc, char *argv[]) { struct parameters params; lists_t_strs *deferred_overrides; lists_t_strs *args; #ifdef HAVE_UNAME_SYSCALL int rc; struct utsname uts; #endif #ifdef PACKAGE_REVISION logit ("This is Music On Console (revision %s)", PACKAGE_REVISION); #else logit ("This is Music On Console (version %s)", PACKAGE_VERSION); #endif #ifdef CONFIGURATION logit ("Configured:%s", CONFIGURATION); #endif #ifdef HAVE_UNAME_SYSCALL rc = uname (&uts); if (rc == 0) logit ("Running on: %s %s %s", uts.sysname, uts.release, uts.machine); #endif log_command_line (argc, argv); files_init (); if (get_home () == NULL) fatal ("Could not determine user's home directory!"); memset (¶ms, 0, sizeof(params)); options_init (); deferred_overrides = lists_strs_new (4); /* set locale according to the environment variables */ if (!setlocale(LC_ALL, "")) logit ("Could not set locale!"); args = process_command_line (argc, argv, ¶ms, deferred_overrides); if (params.dont_run_iface && params.only_server) fatal ("-c, -a and -p options can't be used with --server!"); if (!params.config_file) params.config_file = xstrdup (create_file_name ("config")); options_parse (params.config_file); if (params.config_file) free (params.config_file); params.config_file = NULL; process_deferred_overrides (deferred_overrides); lists_strs_free (deferred_overrides); deferred_overrides = NULL; check_moc_dir (); io_init (); rcc_init (); decoder_init (params.debug); srand (time(NULL)); if (!params.only_server && params.dont_run_iface) server_command (¶ms, args); else start_moc (¶ms, args); lists_strs_free (args); options_free (); decoder_cleanup (); io_cleanup (); rcc_cleanup (); files_cleanup (); compat_cleanup (); exit (EXIT_SUCCESS); }
int main(int argc, char **argv) { TCHAR *fn, *cwd; state *s; int count, status = STATUS_OK; /* Because the main() function can handle wchar_t arguments on Win32, we need a way to reference those values. Thus we make a duplciate of the argc and argv values. */ #ifndef __GLIBC__ __progname = basename(argv[0]); #endif s = (state *)malloc(sizeof(state)); if (NULL == s) { // We can't use fatal_error because it requires a valid state print_status("%s: Unable to allocate state variable", __progname); return STATUS_INTERNAL_ERROR; } if (initialize_state(s)) { print_status("%s: Unable to initialize state variable", __progname); return STATUS_INTERNAL_ERROR; } if (process_command_line(s,argc,argv)) { print_status("%s: Unable to process command line arguments", __progname); return STATUS_INTERNAL_ERROR; } #ifdef _WIN32 if (prepare_windows_command_line(s)) fatal_error(s,"%s: Unable to process command line arguments", __progname); #else s->argc = argc; s->argv = argv; #endif /* Anything left on the command line at this point is a file or directory we're supposed to process. If there's nothing specified, we should tackle standard input */ if (optind == argc) hash_stdin(s); else { MD5DEEP_ALLOC(TCHAR,fn,PATH_MAX); MD5DEEP_ALLOC(TCHAR,cwd,PATH_MAX); cwd = _tgetcwd(cwd,PATH_MAX); if (NULL == cwd) fatal_error(s,"%s: %s", __progname, strerror(errno)); count = optind; while (count < s->argc) { generate_filename(s,fn,cwd,s->argv[count]); #ifdef _WIN32 status = process_win32(s,fn); #else status = process_normal(s,fn); #endif // if (status != STATUS_OK) // return status; ++count; } free(fn); free(cwd); } /* We only have to worry about checking for unused hashes if one of the matching modes was enabled. We let the display_not_matched function determine if it needs to display anything. The function also sets our return values in terms of inputs not being matched or known hashes not being used */ if ((s->mode & mode_match) || (s->mode & mode_match_neg)) s->return_value = finalize_matching(s); return s->return_value; }
int main(int argc, char **argv) { int status; struct sched_param thread_param; int i; int retval = FAILURE; int core; int nthreads; /* Make sure we see all message, even those on stdout. */ setvbuf(stdout, NULL, _IONBF, 0); /* get the number of processors */ num_processors = sysconf(_SC_NPROCESSORS_ONLN); /* calculate the number of inversion groups to run */ ngroups = num_processors == 1 ? 1 : num_processors - 1; /* process command line arguments */ process_command_line(argc, argv); /* lock memory */ if (lockall) if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) { error("mlockall failed\n"); return FAILURE; } /* boost main's priority (so we keep running) :) */ prio_min = sched_get_priority_min(policy); thread_param.sched_priority = MAIN_PRIO(); status = pthread_setschedparam(pthread_self(), policy, &thread_param); if (status) { error("main: boosting to max priority: 0x%x\n", status); return FAILURE; } /* block unwanted signals */ block_signals(); /* allocate our groups array */ groups = calloc(ngroups, sizeof(struct group_parameters)); if (groups == NULL) { error("main: failed to allocate %d groups\n", ngroups); return FAILURE; } /* set up CPU affinity masks */ if (set_cpu_affinity(&test_cpu_mask, &admin_cpu_mask)) return FAILURE; nthreads = ngroups * NUM_TEST_THREADS + NUM_ADMIN_THREADS; /* set up our ready barrier */ if (barrier_init(&all_threads_ready, NULL, nthreads, "all_threads_ready")) return FAILURE; /* set up our done barrier */ if (barrier_init(&all_threads_done, NULL, nthreads, "all_threads_done")) return FAILURE; /* create the groups */ info("Creating %d test groups\n", ngroups); for (core = 0; core < num_processors; core++) if (CPU_ISSET(core, &test_cpu_mask)) break; for (i = 0; i < ngroups; i++) { groups[i].id = i; groups[i].cpu = core++; if (core >= num_processors) core = 0; if (create_group(&groups[i]) != SUCCESS) return FAILURE; } /* prompt if requested */ if (prompt) { printf("Press return to start test: "); getchar(); } /* report */ banner(); start = time(NULL); /* turn loose the threads */ info("Releasing all threads\n"); status = pthread_barrier_wait(&all_threads_ready); if (status && status != PTHREAD_BARRIER_SERIAL_THREAD) { error("main: pthread_barrier_wait(all_threads_ready): 0x%x\n", status); set_shutdown_flag(); return FAILURE; } reporter(NULL); if (!quiet) { fputs(DOWN_ONE, stdout); printf("Stopping test\n"); } set_shutdown_flag(); /* wait for all threads to notice the shutdown flag */ if (have_errors == 0 && interrupted == 0) { info("waiting for all threads to complete\n"); status = pthread_barrier_wait(&all_threads_done); if (status && status != PTHREAD_BARRIER_SERIAL_THREAD) { error ("main: pthread_barrier_wait(all_threads_ready): 0x%x\n", status); return FAILURE; } info("All threads terminated!\n"); retval = SUCCESS; } else kill(0, SIGTERM); finish = time(NULL); summary(); if (lockall) munlockall(); exit(retval); }
main ( int argc, char **argv) { time_t r; int a, b, c, d, e; char time_string[100]; Parameter *PARAM; PARAM=declare_parameter(); get_ref_time (PARAM); argv=break_list ( argv, &argc, "=:;,"); process_command_line ( argc,argv, PARAM); read_command_line ( argc,argv, PARAM); fprintf ( stderr, "\nFINISHED READING PARAMETERS"); declare_dos_2 ( PARAM); INTERACTIVE_PROMPT_SET=(PARAM->BGA)->INTERACTIVE; if ( (PARAM->BGA)->OUTPUT_SCREEN==0) { (PARAM->std0)=stderr; (PARAM->std1)=(PARAM->std2)=fopen ( "/dev/null", "w"); } else if ( (PARAM->BGA)->OUTPUT_SCREEN==1) { (PARAM->std0)=(PARAM->std1)=stderr; (PARAM->std2)=fopen ( "/dev/null", "w"); } else if ((PARAM->BGA)->OUTPUT_SCREEN==2) { (PARAM->std0)=(PARAM->std1)=(PARAM->std2)=stderr; } time(&r); sprintf ( time_string, "%d", (int) r); PARAM->START=r; if ( (PARAM->BGA)->RANDOM_SEED >0) {addrandinit ( (unsigned long) (PARAM->BGA)->RANDOM_SEED); if ( ((PARAM->BGA)->OUTPUT_SCREEN)==1)printf ( "\nRANDOM_SEED= %d",(PARAM->BGA)->RANDOM_SEED); } else if ( (PARAM->BGA)->RANDOM_SEED== -1) { b=0; for ( a= strlen ( time_string)-1; a>=strlen ( time_string)-3; a--) time_string[b++]= time_string[a]; time_string[b]='\0'; (PARAM->BGA)->RANDOM_SEED= atoi ( time_string); addrandinit ( (unsigned long) (PARAM->BGA)->RANDOM_SEED); fprintf ((PARAM->std1), "\nRANDOM_SEED(undet)= %d",(PARAM->BGA)->RANDOM_SEED); } process_param (PARAM); input_data (PARAM); main_do_aln (PARAM); }
void process_environment_variable (char *name) { int argc; char *argv[128], *env, *buffer, *ptr; if (name) { env = getenv (name); if (env) { // // copy enviroment variable // buffer = safe_malloc (strlen (env) + 1); strcpy (buffer, env); ptr = buffer; // // create standard argc and argv parameters // argc = 0; argv[argc++] = environment_variable; argv[argc++] = ptr; while (*ptr) { // // skip white space // while (*ptr) { if (*ptr == ' ') { ptr++; } else { break; } } if (*ptr) { argv[argc++] = ptr; // // skip argument // while (*ptr) { if (!(*ptr == ' ')) { ptr++; } else { break; } } if (*ptr) { *ptr++ = 0; } } } process_command_line (argc, argv); safe_free (buffer); } } }
/************************************************************************* * Entry point for ama *************************************************************************/ int main(int argc, char **argv) { AMA_OPTIONS_T options; ARRAYLST_T *motifs; clock_t c0, c1; // measuring cpu_time MOTIF_AND_PSSM_T *combo; CISML_T *cisml; PATTERN_T** patterns; PATTERN_T *pattern; FILE *fasta_file, *text_output, *cisml_output; int i, seq_loading_num, seq_counter, unique_seqs, seq_len, scan_len, x1, x2, y1, y2; char *seq_name, *path; bool need_postprocessing, created; SEQ_T *sequence; RBTREE_T *seq_ids; RBNODE_T *seq_node; double *logcumback; ALPH_T *alph; // process the command process_command_line(argc, argv, &options); // load DNA motifs motifs = load_motifs(&options); // get the alphabet if (arraylst_size(motifs) > 0) { combo = (MOTIF_AND_PSSM_T*)arraylst_get(0, motifs); alph = alph_hold(get_motif_alph(combo->motif)); } else { alph = alph_dna(); } // pick columns for GC operations x1 = -1; x2 = -1; y1 = -1; y2 = -1; if (alph_size_core(alph) == 4 && alph_size_pairs(alph) == 2) { x1 = 0; // A x2 = alph_complement(alph, x1); // T y1 = (x2 == 1 ? 2 : 1); // C y2 = alph_complement(alph, y1); // G assert(x1 != x2 && y1 != y2 && x1 != y1 && x2 != y2 && x1 != y2 && x2 != y1); } // record starting time c0 = clock(); // Create cisml data structure for recording results cisml = allocate_cisml(PROGRAM_NAME, options.command_line, options.motif_filename, options.fasta_filename); set_cisml_background_file(cisml, options.bg_filename); // make a CISML pattern to hold scores for each motif for (i = 0; i < arraylst_size(motifs); i++) { combo = (MOTIF_AND_PSSM_T*)arraylst_get(i, motifs); add_cisml_pattern(cisml, allocate_pattern(get_motif_id(combo->motif), "")); } // Open the FASTA file for reading. fasta_file = NULL; if (!open_file(options.fasta_filename, "r", false, "FASTA", "sequences", &fasta_file)) { die("Couldn't open the file %s.\n", options.fasta_filename); } if (verbosity >= NORMAL_VERBOSE) { if (options.last == 0) { fprintf(stderr, "Using entire sequence\n"); } else { fprintf(stderr, "Limiting sequence to last %d positions.\n", options.last); } } // // Read in all sequences and score with all motifs // seq_loading_num = 0; // keeps track on the number of sequences read in total seq_counter = 0; // holds the index to the seq in the pattern unique_seqs = 0; // keeps track on the number of unique sequences need_postprocessing = false; sequence = NULL; logcumback = NULL; seq_ids = rbtree_create(rbtree_strcasecmp,rbtree_strcpy,free,rbtree_intcpy,free); while (read_one_fasta(alph, fasta_file, options.max_seq_length, &sequence)) { ++seq_loading_num; seq_name = get_seq_name(sequence); seq_len = get_seq_length(sequence); scan_len = (options.last != 0 ? options.last : seq_len); // red-black trees are only required if duplicates should be combined if (options.combine_duplicates){ //lookup seq id and create new entry if required, return sequence index seq_node = rbtree_lookup(seq_ids, get_seq_name(sequence), true, &created); if (created) { // assign it a loading number rbtree_set(seq_ids, seq_node, &unique_seqs); seq_counter = unique_seqs; ++unique_seqs; } else { seq_counter = *((int*)rbnode_get(seq_node)); } } // // Set up sequence-dependent background model and compute // log cumulative probability of sequence. // This needs the sequence in raw format. // if (options.sdbg_order >= 0) logcumback = log_cumulative_background(alph, options.sdbg_order, sequence); // Index the sequence, throwing away the raw format and ambiguous characters index_sequence(sequence, alph, SEQ_NOAMBIG); // Get the GC content of the sequence if binning p-values by GC // and store it in the sequence object. if (options.num_gc_bins > 1) { ARRAY_T *freqs = get_sequence_freqs(sequence, alph); set_total_gc_sequence(sequence, get_array_item(y1, freqs) + get_array_item(y2, freqs)); // f(C) + f(G) free_array(freqs); // clean up } else { set_total_gc_sequence(sequence, -1); // flag ignore } // Scan with motifs. for (i = 0; i < arraylst_size(motifs); i++) { pattern = get_cisml_patterns(cisml)[i]; combo = (MOTIF_AND_PSSM_T*)arraylst_get(i, motifs); if (verbosity >= HIGHER_VERBOSE) { fprintf(stderr, "Scanning %s sequence with length %d " "abbreviated to %d with motif %s with length %d.\n", seq_name, seq_len, scan_len, get_motif_id(combo->motif), get_motif_length(combo->motif)); } SCANNED_SEQUENCE_T* scanned_seq = NULL; if (!options.combine_duplicates || get_pattern_num_scanned_sequences(pattern) <= seq_counter) { // Create a scanned_sequence record and save it in the pattern. scanned_seq = allocate_scanned_sequence(seq_name, seq_name, pattern); set_scanned_sequence_length(scanned_seq, scan_len); } else { // get existing sequence record scanned_seq = get_pattern_scanned_sequences(pattern)[seq_counter]; set_scanned_sequence_length(scanned_seq, max(scan_len, get_scanned_sequence_length(scanned_seq))); } // check if scanned component of sequence has sufficient length for the motif if (scan_len < get_motif_length(combo->motif)) { // set score to zero and p-value to 1 if not set yet if(!has_scanned_sequence_score(scanned_seq)){ set_scanned_sequence_score(scanned_seq, 0.0); } if(options.pvalues && !has_scanned_sequence_pvalue(scanned_seq)){ set_scanned_sequence_pvalue(scanned_seq, 1.0); } add_scanned_sequence_scanned_position(scanned_seq); if (get_scanned_sequence_num_scanned_positions(scanned_seq) > 0L) { need_postprocessing = true; } if (verbosity >= HIGH_VERBOSE) { fprintf(stderr, "%s too short for motif %s. Score set to 0.\n", seq_name, get_motif_id(combo->motif)); } } else { // scan the sequence using average/maximum motif affinity ama_sequence_scan(alph, sequence, logcumback, combo->pssm_pair, options.scoring, options.pvalues, options.last, scanned_seq, &need_postprocessing); } } // All motifs scanned free_seq(sequence); if (options.sdbg_order >= 0) myfree(logcumback); } // read sequences fclose(fasta_file); if (verbosity >= HIGH_VERBOSE) fprintf(stderr, "(%d) sequences read in.\n", seq_loading_num); if (verbosity >= NORMAL_VERBOSE) fprintf(stderr, "Finished \n"); // if any sequence identifier was multiple times in the sequence set then // postprocess of the data is required if (need_postprocessing || options.normalize_scores) { post_process(cisml, motifs, options.normalize_scores); } // output results if (options.output_format == DIRECTORY_FORMAT) { if (create_output_directory(options.out_dir, options.clobber, verbosity > QUIET_VERBOSE)) { // only warn in higher verbose modes fprintf(stderr, "failed to create output directory `%s' or already exists\n", options.out_dir); exit(1); } path = make_path_to_file(options.out_dir, text_filename); //FIXME check for errors: MEME doesn't either and we at least know we have a good directory text_output = fopen(path, "w"); free(path); path = make_path_to_file(options.out_dir, cisml_filename); //FIXME check for errors cisml_output = fopen(path, "w"); free(path); print_cisml(cisml_output, cisml, true, NULL, false); print_score(cisml, text_output); fclose(cisml_output); fclose(text_output); } else if (options.output_format == GFF_FORMAT) { print_score(cisml, stdout); } else if (options.output_format == CISML_FORMAT) { print_cisml(stdout, cisml, true, NULL, false); } else { die("Output format invalid!\n"); } // // Clean up. // rbtree_destroy(seq_ids); arraylst_destroy(motif_and_pssm_destroy, motifs); free_cisml(cisml); rbtree_destroy(options.selected_motifs); alph_release(alph); // measure time if (verbosity >= NORMAL_VERBOSE) { // starting time c1 = clock(); fprintf(stderr, "cycles (CPU); %ld cycles\n", (long) c1); fprintf(stderr, "elapsed CPU time: %f seconds\n", (float) (c1-c0) / CLOCKS_PER_SEC); } return 0; }
int main(int argc, char *argv[]) { int e = 0; build_image_context context; memset(&context, 0, sizeof(build_image_context)); /* Process command line arguments. */ if (process_command_line(argc, argv, &context) != 0) return -EINVAL; assert(g_bct_parse_interf != NULL); if (help_only) return 1; g_bct_parse_interf->get_value(token_bct_size, &context.bct_size, context.bct); e = init_context(&context); if (e != 0) { printf("context initialization failed. Aborting.\n"); return e; } if (enable_debug) { /* Debugging information... */ printf("bct size: %d\n", e == 0 ? context.bct_size : -1); } /* Open the raw output file. */ context.raw_file = fopen(context.image_filename, "w+"); if (context.raw_file == NULL) { printf("Error opening raw file %s.\n", context.image_filename); goto fail; } /* first, if we aren't generating the bct, read in config file */ if (context.generate_bct == 0) { process_config_file(&context, 1); } /* Generate the new bct file */ else { /* Initialize the bct memory */ init_bct(&context); /* Parse & process the contents of the config file. */ process_config_file(&context, 0); /* Update the BCT */ begin_update(&context); /* Signing the bct. */ e = sign_bct(&context, context.bct); if (e != 0) printf("Signing BCT failed, error: %d.\n", e); fwrite(context.bct, 1, context.bct_size, context.raw_file); printf("New BCT file %s has been successfully generated!\n", context.image_filename); goto fail; } /* Peform final signing & encryption of bct. */ e = sign_bct(&context, context.bct); if (e != 0) { printf("Signing BCT failed, error: %d.\n", e); goto fail; } /* Write the image file. */ /* The image hasn't been written yet. */ if (write_image_file(&context) != 0) printf("Error writing image file.\n"); else printf("Image file %s has been successfully generated!\n", context.image_filename); fail: /* Close the file(s). */ if (context.raw_file) fclose(context.raw_file); /* Clean up memory. */ cleanup_context(&context); if (g_bct_parse_interf) { free(g_bct_parse_interf); g_bct_parse_interf = NULL; } return e; }
int main(int argc, char* argv[]) { MCAST_OPTIONS_T options; process_command_line(argc, argv, &options); // // Create output directory // if (create_output_directory( options.output_dirname, options.allow_clobber, FALSE /* Don't print warning messages */ ) != 0) { // Failed to create output directory. die("Couldn't create output directory %s.\n", options.output_dirname); } // // If needed, convert motif file to MEME format using transfac2meme. // char *motif_basename = basename(options.motif_filename); // Using GNU basename if (options.motif_format == TRANSFAC_FORMAT) { // Build the name for the new MEME format file in the output directory. char *meme_filename = concat_string(motif_basename, ".meme"); char *meme_path = make_path_to_file(options.output_dirname, meme_filename); myfree(meme_filename); run_transfactomeme( options.motif_filename, meme_path, options.bg_filename ); // Replace motif file name with new name. options.motif_filename = meme_path; } // // Build the HMM using mhmm. // char *hmm_basename = concat_string(motif_basename, ".mhmm"); char *hmm_path = make_path_to_file(options.output_dirname, hmm_basename); myfree(hmm_basename); run_mhmm(options.motif_filename, hmm_path); // // Read and score the sequences using mhmmscan. // char *score_path = make_path_to_file( options.output_dirname, options.text_only == TRUE ? "mcast.txt" : "mcast.html" ); run_mhmmscan(&options, hmm_path, options.seq_filename, score_path); // // Clean up // if (options.motif_format == TRANSFAC_FORMAT) { // If transfac format was used we have to // clean up the string naming the MEME format // motif file. myfree(options.motif_filename); } myfree(hmm_path); myfree(score_path); return 0; }
int main(int argc, char **argv) { int count, status = EXIT_SUCCESS; TCHAR *fn; state *s; /* Because the main() function can handle wchar_t arguments on Win32, we need a way to reference those values. Thus we make a duplciate of the argc and argv values. */ #ifndef __GLIBC__ __progname = basename(argv[0]); #endif s = (state *)malloc(sizeof(state)); if (NULL == s) { // We can't use fatal_error because it requires a valid state print_status("%s: Unable to allocate state variable", __progname); return EXIT_FAILURE; } if (initialize_state(s)) { print_status("%s: Unable to initialize state variable", __progname); return EXIT_FAILURE; } process_command_line(s,argc,argv); if (initialize_hashing_algorithms(s)) return EXIT_FAILURE; if (primary_audit == s->primary_function) setup_audit(s); #ifdef _WIN32 if (prepare_windows_command_line(s)) fatal_error(s,"%s: Unable to process command line arguments", __progname); check_wow64(s); #else s->argc = argc; s->argv = argv; #endif MD5DEEP_ALLOC(TCHAR,s->cwd,PATH_MAX); s->cwd = _tgetcwd(s->cwd,PATH_MAX); if (NULL == s->cwd) fatal_error(s,"%s: %s", __progname, strerror(errno)); /* Anything left on the command line at this point is a file or directory we're supposed to process. If there's nothing specified, we should tackle standard input */ if (optind == argc) hash_stdin(s); else { MD5DEEP_ALLOC(TCHAR,fn,PATH_MAX); count = optind; while (count < s->argc) { generate_filename(s,fn,s->cwd,s->argv[count]); #ifdef _WIN32 status = process_win32(s,fn); #else status = process_normal(s,fn); #endif ++count; } free(fn); } if (primary_audit == s->primary_function) status = display_audit_results(s); return status; }
int main(int ac, char* av[]) { po::options_description od_desc("Allowed options"); get_options_description(od_desc); po::variables_map vm; po::store(po::parse_command_line(ac, av, od_desc), vm); if (vm.count("help")) { std::cout << od_desc << "\n"; return 0; } try{ po::notify(vm); } catch(...){ std::cout << od_desc << "\n"; return 0; } auto ret_val = process_command_line(vm, od_desc); if (ret_val != 2) return ret_val; auto db_dbase(vm["dbname"].as<std::string>()); db_dbase = "dbname = " + db_dbase; auto db_host(vm["host"].as<std::string>()); auto db_port(vm["port"].as<std::string>()); auto db_username(vm["username"].as<std::string>()); auto db_pwd(vm["password"].as<std::string>()); auto test(vm["test"].as<bool>()); //auto db_no_pwd(vm["no-password"].as<std::string>()); const char *conninfo = db_dbase.c_str(); PGconn *conn; PGresult *res; int rec_count, col_count; conn = PQconnectdb(conninfo); /* Check to see that the backend connection was successfully made */ if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn)); exit_nicely(conn); exit(0); } std::string data_sql; if (test) { data_sql = "select id, source, target, cost, -1 as reverse_cost from table1 order by id"; // data_sql = "select id, source, target, cost, reverse_cost from edge_table order by id"; } else { std::cout << "Input data query: "; std::getline (std::cin,data_sql); } std::cout << "\nThe data is from:" << data_sql <<"\n"; res = PQexec(conn, data_sql.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { std::cout << "We did not get any data!\n"; exit_nicely(conn); exit(1); } rec_count = PQntuples(res); col_count = PQnfields(res); if (col_count > 5 || col_count < 4) { std::cout << "Max number of columns 5\n"; std::cout << "Min number of columns 4\n"; exit_nicely(conn); exit(1); } auto id_fnum = PQfnumber(res, "id"); auto source_fnum = PQfnumber(res, "source"); auto target_fnum = PQfnumber(res, "target"); auto cost_fnum = PQfnumber(res, "cost"); auto reverse_fnum = PQfnumber(res, "reverse_cost"); pgr_edge_t *data_edges; data_edges = (pgr_edge_t *) malloc(rec_count * sizeof(pgr_edge_t)); printf("We received %d records.\n", rec_count); puts("=========================="); std::string::size_type sz; std::string str; for (int row = 0; row < rec_count; ++row) { str = std::string(PQgetvalue(res, row, id_fnum)); data_edges[row].id = stol(str, &sz); str = std::string(PQgetvalue(res, row, source_fnum)); data_edges[row].source = stol(str, &sz); str = std::string(PQgetvalue(res, row, target_fnum)); data_edges[row].target = stol(str, &sz); str = std::string(PQgetvalue(res, row, cost_fnum)); data_edges[row].cost = stod(str, &sz); if (reverse_fnum != -1) { str = std::string(PQgetvalue(res, row, reverse_fnum)); data_edges[row].reverse_cost = stod(str, &sz); } #if 0 std::cout << "\tid: " << data_edges[row].id << "\t"; std::cout << "\tsource: " << data_edges[row].source << "\t"; std::cout << "\ttarget: " << data_edges[row].target << "\t"; std::cout << "\tcost: " << data_edges[row].cost << "\t"; if (reverse_fnum != -1) { std::cout << "\treverse: " << data_edges[row].reverse_cost << "\t"; } std::cout << "\n"; #endif } puts("=========================="); PQclear(res); PQfinish(conn); ////////////////////// END READING DATA FROM DATABASE /////////////////// std::string directed; std::cout << "Is the graph directed [N,n]? default[Y]"; std::getline(std::cin,directed); graphType gType = (directed.compare("N")==0 || directed.compare("n")==0)? UNDIRECTED: DIRECTED; bool directedFlag = (directed.compare("N")==0 || directed.compare("n")==0)? false: true; const int initial_size = rec_count; Pgr_base_graph< DirectedGraph > digraph(gType, initial_size); Pgr_base_graph< UndirectedGraph > undigraph(gType, initial_size); if (directedFlag) { process(digraph, data_edges, rec_count); } else { process(undigraph, data_edges, rec_count); } }
/*------------------------------------------------------------------------------ main() Main Preconditions: Postconditions: *----------------------------------------------------------------------------*/ int main( int argc, char **argv ) /*----------------------------------------------------------------------------*/ { int user_input; char user_str[128]; ws_init(); tty_init(); // rmcpd_init_listener(); printf("\nIPMI Exerciser -- %s\n", __DATE__); // say Hi process_command_line( argc, argv ); // process command line arguments // Get user keyboard input while( 1 ) { main_menu(); scanf( "%d", &user_input ); fflush( stdin ); switch ( user_input ) { case KBD_APP_CMDS: kbd_app_cmds(); break; case KBD_CHASSIS_CMDS: break; case KBD_EVENT_CMDS: break; case KBD_FIRMWARE_COMMANDS: break; case KBD_NVSTORE_CMDS: break; case KBD_MEDIA_SPECIFIC_CMDS: break; case KBD_PICMG_CMDS: kbd_atca_cmds(); break; case KBD_RUN_UNIX: printf( "Enter command : " ); scanf( "%s", user_str ); //gets( user_str ); fflush( stdin ); if( system( user_str ) == -1 ) printf( "\nError in command\n" ); printf( "\n Press any key to continue\n" ); getchar(); fflush( stdin ); break; case KBD_SETTINGS: kbd_settings(); break; case KBD_QUIT: tty_restore(); exit( EXIT_SUCCESS ); break; default: printf( "Unknown option %d ignored.\n", user_input ); break; } // end switch printf( "Press any key to continue\n" ); getchar(); fflush( stdin ); } }
/************************************************************************* * Entry point for centrimo *************************************************************************/ int main(int argc, char *argv[]) { CENTRIMO_OPTIONS_T options; SEQ_SITES_T seq_sites; SITE_COUNTS_T counts; int seqN, motifN, seqlen, db_i, motif_i, i; double log_pvalue_thresh; SEQ_T** sequences = NULL; ARRAY_T* bg_freqs = NULL; ARRAYLST_T *stats_list; MOTIF_DB_T **dbs, *db; MREAD_T *mread; MOTIF_STATS_T *stats; MOTIF_T *motif, *rev_motif; PSSM_T *pos_pssm, *rev_pssm; char *sites_path, *desc; FILE *sites_file; HTMLWR_T *html; JSONWR_T *json; // COMMAND LINE PROCESSING process_command_line(argc, argv, &options); // load the sequences read_sequences(options.alphabet, options.seq_source, &sequences, &seqN); seqlen = (seqN ? get_seq_length(sequences[0]) : 0); // calculate a sequence background (unless other background is given) if (!options.bg_source) { bg_freqs = calc_bg_from_fastas(options.alphabet, seqN, sequences); } // load the motifs motifN = 0; dbs = mm_malloc(sizeof(MOTIF_DB_T*) * arraylst_size(options.motif_sources)); for (i = 0; i < arraylst_size(options.motif_sources); i++) { char* db_source; db_source = (char*)arraylst_get(i, options.motif_sources); dbs[i] = read_motifs(i, db_source, options.bg_source, &bg_freqs, options.pseudocount, options.selected_motifs, options.alphabet); motifN += arraylst_size(dbs[i]->motifs); } log_pvalue_thresh = log(options.evalue_thresh) - log(motifN); // Setup some things for double strand scanning if (options.scan_both_strands == TRUE) { // Set up hash tables for computing reverse complement setup_hash_alph(DNAB); setalph(0); // Correct background by averaging on freq. for both strands. average_freq_with_complement(options.alphabet, bg_freqs); normalize_subarray(0, alph_size(options.alphabet, ALPH_SIZE), 0.0, bg_freqs); calc_ambigs(options.alphabet, FALSE, bg_freqs); } // Create output directory if (create_output_directory(options.output_dirname, options.allow_clobber, (verbosity >= NORMAL_VERBOSE))) { die("Couldn't create output directory %s.\n", options.output_dirname); } // open output files sites_path = make_path_to_file(options.output_dirname, SITES_FILENAME); sites_file = fopen(sites_path, "w"); free(sites_path); // setup html monolith writer json = NULL; if ((html = htmlwr_create(get_meme_etc_dir(), TEMPLATE_FILENAME))) { htmlwr_set_dest_name(html, options.output_dirname, HTML_FILENAME); htmlwr_replace(html, "centrimo_data.js", "data"); json = htmlwr_output(html); if (json == NULL) die("Template does not contain data section.\n"); } else { DEBUG_MSG(QUIET_VERBOSE, "Failed to open html template file.\n"); } if (json) { // output some top level variables jsonwr_str_prop(json, "version", VERSION); jsonwr_str_prop(json, "revision", REVISION); jsonwr_str_prop(json, "release", ARCHIVE_DATE); jsonwr_str_array_prop(json, "cmd", argv, argc); jsonwr_property(json, "options"); jsonwr_start_object_value(json); jsonwr_dbl_prop(json, "motif-pseudo", options.pseudocount); jsonwr_dbl_prop(json, "score", options.score_thresh); jsonwr_dbl_prop(json, "ethresh", options.evalue_thresh); jsonwr_lng_prop(json, "maxbin", options.max_window+1); jsonwr_bool_prop(json, "norc", !options.scan_both_strands); jsonwr_bool_prop(json, "noflip", options.no_flip); jsonwr_end_object_value(json); // output the description desc = prepare_description(&options); if (desc) { jsonwr_str_prop(json, "job_description", desc); free(desc); } // output size metrics jsonwr_lng_prop(json, "seqlen", seqlen); jsonwr_lng_prop(json, "tested", motifN); // output the fasta db jsonwr_property(json, "sequence_db"); jsonwr_start_object_value(json); jsonwr_str_prop(json, "source", options.seq_source); jsonwr_lng_prop(json, "count", seqN); jsonwr_end_object_value(json); // output the motif dbs jsonwr_property(json, "motif_dbs"); jsonwr_start_array_value(json); for (db_i = 0; db_i < arraylst_size(options.motif_sources); db_i++) { db = dbs[db_i]; jsonwr_start_object_value(json); jsonwr_str_prop(json, "source", db->source); jsonwr_lng_prop(json, "count", arraylst_size(db->motifs)); jsonwr_end_object_value(json); } jsonwr_end_array_value(json); // start the motif array jsonwr_property(json, "motifs"); jsonwr_start_array_value(json); } /************************************************************** * Tally the positions of the best sites for each of the * selected motifs. **************************************************************/ // prepare the sequence sites memset(&seq_sites, 0, sizeof(SEQ_SITES_T)); // prepare the site counts counts.allocated = ((2 * seqlen) - 1); counts.sites = mm_malloc(sizeof(double) * counts.allocated); // prepare the motifs stats list stats_list = arraylst_create(); // prepare the other vars motif = NULL; pos_pssm = NULL; rev_motif = NULL; rev_pssm = NULL; for (db_i = 0; db_i < arraylst_size(options.motif_sources); db_i++) { db = dbs[db_i]; for (motif_i = 0; motif_i < arraylst_size(db->motifs); motif_i++) { motif = (MOTIF_T *) arraylst_get(motif_i, db->motifs); DEBUG_FMT(NORMAL_VERBOSE, "Using motif %s of width %d.\n", get_motif_id(motif), get_motif_length(motif)); // reset the counts for (i = 0; i < counts.allocated; i++) counts.sites[i] = 0; counts.total_sites = 0; // create the pssm pos_pssm = make_pssm(bg_freqs, motif); // If required, do the same for the reverse complement motif. if (options.scan_both_strands) { rev_motif = dup_rc_motif(motif); rev_pssm = make_pssm(bg_freqs, rev_motif); } // scan the sequences for (i = 0; i < seqN; i++) score_sequence(&options, sequences[i], pos_pssm, rev_pssm, &seq_sites, &counts); // DEBUG check that the sum of the sites is close to the site count double sum_check = 0, sum_diff; for (i = 0; i < counts.allocated; i++) sum_check += counts.sites[i]; sum_diff = counts.total_sites - sum_check; if (sum_diff < 0) sum_diff = -sum_diff; if (sum_diff > 0.1) { fprintf(stderr, "Warning: site counts don't sum to accurate value! " "%g != %ld", sum_check, counts.total_sites); } // output the plain text site counts output_site_counts(sites_file, seqlen, db, motif, &counts); // compute the best central window stats = compute_stats(options.max_window, seqlen, db, motif, &counts); // check if it passes the threshold if (json && stats->log_adj_pvalue <= log_pvalue_thresh) { output_motif_json(json, stats, &counts); arraylst_add(stats, stats_list); } else { free(stats); } // Free memory associated with this motif. free_pssm(pos_pssm); free_pssm(rev_pssm); destroy_motif(rev_motif); } } if (json) jsonwr_end_array_value(json); // finish writing sites fclose(sites_file); // finish writing html file if (html) { if (htmlwr_output(html) != NULL) { die("Found another JSON replacement!\n"); } htmlwr_destroy(html); } // write text file output_centrimo_text(&options, motifN, stats_list); // Clean up. for (i = 0; i < seqN; ++i) { free_seq(sequences[i]); } free(sequences); for (i = 0; i < arraylst_size(options.motif_sources); i++) { free_db(dbs[i]); } free(dbs); free_array(bg_freqs); free(counts.sites); free(seq_sites.sites); arraylst_destroy(free, stats_list); cleanup_options(&options); return 0; }