void MemScanWidget::startClickedSlot() { if(!isStarted()) man() -> scanMemory(); else if(!isPaused()) man() -> pause(); else man() -> resume(); }
static int run_manager(CmdArgs::const_iterator it, CmdArgs::const_iterator end, int processor) { vle::manager::Manager man(convert_log_mode(), vle::manager::SIMULATION_NONE | vle::manager::SIMULATION_NO_RETURN, &std::cout); vle::utils::ModuleManager modules; int success = EXIT_SUCCESS; for (; it != end; ++it) { vle::manager::Error error; vle::value::Matrix *res = man.run(new vle::vpz::Vpz(search_vpz(*it)), modules, processor, 0, 1, &error); if (error.code) { std::cerr << vle::fmt(_("Experimental frames `%s' throws error %s")) % (*it) % error.message.c_str(); success = EXIT_FAILURE; } delete res; } return success; }
std::map<int, config> user_choice_manager::get_user_choice_internal(const std::string &name, const mp_sync::user_choice &uch, const std::set<int>& sides) { const bool is_too_early = resources::gamedata->phase() != game_data::START && resources::gamedata->phase() != game_data::PLAY; user_choice_manager man(name, uch, sides); while(!man.finished()) { if(man.waiting()) { if(is_too_early) { wait_prestart(man); } else { wait_ingame(man); } } else if(man.has_local_choice()) { man.ask_local_choice(); } else { man.fix_oos(); } } return man.res_; }
static void printUsage() { PUTS("Valid commands are:"); PUTS("\tq\tQuit"); PUTS("\th\tHelp"); PUTS("\t?\tHelp"); PUTS("\tv\tPrint ION version number."); PUTS("\t1\tInitialize"); PUTS("\t 1"); PUTS("\ta\tAdd"); PUTS("\t a profile <profileID> <maxRtx> <aggrSizeLimit> \ <aggrTimeLimit> <ttl> <custody>.<priority>[.<ordinal>\ [.<unreliable>.<critical>[.<flow_label>]]] <report-to-endpoint> \ [<status_report_flags>]"); PUTS("\td\tDelete"); PUTS("\ti\tInfo"); PUTS("\t {d|i} profile <profileID>"); PUTS("\tl\tList"); PUTS("\t l profile"); PUTS("\ts\tStart"); PUTS("\tx\tStop"); PUTS("\t w { 0 | 1 | <activity spec> }"); PUTS("\t\tActivity spec is a string of all requested activity \ indication characters, e.g., pq. See man(5) for dtpcrc."); PUTS("\te\tEnable or disable echo of printed output to log file"); PUTS("\t e { 0 | 1 }"); PUTS("\t#\tComment"); PUTS("\t # <comment text>"); }
int main() { //Create PluginManager instance with the plugin path "./" PluginManager man("."); man.loadParameterFile("cropsample.wrp"); man.executeWorkflow(); man.saveParameterFile("cropsample2.wrp"); }
void GameOfLife::control_Movie ( wchar_t **nextLattice ) { if ( m_time %3 ==0 ) { if ( carx < m_w-5 ) { carx += 2; } else { carx = 0; } } if ( m_time %6 ==0 ) { if ( manx < m_w-3 ) { ++manx; } else { manx = 0; } } house ( nextLattice, housex, 3*m_h/5 -6 ); car ( nextLattice, carx, 3*m_h/5 +1 ); man ( nextLattice, manx, 3*m_h/5-1 ); }
/// unit tests int test() { std::ofstream log("flowIterated2_HS_Yosemite.log", std::ios::trunc); assert(log.good()); sout.assign(log); // load plugin manager PluginManager man(GLOBAL_PLUGIN_DIR, LOCAL_PLUGIN_DIR); // start tests std::string testfile(TESTDIR "/flowIterated2.wrp"); std::cout << "Loading parameter file \"" << testfile; std::cout << "\"" << std::endl; man.loadParameterFile(testfile); std::cout << "Executing workflow..." << std::endl; FileTool::changeDir(TESTDIR); man.runWorkflow(); std::cout << "Workflow execution finished.\n" << std::endl; // get test instances FlowComparator<double>* comparator = dynamic_cast<FlowComparator<double>*>( man.getInstance("analyzer")); assert(comparator); std::cout << "mean endpoint error: " << comparator->getMeanEndpointError() << std::endl; assert(comparator->getMeanEndpointError() <= 0.1); man.reset(); sout.assign(); log.close(); return EXIT_SUCCESS; }
int main(void) { char *p = "*****@*****.**"; Mailman man("221.215.1.149", "*****@*****.**", "*****@*****.**","eXV4aWFvZmVuZzM=","QWJjZDEyMzQt"); man.sendmail(); return 0; }
static void printUsage() { PUTS("Valid commands are:"); PUTS("\tq\tQuit"); PUTS("\th\tHelp"); PUTS("\t?\tHelp"); PUTS("\t1\tInitialize"); PUTS("\t 1"); PUTS("\tm\tManage"); PUTS("\t m discard { 0 | 1 }"); PUTS("\t m requirecrc { 0 | 1 }"); PUTS("\t m fillchar <file fill character in hex, e.g., 0xaa>"); PUTS("\t m ckperiod <check cycle period, in seconds>"); PUTS("\t m maxtimeouts <max number of check cycle timeouts>"); PUTS("\t m maxtrnbr <max transaction number>"); PUTS("\t m segsize <max bytes per reliable file data segment>"); PUTS("\t m mtusize <max bytes per best-efforts file data segment>"); PUTS("\ti\tInfo"); PUTS("\t i"); PUTS("\ts\tStart"); PUTS("\t s '<UTA command>'"); PUTS("\tx\tStop"); PUTS("\t x"); PUTS("\tw\tWatch CFDP activity"); PUTS("\t w { 0 | 1 | <activity spec> }"); PUTS("\t\tActivity spec is a string of all requested activity \ indication characters, e.g., pq. See man(5) for cfdprc."); PUTS("\te\tEnable or disable echo of printed output to log file"); PUTS("\t e { 0 | 1 }"); PUTS("\t#\tComment"); PUTS("\t # <comment text>"); }
void GameOfLife::control_Movie ( int **nextLattice, int mode ) { if ( m_time %3 ==0 ) { if ( carx < m_w-5 ) { carx += 2; } else { carx = 0; } } if ( m_time %6 ==0 ) { if ( manx < m_w-3 ) { ++manx; } else { manx = 0; } } if ( mode == 1 ) { house ( nextLattice, housex, 3*m_h/5 -6 ); } else if ( mode == 2 ) { car ( nextLattice, carx, 3*m_h/5 +1 ); } else if ( mode == 3 ) { man ( nextLattice, manx, 3*m_h/5-1 ); } else { house ( nextLattice, housex, 3*m_h/5 -6 ); car ( nextLattice, carx, 3*m_h/5 +1 ); man ( nextLattice, manx, 3*m_h/5-1 ); } }
void test_smartpointer() { std::shared_ptr<Man> man(new Man()); std::shared_ptr<Woman> woman(new Woman()); if (man && woman) { man->marriage(woman); woman->marriage(man); } }
int main(int argc, const char*argv[]) { string args; string parameters[8] = {"who", "slack", "weather", "wt", "time", "man", "amac", "exit"}; if (argc == 2){ /* when "jasfom who" command */ if (!(strcmp(argv[1], parameters[0].c_str()))) { outputJasfomInfo(); } /* when "jasfom slack" command */ if(!(strcmp(argv[1], parameters[1].c_str()))) { postSlack(); } /* when "jasfom wt or weather" command */ if (!(strcmp(argv[1], parameters[2].c_str())) || !(strcmp(argv[1], parameters[3].c_str()))){ informWeather(); } /* when "jasfom time" command */ if (!(strcmp(argv[1], parameters[4].c_str()))){ informTime(); } /* when "jasfom man" command */ if (!(strcmp(argv[1], parameters[5].c_str()))){ man(); } /* when "jasfom amac" command */ if (!(strcmp(argv[1], parameters[6].c_str()))){ outputMacInfo(); } /* when "jasfom exit" command */ if (!(strcmp(argv[1], parameters[7].c_str()))){ exitMac(); } } /* long argv */ if (argc > 2) { answerBySentences(argv[1]); } if (argc == 1) { /* when just input jasfom*/ cout << "Jasfom speaking..." << endl; cout << " What can I help you?, Sir." << endl; pipeOpen("say What can I help you?, Sir."); } return 0; }
int main(int argc, char** argv) { std::shared_ptr<Man> man(new Man()); std::shared_ptr<Woman> woman(new Woman()); if (man && woman) { man->marriage(woman); woman->marriage(man); } return 0; }
int main ( int argy , const char *argv[]) { int my; // int name; my = 20; // name = &my; man ( &my); printf ("%d\n",my); return 0; }
int main(int argc,char **argv) { glutInit(&argc,argv); glutInitWindowPosition(100,100); glutInitWindowSize(600,600); glutCreateWindow("ques"); init(); //glClearColor( 0.0f,0.0f, 1.0f, 0.1f); man(300,1000,1); glutDisplayFunc(display); glutMainLoop(); return 1; }
int main(int argc, char** argv) { Raul::Maid maid; DisposableThing* dis = new DisposableThing(); std::shared_ptr<ManageableThing> man(new ManageableThing()); maid.manage(man); maid.dispose(dis); maid.cleanup(); return 0; }
bool StandardParserWithManpage::parse(int argc, const char* argv[]) { if (StandardParser::parse(argc, argv)) return true; if (manpage->isSet()) { // Output the manpage commandline::Manpage man(name(), m_version, m_section, m_author); string hooks(manpage->value()); if (!hooks.empty()) man.readHooks(hooks); man.output(cout, *this); return true; } return false; }
void circle2(float r, int cx, int cy) { int x, y; flag1++; if (flag1 % 350 == 0) flag2++; /*for(int i=0;i<50;i++) for(int j=0;j<1000;j++)*/ //use in case of slow machines glBegin(GL_POLYGON); for (int i = 0; i <360; i++) { float degInRad = i*DEG2RAD; x = cx + cos(degInRad)*r; y = cy + sin(degInRad)*r; glVertex2f(x, y); } glEnd(); if (flag2 % 2 != 0 && flag3 == 0) { man(cx, cy + 30); } else if (flag2 % 2 == 0 && flag3 == 0) { man2(cx, cy + 30); } if (cx <= 400) { flag3 = 1; climax(cx, cy + 30); if (climaxflag == 1000) bloodflag = 1; } }
/* * find man pages mentioning the search string */ void dosearch(int vermaj, char *search) { int sect; char *p; if(strncmp(search, "man=", 4) == 0){ sect = 0; search = hurlunesc(connect, search+4); p = strchr(search, '&'); if(p != nil){ *p++ = 0; if(strncmp(p, "sect=", 5) == 0) sect = atoi(p+5); } man(search, sect, vermaj); return; } if(vermaj){ hokheaders(connect); hprint(hout, "Content-type: text/html\r\n"); hprint(hout, "\r\n"); } if(strncmp(search, "pat=", 4) == 0){ search = hurlunesc(connect, search+4); search = hlower(search); searchfor(search); return; } hprint(hout, "<head><title>illegal search</title></head>\n"); hprint(hout, "<body><p>Illegally formatted Plan 9 man page search</p>\n"); search = hurlunesc(connect, search); hprint(hout, "<body><p>%H</p>\n", search); hprint(hout, "</body>"); }
GeoDataDocument *TileLoader::loadTileVectorData( GeoSceneVectorTile const *textureLayer, TileId const & tileId, DownloadUsage const usage ) { // FIXME: textureLayer->fileFormat() could be used in the future for use just that parser, instead of all available parsers QString const fileName = tileFileName( textureLayer, tileId ); TileStatus status = tileStatus( textureLayer, tileId ); if ( status != Missing ) { // check if an update should be triggered if ( status == Available ) { mDebug() << Q_FUNC_INFO << tileId << "StateUptodate"; } else { Q_ASSERT( status == Expired ); mDebug() << Q_FUNC_INFO << tileId << "StateExpired"; triggerDownload( textureLayer, tileId, usage ); } QFile file ( fileName ); if ( file.exists() ) { // File is ready, so parse and return the vector data in any case ParsingRunnerManager man( m_pluginManager ); GeoDataDocument* document = man.openFile( fileName ); if (document){ return document; } } } // tile was not locally available => trigger download triggerDownload( textureLayer, tileId, usage ); return new GeoDataDocument; }
int main(int argc, char **argv) { uint32_t rank = 0; uint32_t world = 0; bool show = false; bool result; vle::Init app; if ((result = mvle_mpi_init(&argc, &argv, &rank, &world))) { int vpz; if ((result = mvle_parse_arg(argc, argv, &vpz, &show))) { if (show) { while (vpz < argc) { mvle_show( vle::utils::Path::path(). getPackageExpFile(argv[vpz])); vpz++; } } else { try { vle::manager::Manager man(vle::manager::LOG_SUMMARY, vle::manager::SIMULATION_NONE | vle::manager::SIMULATION_NO_RETURN, &std::cout); vle::utils::ModuleManager modules; mvle_print("MPI node %d/%d start\n", rank, world); while (vpz < argc) { vle::manager::Error error; vle::value::Matrix *res = man.run( new vle::vpz::Vpz(vle::utils::Path::path(). getPackageExpFile(argv[vpz])), modules, 1, rank, world, &error); if (error.code) { mvle_print_error("Experimental frames `%s' throws error %s", argv[vpz], error.message.c_str()); } delete res; vpz++; } mvle_print("MPI node %d/%d end\n", rank, world); } catch (const std::exception& e) { mvle_print_error("manager problem: %s", e.what()); } } } } MPI_Finalize(); return result ? EXIT_SUCCESS : EXIT_FAILURE; }
VALUE load_test(){ void (*man)()=dlsym(sl,"main"); man(); return Qnil; }
int set_app(QStringList command) { qDebug() << "set_app(" << command.join(" ") << ")" << endl; /** * Debug */ for(int i=0;i<command.size();i++) { qDebug() << "command.at(" << i << ")" << command.at(i) << endl; } /** * Check input */ QTextStream errorStream(stderr); if(command.size() != 5) { errorStream << "Error: set_app(" << command.join(" ") << "): No valid number of arguments!" << endl; man("usage set_app"); return 1; } if(command.at(0)!="set_app") { errorStream << "Error: set_app(" << command.join(" ") << "): No valid command!" << endl; man("usage set_app"); return 1; } if(! command.at(2).contains(QRegExp("^(binary|integer|hex|cip)$"))) { errorStream << "Error: set_app(" << command.join(" ") << "): No valid CIP mode!" << endl; man("usage set_app"); return 1; } if(! command.at(3).contains(QRegExp("^(type|size|data)$"))) { errorStream << "Error: set_app(" << command.join(" ") << "): No valid key!" << endl; man("usage set_app"); return 1; } /** * Check value for integer and single value */ if(command.at(2)=="integer" && command.at(3).contains(QRegExp("^(type|size)$")) && // not uint8 (0-255) ((! command.at(4).contains(QRegExp("^\\d\\d?\\d?$"))) || command.at(4).toInt() < 0 || command.at(4).toInt() > 255)) { errorStream << "Error: set_ci(" << command.join(" ") << "): No valid value!" << endl; man("usage set_ci"); return 1; } /** * Check value for binary and single value */ if(command.at(2)=="binary" && command.at(3).contains(QRegExp("^(type|size)$")) && // not uint8 (00000000-11111111) ((! command.at(4).contains(QRegExp("^(0|1){8}$"))))) { errorStream << "Error: set_ci(" << command.join(" ") << "): No valid value!" << endl; man("usage set_ci"); return 1; } /** * Check value for hex and single value */ if(command.at(2)=="hex" && command.at(3).contains(QRegExp("^(type|size)$")) && // not uint8 (00-ff) ((! command.at(4).contains(QRegExp("^(\\d|a|b|c|d|e|f){2}$"))))) { errorStream << "Error: set_ci(" << command.join(" ") << "): No valid value!" << endl; man("usage set_ci"); return 1; } /** * Read file */ QString filePath; filePath = CIP_ROOT; filePath += "/" + command.at(1); qDebug() << "filePath: " << filePath << endl; QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { errorStream << "Error: set_ci(" << command.join(" ") << ") can not read " << filePath << endl; return 1; } QByteArray byteArray; byteArray = file.readAll(); file.close(); qDebug() << "byteArray.size(): " << byteArray.size() << endl; /** * Define map with start position */ QMap<QString, int> keys; int pos; int i = byteArray.at(35) + 39; i += byteArray.at(i)*2; keys["type"] = ++i; keys["size"] = ++i; keys["data"] = ++i; QByteArray value; bool ok; /** * One byte keys (without size) */ if(command.at(3).contains(QRegExp("^(type|size)$"))) { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; if(command.at(2)=="binary") { value.append(command.at(4).toUInt(&ok, 2)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 2!" << endl; return 1; } } if(command.at(2)=="integer") { value.append(command.at(4).toUInt(&ok, 10)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 10!" << endl; return 1; } } if(command.at(2)=="hex") { value.append(command.at(4).toUInt(&ok, 16)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 16!" << endl; return 1; } } if(command.at(2)=="cip") { errorStream << "Not yet specified!" << endl; return 1; } pos = keys[command.at(3)]; qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl; byteArray.replace(pos, 1, value); } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } } /** * data */ if(command.at(3)=="data") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } // Remove old contents qDebug().noquote().nospace() << "Remove " << (int) byteArray.at(keys["size"]) << " byte(s) of data" << endl; pos = keys["size"]; int oldContentsSize = byteArray.at(keys["size"]); for (int i=0; i < oldContentsSize; i++) { byteArray.remove(pos, 1); qDebug().noquote().nospace() << "Remove " << pos << endl; } // Set size QString size = QString("%1").arg(command.at(4).size()); value.append(size.toUInt(&ok, 10)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 10!" << endl; return 1; } byteArray.replace(keys["size"], 1, value); qDebug().noquote().nospace() << "Set size to " << size << endl; // Set contents pos = keys[command.at(3)]; const QChar *data = command.at(4).data(); while (!data->isNull()) { qDebug() << data->toLatin1() << " (" << data->unicode() << ")"; byteArray.insert(pos++, data->toLatin1()); ++data; } } /** * Write file */ if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { errorStream << "Error: set_ci(" << command.join(" ") << ") can not write to file " << filePath << endl; return 1; } file.write(byteArray); file.close(); qDebug() << "filePath: " << filePath << endl; return 0; }
// // Main Routine // int main(void) { #ifdef DEBUG CSerial ser; // declare a UART object ser.enable(); CDebug dbg(ser); // Debug stream use the UART object dbg.start(); #endif // // SoftDevice // bleDevice ble; ble.enable("Shutter", "1234"); // enable BLE SoftDevice task // Pin to clear all center list CPin btn(17); btn.input(); // Device Manager for bond device. bleDeviceManager man(ble, (btn==LOW ? true : false)); man.connect_directed_mode(); // enable "connect directed" mode to fast connected. (BT 4.1 spec.) // GAP ble.m_gap.settings( DEVICE_NAME, 20, // min. connection interval in millisecond 100, // max. connection interval in millisecond 12); // slave latency (save power) ble.m_gap.tx_power(BLE_TX_0dBm); // // HID Keyboard Service // bleServiceKB kbs(ble); // // Battery Level Service // bleServiceBattery bat(ble); // // Optional: Add "Connection Parameters Update" negotiation. // bleConnParams conn(ble); // // BLE Advertising // ble.m_advertising.add_uuid_to_complete_list(bat); // add bat object to the uuid list of advertising ble.m_advertising.add_uuid_to_complete_list(kbs); // add kbs object to the uuid list of advertising // Optional: add appearance to indicate who you are in advertisement. ble.m_advertising.appearance(BLE_APPEARANCE_HID_KEYBOARD); ble.m_advertising.update(); // update advertisement data // Start advertising ble.m_advertising.interval(APP_ADV_INTERVAL); // set advertising interval ble.m_advertising.timeout(30); // Enter system power off mode when adv. timeout. (disable system off if timeout=0) ble.m_advertising.start(); // // Optional: Enable tickless technology // #ifndef DEBUG CPowerSave::tickless(true); #endif // // Key Test Task // CThread t(keyTask); t.start("kb", 76); // start the keyTask // // Analog // CAdc::init(); CAdc::source(VDD_1_3); // to detect the VDD voltage CAdc::enable(); // // LED // CPin led(LED_PIN_0); led.output(); CTimeout tmBAT, tmLED; uint16_t value; float percentage; // // Enter main loop. // while(1) { // // BLE Battery Service // if ( bat.isAvailable() ) { if ( tmBAT.isExpired(1000) ) { tmBAT.reset(); if ( CAdc::read(value) ) { percentage = (value / 1024.0f) * 100; bat.send(percentage); } } } // // blink led // led = LED_ON; sleep(10); led = LED_OFF; if ( ble.isConnected() ) { sleep(290); } else { sleep(1990); } // Negotiate the "connection parameters update" in main-loop conn.negotiate(); } }
//--------------------------------- SHELL core os.c--------- char listen_key(){ // unsigned short int init_pos = get_pointer_pos(); flag_len=17; char i = gets( key); screen_sc_T = 1; Print_flag_mark = 1; if( strcmp( key, "clear\0")){ // char *,const char * clear(); return i; } if( strcmp( key, "time\0")){ time(); return i; } if( strcmp( key, "date\0")){ date(); return i; } if( strcmp( key, "python\0")){ python(); return i; } if( strcmp( key, "start\0")){ screen_init(); Print_flag_mark = 0; Process(); return i; } if( strcmp( key, "help\0")){ //can't refer 2 two times, so... init_flag_position(); screen_init(); print_welcome_msg(); print_message(); print_flag(); //root@wangqin4377@: position return i; } //---------------------------------mark: man xxx, run xxx,asc xx... if( synCheck( key, "asc\0")){ asc( key); return i; } if( synCheck( key, "man\0")){ man( key); return i; } if( synCheck( key, "run\0")){ run( key); return i; } if( synCheck( key, "syscall\0")){ syscall_test(); return i; } if( synCheck( key, "int\0")){ if( strcmp( key, "int 33h")){ __asm__( "int $0x33"); return i; } if( strcmp( key, "int 34h")){ __asm__( "int $0x34"); return i; } if( strcmp( key, "int 35h")){ __asm__( "int $0x35"); return i; } if( strcmp( key, "int 36h")){ __asm__( "int $0x36"); return i; } } if( key[0] == '\0'){ return i; } flag_scroll(); set_pointer_pos(); print_str(" No such file or Directory", 27); screen_sc_T = 2; return i; }
bool RClient::parse(int &argc, char **argv) { Rct::findExecutablePath(*argv); mSocketFile = Path::home() + ".rdm"; List<option> options; options.reserve(sizeof(opts) / sizeof(Option)); List<std::shared_ptr<QueryCommand> > projectCommands; String shortOptionString; Hash<int, Option*> shortOptions, longOptions; for (int i=0; opts[i].description; ++i) { if (opts[i].option != None) { const option opt = { opts[i].longOpt, opts[i].argument, 0, opts[i].shortOpt }; if (opts[i].shortOpt) { shortOptionString.append(opts[i].shortOpt); switch (opts[i].argument) { case no_argument: break; case required_argument: shortOptionString.append(':'); break; case optional_argument: shortOptionString.append("::"); break; } assert(!shortOptions.contains(opts[i].shortOpt)); shortOptions[opts[i].shortOpt] = &opts[i]; } if (opts[i].longOpt) longOptions[options.size()] = &opts[i]; options.push_back(opt); } } if (getenv("RTAGS_DUMP_UNUSED")) { String unused; for (int i=0; i<26; ++i) { if (!shortOptionString.contains('a' + i)) unused.append('a' + i); if (!shortOptionString.contains('A' + i)) unused.append('A' + i); } printf("Unused: %s\n", unused.constData()); for (int i=0; opts[i].description; ++i) { if (opts[i].longOpt) { if (!opts[i].shortOpt) { printf("No shortoption for %s\n", opts[i].longOpt); } else if (opts[i].longOpt[0] != opts[i].shortOpt) { printf("Not ideal option for %s|%c\n", opts[i].longOpt, opts[i].shortOpt); } } } return 0; } { const option opt = { 0, 0, 0, 0 }; options.push_back(opt); } Path logFile; unsigned logFlags = 0; enum State { Parsing, Done, Error } state = Parsing; while (true) { int idx = -1; const int c = getopt_long(argc, argv, shortOptionString.constData(), options.data(), &idx); switch (c) { case -1: state = Done; break; case '?': case ':': state = Error; break; default: break; } if (state != Parsing) break; const Option *opt = (idx == -1 ? shortOptions.value(c) : longOptions.value(idx)); assert(opt); switch (opt->option) { case None: assert(0); break; case Help: help(stdout, argv[0]); return 0; case Man: man(); return 0; case SocketFile: mSocketFile = optarg; break; case IMenu: mQueryFlags |= QueryMessage::IMenu; break; case ContainingFunction: mQueryFlags |= QueryMessage::ContainingFunction; break; case DeclarationOnly: mQueryFlags |= QueryMessage::DeclarationOnly; break; case FindVirtuals: mQueryFlags |= QueryMessage::FindVirtuals; break; case FindFilePreferExact: mQueryFlags |= QueryMessage::FindFilePreferExact; break; case CursorInfoIncludeParents: mQueryFlags |= QueryMessage::CursorInfoIncludeParents; break; case CursorInfoIncludeTargets: mQueryFlags |= QueryMessage::CursorInfoIncludeTargets; break; case CursorInfoIncludeReferences: mQueryFlags |= QueryMessage::CursorInfoIncludeReferences; break; case CursorKind: mQueryFlags |= QueryMessage::CursorKind; break; case CodeComplete: // logFile = "/tmp/rc.log"; mCommands.append(std::shared_ptr<RCCommand>(new CompletionCommand)); break; case Context: mContext = optarg; break; case CodeCompleteAt: { const String arg = optarg; List<RegExp::Capture> caps; RegExp rx("^\\(.*\\):\\([0-9][0-9]*\\):\\([0-9][0-9]*\\)$"); if (rx.indexIn(arg, 0, &caps) != 0 || caps.size() != 4) { fprintf(stderr, "Can't decode argument for --code-complete-at [%s]\n", optarg); return false; } const Path path = Path::resolved(caps[1].capture, Path::MakeAbsolute); if (!path.exists()) { fprintf(stderr, "Can't decode argument for --code-complete-at [%s]\n", optarg); return false; } String out; { Serializer serializer(out); serializer << path << atoi(caps[2].capture.constData()) << atoi(caps[3].capture.constData()); } CompletionCommand *cmd = new CompletionCommand(path, atoi(caps[2].capture.constData()), atoi(caps[3].capture.constData())); mCommands.append(std::shared_ptr<RCCommand>(cmd)); break; } case DisplayName: mQueryFlags |= QueryMessage::DisplayName; break; case AllReferences: mQueryFlags |= QueryMessage::AllReferences; break; case MatchCaseInsensitive: mQueryFlags |= QueryMessage::MatchCaseInsensitive; break; case MatchRegexp: mQueryFlags |= QueryMessage::MatchRegexp; break; case AbsolutePath: mQueryFlags |= QueryMessage::AbsolutePath; break; case ReverseSort: mQueryFlags |= QueryMessage::ReverseSort; break; case ElispList: mQueryFlags |= QueryMessage::ElispList; break; case FilterSystemHeaders: mQueryFlags |= QueryMessage::FilterSystemIncludes; break; case NoContext: mQueryFlags |= QueryMessage::NoContext; break; case PathFilter: { Path p = optarg; p.resolve(); mPathFilters.insert(p); break; } case RangeFilter: { List<RegExp::Capture> caps; RegExp rx("^\\([0-9][0-9]*\\)-\\([0-9][0-9]*\\)$"); if (rx.indexIn(optarg, 0, &caps) != 0 || caps.size() != 3) { fprintf(stderr, "Can't parse range, must be uint-uint. E.g. 1-123\n"); return false; } else { mMinOffset = atoi(caps.at(1).capture.constData()); mMaxOffset = atoi(caps.at(2).capture.constData()); if (mMaxOffset <= mMinOffset || mMinOffset < 0) { fprintf(stderr, "Invalid range (%d-%d), must be uint-uint. E.g. 1-123\n", mMinOffset, mMaxOffset); return false; } } break; } case LineNumbers: mQueryFlags |= QueryMessage::LineNumbers; break; case Verbose: ++mLogLevel; break; case Silent: mLogLevel = -1; break; case LogFile: logFile = optarg; break; case StripParen: mQueryFlags |= QueryMessage::StripParentheses; break; case ConnectTimeout: mConnectTimeout = atoi(optarg); if (mConnectTimeout < 0) { fprintf(stderr, "--connect-timeout [arg] must be >= 0\n"); return false; } break; case Max: mMax = atoi(optarg); if (mMax <= 0) { fprintf(stderr, "-M [arg] must be positive integer\n"); return false; } break; case Timeout: mTimeout = atoi(optarg); if (mTimeout <= 0) { fprintf(stderr, "-y [arg] must be positive integer\n"); return false; } break; case UnsavedFile: { const String arg(optarg); const int colon = arg.lastIndexOf(':'); if (colon == -1) { fprintf(stderr, "Can't parse -u [%s]\n", optarg); return false; } const int bytes = atoi(arg.constData() + colon + 1); if (!bytes) { fprintf(stderr, "Can't parse -u [%s]\n", optarg); return false; } const Path path = Path::resolved(arg.left(colon), Path::MakeAbsolute); if (!path.isFile()) { fprintf(stderr, "Can't open [%s] for reading\n", arg.left(colon).nullTerminated()); return false; } String contents(bytes, '\0'); const int r = fread(contents.data(), 1, bytes, stdin); if (r != bytes) { fprintf(stderr, "Read error %d (%s). Got %d, expected %d\n", errno, strerror(errno), r, bytes); return false; } mUnsavedFiles[path] = contents; break; } case FollowLocation: case CursorInfo: case ReferenceLocation: { const String encoded = Location::encodeClientLocation(optarg); if (encoded.isEmpty()) { fprintf(stderr, "Can't resolve argument %s\n", optarg); return false; } QueryMessage::Type type = QueryMessage::Invalid; switch (opt->option) { case FollowLocation: type = QueryMessage::FollowLocation; break; case CursorInfo: type = QueryMessage::CursorInfo; break; case ReferenceLocation: type = QueryMessage::ReferencesLocation; break; default: assert(0); break; } addQuery(type, encoded); break; } case WithProject: mProjects.append(optarg); break; case ReloadFileManager: addQuery(QueryMessage::ReloadFileManager); break; case ReloadProjects: addQuery(QueryMessage::ReloadProjects); break; case Clear: addQuery(QueryMessage::ClearProjects); break; case RdmLog: addLog(RdmLogCommand::Default); break; case Diagnostics: addLog(RTags::CompilationError); break; case XmlDiagnostics: addLog(RTags::CompilationErrorXml); break; case QuitRdm: addQuery(QueryMessage::Shutdown); break; case DeleteProject: addQuery(QueryMessage::DeleteProject, optarg); break; case CodeCompletionEnabled: addQuery(QueryMessage::CodeCompletionEnabled); break; case UnloadProject: addQuery(QueryMessage::UnloadProject, optarg); break; case FindProjectRoot: { const Path p = Path::resolved(optarg); printf("findProjectRoot [%s] => [%s]\n", p.constData(), RTags::findProjectRoot(p).constData()); return 0; } case Reindex: case Project: case FindFile: case ListSymbols: case FindSymbols: case JSON: case Builds: case JobCount: case Status: { QueryMessage::Type type = QueryMessage::Invalid; switch (opt->option) { case Reindex: type = QueryMessage::Reindex; break; case Project: type = QueryMessage::Project; break; case FindFile: type = QueryMessage::FindFile; break; case Builds: type = QueryMessage::Builds; break; case Status: type = QueryMessage::Status; break; case JSON: type = QueryMessage::JSON; break; case ListSymbols: type = QueryMessage::ListSymbols; break; case FindSymbols: type = QueryMessage::FindSymbols; break; case JobCount: type = QueryMessage::JobCount; break; default: assert(0); break; } if (optarg) { addQuery(type, optarg); } else if (optind < argc && argv[optind][0] != '-') { addQuery(type, argv[optind++]); } else { addQuery(type); } assert(!mCommands.isEmpty()); if (type == QueryMessage::Project) projectCommands.append(std::static_pointer_cast<QueryCommand>(mCommands.back())); break; } case LoadCompilationDatabase: { Path dir; if (optarg) { dir = optarg; } else if (optind < argc && argv[optind][0] != '-') { dir = argv[optind++]; } else { dir = Path::pwd(); } dir.resolve(Path::MakeAbsolute); if (!dir.exists()) { fprintf(stderr, "%s does not seem to exist\n", dir.constData()); return false; } if (!dir.isDir()) { fprintf(stderr, "%s is not a directory\n", dir.constData()); return false; } if (!dir.endsWith('/')) dir += '/'; const Path file = dir + "compile_commands.json"; if (!file.isFile()) { fprintf(stderr, "no compile_commands.json file in %s\n", dir.constData()); return false; } addQuery(QueryMessage::LoadCompilationDatabase, dir); break; } case HasFileManager: { Path p; if (optarg) { p = optarg; } else if (optind < argc && argv[optind][0] != '-') { p = argv[optind++]; } else { p = "."; } p.resolve(Path::MakeAbsolute); if (!p.exists()) { fprintf(stderr, "%s does not seem to exist\n", optarg); return false; } if (p.isDir()) p.append('/'); addQuery(QueryMessage::HasFileManager, p); break; } case SuspendFile: { Path p; if (optarg) { p = optarg; } else if (optind < argc && argv[optind][0] != '-') { p = argv[optind++]; } if (!p.isEmpty()) { if (p == "clear" && !p.exists()) { } else { p.resolve(Path::MakeAbsolute); if (!p.isFile() && p != "clear") { fprintf(stderr, "%s is not a file\n", optarg); return false; } } } addQuery(QueryMessage::SuspendFile, p); break; } case Compile: { String args = optarg; while (optind < argc) { args.append(' '); args.append(argv[optind++]); } addCompile(Path::pwd(), args); break; } case IsIndexing: addQuery(QueryMessage::IsIndexing); break; case IsIndexed: case DumpFile: case Dependencies: case FixIts: { Path p = optarg; if (!p.exists()) { fprintf(stderr, "%s does not exist\n", optarg); return false; } if (!p.isAbsolute()) p.prepend(Path::pwd()); if (p.isDir()) { if (opt->option != IsIndexed) { fprintf(stderr, "%s is not a file\n", optarg); return false; } else if (!p.endsWith('/')) { p.append('/'); } } QueryMessage::Type type = QueryMessage::Invalid; switch (opt->option) { case Dependencies: type = QueryMessage::Dependencies; break; case FixIts: type = QueryMessage::FixIts; break; case IsIndexed: type = QueryMessage::IsIndexed; break; case DumpFile: type = QueryMessage::DumpFile; break; default: assert(0); break; } addQuery(type, p); break; } case PreprocessFile: { Path p = optarg; p.resolve(Path::MakeAbsolute); if (!p.isFile()) { fprintf(stderr, "%s is not a file\n", optarg); return false; } addQuery(QueryMessage::PreprocessFile, p); break; } case RemoveFile: { const Path p = Path::resolved(optarg, Path::MakeAbsolute); if (!p.exists()) { addQuery(QueryMessage::RemoveFile, p); } else { addQuery(QueryMessage::RemoveFile, optarg); } break; } case ReferenceName: addQuery(QueryMessage::ReferencesName, optarg); break; } } if (state == Error) { help(stderr, argv[0]); return false; } if (optind < argc) { fprintf(stderr, "rc: unexpected option -- '%s'\n", argv[optind]); return false; } if (!initLogging(argv[0], LogStderr, mLogLevel, logFile, logFlags)) { fprintf(stderr, "Can't initialize logging with %s %d %d %s 0x%0x\n", argv[0], LogStderr, mLogLevel, logFile.constData(), logFlags); return false; } if (mCommands.isEmpty()) { help(stderr, argv[0]); return false; } if (mCommands.size() > projectCommands.size()) { // If there's more than one command one likely does not want output from // the queryCommand (unless there's no arg specified for it). This is so // we don't have to pass a different flag for auto-updating project // using the current buffer but rather piggy-back on --project const int count = projectCommands.size(); for (int i=0; i<count; ++i) { std::shared_ptr<QueryCommand> &cmd = projectCommands[i]; if (!cmd->query.isEmpty()) { cmd->extraQueryFlags |= QueryMessage::Silent; } } } if (!logFile.isEmpty() || mLogLevel > 0) { Log l(1); l << argc; for (int i = 0; i < argc; ++i) l << " " << argv[i]; } mArgc = argc; mArgv = argv; return true; }
int set_head(QStringList command) { qDebug() << "set_head(" << command.join(" ") << ")" << endl; /** * Debug */ for(int i=0;i<command.size();i++) { qDebug() << "command.at(" << i << ")" << command.at(i) << endl; } /** * Check input */ QTextStream errorStream(stderr); if(command.size() != 5) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid number of arguments!" << endl; man("usage set_head"); return 1; } if(command.at(0)!="set_head") { errorStream << "Error: set_head(" << command.join(" ") << "): No valid command!" << endl; man("usage set_head"); return 1; } if(! command.at(2).contains(QRegExp("^(binary|integer|hex|cip)$"))) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid CIP omode!" << endl; man("usage set_head"); return 1; } if(! command.at(3).contains(QRegExp("^(request|profile|version|channel|uuid|ip|port|time|type|size|data)$"))) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid header key!" << endl; man("usage set_head"); return 1; } /** * Check value for integer and single value */ if(command.at(2)=="integer" && command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$")) && // not uint8 (0-255) ((! command.at(4).contains(QRegExp("^\\d\\d?\\d?$"))) || command.at(4).toInt() < 0 || command.at(4).toInt() > 255)) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl; man("usage set_head"); return 1; } /** * Check value for binary and single value */ if(command.at(2)=="binary" && command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$")) && // not uint8 (00000000-11111111) ((! command.at(4).contains(QRegExp("^(0|1){8}$"))))) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl; man("usage set_head"); return 1; } /** * Check value for hex and single value */ if(command.at(2)=="hex" && command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$")) && // not uint8 (00-ff) ((! command.at(4).contains(QRegExp("^(\\d|a|b|c|d|e|f){2}$"))))) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl; man("usage set_head"); return 1; } /** * Check value for binary and uuid */ if(command.at(2)=="binary" && command.at(3)=="uuid") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for integer and uuid */ if(command.at(2)=="integer" && command.at(3)=="uuid") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for hex and uuid */ if(command.at(2)=="hex" && command.at(3)=="uuid" && // not (0-16^32) ((! command.at(4).contains(QRegExp("^(\\d|a|b|c|d|e|f){32}$"))))) { errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl; man("usage set_head"); return 1; } /** * Check value for cip and uuid */ if(command.at(2)=="cip" && command.at(3)=="uuid") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for binary and ip */ if(command.at(2)=="binary" && command.at(3)=="ip") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for integer and ip */ if(command.at(2)=="integer" && command.at(3)=="ip") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for hex and ip */ if(command.at(2)=="hex" && command.at(3)=="ip") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for cip and ip */ if(command.at(2)=="cip" && command.at(3)=="ip") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for binary and port */ if(command.at(2)=="binary" && command.at(3)=="port") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for integer and port */ if(command.at(2)=="integer" && command.at(3)=="port") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for hex and port */ if(command.at(2)=="hex" && command.at(3)=="port") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for cip and port */ if(command.at(2)=="cip" && command.at(3)=="port") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for binary and time */ if(command.at(2)=="binary" && command.at(3)=="time") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for integer and time */ if(command.at(2)=="integer" && command.at(3)=="time") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for hex and time */ if(command.at(2)=="hex" && command.at(3)=="time") { errorStream << "Not yet implemented!" << endl; return 1; } /** * Check value for cip and time */ if(command.at(2)=="cip" && command.at(3)=="time" && command.at(4)!="now") { errorStream << "Error: set_head(" << command.join(" ") << "): No valid header value!" << endl; man("usage set_head time"); return 1; } /** * Read file */ QString filePath; filePath = CIP_ROOT; filePath += "/" + command.at(1); qDebug() << "filePath: " << filePath << endl; QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { errorStream << "Error: set_head(" << command.join(" ") << ") can not read " << filePath << endl; return 1; } QByteArray byteArray; byteArray = file.readAll(); file.close(); qDebug() << "byteArray.size(): " << byteArray.size() << endl; /** * Define map with start position */ QMap<QString, int> keys; int pos; keys["request"] = 0; keys["profile"] = 1; keys["version"] = 2; keys["channel"] = 3; keys["uuid"] = 4; keys["ip"] = 20; keys["port"] = 24; keys["time"] = 26; keys["type"] = 34; keys["size"] = 35; QByteArray value; bool ok; /** * One byte keys (without size) */ if(command.at(3).contains(QRegExp("^(request|profile|version|channel|type|size)$"))) { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; if(command.at(2)=="binary") { value.append(command.at(4).toUInt(&ok, 2)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 2!" << endl; return 1; } } if(command.at(2)=="integer") { value.append(command.at(4).toUInt(&ok, 10)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 10!" << endl; return 1; } } if(command.at(2)=="hex") { value.append(command.at(4).toUInt(&ok, 16)); if(!ok) { errorStream << "Cannot convert "<< command.at(4) << " to base 16!" << endl; return 1; } } if(command.at(2)=="cip") { errorStream << "Not yet specified!" << endl; return 1; } pos = keys[command.at(3)]; qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl; byteArray.replace(pos, 1, value); } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } } /** * uuid (16) */ if(command.at(3)=="uuid") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; value.append(command.at(4).toLatin1()); value.insert(20, '-'); value.insert(16, '-'); value.insert(12, '-'); value.insert(8, '-'); qDebug() << "value: " << value << endl; QUuid uuid(value); pos = keys[command.at(3)]; qDebug() << "byteArray.replace(" << pos << ", 16, " << uuid << ")" << endl; byteArray.replace(pos, 16, uuid.toRfc4122()); } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } } /** * ip (4) */ if(command.at(3)=="ip") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } errorStream << "Not yet implemented!" << endl; return 1; } /** * port (2) */ if(command.at(3)=="port") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } errorStream << "Not yet implemented!" << endl; return 1; } /** * time (8) */ if(command.at(3)=="time") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } uint unixTime = QDateTime::currentDateTime().toTime_t(); qDebug().noquote().nospace() << "NOW: " << QDateTime::fromTime_t(unixTime).toString() << endl; pos = keys[command.at(3)]; for(int j = 0; j < 8; j++) { byteArray[pos++] = unixTime%256; qDebug().noquote().nospace() << "time[" << j << "]: " << QString("%1").arg(unixTime%256, 8, 2, QLatin1Char('0')); unixTime = unixTime >> 8; } } /** * size (1) */ if(command.at(3)=="size") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } pos = keys[command.at(3)]; qDebug() << "byteArray.replace(" << pos << ", 1, " << value << ")" << endl; byteArray.replace(pos, 1, value); } /** * data (size) */ if(command.at(3)=="data") { if (keys.contains(command.at(3))) { qDebug() << "keys.contains(" << command.at(3) << ")" << endl; } else { errorStream << "Cannot find key for "<< command.at(3) << "!" << endl; return 1; } errorStream << "Not yet implemented!" << endl; return 1; } /** * Write file */ if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { errorStream << "Error: set_head(" << command.join(" ") << ") can not write to file " << filePath << endl; return 1; } file.write(byteArray); file.close(); qDebug() << "filePath: " << filePath << endl; return 0; }
int main (int argc, char **argv) { Q330 q330; Q330_ADDR addr; init(argc, argv, &q330); switch (q330.cmd.code) { case Q330_CMD_REBOOT: boot(&q330); break; case Q330_CMD_SAVE: save(&q330); break; case Q330_CMD_SAVEBOOT: save(&q330); sleep(5); boot(&q330); break; case Q330_CMD_RESYNC: resync(&q330); break; case Q330_CMD_GPS_ON: gpsON(&q330); break; case Q330_CMD_GPS_OFF: gpsOFF(&q330); break; case Q330_CMD_GPS_COLD: gpsColdStart(&q330); break; case Q330_CMD_GPS_CNF: gpsCnf(&q330); break; case Q330_CMD_GPS_ID: gpsId(&q330); break; case Q330_CMD_CAL_START: calStart(&q330); break; case Q330_CMD_CAL_STOP: calStop(&q330); break; case Q330_CMD_IFCONFIG: ifconfig(&q330); break; case Q330_CMD_STATUS: status(&q330); break; case Q330_CMD_FIX: fix(&q330); break; case Q330_CMD_GLOB: glob(&q330); break; case Q330_CMD_SC: sc(&q330); break; case Q330_CMD_PULSE: pulse(&q330); break; case Q330_CMD_AMASS: amass(&q330); break; case Q330_CMD_DCP: dcp(&q330); break; case Q330_CMD_SPP: spp(&q330); break; case Q330_CMD_MAN: man(&q330); break; case Q330_CMD_CO: checkout(&q330); break; default: fprintf(stderr, "ERROR: command '%s' is unsupported\n", q330.cmd.name); break; } if (q330.qdp != NULL) qdpDeregister(q330.qdp, TRUE); }
//afisare Mandelbrot void Display8() { double x; double y; Mandelbrot man(0,0,1); glBegin(GL_POINTS); for(x=-2;x<2;x+=0.01) for(y=-2;y<2;y+=0.01) { man=Mandelbrot(x,y,100); man.trym(); if(man.ism==0) { if(man.iter<2) glColor3f(0,0,0); else if(man.iter<3) glColor3f(0.1,0,0); else if(man.iter<5) glColor3f(0.2,0,0); else if(man.iter<10) glColor3f(0.4,0,0); else if(man.iter<15) glColor3f(0.6,0,0); else if(man.iter<20) glColor3f(0.8,0,0); glVertex2d(x/2, y/2); } else { glColor3f(1,0.5,0.5); glVertex2d(x/2, y/2); } } glEnd(); /* char cx[3]; sprintf(cx, "%2d", x); char cy[3]; sprintf(cy, "%2d", y); glRasterPos2d(-0.98,-0.98); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, '('); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, cx[0]); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, cx[1]); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ','); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, cy[0]); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, cy[1]); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ')'); */ glRasterPos2d(-1.0,0.9); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'M'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'u'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'l'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 't'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'i'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'm'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'e'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'a'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ' '); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'M'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'a'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'n'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'd'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'e'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, '1'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'b'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'r'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'o'); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 't'); }
RClient::ParseStatus RClient::parse(int &argc, char **argv) { Rct::findExecutablePath(*argv); mSocketFile = Path::home() + ".rdm"; List<option> options; options.reserve(sizeof(opts) / sizeof(Option)); List<std::shared_ptr<QueryCommand> > projectCommands; String shortOptionString; Hash<int, Option*> shortOptions, longOptions; for (int i=0; opts[i].description; ++i) { if (opts[i].option != None) { const option opt = { opts[i].longOpt, opts[i].argument, 0, opts[i].shortOpt }; if (opts[i].shortOpt) { shortOptionString.append(opts[i].shortOpt); switch (opts[i].argument) { case no_argument: break; case required_argument: shortOptionString.append(':'); break; case optional_argument: shortOptionString.append("::"); break; } assert(!shortOptions.contains(opts[i].shortOpt)); shortOptions[opts[i].shortOpt] = &opts[i]; } if (opts[i].longOpt) longOptions[options.size()] = &opts[i]; options.push_back(opt); } } if (getenv("RTAGS_DUMP_UNUSED")) { String unused; for (int i=0; i<26; ++i) { if (!shortOptionString.contains('a' + i)) unused.append('a' + i); if (!shortOptionString.contains('A' + i)) unused.append('A' + i); } printf("Unused: %s\n", unused.constData()); for (int i=0; opts[i].description; ++i) { if (opts[i].longOpt) { if (!opts[i].shortOpt) { printf("No shortoption for %s\n", opts[i].longOpt); } else if (opts[i].longOpt[0] != opts[i].shortOpt) { printf("Not ideal option for %s|%c\n", opts[i].longOpt, opts[i].shortOpt); } } } return Parse_Ok; } { const option opt = { 0, 0, 0, 0 }; options.push_back(opt); } Path logFile; Flags<LogFileFlag> logFlags; enum State { Parsing, Done, Error } state = Parsing; while (true) { int idx = -1; const int c = getopt_long(argc, argv, shortOptionString.constData(), options.data(), &idx); switch (c) { case -1: state = Done; break; case '?': case ':': state = Error; break; default: break; } if (state != Parsing) break; const Option *opt = (idx == -1 ? shortOptions.value(c) : longOptions.value(idx)); assert(opt); if (!isatty(STDOUT_FILENO)) { mQueryFlags |= QueryMessage::NoColor; } switch (opt->option) { case None: case NumOptions: assert(0); break; case Help: help(stdout, argv[0]); return Parse_Ok; case Man: man(); return Parse_Ok; case SocketFile: mSocketFile = optarg; break; case GuessFlags: mGuessFlags = true; break; case Wait: mQueryFlags |= QueryMessage::Wait; break; case IMenu: mQueryFlags |= QueryMessage::IMenu; break; case CompilationFlagsOnly: mQueryFlags |= QueryMessage::CompilationFlagsOnly; break; case NoColor: mQueryFlags |= QueryMessage::NoColor; break; case CompilationFlagsSplitLine: mQueryFlags |= QueryMessage::CompilationFlagsSplitLine; break; case ContainingFunction: mQueryFlags |= QueryMessage::ContainingFunction; break; case ContainingFunctionLocation: mQueryFlags |= QueryMessage::ContainingFunctionLocation; break; case DeclarationOnly: mQueryFlags |= QueryMessage::DeclarationOnly; break; case DefinitionOnly: mQueryFlags |= QueryMessage::DefinitionOnly; break; case FindVirtuals: mQueryFlags |= QueryMessage::FindVirtuals; break; case FindFilePreferExact: mQueryFlags |= QueryMessage::FindFilePreferExact; break; case SymbolInfoIncludeParents: mQueryFlags |= QueryMessage::SymbolInfoIncludeParents; break; case SymbolInfoExcludeTargets: mQueryFlags |= QueryMessage::SymbolInfoExcludeTargets; break; case SymbolInfoExcludeReferences: mQueryFlags |= QueryMessage::SymbolInfoExcludeReferences; break; case CursorKind: mQueryFlags |= QueryMessage::CursorKind; break; case SynchronousCompletions: mQueryFlags |= QueryMessage::SynchronousCompletions; break; case DisplayName: mQueryFlags |= QueryMessage::DisplayName; break; case AllReferences: mQueryFlags |= QueryMessage::AllReferences; break; case AllTargets: mQueryFlags |= QueryMessage::AllTargets; break; case MatchCaseInsensitive: mQueryFlags |= QueryMessage::MatchCaseInsensitive; break; case MatchRegex: mQueryFlags |= QueryMessage::MatchRegex; break; case AbsolutePath: mQueryFlags |= QueryMessage::AbsolutePath; break; case ReverseSort: mQueryFlags |= QueryMessage::ReverseSort; break; case Rename: mQueryFlags |= QueryMessage::Rename; break; case Elisp: mQueryFlags |= QueryMessage::Elisp; break; case FilterSystemHeaders: mQueryFlags |= QueryMessage::FilterSystemIncludes; break; case NoContext: mQueryFlags |= QueryMessage::NoContext; break; case PathFilter: { Path p = optarg; p.resolve(); mPathFilters.insert({ p, QueryMessage::PathFilter::Self }); break; } case DependencyFilter: { Path p = optarg; p.resolve(); if (!p.isFile()) { fprintf(stderr, "%s doesn't seem to be a file\n", optarg); return Parse_Error; } mPathFilters.insert({ p, QueryMessage::PathFilter::Dependency }); break; } case KindFilter: mKindFilters.insert(optarg); break; case WildcardSymbolNames: mQueryFlags |= QueryMessage::WildcardSymbolNames; break; case RangeFilter: { char *end; mMinOffset = strtoul(optarg, &end, 10); if (*end != '-') { fprintf(stderr, "Can't parse range, must be uint-uint. E.g. 1-123\n"); return Parse_Error; } mMaxOffset = strtoul(end + 1, &end, 10); if (*end) { fprintf(stderr, "Can't parse range, must be uint-uint. E.g. 1-123\n"); return Parse_Error; } if (mMaxOffset <= mMinOffset || mMinOffset < 0) { fprintf(stderr, "Invalid range (%d-%d), must be uint-uint. E.g. 1-123\n", mMinOffset, mMaxOffset); return Parse_Error; } break; } case Version: fprintf(stdout, "%s\n", RTags::versionString().constData()); return Parse_Ok; case Verbose: ++mLogLevel; break; case PrepareCodeCompleteAt: case CodeCompleteAt: { const String encoded = Location::encode(optarg); if (encoded.isEmpty()) { fprintf(stderr, "Can't resolve argument %s\n", optarg); return Parse_Error; } addQuery(opt->option == CodeCompleteAt ? QueryMessage::CodeCompleteAt : QueryMessage::PrepareCodeCompleteAt, encoded); break; } case Silent: mLogLevel = LogLevel::None; break; case LogFile: logFile = optarg; break; case StripParen: mQueryFlags |= QueryMessage::StripParentheses; break; case DumpIncludeHeaders: mQueryFlags |= QueryMessage::DumpIncludeHeaders; break; case SilentQuery: mQueryFlags |= QueryMessage::SilentQuery; break; case BuildIndex: { bool ok; mBuildIndex = String(optarg).toULongLong(&ok); if (!ok) { fprintf(stderr, "--build-index [arg] must be >= 0\n"); return Parse_Error; } break; } case ConnectTimeout: mConnectTimeout = atoi(optarg); if (mConnectTimeout < 0) { fprintf(stderr, "--connect-timeout [arg] must be >= 0\n"); return Parse_Error; } break; case Max: mMax = atoi(optarg); if (mMax < 0) { fprintf(stderr, "-M [arg] must be >= 0\n"); return Parse_Error; } break; case Timeout: mTimeout = atoi(optarg); if (!mTimeout) { mTimeout = -1; } else if (mTimeout < 0) { fprintf(stderr, "-y [arg] must be >= 0\n"); return Parse_Error; } break; case UnsavedFile: { const String arg(optarg); const int colon = arg.lastIndexOf(':'); if (colon == -1) { fprintf(stderr, "Can't parse -u [%s]\n", optarg); return Parse_Error; } const int bytes = atoi(arg.constData() + colon + 1); if (!bytes) { fprintf(stderr, "Can't parse -u [%s]\n", optarg); return Parse_Error; } const Path path = Path::resolved(arg.left(colon)); if (!path.isFile()) { fprintf(stderr, "Can't open [%s] for reading\n", arg.left(colon).nullTerminated()); return Parse_Error; } String contents(bytes, '\0'); const int r = fread(contents.data(), 1, bytes, stdin); if (r != bytes) { fprintf(stderr, "Read error %d (%s). Got %d, expected %d\n", errno, Rct::strerror(errno).constData(), r, bytes); return Parse_Error; } mUnsavedFiles[path] = contents; break; } case FollowLocation: case SymbolInfo: case ClassHierarchy: case ReferenceLocation: { const String encoded = Location::encode(optarg); if (encoded.isEmpty()) { fprintf(stderr, "Can't resolve argument %s\n", optarg); return Parse_Error; } QueryMessage::Type type = QueryMessage::Invalid; switch (opt->option) { case FollowLocation: type = QueryMessage::FollowLocation; break; case SymbolInfo: type = QueryMessage::SymbolInfo; break; case ReferenceLocation: type = QueryMessage::ReferencesLocation; break; case ClassHierarchy: type = QueryMessage::ClassHierarchy; break; default: assert(0); break; } addQuery(type, encoded, QueryMessage::HasLocation); break; } case CurrentFile: mCurrentFile.append(Path::resolved(optarg)); break; case ReloadFileManager: addQuery(QueryMessage::ReloadFileManager); break; case DumpCompletions: addQuery(QueryMessage::DumpCompletions); break; case DumpCompilationDatabase: addQuery(QueryMessage::DumpCompilationDatabase); break; case Clear: addQuery(QueryMessage::ClearProjects); break; case RdmLog: addLog(RdmLogCommand::Default); break; case Diagnostics: addLog(RTags::Diagnostics); break; case QuitRdm: { const char *arg = 0; if (optarg) { arg = optarg; } else if (optind < argc && argv[optind][0] != '-') { arg = argv[optind++]; } int exit = 0; if (arg) { bool ok; exit = String(arg).toLongLong(&ok); if (!ok) { fprintf(stderr, "Invalid argument to -q\n"); return Parse_Error; } } addQuitCommand(exit); break; } case DeleteProject: addQuery(QueryMessage::DeleteProject, optarg); break; case SendDiagnostics: addQuery(QueryMessage::SendDiagnostics, optarg); break; case FindProjectRoot: { const Path p = Path::resolved(optarg); printf("findProjectRoot [%s] => [%s]\n", p.constData(), RTags::findProjectRoot(p, RTags::SourceRoot).constData()); return Parse_Ok; } case FindProjectBuildRoot: { const Path p = Path::resolved(optarg); printf("findProjectRoot [%s] => [%s]\n", p.constData(), RTags::findProjectRoot(p, RTags::BuildRoot).constData()); return Parse_Ok; } case RTagsConfig: { const Path p = Path::resolved(optarg); Map<String, String> config = RTags::rtagsConfig(p); printf("rtags-config: %s:\n", p.constData()); for (const auto &it : config) { printf("%s: \"%s\"\n", it.first.constData(), it.second.constData()); } return Parse_Ok; } case CurrentProject: addQuery(QueryMessage::Project, String(), QueryMessage::CurrentProjectOnly); break; case CheckReindex: case Reindex: case Project: case FindFile: case ListSymbols: case FindSymbols: case Sources: case IncludeFile: case JobCount: case Status: { Flags<QueryMessage::Flag> extraQueryFlags; QueryMessage::Type type = QueryMessage::Invalid; bool resolve = true; switch (opt->option) { case CheckReindex: type = QueryMessage::CheckReindex; break; case Reindex: type = QueryMessage::Reindex; break; case Project: type = QueryMessage::Project; break; case FindFile: type = QueryMessage::FindFile; resolve = false; break; case Sources: type = QueryMessage::Sources; break; case IncludeFile: type = QueryMessage::IncludeFile; resolve = false; break; case Status: type = QueryMessage::Status; break; case ListSymbols: type = QueryMessage::ListSymbols; break; case FindSymbols: type = QueryMessage::FindSymbols; break; case JobCount: type = QueryMessage::JobCount; break; default: assert(0); break; } const char *arg = 0; if (optarg) { arg = optarg; } else if (optind < argc && argv[optind][0] != '-') { arg = argv[optind++]; } if (arg) { Path p(arg); if (resolve && p.exists()) { p.resolve(); addQuery(type, p, extraQueryFlags); } else { addQuery(type, arg, extraQueryFlags); } } else { addQuery(type, String(), extraQueryFlags); } assert(!mCommands.isEmpty()); if (type == QueryMessage::Project) projectCommands.append(std::static_pointer_cast<QueryCommand>(mCommands.back())); break; } case ListBuffers: addQuery(QueryMessage::SetBuffers); break; case SetBuffers: { const char *arg = 0; if (optarg) { arg = optarg; } else if (optind < argc && (argv[optind][0] != '-' || !strcmp(argv[optind], "-"))) { arg = argv[optind++]; } String encoded; if (arg) { List<Path> paths; auto addBuffer = [&paths](const String &p) { if (p.isEmpty()) return; Path path(p); if (path.resolve() && path.isFile()) { paths.append(path); } else { fprintf(stderr, "\"%s\" doesn't seem to be a file.\n", p.constData()); } }; if (!strcmp(arg, "-")) { char buf[1024]; while (fgets(buf, sizeof(buf), stdin)) { String arg(buf); if (arg.endsWith('\n')) arg.chop(1); addBuffer(arg); } } else { for (const String &buffer : String(arg).split(';')) { addBuffer(buffer); } } Serializer serializer(encoded); serializer << paths; } addQuery(QueryMessage::SetBuffers, encoded); break; } case LoadCompilationDatabase: { #if CLANG_VERSION_MAJOR > 3 || (CLANG_VERSION_MAJOR == 3 && CLANG_VERSION_MINOR > 3) Path dir; if (optarg) { dir = optarg; } else if (optind < argc && argv[optind][0] != '-') { dir = argv[optind++]; } else { dir = Path::pwd(); } dir.resolve(Path::MakeAbsolute); if (!dir.exists()) { fprintf(stderr, "%s does not seem to exist\n", dir.constData()); return Parse_Error; } if (!dir.isDir()) { if (dir.isFile() && dir.endsWith("/compile_commands.json")) { dir = dir.parentDir(); } else { fprintf(stderr, "%s is not a directory\n", dir.constData()); return Parse_Error; } } if (!dir.endsWith('/')) dir += '/'; const Path file = dir + "compile_commands.json"; if (!file.isFile()) { fprintf(stderr, "no compile_commands.json file in %s\n", dir.constData()); return Parse_Error; } addCompile(dir, Escape_Auto); #endif break; } case HasFileManager: { Path p; if (optarg) { p = optarg; } else if (optind < argc && argv[optind][0] != '-') { p = argv[optind++]; } else { p = "."; } p.resolve(Path::MakeAbsolute); if (!p.exists()) { fprintf(stderr, "%s does not seem to exist\n", optarg); return Parse_Error; } if (p.isDir()) p.append('/'); addQuery(QueryMessage::HasFileManager, p); break; } case ProjectRoot: { Path p = optarg; if (!p.isDir()) { fprintf(stderr, "%s does not seem to be a directory\n", optarg); return Parse_Error; } p.resolve(Path::MakeAbsolute); mProjectRoot = p; break; } case Suspend: { Path p; if (optarg) { p = optarg; } else if (optind < argc && argv[optind][0] != '-') { p = argv[optind++]; } if (!p.isEmpty()) { if (p != "clear" && p != "all") { p.resolve(Path::MakeAbsolute); if (!p.isFile()) { fprintf(stderr, "%s is not a file\n", optarg); return Parse_Error; } } } addQuery(QueryMessage::Suspend, p); break; } case Compile: { String args = optarg; while (optind < argc) { if (!args.isEmpty()) args.append(' '); args.append(argv[optind++]); } if (args == "-" || args.isEmpty()) { char buf[16384]; while (fgets(buf, sizeof(buf), stdin)) { addCompile(Path::pwd(), buf, Escape_Do); } } else { addCompile(Path::pwd(), args, Escape_Dont); } break; } case IsIndexing: addQuery(QueryMessage::IsIndexing); break; case UnescapeCompileCommands: mEscapeMode = Escape_Do; break; case NoUnescapeCompileCommands: mEscapeMode = Escape_Dont; break; case NoSortReferencesByInput: mQueryFlags |= QueryMessage::NoSortReferencesByInput; break; case IsIndexed: case DumpFile: case CheckIncludes: case GenerateTest: case Diagnose: case FixIts: { Path p = optarg; if (!p.exists()) { fprintf(stderr, "%s does not exist\n", optarg); return Parse_Error; } if (!p.isAbsolute()) p.prepend(Path::pwd()); if (p.isDir()) { if (opt->option != IsIndexed) { fprintf(stderr, "%s is not a file\n", optarg); return Parse_Error; } else if (!p.endsWith('/')) { p.append('/'); } } p.resolve(); Flags<QueryMessage::Flag> extraQueryFlags; QueryMessage::Type type = QueryMessage::Invalid; switch (opt->option) { case GenerateTest: type = QueryMessage::GenerateTest; break; case FixIts: type = QueryMessage::FixIts; break; case DumpFile: type = QueryMessage::DumpFile; break; case CheckIncludes: type = QueryMessage::DumpFile; extraQueryFlags |= QueryMessage::DumpCheckIncludes; break; case Diagnose: type = QueryMessage::Diagnose; break; case IsIndexed: type = QueryMessage::IsIndexed; break; default: assert(0); break; } addQuery(type, p, extraQueryFlags); break; } case AllDependencies: { String encoded; List<String> args; while (optind < argc && argv[optind][0] != '-') { args.append(argv[optind++]); } Serializer s(encoded); s << Path() << args; addQuery(QueryMessage::Dependencies, encoded); break; } case DumpFileMaps: case Dependencies: { Path p = optarg; if (!p.isFile()) { fprintf(stderr, "%s is not a file\n", optarg); return Parse_Error; } p.resolve(); List<String> args; while (optind < argc && argv[optind][0] != '-') { args.append(argv[optind++]); } String encoded; Serializer s(encoded); s << p << args; addQuery(opt->option == DumpFileMaps ? QueryMessage::DumpFileMaps : QueryMessage::Dependencies, encoded); break; } case PreprocessFile: { Path p = optarg; p.resolve(Path::MakeAbsolute); if (!p.isFile()) { fprintf(stderr, "%s is not a file\n", optarg); return Parse_Error; } addQuery(QueryMessage::PreprocessFile, p); break; } case RemoveFile: { const Path p = Path::resolved(optarg, Path::MakeAbsolute); if (!p.exists()) { addQuery(QueryMessage::RemoveFile, p); } else { addQuery(QueryMessage::RemoveFile, optarg); } break; } case ReferenceName: addQuery(QueryMessage::ReferencesName, optarg); break; } } if (state == Error) { help(stderr, argv[0]); return Parse_Error; } if (optind < argc) { fprintf(stderr, "rc: unexpected option -- '%s'\n", argv[optind]); return Parse_Error; } if (!initLogging(argv[0], LogStderr, mLogLevel, logFile, logFlags)) { fprintf(stderr, "Can't initialize logging with %d %s %s\n", mLogLevel.toInt(), logFile.constData(), logFlags.toString().constData()); return Parse_Error; } if (mCommands.isEmpty()) { help(stderr, argv[0]); return Parse_Error; } if (mCommands.size() > projectCommands.size()) { // If there's more than one command one likely does not want output from // the queryCommand (unless there's no arg specified for it). This is so // we don't have to pass a different flag for auto-updating project // using the current buffer but rather piggy-back on --project const int count = projectCommands.size(); for (int i=0; i<count; ++i) { std::shared_ptr<QueryCommand> &cmd = projectCommands[i]; if (!cmd->query.isEmpty()) { cmd->extraQueryFlags |= QueryMessage::Silent; } } } if (!logFile.isEmpty() || mLogLevel > LogLevel::Error) { Log l(LogLevel::Warning); l << argc; for (int i = 0; i < argc; ++i) l << " " << argv[i]; } mArgc = argc; mArgv = argv; return Parse_Exec; }