/* solve the problem */ int main (int argc, char *argv[]) { int p, q, l, r, loop, result; int **schedules; if (debug_on) printf("\nP7 - Chat Online:\n"); schedules = readArgs(&p, &q, &l, &r, argc, argv); if (debug_on) printArgs(p,q,l,r,schedules); if (p<1 || p>50 || q<1 || q>50 || l<0 || l>1000 || r<0 || r>1000) { printf("Invalid schedules. Aborting...\n"); printf("\n--------------------\n"); return 1; } if (debug_on) printf("\nProblem Solution:\n"); result = 0; for (loop=l; loop<=r; loop++) { if (momentSuits(loop,p,q,schedules) == true) result++; } printf("%d", result); if (debug_on) printf("\n--------------------\n"); return 0; }
/* solve the problem */ int main (int argc, char *argv[]) { int n; long wallsToPaint; char labyrinth[MAX_SIZE][MAX_SIZE]; int wasProcessed[MAX_SIZE][MAX_SIZE]; #ifdef debug_on printf("\nP12 - Labyrinth:\n"); #endif n = readArgs(labyrinth, argc, argv); #ifdef debug_on printArgs(n,labyrinth); printf("\nProblem Solution:\n"); #endif /* Solution */ wallsToPaint = process(0,0,n,labyrinth,wasProcessed); if (wasProcessed[n-1][n-1] == 0) wallsToPaint += process(n-1,n-1,n,labyrinth,wasProcessed); printf("%ld\n", 3*3*wallsToPaint); #ifdef debug_on printf("\n--------------------\n"); #endif return 0; }
/** * \brief Main function * \details -- * \param int argc * \param char const** argv * \return \e int */ int main( int argc, char const** argv ) { /*------------------------------------------------*/ /* 1) read command line arguments */ /*------------------------------------------------*/ size_t backup_start = 0; size_t backup_end = 0; size_t backup_step = 0; readArgs(argc, argv, backup_start, backup_end, backup_step); /*------------------------------------------------*/ /* 2) print header */ /*------------------------------------------------*/ printHeader(); /*------------------------------------------------*/ /* 3) recover the simulation state at each backup */ /*------------------------------------------------*/ std::ofstream file("./statistics/SL_diversity.txt", std::ios::out | std::ios::trunc); file << "backup SpA SpB\n"; size_t current_step = backup_start; while (current_step <= backup_end) { std::cout << "> Working with backup " << current_step << " ...\n"; /*----------------------------------------*/ /* 3.1) Open the backups */ /*----------------------------------------*/ Parameters* parameters = new Parameters(current_step); Simulation* simulation = new Simulation(parameters, current_step, false); simulation->initialize(FROM_BACKUP); /*----------------------------------------*/ /* 3.2) Compute SL diversity and write it */ /*----------------------------------------*/ double Sp_A = 0.0; double Sp_B = 0.0; double depth = (double)current_step-simulation->get_phylogenetic_tree()->get_common_ancestor_age(); simulation->get_phylogenetic_tree()->compute_common_ancestor_SL_repartition(Sp_A, Sp_B); if (Sp_A != -1.0 && Sp_B != -1.0) { file << current_step << " " << Sp_A << " " << Sp_B << " " << depth << "\n"; } /*----------------------------------------*/ /* 3.3) Free memory */ /*----------------------------------------*/ delete simulation; simulation = NULL; delete parameters; parameters = NULL; current_step += backup_step; } file.close(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { int* args = readArgs(argc, argv); if(args[0]) decode(); else encode(args); free(args); return 0; }
// // SourceTokenizerC::expand // // Expands a token. // void SourceTokenizerC::expand(MacroVec &out, std::set<std::string> &used, SourcePosition const &pos, SourceTokenC::Reference tok, SourceStream *in, MacroArgs const *altArgs, MacroParm const *altParm) { // Check for function-like macro expansion. // That is, a function-like macro name followed by an open parenthesis. // And of course, that name must not have been expanded yet. if(tok->type == SourceTokenC::TT_PAREN_O && !out.empty() && out.back()->type == SourceTokenC::TT_NAM && hasMacro(out.back()->data) && !used.count(out.back()->data)) { tok = out.back(); out.pop_back(); MacroData const &mdata = macros[tok->data]; MacroArgs margs; readArgs(margs, in, mdata, pos, altArgs, altParm); used.insert(tok->data); expand(out, used, pos, mdata, margs); used.erase(tok->data); return; } // Check for object-like macro expansion. // Like above, but it only needs one token to trigger. if(tok->type == SourceTokenC::TT_NAM && hasDefine(tok->data) && !used.count(tok->data)) { used.insert(tok->data); expand(out, used, pos, defines[tok->data]); used.erase(tok->data); return; } // Then check for __FILE__ specifically. if(tok->type == SourceTokenC::TT_NAM && tok->data == "__FILE__") { out.push_back(SourceTokenC::create(pos, pos.filename, SourceTokenC::TT_STR)); return; } // And __LINE__. if(tok->type == SourceTokenC::TT_NAM && tok->data == "__LINE__") { std::ostringstream oss; oss << pos.line; out.push_back(SourceTokenC::create(pos, oss.str(), SourceTokenC::TT_INT)); return; } // If it actually isn't any of those things, then consider the token expanded. out.push_back(tok); }
int main (int argc, char* argv[]) { int status; Ice::CommunicatorPtr ic; try { ic = Ice::initialize(argc, argv); readArgs(&argc, argv); // Contact to Encoders Ice::ObjectPrx Encoders = ic->propertyToProxy("automata.Encoders.Proxy"); if (Encoders == 0) throw "Could not create proxy with Encoders"; Encodersprx = jderobot::EncodersPrx::checkedCast(Encoders); if (Encodersprx == 0) throw "Invalid proxy automata.Encoders.Proxy"; std::cout << "Encoders connected" << std::endl; // Contact to Motors Ice::ObjectPrx Motors = ic->propertyToProxy("automata.Motors.Proxy"); if (Motors == 0) throw "Could not create proxy with Motors"; Motorsprx = jderobot::MotorsPrx::checkedCast(Motors); if (Motorsprx == 0) throw "Invalid proxy automata.Motors.Proxy"; std::cout << "Motors connected" << std::endl; if (displayGui){ automatagui = new AutomataGui(argc, argv); displayGui = showAutomataGui(); } pthread_create(&thr_sub_1, NULL, &subautomata_1, NULL); pthread_create(&thr_sub_2, NULL, &subautomata_2, NULL); pthread_create(&thr_sub_3, NULL, &subautomata_3, NULL); pthread_join(thr_sub_1, NULL); pthread_join(thr_sub_2, NULL); pthread_join(thr_sub_3, NULL); if (displayGui) pthread_join(thr_automatagui, NULL); } catch ( const Ice::Exception& ex ) { std::cerr << ex << std::endl; status = 1; } catch ( const char* msg ) { std::cerr << msg << std::endl; status = 1; } if (ic) ic->destroy(); return status; }
int main(int argc, char *argv[]) { #ifdef _WIN32 WSADATA wsaData; int result = WSAStartup(MAKEWORD(1, 1), &wsaData); if (result != 0) { fprintf(stderr, "Your computer was not connected " "to the Internet at the time that " "this program was launched, or you " "do not have a 32-bit " "connection to the Internet."); exit(1); } #else openlog("rinetd", LOG_PID, LOG_DAEMON); #endif readArgs(argc, argv, &options); #if HAVE_DAEMON && !DEBUG if (!options.foreground && daemon(0, 0) != 0) { exit(0); } #elif HAVE_FORK && !DEBUG if (!options.foreground && fork() != 0) { exit(0); } #endif #if HAVE_SIGACTION struct sigaction act; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = SA_RESTART; sigaction(SIGPIPE, &act, NULL); act.sa_handler = &hup; sigaction(SIGHUP, &act, NULL); #elif !_WIN32 signal(SIGPIPE, plumber); signal(SIGHUP, hup); #endif signal(SIGINT, quit); signal(SIGTERM, quit); readConfiguration(); registerPID(); syslog(LOG_INFO, "Starting redirections..."); while (1) { selectPass(); } return 0; }
int main (int argc, const char * argv[]) { int port = DEFAULT_PORT; int bufferSize = DEFAULT_BUFFER_SIZE; bool isQuiet = DEFAULT_QUIET; bool isDebug = DEFAULT_DEBUG; int maxClient = DEFAULT_MAXCLIENT; signal(SIGINT, signalHandler); signal(SIGTERM, signalHandler); readArgs(argc,argv,&port,&bufferSize,&isQuiet,&isDebug,&maxClient); logger.setQuiet(isQuiet); logger.setDebug(isDebug); if(!isQuiet) { printInfo(port,bufferSize,isDebug,maxClient); } List<Client*> list; sf::Mutex listMutex; sf::SocketSelector selector; Buffer exchangeBuffer; setupExchangeBuffer(&exchangeBuffer, bufferSize); logger.printLog("Init'ed ..."); ClientsContainer container(&list,&listMutex,&selector); sf::Thread answerThread(&answerToClient,AnswerDataSet(&container,port,maxClient)); answerThread.launch(); sf::Thread checkThread(&checkForInputs,CheckDataSet(&container,&exchangeBuffer)); checkThread.launch(); while(1) //TODO graphic stats { if(checkStopThreads()) { break; } sf::sleep(sf::milliseconds(5)); } return 0; }
CollectionScanner::CollectionScanner( int &argc, char **argv ) : QCoreApplication( argc, argv ) , m_batch( false ) , m_importPlaylists( false ) , m_batchFolderTime() , m_recursively( false ) , m_incremental( false ) , m_restart( false ) , m_amarokCollectionInterface( 0 ) { setObjectName( "amarokcollectionscanner" ); //seed for unique id generation if file lookup fails srand( (unsigned)time( 0 ) ); s_time.start(); readArgs(); #ifdef TAGLIB_EXTRAS_FOUND TagLib::FileRef::addFileTypeResolver(new MP4FileTypeResolver); TagLib::FileRef::addFileTypeResolver(new ASFFileTypeResolver); TagLib::FileRef::addFileTypeResolver(new RealMediaFileTypeResolver); TagLib::FileRef::addFileTypeResolver(new AudibleFileTypeResolver); TagLib::FileRef::addFileTypeResolver(new WavFileTypeResolver); #endif m_logfile = ( m_batch ? ( m_incremental ? "amarokcollectionscanner_batchincrementalscan.log" : "amarokcollectionscanner_batchfullscan.log" ) : m_saveLocation + "collection_scan.log" ); if( !m_restart ) QFile::remove( m_logfile ); if( !m_collectionId.isEmpty() ) { if( m_amarokPid.isEmpty() ) m_amarokCollectionInterface = new QDBusInterface( "org.kde.amarok", "/SqlCollection/" + m_collectionId ); else m_amarokCollectionInterface = new QDBusInterface( "org.kde.amarok-" + m_amarokPid, "/SqlCollection/" + m_collectionId ); } if( m_batch && m_incremental ) { bool success = readBatchIncrementalFile(); if( !success ) return; } QTimer::singleShot( 0, this, SLOT( doJob() ) ); }
int main(int argc, char *argv[]) { char *inFile; /* Name of the file with image names one per line */ char *outFile; /* Name of the file to which results are written */ FSU* head = NULL; /* Head pointer to the linked list of subjects */ if (PRINT_LEVEL > 0) printf("\n%s\n%s", OPENNING, VERSION); readArgs(argc, argv, &inFile, &outFile); if (PRINT_LEVEL > 0) printf("\nReading from %s and building subject/replicates linked lists.", inFile); head = insertSubjectsFromFile(inFile); printSubjectReplicatesFile(head, outFile); if (PRINT_LEVEL > 0) printf("\nFinished. \n"); return 0; }
// // SourceTokenizerC::expandMacro // void SourceTokenizerC::expandMacro(SourceTokenC *tok) { MacroVec out; MacroArgs args; MacroData const &data = macros[tok->data]; std::set<std::string> used; // Process the arguments, preserving whitespace in TT_NONEs. readArgs(args, inStack.back(), data, tok->pos); // Invoke the macro expander, capturing the result in out. used.insert(tok->data); expand(out, used, tok->pos, data, args); used.erase(tok->data); // Push out onto the unget stack. for(MacroVec::iterator end = out.begin(), itr = out.end(); itr-- != end;) ungetStack.push_back(*itr); }
CollectionScanner::Scanner::Scanner( int &argc, char **argv ) : QCoreApplication( argc, argv ) , m_charset( false ) , m_newerTime(0) , m_incremental( false ) , m_recursively( false ) , m_restart( false ) , m_idlePriority( false ) { setObjectName( "amarokcollectionscanner" ); readArgs(); if( m_idlePriority ) { if( QThread::currentThread() ) QThread::currentThread()->setPriority( QThread::IdlePriority ); } }
int main(int argc, char** argv) { Inputs inputs = readArgs(argc, argv); auto begin = std::chrono::high_resolution_clock::now(); Result r; switch (inputs.algorithm) { case Algorithm::GREEDY: r = greedyAlgorithm(inputs); break; case Algorithm::DYNAMIC: r = dynamicAlgorithm(inputs); break; case Algorithm::LOCAL: r = localAlgorithm(inputs); break; default: std::cout << "Error, unknown algorithm" << std::endl; break; } auto end = std::chrono::high_resolution_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() / 1000000000.0; if (inputs.benchmark) { std::cout << r.revenu << std::endl << elapsed; } else { if (inputs.print) { std::cout << "Emplacements : "; for (auto loc : r.locations) { std::cout << loc.id << " "; } std::cout << std::endl << "Revenu : " << r.revenu << std::endl; } std::cout << "Temps : " << elapsed << "s" << std::endl; } }
int main(int argc, char *argv[]) { WSADATA wsaData; int result = WSAStartup(MAKEWORD(1, 1), &wsaData); if (result != 0) { fprintf(stderr, "Your computer was not connected " "to the Internet at the time that " "this program was launched, or you " "do not have a 32-bit " "connection to the Internet."); exit(1); } readArgs(argc, argv, &options); #ifndef WIN32 #ifndef DEBUG if (!fork()) { if (!fork()) { #endif /* DEBUG */ signal(SIGPIPE, plumber); signal(SIGHUP, hup); #endif /* WIN32 */ signal(SIGTERM, term); initArrays(); readConfiguration(); RegisterPID(); selectLoop(); #ifndef WIN32 #ifndef DEBUG } else { exit(0); } } else { exit(0); } #endif /* DEBUG */ #endif /* WIN32 */ return 0; }
int main(int argc, char *argv[]){ toCargs *pars; if(argc<12){ std::cout << "\t-> Please input -g GENOTYPEFILE -LD {0,1} -back BACK -threshold prune_val -filename OUTPUTDATA -snps KEEPLIST\n"; return 0; } //get commandline args pars = readArgs(argc,argv); pars->doPrune = 1; //check if fileexists if(fexists(pars->data_filename)){ printf("\t-> outputfile:%s exists, will exit\n",pars->data_filename.c_str()); return 0; } if(fexists(pars->usedSnps_filename)){ printf("\t-> outputfile:%s exists will exit\n",pars->usedSnps_filename.c_str()); return 0; } //run prune prune object; print_functionPars(pars); fromCres *fromObject = object.main_run(pars); //write results write_iMatrix_to_file(pars->data_filename,fromObject->data); write_iArray_to_file(pars->usedSnps_filename,fromObject->usedSnps); killArray(fromObject->usedSnps); killMatrix(fromObject->data); killMatrix(pars->data); return 0; }
int main () { signal(SIGINT,killChild); signal(SIGSTOP,stop); signal(SIGCHLD,children); int bg; char *in,*out; in = out = NULL; char *exec = readInput(&bg); char *command; while(strcmp(exec,"exit") != 0) { char **args = readArgs(exec,&in,&out); if(strcmp(args[0],"cd") == 0) { chdir(args[1]); } command = exec; run(args,bg,command,in,out); free(exec); exec = readInput(&bg); } }
void readCommand() { /* allocate files used for redirection of stderr, stdin, stdout */ char **file = calloc(3, sizeof(char*)); if (!file) { memoryError(); } for (int i = 0; i < 3; i++) { file[i] = calloc(MAX_INPUT_LENGTH + 1, sizeof(char)); if (!file[i]) { memoryError(); } } /* initialize status to designate different modes as identified in #defines */ status parseStatus = 0; char** args = readArgs(&parseStatus, file); /* determine whether shell should exit after executing command */ bool terminate = EOF_FOUND & parseStatus; //Bit masking is used to use a single value for status. switch(parseStatus & (INVALID_SYNTAX | INVALID_ESCAPE)){ case INVALID_SYNTAX: printf("Error: Invalid syntax.\n"); if (terminate) do_exit(); return; case INVALID_ESCAPE: printf("Error: Unrecognized escape sequence.\n"); if (terminate) do_exit(); return; } /* if "exit" is inputted, quit the shell */ if (args[0]) { if (args[1] == NULL && strncmp(args[0], EXIT_COMMAND, strlen(EXIT_COMMAND)) == 0) { do_exit(); } } int restore_stdout = 0; int restore_stdin = 0; int restore_stderr = 0; int f = -1; /* check if any redirection was requested and set up proper files */ if (parseStatus & REDIR_STDOUT) { /*open afile with read and write permissions for the user. */ /*Create it if needed, and truncate it if opened*/ f = open(file[STDOUT],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (f == -1) //-1 indicates that there was a problem with the file { printf("Error: Invalid syntax.\n"); if (terminate) {//if it is EOF, terminate do_exit(); } return; //otherwise, print another prompt } /*Open a file with the path "file" and the intention to read and write from it. */ /*If it does not exist create it and give read and write permissions to the user*/ restore_stdout = dup(STDOUT); //keep a copy of STDOUT close(STDOUT); //Close STDOUT dup(f); //Copy the same file descriptor but set it to the newly closed STDOUT close(f); //Close original file } if (parseStatus & REDIR_STDERR) { f = open(file[STDERR],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (f == -1) { printf("Error: Invalid syntax.\n"); if (terminate) { do_exit(); } return; } restore_stderr = dup(STDERR); //keep a copy of STDOUT close(STDERR); //Close STDOUT dup(f); //Copy the same file descriptor but set it to the newly closed STDOUT close(f); //Close original file } if (parseStatus & REDIR_STDIN)//type==(2<<STDIN)) { /*Do not create a file, as it would be empty and useless to STDIN*/ /*Open as read only because it is an input source*/ f = open(file[STDIN],O_RDONLY); if (f == -1) { printf("Error: Unable to open redirection file.\n"); if (terminate) { do_exit(); } return; } restore_stdin = dup(STDIN); close(STDIN); dup(f); close(f); } /* workaround to allow 'cd' command */ if(args[0] && strncmp(args[0], "cd", 2) == 0) { int error = 0; if(args[1]) error = chdir(args[1]); else error = chdir("/home"); if(error) printf("cd: %s: No such file or directory\n",args[1]); return; } pid_t parent = fork(); if (parent < 0) { printf("Error: process creation failed"); do_exit(); } /* if we are in the child process, execute the command */ else if (!parent) { if (execvp(args[0], args)) { if((*args)[0]) { printf("Error: "); switch(errno) { //based on values in `man errno` case 1: printf("Permission denied.\n"); break; case 2: printf("Command not found.\n"); break; case 13: printf("Permission denied.\n"); break; default: printf("Unkown error.\n"); break; } } } exit(0); } else { /* in parent, wait for child if not a background process */ if (!(parseStatus & BACKGROUND)) { waitpid(parent, NULL, 0); } if (terminate) { do_exit(); } } /* restore any file redirections as necessary */ if(restore_stdin) { close(STDIN); dup(restore_stdin); close(restore_stdin); } if(restore_stdout) { close(STDOUT); dup(restore_stdout); close(restore_stdout); } if(restore_stderr) { close(STDERR); dup(restore_stderr); close(restore_stderr); } /* free all allocated memory */ for (int i = 0; i < 3; i++) { free(file[i]); } free(file); deleteArgs(args); free(args); }
int main(int argc, char * const * argv) { ExitStatus result = EX_SOFTWARE; KcgenArgs toolArgs; Boolean fatal = false; /***** * Find out what the program was invoked as. */ progname = rindex(argv[0], '/'); if (progname) { progname++; // go past the '/' } else { progname = (char *)argv[0]; } /* Set the OSKext log callback right away. */ OSKextSetLogOutputFunction(&tool_log); /* Make the library not sort opened kexts by version for bundle ID lookups. */ _OSKextSetStrictRecordingByLastOpened(TRUE); /***** * Check if we were spawned by kextd, set up straightaway * for service log filtering, and hook up to ASL. */ if (getenv("KEXTD_SPAWNED")) { OSKextSetLogFilter(kDefaultServiceLogFilter | kOSKextLogKextOrGlobalMask, /* kernel? */ false); OSKextSetLogFilter(kDefaultServiceLogFilter | kOSKextLogKextOrGlobalMask, /* kernel? */ true); tool_openlog("com.apple.kcgen"); } /***** * Process args & check for permission to load. */ result = readArgs(&argc, &argv, &toolArgs); if (result != EX_OK) { if (result == kKcgenExitHelp) { result = EX_OK; } goto finish; } result = checkArgs(&toolArgs); if (result != EX_OK) { goto finish; } /* From here on out the default exit status is ok. */ result = EX_OK; /* The whole point of this program is to update caches, so let's not * try to read any (we'll briefly turn this back on when checking them). */ OSKextSetUsesCaches(false); /* If we're compressing the prelinked kernel, take care of that here * and exit. */ if (toolArgs.prelinkedKernelPath && !CFArrayGetCount(toolArgs.argURLs) && (toolArgs.compress || toolArgs.uncompress)) { result = compressPrelinkedKernel(toolArgs.prelinkedKernelPath, toolArgs.compress); goto finish; } /***** * Read the kexts we'll be working with; first the set of all kexts, then * the repository and named kexts for use with mkext-creation flags. */ if (toolArgs.printTestResults) { OSKextSetRecordsDiagnostics(kOSKextDiagnosticsFlagAll); } toolArgs.allKexts = OSKextCreateKextsFromURLs(kCFAllocatorDefault, toolArgs.argURLs); if (!toolArgs.allKexts || !CFArrayGetCount(toolArgs.allKexts)) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Error - no kernel extensions found."); result = EX_SOFTWARE; goto finish; } toolArgs.repositoryKexts = OSKextCreateKextsFromURLs(kCFAllocatorDefault, toolArgs.repositoryURLs); toolArgs.namedKexts = OSKextCreateKextsFromURLs(kCFAllocatorDefault, toolArgs.namedKextURLs); if (!toolArgs.repositoryKexts || !toolArgs.namedKexts) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Error - failed to read extensions."); result = EX_SOFTWARE; goto finish; } if (result != EX_OK) { goto finish; } if (toolArgs.prelinkedKernelPath) { result = createPrelinkedKernel(&toolArgs); if (result != EX_OK) { goto finish; } } finish: /* We're actually not going to free anything else because we're exiting! */ exit(result); SAFE_RELEASE(toolArgs.kextIDs); SAFE_RELEASE(toolArgs.argURLs); SAFE_RELEASE(toolArgs.repositoryURLs); SAFE_RELEASE(toolArgs.namedKextURLs); SAFE_RELEASE(toolArgs.allKexts); SAFE_RELEASE(toolArgs.repositoryKexts); SAFE_RELEASE(toolArgs.namedKexts); SAFE_RELEASE(toolArgs.kernelFile); SAFE_RELEASE(toolArgs.symbolDirURL); SAFE_FREE(toolArgs.prelinkedKernelPath); SAFE_FREE(toolArgs.kernelPath); return result; }
ExitStatus main(int argc, char * const * argv) { ExitStatus result = EX_OK; KextstatArgs toolArgs; CFDictionaryRef * kextInfoList = NULL; // must free CFIndex count, i; if (argv[0]) { progname = argv[0]; } /* Set the OSKext log callback right away. */ OSKextSetLogOutputFunction(&tool_log); result = readArgs(argc, argv, &toolArgs); if (result != EX_OK) { if (result == kKextstatExitHelp) { result = EX_OK; } goto finish; } toolArgs.runningKernelArch = OSKextGetRunningKernelArchitecture(); if (!toolArgs.runningKernelArch) { result = EX_OSERR; goto finish; } toolArgs.loadedKextInfo = OSKextCopyLoadedKextInfo(toolArgs.bundleIDs, NULL /* all info */); if (!toolArgs.loadedKextInfo) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag | kOSKextLogIPCFlag, "Couldn't get list of loaded kexts from kernel."); result = EX_OSERR; goto finish; } if (!toolArgs.flagListOnly) { printf("Index Refs Address "); if (toolArgs.runningKernelArch->cputype & CPU_ARCH_ABI64) { printf(" "); } printf("Size Wired "); if (toolArgs.flagShowArchitecture) { printf("Architecture "); } printf("Name (Version) <Linked Against>\n"); } count = CFDictionaryGetCount(toolArgs.loadedKextInfo); if (!count) { goto finish; } kextInfoList = (CFDictionaryRef *)malloc(count * sizeof(CFDictionaryRef)); if (!kextInfoList) { OSKextLogMemError(); result = EX_OSERR; goto finish; } CFDictionaryGetKeysAndValues(toolArgs.loadedKextInfo, /* keys */ NULL, (const void **)kextInfoList); qsort(kextInfoList, count, sizeof(CFDictionaryRef), &compareKextInfo); for (i = 0; i < count; i++) { printKextInfo(kextInfoList[i], &toolArgs); } finish: exit(result); SAFE_FREE(kextInfoList); return result; }
int main(int argc, char** argv) { char SQLq[2048]; /* exit routine */ atexit (exitProc); /* check arguments */ if (readArgs(argc, argv) == FALSE) { fprintf (stderr, "You have to provide DB-Connection infos and the input directory with the XML-Files.\n"); return EXIT_FAILURE; } /* connect to Database, keep connection Idle */ if (!connectDB()) return EXIT_FAILURE; setlocale (LC_CTYPE,""); /* Drop old tables if they exist */ bzero (SQLq, 2048); sprintf (SQLq, db_DROP_TABLE, db_tvtable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while droping Table:%s.\n\t%s", db_tvtable, mysql_error(mysql_conn)); } printD ("Dropped Table:%s\n", db_tvtable); bzero (SQLq, 2048); sprintf (SQLq, db_CREATE_TVTABLE, db_tvtable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while creating Table:%s.\n\t%s", db_tvtable, mysql_error(mysql_conn)); } printD ("Created Table:%s\n", db_tvtable); /****TVEND****/ bzero (SQLq, 2048); sprintf (SQLq, db_DROP_TABLE, db_movietable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while droping Table:%s.\n\t%s", db_tvtable, mysql_error(mysql_conn)); } printD ("Dropped Table:%s\n", db_movietable); bzero (SQLq, 2048); sprintf (SQLq, db_CREATE_MOVIETABLE, db_movietable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while creating Table:%s.\n\t%s", db_movietable, mysql_error(mysql_conn)); } printD ("Created Table:%s\n", db_movietable); /****MOVIEEND****/ if (db_newstable) { bzero (SQLq, 2048); sprintf (SQLq, db_DROP_TABLE, db_newstable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while droping Table:%s.\n\t%s", db_newstable, mysql_error(mysql_conn)); } printD ("Dropped Table:%s\n", db_newstable); bzero (SQLq, 2048); sprintf (SQLq, db_CREATE_NEWS, db_newstable); if (mysql_real_query(mysql_conn, SQLq, strlen(SQLq)) != 0) { fprintf (stderr, "Error while creating Table:%s.\n\t%s", db_newstable, mysql_error(mysql_conn)); } printD ("Created Table:%s\n", db_newstable); } /****NEWSEND****/ /* enter Mainloop and walk thru directory... */ mainLoop(); printD ("Mainloop returned gracefully, cleaning up the mess and leaving...\n"); return EXIT_SUCCESS; }
/** * main entry point */ int main(int argc ,char **argv) { bool result=true; if(argc < 5) { printf("Usage: %s 61.135.250.1 80 61.135.250.2 80\n", argv[0]); exit(1); } initLogInfo(); logInfo(LOG_NOTICE,"%s %s %s %s %s",argv[0],argv[1], argv[2],argv[3],argv[4]); logInfo(LOG_NOTICE,"tcpcopy version:%s",VERSION); #if (TCPCOPY_MYSQL_SKIP) logInfo(LOG_NOTICE,"TCPCOPY_MYSQL_SKIP mode"); #endif #if (TCPCOPY_MYSQL_NO_SKIP) logInfo(LOG_NOTICE,"TCPCOPY_MYSQL_NO_SKIP mode"); #endif result=retrieveVirtualIPAddress(argv[1]); if(!result) { printf("it does not support local ip addr or domain name"); logInfo(LOG_ERR,"it does not support local ip addr or domain name"); } local_port = htons(atoi(argv[2])); remote_ip = inet_addr(argv[3]); remote_port = htons(atoi(argv[4])); if(argc>5) { if(!readArgs(argc,argv,&options)) { #if (TCPCOPY_MYSQL_ADVANCED) logInfo(LOG_ERR,"user password pair is missing:%d",argc); #endif } }else { #if (TCPCOPY_MYSQL_ADVANCED) logInfo(LOG_ERR,"user password pair is missing"); printf("Usage: %s 1.1.1.1 80 1.1.1.2 80 -p user1@psw1:user2@psw2:...\n", argv[0]); exit(1); #endif } if(port_shift_factor||replica_num>1) { struct timeval tp; gettimeofday(&tp,NULL); unsigned int seed=tp.tv_usec; rand_shift_port=(int)((rand_r(&seed)/(RAND_MAX+1.0))*512); if(port_shift_factor) { logInfo(LOG_NOTICE,"port shift factor:%u",port_shift_factor); }else { logInfo(LOG_NOTICE,"replica num:%d",replica_num); } logInfo(LOG_NOTICE,"random shift port:%u",rand_shift_port); } set_signal_handler(); if(SUCCESS==init_tcp_copy()) { select_server_run(); return 0; }else { return 1; } }
int main() { int msg_type = 0; int msg_len = 0; int pipe_fd_one,pipe_fd_two; int first_res,second_res; char buffer[BUF_SIZE]; Message send_msg; Message recv_msg; if(access(FIRST_FIFO_NAME,F_OK) == -1 || access(SECOND_FIFO_NAME,F_OK) == -1) { first_res = mkfifo(FIRST_FIFO_NAME,0777); if(first_res != 0) { fprintf(stderr,"Could not create fifo %s\n",FIRST_FIFO_NAME); exit(EXIT_FAILURE); } second_res = mkfifo(SECOND_FIFO_NAME,0777); if(second_res != 0) { fprintf(stderr,"Could not create fifo %s\n",SECOND_FIFO_NAME); exit(EXIT_FAILURE); } } pid_t child_pid = fork(); switch(child_pid) { case -1 : perror("fork failure "); exit(EXIT_FAILURE); case 0 : pipe_fd_one = open(FIRST_FIFO_NAME,O_WRONLY); pipe_fd_two = open(SECOND_FIFO_NAME,O_RDONLY); if(pipe_fd_one != -1 && pipe_fd_two != -1) { while(1) { read(pipe_fd_two, &recv_msg, sizeof(Message)); if(needExit(recv_msg)) { printf("\nChild process exit\n"); exit(CHILD_EXIT); } printf("\nIn child process:\n"); printf("receive message form parent\n"); showMsg(&recv_msg); readArgs(&msg_type,&msg_len,buffer,"parent"); initMsg(&send_msg,msg_type,msg_len,buffer); write(pipe_fd_one, &send_msg, sizeof(Message)); if(needExit(send_msg)) { printf("\nChild process exit\n"); exit(CHILD_EXIT); } } (void)close(pipe_fd_one); (void)close(pipe_fd_two); }else { fprintf(stderr,"FIFO open failed in child process\n"); exit(EXIT_FAILURE); } break; default : pipe_fd_one = open(FIRST_FIFO_NAME,O_RDONLY); pipe_fd_two = open(SECOND_FIFO_NAME,O_WRONLY); if(pipe_fd_one != -1 && pipe_fd_two != -1) { while(1) { printf("\nIn parent process:\n"); readArgs(&msg_type,&msg_len,buffer,"child"); initMsg(&send_msg,msg_type,msg_len,buffer); write(pipe_fd_two, &send_msg, sizeof(Message)); if(needExit(send_msg)) { parentExit(); } read(pipe_fd_one, &recv_msg, sizeof(Message)); if(needExit(recv_msg)) { parentExit(); } printf("\nIn parent process:\n"); printf("receive message form child.\n"); showMsg(&recv_msg); printf("\n"); } (void)close(pipe_fd_one); (void)close(pipe_fd_two); }else { fprintf(stderr,"FIFO open failed in parent process\n"); exit(EXIT_FAILURE); } break; } }
int main(int argc, char * const argv[]) { ExitStatus result = EX_SOFTWARE; KctoolArgs toolArgs; int kernelcache_fd = -1; // must close() void * fat_header = NULL; // must unmapFatHeaderPage() struct fat_arch * fat_arch = NULL; CFDataRef rawKernelcache = NULL; // must release CFDataRef kernelcacheImage = NULL; // must release void * prelinkInfoSect = NULL; const char * prelinkInfoBytes = NULL; CFPropertyListRef prelinkInfoPlist = NULL; // must release bzero(&toolArgs, sizeof(toolArgs)); /***** * Find out what the program was invoked as. */ progname = rindex(argv[0], '/'); if (progname) { progname++; // go past the '/' } else { progname = (char *)argv[0]; } /* Set the OSKext log callback right away. */ OSKextSetLogOutputFunction(&tool_log); /***** * Process args & check for permission to load. */ result = readArgs(&argc, &argv, &toolArgs); if (result != EX_OK) { if (result == kKctoolExitHelp) { result = EX_OK; } goto finish; } kernelcache_fd = open(toolArgs.kernelcachePath, O_RDONLY); if (kernelcache_fd == -1) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Can't open %s: %s.", toolArgs.kernelcachePath, strerror(errno)); result = EX_OSERR; goto finish; } fat_header = mapAndSwapFatHeaderPage(kernelcache_fd); if (!fat_header) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Can't map %s: %s.", toolArgs.kernelcachePath, strerror(errno)); result = EX_OSERR; goto finish; } fat_arch = getFirstFatArch(fat_header); if (fat_arch && !toolArgs.archInfo) { toolArgs.archInfo = NXGetArchInfoFromCpuType(fat_arch->cputype, fat_arch->cpusubtype); } rawKernelcache = readMachOSliceForArch(toolArgs.kernelcachePath, toolArgs.archInfo, /* checkArch */ FALSE); if (!rawKernelcache) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Can't read arch %s from %s.", toolArgs.archInfo->name, toolArgs.kernelcachePath); goto finish; } if (MAGIC32(CFDataGetBytePtr(rawKernelcache)) == OSSwapHostToBigInt32('comp')) { kernelcacheImage = uncompressPrelinkedSlice(rawKernelcache); if (!kernelcacheImage) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Can't uncompress kernelcache slice."); goto finish; } } else { kernelcacheImage = CFRetain(rawKernelcache); } toolArgs.kernelcacheImageBytes = CFDataGetBytePtr(kernelcacheImage); if (ISMACHO64(MAGIC32(toolArgs.kernelcacheImageBytes))) { prelinkInfoSect = (void *)macho_get_section_by_name_64( (struct mach_header_64 *)toolArgs.kernelcacheImageBytes, "__PRELINK_INFO", "__info"); } else { prelinkInfoSect = (void *)macho_get_section_by_name( (struct mach_header *)toolArgs.kernelcacheImageBytes, "__PRELINK_INFO", "__info"); } if (!prelinkInfoSect) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Can't find prelink info section."); goto finish; } if (ISMACHO64(MAGIC32(toolArgs.kernelcacheImageBytes))) { prelinkInfoBytes = ((char *)toolArgs.kernelcacheImageBytes) + ((struct section_64 *)prelinkInfoSect)->offset; } else { prelinkInfoBytes = ((char *)toolArgs.kernelcacheImageBytes) + ((struct section *)prelinkInfoSect)->offset; } toolArgs.kernelcacheInfoPlist = (CFPropertyListRef)IOCFUnserialize(prelinkInfoBytes, kCFAllocatorDefault, /* options */ 0, /* errorString */ NULL); if (!toolArgs.kernelcacheInfoPlist) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogGeneralFlag, "Can't unserialize prelink info."); goto finish; } result = printKextInfo(&toolArgs); if (result != EX_OK) { goto finish; } result = EX_OK; finish: SAFE_RELEASE(toolArgs.kernelcacheInfoPlist); SAFE_RELEASE(kernelcacheImage); SAFE_RELEASE(rawKernelcache); if (fat_header) { unmapFatHeaderPage(fat_header); } if (kernelcache_fd != -1) { close(kernelcache_fd); } return result; }
int main (int argc, char *argv[]) { printf("Start: %s\n", getTime()); //================================================== // define arguments and usage char *optv[MAX_ARGS] = { "-i", "-o", "-s", "-r", "-v", "-l", "-z", "-t", "-f", "-c", "-a" }; char *optd[MAX_ARGS] = {"efm file (tab separated like: 0.4\t0\t-0.24)", "output file [default: ltcs.out]", "stoichiometric matrix file [optional, needed to find internal loops]", "reaction file [optional, but necessary if option -a is set]", "reversibility file [optional, but saves memory!]", "loops output [only if stoichiometric matrix is given, default: loops.out]", "zero threshold [default: 1e-10]", "number of threads [default: 1]", "full output [yes/no; default: yes] if set to no only summary is printed and ltcs are not saved", "print ltcs in csv format [yes/no; default: yes] if set to no ltcs output will be e.g. 10011 instead of 1,0,0,1,1", "analysis output file - needs option -r"}; char *optr[MAX_ARGS]; char *description = "Calculate largest thermodynamically consistent sets of " "EFMs\nbased only on the reversibility of the reactions"; char *usg = "\n calcLtcs -i efms.txt -o ltcs.out\n calcLtcs -i efms.txt -o ltcs.out -s sfile -v rvfile -z 1e-6 -t 8 -a yes -r rfile"; // end define arguments and usage //================================================== //================================================== // read arguments readArgs(argc, argv, MAX_ARGS, optv, optr); if ( !optr[ARG_INPUT] ) { usage(description, usg, MAX_ARGS, optv, optd); quitError("Missing argument\n", ERROR_ARGS); } char* ltcsout = optr[ARG_LTCS_OUT] ? optr[ARG_LTCS_OUT] : "ltcs.out"; char* arg_rvfile = optr[ARG_RVFILE] ? optr[ARG_RVFILE] : "not available"; char* arg_sfile = optr[ARG_SFILE] ? optr[ARG_SFILE] : "not available"; char* arg_rfile = optr[ARG_RFILE] ? optr[ARG_RFILE] : "not available"; char* loopout = optr[ARG_SFILE] ? (optr[ARG_LOOPS] ? optr[ARG_LOOPS] : "loops.out") : "not available"; double threshold = optr[ARG_ZERO] ? atof(optr[ARG_ZERO]) : 1e-10; int threads = optr[ARG_THREADS] ? atoi(optr[ARG_THREADS]) : 1; int full_out = optr[ARG_FULL_OUT] ? (!strcmp(optr[ARG_FULL_OUT], "no") ? 0 : 1) : 1; int csv_out = optr[ARG_CSV_OUT] ? (!strcmp(optr[ARG_CSV_OUT], "no") ? 0 : 1) : 1; int arg_analysis = optr[ARG_ANALYSIS] ? (optr[ARG_RFILE] ? 1 : 0) : 0; char* arg_analysisfile = optr[ARG_ANALYSIS] ? optr[ARG_ANALYSIS] : "not available"; // end read arguments //================================================== //================================================== // print arguments summary printf("\n"); printf("Input: %s\n", optr[ARG_INPUT]); printf("Output: %s\n", ltcsout); printf("sfile: %s\n", arg_sfile); printf("rvfile: %s\n", arg_rvfile); printf("rfile: %s\n", arg_rfile); printf("Zero threshold: %.2e\n", threshold); printf("Threads: %d\n", threads); printf("Loops output: %s\n", full_out > 0 ? loopout : "no"); printf("Full output: %s\n", full_out > 0 ? "yes" : "no"); if (full_out > 0) { printf("csv output: %s\n", csv_out > 0 ? "yes (1,0,1,1)" : "no (1011)"); } printf("Perform analysis: %s\n", arg_analysis > 0 ? "yes" : "no"); if (arg_analysis > 0) { printf("analysis file: %s\n", arg_analysisfile); } printf("\n"); // end print arguments summary //================================================== //================================================== // check files FILE *file = fopen(optr[ARG_INPUT], "r"); FILE *fileout = NULL; FILE *fileloops = NULL; FILE *fileanalysis = NULL; if (!file) { quitError("Error in opening input file\n", ERROR_FILE); } if (full_out > 0) { fileout = fopen(ltcsout, "w"); if (!fileout) { quitError("Error in opening output file\n", ERROR_FILE); } if (optr[ARG_SFILE]) { fileloops = fopen(loopout, "w"); if (!fileloops) { quitError("Error in opening loop outputfile\n", ERROR_FILE); } } } if (arg_analysis > 0) { fileanalysis = fopen(arg_analysisfile, "w"); if (!fileanalysis) { quitError("Error in opening analysis file\n", ERROR_FILE); } } // end check files //================================================== //================================================== // read number of reactions int rx_count = getRxCount(file); fclose(file); if (rx_count < 1) { quitError("Error in EFM file format; number of reactions < 1\n", ERROR_FILE); } // end read number of reactions //================================================== //================================================== // define exchange reactions char* exchange_reaction = NULL; int s_cols = 0; if (optr[ARG_SFILE]) { defineExchangeReactions(&s_cols, &exchange_reaction, threshold, optr[ARG_SFILE]); if (s_cols != rx_count) { quitError("Error in EFM of stoichiometric file format. Number of reactions is not equal\n", ERROR_FILE); } } // end define exchange reactions //================================================== //================================================== // define reversible reactions unsigned int rev_rx_count = 0; unsigned long rev_rx_bitsize = getBitsize(rx_count); char* reversible_reactions = calloc(1, rev_rx_bitsize); int i; for (i = 0; i < rx_count; i++) { BITSET(reversible_reactions, i); } if (optr[ARG_RVFILE]) { readReversibleFile(optr[ARG_RVFILE], reversible_reactions, rx_count); } else { for (i = 0; i < rx_count; i++) { BITSET(reversible_reactions, i); } } // end define reversible reactions //================================================== //================================================== // read reaction names char** reaction_names = NULL; if (arg_analysis > 0) { readReactions(optr[ARG_RFILE], &reaction_names, rx_count); } // //================================================== //================================================== // read efm matrix char* loops = NULL; char** initial_mat = NULL; char** full_mat = NULL; unsigned long efm_count = 0; int checkLoops = optr[ARG_SFILE] ? 1 : 0; readInitialMatrix(rx_count, &efm_count, reversible_reactions, &rev_rx_count, &initial_mat, &full_mat, arg_analysis, exchange_reaction, &loops, checkLoops, 1e-8, optr[ARG_INPUT]); // end read efm matrix //================================================== //================================================== // find ltcs unsigned long ltcs_count = 0; char** ltcs = NULL; findLtcs(rev_rx_count, efm_count, initial_mat, loops, <cs, <cs_count, threads); // end find ltcs //================================================== //================================================== // filter ltcs to remove subsets printf("%s filter LTCS to remove subsets\n", getTime()); char* notAnLtcs = NULL; filterLtcs(ltcs, ¬AnLtcs, ltcs_count, efm_count); // end filter ltcs to remove subsets //================================================== //================================================== // print ltcs to file if (full_out > 0) { printf("%s save ltcs\n", getTime()); } unsigned long li; unsigned long ul; unsigned long result_ltcs_count = 0; int makeSep = 0; for (li = 0; li < ltcs_count; li++) { if (!BITTEST(notAnLtcs, li)) { makeSep = 0; result_ltcs_count++; if (full_out > 0) { for (ul = 0; ul < efm_count; ul++) { if (makeSep > 0 && csv_out > 0) { fprintf(fileout, ","); } makeSep = 1; if (BITTEST(ltcs[li],ul)) { fprintf(fileout, "1"); } else { fprintf(fileout, "0"); } } fprintf(fileout, "\n"); } } } if (full_out > 0) { fclose(fileout); } // end print ltcs to file //================================================== //================================================== // perform analysis if (arg_analysis > 0) { printf("%s perform and save analysis of LTCS\n", getTime()); double** analysis_values = NULL; performAnalysis(&analysis_values, ltcs, full_mat, reaction_names, ltcs_count, efm_count, rx_count); unsigned long lj; for (li = 0; li < rx_count; li++) { fprintf(fileanalysis, "%s", reaction_names[li]); for (lj = 0; lj < ltcs_count; lj++) { fprintf(fileanalysis, ",%.2f", analysis_values[li][lj]); } fprintf(fileanalysis, "\n"); } fclose(fileanalysis); for (li = 0; li < rx_count; li++) { free(analysis_values[li]); free(reaction_names[li]); } free(analysis_values); free(reaction_names); } // end perform analysis //================================================== //================================================== // set initial_mat memory free for (li=0; li<efm_count; li++) { if (!BITTEST(loops, li)) { free(initial_mat[li]); } } free(initial_mat); initial_mat = NULL; if (arg_analysis > 0) { for (li=0; li<efm_count; li++) { if (!BITTEST(loops, li)) { free(full_mat[li]); } } free(full_mat); full_mat = NULL; } // end set initial_mat memory free //================================================== //================================================== // count and print loops to file unsigned long loop_count = 0; if (optr[ARG_SFILE]) { if (full_out > 0) { printf("%s save internal loops\n", getTime()); for (ul = 0; ul < efm_count; ul++) { if (ul > 0 && csv_out > 0) { fprintf(fileloops, ","); } if (BITTEST(loops, ul)) { fprintf(fileloops, "1"); loop_count++; } else { fprintf(fileloops, "0"); } } fclose(fileloops); } else { for (ul = 0; ul < efm_count; ul++) { if (BITTEST(loops, ul)) { loop_count++; } } } } // end count and print loops to file //================================================== //================================================== // print summary printf("\n"); printf("Nr of EFMS: %lu\n", efm_count); printf("Nr of LTCS: %lu\n", result_ltcs_count); if (optr[ARG_SFILE]) { printf("Nr of internal loops: %lu\n", loop_count); } printf("\nSizes of LTCS:\n"); for (li = 0; li < ltcs_count; li++) { if (!BITTEST(notAnLtcs, li)) { if (li > 0) { printf(","); } printf("%lu", getLtcsCardinality(ltcs[li], efm_count)); } } printf("\n\n"); printf("End: %s\n", getTime()); // end print summary //================================================== //================================================== // set memory free free(loops); free(exchange_reaction); loops = NULL; for (li = 0; li < ltcs_count; li++) { if (!BITTEST(notAnLtcs, li)) { free(ltcs[li]); } } free(ltcs); free(notAnLtcs); ltcs = NULL; free(reversible_reactions); reversible_reactions = NULL; // end set memory free //================================================== return EXIT_SUCCESS; }
int main(int argc, char *argv[]){ Params params; std::map<std::string, std::string> args; readArgs(argc, argv, args); if(args.find("algo")!=args.end()){ params.algo = args["algo"]; }else{ params.algo = "qdMCNat"; } if(args.find("inst_file")!=args.end()) setParamsFromFile(args["inst_file"], args, params); else setParams(params.algo, args, params); createLogDir(params.dir_path); gen.seed(params.seed); // Load the dataset MyMatrix X_train, X_valid; VectorXd Y_train, Y_valid; loadMnist(params.ratio_train, X_train, X_valid, Y_train, Y_valid); //loadCIFAR10(params.ratio_train, X_train, X_valid, Y_train, Y_valid); //loadLightCIFAR10(params.ratio_train, X_train, X_valid, Y_train, Y_valid); // ConvNet parameters std::vector<ConvLayerParams> conv_params; ConvLayerParams conv_params1; conv_params1.Hf = 5; conv_params1.stride = 1; conv_params1.n_filter = 20; conv_params1.padding = 0; conv_params.push_back(conv_params1); ConvLayerParams conv_params2; conv_params2.Hf = 5; conv_params2.stride = 1; conv_params2.n_filter = 50; conv_params2.padding = 0; conv_params.push_back(conv_params2); std::vector<PoolLayerParams> pool_params; PoolLayerParams pool_params1; pool_params1.Hf = 2; pool_params1.stride = 2; pool_params.push_back(pool_params1); PoolLayerParams pool_params2; pool_params2.Hf = 2; pool_params2.stride = 2; pool_params.push_back(pool_params2); const unsigned n_conv_layer = conv_params.size(); for(unsigned l = 0; l < conv_params.size(); l++){ if(l==0){ conv_params[l].filter_size = conv_params[l].Hf * conv_params[l].Hf * params.img_depth; conv_params[l].N = (params.img_width - conv_params[l].Hf + 2*conv_params[l].padding)/conv_params[l].stride + 1; } else{ conv_params[l].filter_size = conv_params[l].Hf * conv_params[l].Hf * conv_params[l-1].n_filter; conv_params[l].N = (pool_params[l-1].N - conv_params[l].Hf + 2*conv_params[l].padding)/conv_params[l].stride + 1; } pool_params[l].N = (conv_params[l].N - pool_params[l].Hf)/pool_params[l].stride + 1; } // Neural Network parameters const unsigned n_training = X_train.rows(); const unsigned n_valid = X_valid.rows(); const unsigned n_feature = X_train.cols(); const unsigned n_label = Y_train.maxCoeff() + 1; params.nn_arch.insert(params.nn_arch.begin(),conv_params[n_conv_layer-1].n_filter * pool_params[n_conv_layer-1].N * pool_params[n_conv_layer-1].N); params.nn_arch.push_back(n_label); const unsigned n_layers = params.nn_arch.size(); // Optimization parameter const int n_train_batch = ceil(n_training/(float)params.train_minibatch_size); const int n_valid_batch = ceil(n_valid/(float)params.valid_minibatch_size); double prev_loss = std::numeric_limits<double>::max(); double eta = params.eta; // Create the convolutional layer std::vector<MyMatrix> conv_W(n_conv_layer); std::vector<MyMatrix> conv_W_T(n_conv_layer); std::vector<MyVector> conv_B(n_conv_layer); // Create the neural network MyMatrix W_out(params.nn_arch[n_layers-2],n_label); std::vector<MySpMatrix> W(n_layers-2); std::vector<MySpMatrix> Wt(n_layers-2); std::vector<MyVector> B(n_layers-1); double init_sigma = 0.; ActivationFunction act_func; ActivationFunction eval_act_func; if(params.act_func_name=="sigmoid"){ init_sigma = 4.0; act_func = std::bind(logistic,true,_1,_2,_3); eval_act_func = std::bind(logistic,false,_1,_2,_3); }else if(params.act_func_name=="tanh"){ init_sigma = 1.0; act_func = std::bind(my_tanh,true,_1,_2,_3); eval_act_func = std::bind(my_tanh,false,_1,_2,_3); }else if(params.act_func_name=="relu"){ init_sigma = 1.0; // TODO: Find the good value act_func = std::bind(relu,true,_1,_2,_3); eval_act_func = std::bind(relu,false,_1,_2,_3); }else{ std::cout << "Not implemented yet!" << std::endl; assert(false); } std::cout << "Initializing the network... "; params.n_params = initNetwork(params.nn_arch, params.act_func_name, params.sparsity, conv_params, pool_params, W_out, W, Wt, B, conv_W, conv_W_T, conv_B); // TODO: Init the conv bias // Deep copy of parameters for the adaptive rule std::vector<MyMatrix> mu_dW(n_layers-1); std::vector<MyVector> mu_dB(n_layers-1); MyMatrix pW_out = W_out; std::vector<MySpMatrix> pW = W; std::vector<MySpMatrix> pWt = Wt; std::vector<MyVector> pB = B; MyMatrix ppMii_out, ppM0i_out; MyVector ppM00_out; std::vector<MySpMatrix> ppMii,ppM0i; std::vector<MyVector> ppM00; MyMatrix pMii_out,pM0i_out; MyVector pM00_out; std::vector<MySpMatrix> pMii,pM0i; std::vector<MyVector> pM00; std::vector<MyMatrix> conv_ppMii, conv_ppM0i; std::vector<MyVector> conv_ppM00; std::vector<MyMatrix> conv_pMii, conv_pM0i; std::vector<MyVector> conv_pM00; // Convert the labels to one-hot vector MyMatrix one_hot = MyMatrix::Zero(n_training, n_label); labels2oneHot(Y_train,one_hot); // Configure the logger std::ostream* logger; if(args.find("verbose")!=args.end()){ getOutput("",logger); }else{ getOutput(params.file_path,logger); } double cumul_time = 0.; printDesc(params, logger); printConvDesc(params, conv_params, pool_params, logger); std::cout << "Starting the learning phase... " << std::endl; *logger << "Epoch Time(s) train_loss train_accuracy valid_loss valid_accuracy eta" << std::endl; for(unsigned i = 0; i < params.n_epoch; i++){ for(unsigned j = 0; j < n_train_batch; j++){ // Mini-batch creation unsigned curr_batch_size = 0; MyMatrix X_batch, one_hot_batch; getMiniBatch(j, params.train_minibatch_size, X_train, one_hot, params, conv_params[0], curr_batch_size, X_batch, one_hot_batch); double prev_time = gettime(); // Forward propagation for conv layer std::vector<std::vector<unsigned>> poolIdxX1(n_conv_layer); std::vector<std::vector<unsigned>> poolIdxY1(n_conv_layer); MyMatrix z0; std::vector<MyMatrix> conv_A(conv_W.size()); std::vector<MyMatrix> conv_Ap(conv_W.size()); convFprop(curr_batch_size, conv_params, pool_params, act_func, conv_W, conv_B, X_batch, conv_A, conv_Ap, z0, poolIdxX1, poolIdxY1); // Forward propagation std::vector<MyMatrix> Z(n_layers-1); std::vector<MyMatrix> A(n_layers-2); std::vector<MyMatrix> Ap(n_layers-2); fprop(params.dropout_flag, act_func, W, W_out, B, z0, Z, A, Ap); // Compute the output and the error MyMatrix out; softmax(Z[n_layers-2], out); std::vector<MyMatrix> gradB(n_layers-1); gradB[n_layers-2] = out - one_hot_batch; // Backpropagation bprop(Wt, W_out, Ap, gradB); // Backpropagation for conv layer std::vector<MyMatrix> conv_gradB(conv_W.size()); MyMatrix layer_gradB = (gradB[0] * W[0].transpose()); MyMatrix pool_gradB; layer2pool(curr_batch_size, pool_params[conv_W.size()-1].N, conv_params[conv_W.size()-1].n_filter, layer_gradB, pool_gradB); convBprop(curr_batch_size, conv_params, pool_params, conv_W_T, conv_Ap, pool_gradB, conv_gradB, poolIdxX1, poolIdxY1); if(params.algo == "bprop"){ update(eta, gradB, A, z0, params.regularizer, params.lambda, W_out, W, Wt, B); convUpdate(curr_batch_size, eta, conv_params, conv_gradB, conv_A, X_batch, "", 0., conv_W, conv_W_T, conv_B); }else{ // Compute the metric std::vector<MyMatrix> metric_gradB(n_layers-1); std::vector<MyMatrix> metric_conv_gradB(conv_params.size()); if(params.algo=="qdMCNat"){ // Monte-Carlo Approximation of the metric std::vector<MyMatrix> mc_gradB(n_layers-1); computeMcError(out, mc_gradB[n_layers-2]); // Backpropagation bprop(Wt, W_out, Ap, mc_gradB); for(unsigned k = 0; k < gradB.size(); k++){ metric_gradB[k] = mc_gradB[k].array().square(); } // Backpropagation for conv layer std::vector<MyMatrix> mc_conv_gradB(conv_W.size()); MyMatrix mc_layer_gradB = (mc_gradB[0] * W[0].transpose()); MyMatrix mc_pool_gradB; layer2pool(curr_batch_size, pool_params[conv_W.size()-1].N, conv_params[conv_W.size()-1].n_filter, mc_layer_gradB, mc_pool_gradB); convBprop(curr_batch_size, conv_params, pool_params, conv_W_T, conv_Ap, mc_pool_gradB, mc_conv_gradB, poolIdxX1, poolIdxY1); for(unsigned k = 0; k < conv_params.size(); k++){ metric_conv_gradB[k] = mc_conv_gradB[k].array().square(); } } else if(params.algo=="qdop"){ for(unsigned k = 0; k < conv_params.size(); k++){ metric_conv_gradB[k] = conv_gradB[k].array().square(); } for(unsigned k = 0; k < gradB.size(); k++){ metric_gradB[k] = gradB[k].array().square(); } } else if(params.algo=="qdNat"){ for(unsigned k = 0; k < conv_params.size(); k++){ metric_conv_gradB[k] = conv_gradB[k].array().square(); } for(unsigned k = 0; k < metric_gradB.size(); k++){ metric_gradB[k] = MyMatrix::Zero(gradB[k].rows(),gradB[k].cols()); } for(unsigned l = 0; l < n_label; l++){ MyMatrix fisher_ohbatch = MyMatrix::Zero(curr_batch_size, n_label); fisher_ohbatch.col(l).setOnes(); std::vector<MyMatrix> fgradB(n_layers-1); fgradB[n_layers-2] = out - fisher_ohbatch; bprop(Wt, W_out, Ap, fgradB); // Backpropagation for conv layer std::vector<MyMatrix> fisher_conv_gradB(conv_W.size()); MyMatrix fisher_layer_gradB = (fgradB[0] * W[0].transpose()); MyMatrix fisher_pool_gradB; layer2pool(curr_batch_size, pool_params[conv_W.size()-1].N, conv_params[conv_W.size()-1].n_filter, fisher_layer_gradB, fisher_pool_gradB); convBprop(curr_batch_size, conv_params, pool_params, conv_W_T, conv_Ap, fisher_pool_gradB, fisher_conv_gradB, poolIdxX1, poolIdxY1); for(unsigned k = 0; k < conv_params.size(); k++){ MyMatrix fisher_conv_gradB_sq = fisher_conv_gradB[k].array().square(); for(unsigned m = 0; m < out.rows(); m++){ for(unsigned f = 0; f < conv_params[k].n_filter; f++){ for(unsigned n = 0; n < conv_params[k].N * conv_params[k].N; n++){ fisher_conv_gradB_sq(f,m*conv_params[k].N*conv_params[k].N+n) *= out(m,l); } } } metric_conv_gradB[k] += fisher_conv_gradB_sq; } for(unsigned k = 0; k < W.size(); k++){ const unsigned rev_k = n_layers - k - 2; metric_gradB[rev_k] += (fgradB[rev_k].array().square().array().colwise() * out.array().col(l)).matrix(); } } } bool init_flag = false; if(i == 0 && j == 0 && !params.init_metric_id){ init_flag = true; } std::vector<MyMatrix> conv_Mii(conv_params.size()); std::vector<MyMatrix> conv_M0i(conv_params.size()); std::vector<MyVector> conv_M00(conv_params.size()); buildConvQDMetric(curr_batch_size, metric_conv_gradB, conv_A, X_batch, conv_W, params.matrix_reg, conv_Mii, conv_M0i, conv_M00); updateConvMetric(init_flag, params.metric_gamma, conv_pMii, conv_pM0i, conv_pM00, conv_Mii, conv_M0i, conv_M00); MyMatrix Mii_out, M0i_out; MyVector M00_out; std::vector<MySpMatrix> Mii(W.size()); std::vector<MySpMatrix> M0i(W.size()); std::vector<MyVector> M00(W.size()); buildQDMetric(metric_gradB, A, z0, W_out, W, params.matrix_reg, Mii_out, M0i_out, M00_out, Mii, M0i, M00); updateMetric(init_flag, params.metric_gamma, Mii_out, M0i_out, M00_out, Mii, M0i, M00, pMii_out, pM0i_out, pM00_out, pMii, pM0i, pM00); update(eta, gradB, A, z0, params.regularizer, params.lambda, W_out, W, Wt, B, Mii_out, M0i_out, M00_out, Mii, M0i, M00); } double curr_time = gettime(); cumul_time += curr_time - prev_time; if(params.minilog_flag){ double train_loss = 0.; double train_accuracy = 0.; double valid_loss = 0.; double valid_accuracy = 0.; evalModel(eval_act_func, params, n_train_batch, n_training, X_train, Y_train, conv_params, pool_params, conv_W, conv_B, W_out, W, B, train_loss, train_accuracy); evalModel(eval_act_func, params, n_valid_batch, n_valid, X_valid, Y_valid, conv_params, pool_params, conv_W, conv_B, W_out, W, B, valid_loss, valid_accuracy); // Logging *logger << i + float(j)/n_train_batch << " " << cumul_time << " " << train_loss << " " << train_accuracy << " " << valid_loss << " " << valid_accuracy << " " << eta << std::endl; } } if(!params.minilog_flag || params.adaptive_flag){ double train_loss = 0.; double train_accuracy = 0.; double valid_loss = 0.; double valid_accuracy = 0.; evalModel(eval_act_func, params, n_train_batch, n_training, X_train, Y_train, conv_params, pool_params, conv_W, conv_B, W_out, W, B, train_loss, train_accuracy); evalModel(eval_act_func, params, n_valid_batch, n_valid, X_valid, Y_valid, conv_params, pool_params, conv_W, conv_B, W_out, W, B, valid_loss, valid_accuracy); // if(params.adaptive_flag) // adaptiveRule(train_loss, prev_loss, eta, W, B, pMii, pM0i, pM00, pW, pB, ppMii, ppM0i, ppM00); // Logging if(!params.minilog_flag){ *logger << i << " " << cumul_time << " " << train_loss << " " << train_accuracy << " " << valid_loss << " " << valid_accuracy << " " << eta << std::endl; } } } }
void SingleServer::newConn() { clientConnection = server->nextPendingConnection(); connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readArgs())); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); }
/** * \brief Main function * \details -- * \param int argc * \param char const** argv * \return \e int */ int main( int argc, char const** argv ) { /*--------------------------------*/ /* 1) Read command line arguments */ /*--------------------------------*/ size_t rep = 0; std::string optional_filename = ""; std::string optional_population_path = ""; readArgs(argc, argv, rep, optional_filename, optional_population_path); /*--------------------------------*/ /* 2) Load parameters from file */ /*--------------------------------*/ printHeader(); Parameters* parameters = new Parameters(); bool load_successful = false; if (strcmp(optional_filename.c_str(), "") != 0) { load_successful = parameters->load_parameters_from_file(optional_filename); } else { load_successful = parameters->load_parameters_from_file(DEFAULT_FILENAME); } if (!load_successful) { std::cout << "Error during parameters loading.\n"; exit(EXIT_FAILURE); } /*--------------------------------*/ /* 3) Load the evolved population */ /*--------------------------------*/ Population* evolved_population = NULL; if (strcmp(optional_population_path.c_str(), "") != 0) { gzFile pop_file = gzopen(optional_population_path.c_str(), "r"); evolved_population = new Population(parameters, pop_file); gzclose(pop_file); } else { gzFile pop_file = gzopen(DEFAULT_POPULATION_PATH.c_str(), "r"); evolved_population = new Population(parameters, pop_file); gzclose(pop_file); } /*--------------------------------*/ /* 4) Run the post-treatment */ /*--------------------------------*/ measure_frequency_dependent_fitness(parameters, evolved_population, rep); /*--------------------------------*/ /* 5) Free the memory */ /*--------------------------------*/ delete evolved_population; evolved_population = NULL; delete parameters; parameters = NULL; return EXIT_SUCCESS; }