예제 #1
0
파일: clamd.c 프로젝트: Distrotech/clamav
int main(int argc, char **argv)
{
    static struct cl_engine *engine = NULL;
    const struct optstruct *opt;
#ifndef	_WIN32
    struct passwd *user = NULL;
    struct sigaction sa;
    struct rlimit rlim;
#endif
    time_t currtime;
    const char *dbdir, *cfgfile;
    char *pua_cats = NULL, *pt;
    int ret, tcpsock = 0, localsock = 0, min_port, max_port;
    unsigned int sigs = 0;
    int *lsockets=NULL;
    unsigned int nlsockets = 0;
    unsigned int dboptions = 0;
    unsigned int i;
#ifdef C_LINUX
    STATBUF sb;
#endif

    if(check_flevel())
        exit(1);

#ifndef _WIN32
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = SIG_IGN;
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGUSR2, &sa, NULL);
#endif

    if((opts = optparse(NULL, argc, argv, 1, OPT_CLAMD, 0, NULL)) == NULL) {
        mprintf("!Can't parse command line options\n");
        return 1;
    }

    if(optget(opts, "help")->enabled) {
        help();
        optfree(opts);
        return 0;
    }

    if(optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
        /* [email protected]: create a dump if needed */
        rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
        if(setrlimit(RLIMIT_CORE, &rlim) < 0)
            perror("setrlimit");
#endif
        debug_mode = 1;
    }

    /* parse the config file */
    cfgfile = optget(opts, "config-file")->strarg;
    pt = strdup(cfgfile);
    if (pt == NULL) {
	fprintf(stderr, "ERROR: Unable to allocate memory for config file\n");
	return 1;
    }
    if((opts = optparse(cfgfile, 0, NULL, 1, OPT_CLAMD, 0, opts)) == NULL) {
        fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", pt);
        free(pt);
        return 1;
    }
    free(pt);

    if(optget(opts, "version")->enabled) {
        print_version(optget(opts, "DatabaseDirectory")->strarg);
        optfree(opts);
        return 0;
    }

    /* drop privileges */
#ifndef _WIN32
    if(geteuid() == 0 && (opt = optget(opts, "User"))->enabled) {
        if((user = getpwnam(opt->strarg)) == NULL) {
            fprintf(stderr, "ERROR: Can't get information about user %s.\n", opt->strarg);
            optfree(opts);
            return 1;
        }

        if(optget(opts, "AllowSupplementaryGroups")->enabled) {
#ifdef HAVE_INITGROUPS
            if(initgroups(opt->strarg, user->pw_gid)) {
                fprintf(stderr, "ERROR: initgroups() failed.\n");
                optfree(opts);
                return 1;
            }
#else
            mprintf("!AllowSupplementaryGroups: initgroups() is not available, please disable AllowSupplementaryGroups in %s\n", cfgfile);
            optfree(opts);
            return 1;
#endif
        } else {
#ifdef HAVE_SETGROUPS
            if(setgroups(1, &user->pw_gid)) {
                fprintf(stderr, "ERROR: setgroups() failed.\n");
                optfree(opts);
                return 1;
            }
#endif
        }

        if(setgid(user->pw_gid)) {
            fprintf(stderr, "ERROR: setgid(%d) failed.\n", (int) user->pw_gid);
            optfree(opts);
            return 1;
        }

        if(setuid(user->pw_uid)) {
            fprintf(stderr, "ERROR: setuid(%d) failed.\n", (int) user->pw_uid);
            optfree(opts);
            return 1;
        }
    }
#endif

    /* initialize logger */
    logg_lock = !optget(opts, "LogFileUnlock")->enabled;
    logg_time = optget(opts, "LogTime")->enabled;
    logok = optget(opts, "LogClean")->enabled;
    logg_size = optget(opts, "LogFileMaxSize")->numarg;
    logg_verbose = mprintf_verbose = optget(opts, "LogVerbose")->enabled;
    if (logg_size)
        logg_rotate = optget(opts, "LogRotate")->enabled;
    mprintf_send_timeout = optget(opts, "SendBufTimeout")->numarg;

    do { /* logger initialized */
        if((opt = optget(opts, "LogFile"))->enabled) {
            char timestr[32];
            logg_file = opt->strarg;
            if(!cli_is_abspath(logg_file)) {
                fprintf(stderr, "ERROR: LogFile requires full path.\n");
                ret = 1;
                break;
            }
            time(&currtime);
            if(logg("#+++ Started at %s", cli_ctime(&currtime, timestr, sizeof(timestr)))) {
                fprintf(stderr, "ERROR: Can't initialize the internal logger\n");
                ret = 1;
                break;
            }
        } else {
            logg_file = NULL;
        }

        if (optget(opts,"DevLiblog")->enabled)
            cl_set_clcb_msg(msg_callback);

        if((ret = cl_init(CL_INIT_DEFAULT))) {
            logg("!Can't initialize libclamav: %s\n", cl_strerror(ret));
            ret = 1;
            break;
        }

        if(optget(opts, "Debug")->enabled) {
            /* enable debug messages in libclamav */
            cl_debug();
            logg_verbose = 2;
        }

#if defined(USE_SYSLOG) && !defined(C_AIX)
        if(optget(opts, "LogSyslog")->enabled) {
            int fac = LOG_LOCAL6;

            opt = optget(opts, "LogFacility");
            if((fac = logg_facility(opt->strarg)) == -1) {
                logg("!LogFacility: %s: No such facility.\n", opt->strarg);
                ret = 1;
                break;
            }

            openlog("clamd", LOG_PID, fac);
            logg_syslog = 1;
        }
#endif

#ifdef C_LINUX
        procdev = 0;
        if(CLAMSTAT("/proc", &sb) != -1 && !sb.st_size)
            procdev = sb.st_dev;
#endif

        /* check socket type */

        if(optget(opts, "TCPSocket")->enabled)
            tcpsock = 1;

        if(optget(opts, "LocalSocket")->enabled)
            localsock = 1;

        if(!tcpsock && !localsock) {
            logg("!Please define server type (local and/or TCP).\n");
            ret = 1;
            break;
        }

        logg("#clamd daemon %s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")\n", get_version());

#ifndef _WIN32
        if(user)
            logg("#Running as user %s (UID %u, GID %u)\n", user->pw_name, user->pw_uid, user->pw_gid);
#endif

#if defined(RLIMIT_DATA) && defined(C_BSD)
        if (getrlimit(RLIMIT_DATA, &rlim) == 0) {
           /* bb #1941.
            * On 32-bit FreeBSD if you set ulimit -d to >2GB then mmap() will fail
            * too soon (after ~120 MB).
            * Set limit lower than 2G if on 32-bit */
           uint64_t lim = rlim.rlim_cur;
           if (sizeof(void*) == 4 &&
               lim > (1ULL << 31)) {
               rlim.rlim_cur = 1ULL << 31;
               if (setrlimit(RLIMIT_DATA, &rlim) < 0)
                   logg("!setrlimit(RLIMIT_DATA) failed: %s\n", strerror(errno));
               else
                   logg("Running on 32-bit system, and RLIMIT_DATA > 2GB, lowering to 2GB!\n");
           }
        }
#endif


        if(logg_size)
            logg("#Log file size limited to %u bytes.\n", logg_size);
        else
            logg("#Log file size limit disabled.\n");

        min_port = optget(opts, "StreamMinPort")->numarg;
        max_port = optget(opts, "StreamMaxPort")->numarg;
        if (min_port < 1024 || min_port > max_port || max_port > 65535) {
            logg("!Invalid StreamMinPort/StreamMaxPort: %d, %d\n", min_port, max_port);
            ret = 1;
            break;
        }

        if(!(engine = cl_engine_new())) {
            logg("!Can't initialize antivirus engine\n");
            ret = 1;
            break;
        }

        if (optget(opts, "disable-cache")->enabled)
            cl_engine_set_num(engine, CL_ENGINE_DISABLE_CACHE, 1);

        /* load the database(s) */
        dbdir = optget(opts, "DatabaseDirectory")->strarg;
        logg("#Reading databases from %s\n", dbdir);

        if(optget(opts, "DetectPUA")->enabled) {
            dboptions |= CL_DB_PUA;

            if((opt = optget(opts, "ExcludePUA"))->enabled) {
                dboptions |= CL_DB_PUA_EXCLUDE;
                i = 0;
                logg("#Excluded PUA categories:");

                while(opt) {
                    if(!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
                        logg("!Can't allocate memory for pua_cats\n");
                        cl_engine_free(engine);
                        ret = 1;
                        break;
                    }

                    logg("# %s", opt->strarg);

                    sprintf(pua_cats + i, ".%s", opt->strarg);
                    i += strlen(opt->strarg) + 1;
                    pua_cats[i] = 0;
                    opt = opt->nextarg;
                }

                if (ret)
                    break;

                logg("#\n");
                pua_cats[i] = '.';
                pua_cats[i + 1] = 0;
            }

            if((opt = optget(opts, "IncludePUA"))->enabled) {
                if(pua_cats) {
                    logg("!ExcludePUA and IncludePUA cannot be used at the same time\n");
                    free(pua_cats);
                    ret = 1;
                    break;
                }

                dboptions |= CL_DB_PUA_INCLUDE;
                i = 0;
                logg("#Included PUA categories:");
                while(opt) {
                    if(!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
                        logg("!Can't allocate memory for pua_cats\n");
                        ret = 1;
                        break;
                    }

                    logg("# %s", opt->strarg);

                    sprintf(pua_cats + i, ".%s", opt->strarg);
                    i += strlen(opt->strarg) + 1;
                    pua_cats[i] = 0;
                    opt = opt->nextarg;
                }

                if (ret)
                    break;

                logg("#\n");
                pua_cats[i] = '.';
                pua_cats[i + 1] = 0;
            }

            if(pua_cats) {
                if((ret = cl_engine_set_str(engine, CL_ENGINE_PUA_CATEGORIES, pua_cats))) {
                    logg("!cli_engine_set_str(CL_ENGINE_PUA_CATEGORIES) failed: %s\n", cl_strerror(ret));
                    free(pua_cats);
                    ret = 1;
                    break;
                }
                free(pua_cats);
            }
        } else {
            logg("#Not loading PUA signatures.\n");
        }

        if (optget(opts, "StatsEnabled")->enabled) {
            cl_engine_stats_enable(engine);
        }

        if (optget(opts, "StatsPEDisabled")->enabled) {
            cl_engine_set_num(engine, CL_ENGINE_DISABLE_PE_STATS, 1);
        }

        if (optget(opts, "StatsTimeout")->enabled) {
            cl_engine_set_num(engine, CL_ENGINE_STATS_TIMEOUT, optget(opts, "StatsTimeout")->numarg);
        }

        if (optget(opts, "StatsHostID")->enabled) {
            char *p = optget(opts, "StatsHostID")->strarg;

            if (strcmp(p, "default")) {
                if (!strcmp(p, "none")) {
                    cl_engine_set_clcb_stats_get_hostid(engine, NULL);
                } else if (!strcmp(p, "anonymous")) {
                    strcpy(hostid, STATS_ANON_UUID);
                } else {
                    if (strlen(p) > 36) {
                        logg("!Invalid HostID\n");
                        cl_engine_set_clcb_stats_submit(engine, NULL);
                        cl_engine_free(engine);
                        ret = 1;
                        break;
                    }

                    strcpy(hostid, p);
                }

                cl_engine_set_clcb_stats_get_hostid(engine, get_hostid);
            }
        }

        if(optget(opts, "OfficialDatabaseOnly")->enabled) {
            dboptions |= CL_DB_OFFICIAL_ONLY;
            logg("#Only loading official signatures.\n");
        }

        /* set the temporary dir */
        if((opt = optget(opts, "TemporaryDirectory"))->enabled) {
            if((ret = cl_engine_set_str(engine, CL_ENGINE_TMPDIR, opt->strarg))) {
                logg("!cli_engine_set_str(CL_ENGINE_TMPDIR) failed: %s\n", cl_strerror(ret));
                ret = 1;
                break;
            }
        }

        cl_engine_set_clcb_hash(engine, hash_callback);

        cl_engine_set_clcb_virus_found(engine, clamd_virus_found_cb);

        if(optget(opts, "LeaveTemporaryFiles")->enabled)
            cl_engine_set_num(engine, CL_ENGINE_KEEPTMP, 1);

        if(optget(opts, "ForceToDisk")->enabled)
            cl_engine_set_num(engine, CL_ENGINE_FORCETODISK, 1);

        if(optget(opts, "PhishingSignatures")->enabled)
            dboptions |= CL_DB_PHISHING;
        else
            logg("#Not loading phishing signatures.\n");

        if(optget(opts,"Bytecode")->enabled) {
            dboptions |= CL_DB_BYTECODE;
            if((opt = optget(opts,"BytecodeSecurity"))->enabled) {
                enum bytecode_security s;

                if (!strcmp(opt->strarg, "TrustSigned")) {
                    s = CL_BYTECODE_TRUST_SIGNED;
                    logg("#Bytecode: Security mode set to \"TrustSigned\".\n");
                } else if (!strcmp(opt->strarg, "Paranoid")) {
                    s = CL_BYTECODE_TRUST_NOTHING;
                    logg("#Bytecode: Security mode set to \"Paranoid\".\n");
                } else {
                    logg("!Unable to parse bytecode security setting:%s\n",
                        opt->strarg);
                    ret = 1;
                    break;
                }

                if ((ret = cl_engine_set_num(engine, CL_ENGINE_BYTECODE_SECURITY, s))) {
                    logg("^Invalid bytecode security setting %s: %s\n", opt->strarg, cl_strerror(ret));
                    ret = 1;
                    break;
                }
            }
            if((opt = optget(opts,"BytecodeUnsigned"))->enabled) {
                dboptions |= CL_DB_BYTECODE_UNSIGNED;
                logg("#Bytecode: Enabled support for unsigned bytecode.\n");
            }

            if((opt = optget(opts,"BytecodeMode"))->enabled) {
                enum bytecode_mode mode;

                if (!strcmp(opt->strarg, "ForceJIT"))
                    mode = CL_BYTECODE_MODE_JIT;
                else if(!strcmp(opt->strarg, "ForceInterpreter"))
                    mode = CL_BYTECODE_MODE_INTERPRETER;
                else if(!strcmp(opt->strarg, "Test"))
                    mode = CL_BYTECODE_MODE_TEST;
                else
                    mode = CL_BYTECODE_MODE_AUTO;
                cl_engine_set_num(engine, CL_ENGINE_BYTECODE_MODE, mode);
            }

            if((opt = optget(opts,"BytecodeTimeout"))->enabled) {
                cl_engine_set_num(engine, CL_ENGINE_BYTECODE_TIMEOUT, opt->numarg);
            }
        } else {
            logg("#Bytecode support disabled.\n");
        }

        if(optget(opts,"PhishingScanURLs")->enabled)
            dboptions |= CL_DB_PHISHING_URLS;
        else
            logg("#Disabling URL based phishing detection.\n");

        if(optget(opts,"DevACOnly")->enabled) {
            logg("#Only using the A-C matcher.\n");
            cl_engine_set_num(engine, CL_ENGINE_AC_ONLY, 1);
        }

        if((opt = optget(opts, "DevACDepth"))->enabled) {
            cl_engine_set_num(engine, CL_ENGINE_AC_MAXDEPTH, opt->numarg);
            logg("#Max A-C depth set to %u\n", (unsigned int) opt->numarg);
        }

        if((ret = cl_load(dbdir, engine, &sigs, dboptions))) {
            logg("!%s\n", cl_strerror(ret));
            ret = 1;
            break;
        }

        if((ret = statinidir_th(dbdir))) {
            logg("!%s\n", cl_strerror(ret));
            ret = 1;
            break;
        }

        if (optget(opts, "DisableCertCheck")->enabled)
            engine->dconf->pe |= PE_CONF_DISABLECERT;

        logg("#Loaded %u signatures.\n", sigs);

        if((ret = cl_engine_compile(engine)) != 0) {
            logg("!Database initialization error: %s\n", cl_strerror(ret));
            ret = 1;
            break;
        }

        if(tcpsock) {
            opt = optget(opts, "TCPAddr");
            if (opt->enabled) {
                int breakout = 0;

                while (opt && opt->strarg) {
                    char *ipaddr = (!strcmp(opt->strarg, "all") ? NULL : opt->strarg);

                    if (tcpserver(&lsockets, &nlsockets, ipaddr, opts) == -1) {
                        ret = 1;
                        breakout = 1;
                        break;
                    }

                    opt = opt->nextarg;
                }

                if (breakout)
                    break;
            } else {
                if (tcpserver(&lsockets, &nlsockets, NULL, opts) == -1) {
                    ret = 1;
                    break;
                }
            }
        }
#ifndef _WIN32
        if(localsock) {
            int *t;
            mode_t sock_mode, umsk = umask(0777); /* socket is created with 000 to avoid races */

            t = realloc(lsockets, sizeof(int) * (nlsockets + 1));
            if (!(t)) {
                ret = 1;
                break;
            }
            lsockets = t;

            if ((lsockets[nlsockets] = localserver(opts)) == -1) {
                ret = 1;
                umask(umsk);
                break;
            }
            umask(umsk); /* restore umask */

            if(optget(opts, "LocalSocketGroup")->enabled) {
                char *gname = optget(opts, "LocalSocketGroup")->strarg, *end;
                gid_t sock_gid = strtol(gname, &end, 10);

                if(*end) {
                    struct group *pgrp = getgrnam(gname);

                    if(!pgrp) {
                        logg("!Unknown group %s\n", gname);
                        ret = 1;
                        break;
                    }

                    sock_gid = pgrp->gr_gid;
                }
                if(chown(optget(opts, "LocalSocket")->strarg, -1, sock_gid)) {
                    logg("!Failed to change socket ownership to group %s\n", gname);
                    ret = 1;
                    break;
                }
            }
            if(optget(opts, "LocalSocketMode")->enabled) {
                char *end;

                sock_mode = strtol(optget(opts, "LocalSocketMode")->strarg, &end, 8);

                if(*end) {
                    logg("!Invalid LocalSocketMode %s\n", optget(opts, "LocalSocketMode")->strarg);
                    ret = 1;
                    break;
                }
            } else {
                sock_mode = 0777 /* & ~umsk*/; /* conservative default: umask was 0 in clamd < 0.96 */
            }

            if(chmod(optget(opts, "LocalSocket")->strarg, sock_mode & 0666)) {
                logg("!Cannot set socket permission to %s\n", optget(opts, "LocalSocketMode")->strarg);
                ret = 1;
                break;
            }

            nlsockets++;
        }

        /* fork into background */
        if(!optget(opts, "Foreground")->enabled) {
#ifdef C_BSD	    
            /* workaround for OpenBSD bug, see https://wwws.clamav.net/bugzilla/show_bug.cgi?id=885 */
            for(ret=0;(unsigned int)ret<nlsockets;ret++) {
                if (fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) | O_NONBLOCK) == -1) {
                    logg("!fcntl for lsockets[] failed\n");
                    close(lsockets[ret]);
                    ret = 1;
                    break;
                }
            }
#endif
            gengine = engine;
            atexit(free_engine);
            if(daemonize() == -1) {
                logg("!daemonize() failed: %s\n", strerror(errno));
                ret = 1;
                break;
            }
            gengine = NULL;
#ifdef C_BSD
            for(ret=0;(unsigned int)ret<nlsockets;ret++) {
                if (fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) & ~O_NONBLOCK) == -1) {
                    logg("!fcntl for lsockets[] failed\n");
                    close(lsockets[ret]);
                    ret = 1;
                    break;
                }
            }
#endif
            if(!debug_mode)
                if(chdir("/") == -1)
                    logg("^Can't change current working directory to root\n");

        } else {
            foreground = 1;
        }
#endif

        if (nlsockets == 0) {
            logg("!Not listening on any interfaces\n");
            ret = 1;
            break;
        }

        ret = recvloop_th(lsockets, nlsockets, engine, dboptions, opts);

    } while (0);

    logg("*Closing the main socket%s.\n", (nlsockets > 1) ? "s" : "");

    for (i = 0; i < nlsockets; i++) {
        closesocket(lsockets[i]);
    }

#ifndef _WIN32
    if(nlsockets && localsock) {
        opt = optget(opts, "LocalSocket");

        if(unlink(opt->strarg) == -1)
            logg("!Can't unlink the socket file %s\n", opt->strarg);
        else
            logg("Socket file removed.\n");
    }
#endif

    free(lsockets);

    logg_close();
    optfree(opts);

    cl_cleanup_crypto();

    return ret;
}
예제 #2
0
// encode用のmain関数
int main(int argc, char *argv[])
{
  char *target_filename = NULL;
  //char output_filename[1024];
  char *output_filename = NULL;
  char *dict_filename = NULL;
  unsigned int codewordlength = 0;
  unsigned int shared_dictsize = 0;
  unsigned long int block_length = 0;
  unsigned int length;
  char *rest;
  FILE *input, *output, *dictfile;
  DICT *dict;
  EDICT *edict;
  USEDCHARTABLE ut;
  int result;
  unsigned int b;
  unsigned char *buf;
  unsigned int  *buf2 = NULL;
  OBITFS seqout, dicout;
  int header_output = 0;
  uint i;

   /* オプションの解析 */
  while ((result = getopt(argc, argv, "r:w:b:l:d:s:")) != -1) {
    switch (result) {
    case 'r':
      target_filename = optarg;
      break;
      
    case 'w':
      output_filename = optarg;
      break;
      
    case 'd':
      dict_filename = optarg;
      break;
      
    case 'b':
      block_length = strtoul(optarg, &rest, 10);
      if (*rest != '\0') {
	help(argv);
      }
      break;
      
    case 'l':
      codewordlength = strtoul(optarg, &rest, 10);
      if (*rest != '\0') {
	help(argv);
      }
      break;
      
    case 's':
      shared_dictsize = strtoul(optarg, &rest, 10);
      if (*rest != '\0') {
	help(argv);
      }
      break;
      
    case '?':
      help(argv);
      break;
    }
  }

  // 必要なオプションがそろっているかを確認する
  if (!(target_filename && output_filename && dict_filename && block_length && codewordlength)) {
    help(argv);
  }
  
  // 入力ファイルをオープンする
  input  = fopen(target_filename, "r");
  if (input == NULL) {
    puts("Input file open error at the beginning.");
    exit(1);
  }
  
  // 圧縮データファイルをオープンする
  output = fopen(output_filename, "wb");
  if (output == NULL) {
    puts("Output file open error at the beginning.");
    exit(1);
  }
  
  // 辞書ファイルをオープンする
  dictfile = fopen(dict_filename, "wb");
  if (!dictfile) {
    puts("Dictionary file open error at the beginning.");
    exit(EXIT_FAILURE);
  }

  //  if (NULL == (buf = (unsigned char*)malloc(sizeof(unsigned char) * block_length))) { // || NULL == (buf2 = (unsigned int*)malloc(sizeof(unsigned int) * block_length))) {
  //    puts("malloc fault.");
    //    exit(EXIT_FAILURE);
  //  }

  chartable_init(&ut);
  fill_chartable(input, &ut);
  fseeko(input, 0, SEEK_END);
  dict = createDict(ftello(input));
  fseeko(input, 0, SEEK_SET);
  b = 0;
  obitfs_init(&seqout, output);
  obitfs_init(&dicout, dictfile);
  if (shared_dictsize < ut.size) shared_dictsize = ut.size;
  printf("Generating CFG..."); fflush(stdout);
  outputHeader(&dicout, dict, (unsigned int) codewordlength, (unsigned int) block_length, &ut);
  while (!feof(input)) {
    //    printf("************ Block #%d ************\n", b);
    //    length = fread(buf, sizeof(unsigned char), block_length, input);
    //    if (!length) break;
    //    for (i = 0; i < length; i++) {
    //      buf2[i] = buf[i];
    //    }
    /* for (unsigned int i = 0; i < length; i++) { */
    /*   printf("%u ", buf2[i]); */
    /* } */
    /* puts(""); */
    dict = RunRepair(dict, input, block_length, shared_dictsize, codewordlength, &ut);
    if (!dict) break;
    edict = convertDict(dict, &ut);
    if ((dict->num_rules - CHAR_SIZE + ut.size >= shared_dictsize || feof(input)) && !header_output) {
      header_output = 1;
      outputSharedDictionary(&dicout, edict, &ut, codewordlength, shared_dictsize, b);
    }
    if (header_output) {
      outputLocalDictionary(&dicout, edict, &ut, codewordlength, shared_dictsize, b);
    }
    EncodeCFG(edict, &seqout, codewordlength);
    CleanEDict(edict);
    b++;
  }
  if (!header_output) {
    header_output = 1;
    outputSharedDictionary(&dicout, edict, &ut, codewordlength, shared_dictsize, b);
  }

  printf("Finished!\n"); fflush(stdout);
  if (dict) {
    free(dict->rule);
    free(dict->comp_seq);
    free(dict);
  }
  obitfs_finalize(&seqout);
  obitfs_finalize(&dicout);
  fclose(input);
  fclose(output);
  fclose(dictfile);
  exit(0);
}
예제 #3
0
int
main(int argc, char *argv[])
{
	struct ncp_conn_spec spec;
	struct ncp_conn *conn;
	char *server = NULL;
	char *user_name = NULL;
	char *object_name = NULL;
	int object_type = NCP_BINDERY_USER;
	unsigned char ncp_key[8];
	struct ncp_bindery_object user;
	unsigned char buf_obj_name[50];
	long err;

	char *str;

	char oldpass[200], newpass1[200], newpass2[200];

	int opt;

	setlocale(LC_ALL, "");
	bindtextdomain(NCPFS_PACKAGE, LOCALEDIR);
	textdomain(NCPFS_PACKAGE);

	progname = argv[0];

	while ((opt = getopt(argc, argv, "h?S:U:O:t:")) != EOF)
	{
		switch (opt)
		{
		case 'S':
			server = optarg;
			break;
		case 'U':
			user_name = optarg;
			break;
		case 'O':
			object_name = optarg;
			break;
		case 't':
			object_type = atoi(optarg);
			break;
		case 'h':
		case '?':
			help();
			exit(1);
		default:
			usage();
			exit(1);
		}
	}
	err = ncp_find_conn_spec3(server, user_name, "",
				  1, getuid(), 0, &spec);

	if (err)
	{
		com_err(argv[0], err, _("trying to find server"));
		exit(1);
	}
	if (!object_name)
	{
		object_name = spec.user;
	} else
	{
		strcpy(buf_obj_name, object_name);
		object_name = buf_obj_name;
		str_upper(object_name);
	}
	spec.login_type = object_type;

	printf(_("Changing password for user %s on server %s\n"),
	       object_name, spec.server);

	if (object_name == spec.user)
	{
		str = getpass(_("Enter old password: "******"Enter password for %s: "), spec.user);
		str = getpass(sx);
	}
	if (strlen(str) >= sizeof(oldpass))
	{
		printf(_("Password too long\n"));
		exit(1);
	}
	strcpy(oldpass, str);

	str = getpass(_("Enter new password: "******"Password too long\n"));
		exit(1);
	}
	strcpy(newpass1, str);

	str = getpass(_("Re-Enter new password: "******"Password too long\n"));
		exit(1);
	}
	strcpy(newpass2, str);

	str_upper(oldpass);
	str_upper(newpass1);
	str_upper(newpass2);

	if (strcmp(newpass1, newpass2) != 0)
	{
		printf(_("You mistype the new password, try again\n"));
		exit(1);
	}
	strcpy(spec.password, oldpass);

	if ((conn = ncp_open(&spec, &err)) == NULL)
	{
		com_err(argv[0], err, _("when trying to open connection"));
		exit(1);
	}
	if (object_name != spec.user)
	{
		if (!(err = ncp_get_bindery_object_id(conn, 1, spec.user,
						      &user))
		    && !(err = ncp_login_user(conn, spec.user, oldpass)))
		{
			*oldpass = '******';
		} else
		{
			com_err(argv[0], err, _("not own password"));
		}
	}
	if (((err = ncp_get_encryption_key(conn, ncp_key)) != 0)
	    || ((err = ncp_get_bindery_object_id(conn, 1, object_name,
						 &user)) != 0)
	    || ((err = ncp_change_login_passwd(conn, &user, ncp_key,
					       oldpass, newpass1)) != 0))
	{
		com_err(argv[0], err, _("trying to change password"));
	}
	ncp_close(conn);
	return 0;
}
예제 #4
0
//**********************************************************************************************************************
ReadDistCommand::ReadDistCommand(string option) {
	try {
		abort = false; calledHelp = false;   
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			/*//valid paramters for this command
			string Array[] =  {"phylip", "column", "name", "cutoff", "precision", "group","outputdir","inputdir","sim"};
			vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
			
			OptionParser parser(option);
			map<string, string> parameters = parser.getParameters();
			
			ValidParameters validParameter;
			map<string,string>::iterator it;
		
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			globaldata->newRead();
			
			//if the user changes the input directory command factory will send this info to us in the output parameter 
			string inputDir = validParameter.validFile(parameters, "inputdir", false);		
			if (inputDir == "not found"){	inputDir = "";		}
			else {
				string path;
				it = parameters.find("phylip");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["phylip"] = inputDir + it->second;		}
				}
				
				it = parameters.find("column");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["column"] = inputDir + it->second;		}
				}
				
				it = parameters.find("name");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["name"] = inputDir + it->second;		}
				}
				
				it = parameters.find("group");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["group"] = inputDir + it->second;		}
				}
			}

			//if the user changes the output directory command factory will send this info to us in the output parameter 
			outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found"){	outputDir = "";	}

			//check for required parameters
			phylipfile = validParameter.validFile(parameters, "phylip", true);
			if (phylipfile == "not open") { abort = true; }
			else if (phylipfile == "not found") { phylipfile = ""; }	
			else {  globaldata->setPhylipFile(phylipfile);  globaldata->setFormat("phylip"); 	}
			
			columnfile = validParameter.validFile(parameters, "column", true);
			if (columnfile == "not open") { abort = true; }	
			else if (columnfile == "not found") { columnfile = ""; }
			else {  globaldata->setColumnFile(columnfile); globaldata->setFormat("column");	}
			
			groupfile = validParameter.validFile(parameters, "group", true);
			if (groupfile == "not open") { abort = true; }	
			else if (groupfile == "not found") { groupfile = ""; }
			else {  
				globaldata->setGroupFile(groupfile); 
				//groupMap = new GroupMap(groupfile);
				//groupMap->readMap();
			}

			namefile = validParameter.validFile(parameters, "name", true);
			if (namefile == "not open") { abort = true; }	
			else if (namefile == "not found") { namefile = ""; }
			else {  globaldata->setNameFile(namefile);	}
			
			//you are doing a list and group shared
			if ((phylipfile != "") && (groupfile != "")) { 
			globaldata->setFormat("matrix"); }
			
			if ((phylipfile == "") && (columnfile == "")) { m->mothurOut("When executing a read.dist command you must enter a phylip or a column."); m->mothurOutEndLine(); abort = true; }
			else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When executing a read.dist command you must enter ONLY ONE of the following: phylip or column."); m->mothurOutEndLine(); abort = true; }
		
			if (columnfile != "") {
				if (namefile == "") {  cout << "You need to provide a namefile if you are going to use the column format." << endl; abort = true; }
			}
			
			//check for optional parameter and set defaults
			// ...at some point should added some additional type checking...
			//get user cutoff and precision or use defaults
			string temp;
			temp = validParameter.validFile(parameters, "precision", false);		if (temp == "not found") { temp = "100"; }
			m->mothurConvert(temp, precision); 
			
			temp = validParameter.validFile(parameters, "sim", false);				if (temp == "not found") { temp = "F"; }
			sim = m->isTrue(temp); 
			globaldata->sim = sim;
			
			temp = validParameter.validFile(parameters, "cutoff", false);			if (temp == "not found") { temp = "10"; }
			convert(temp, cutoff); 
			cutoff += (5 / (precision * 10.0)); 
			
			if (abort == false) {
				distFileName = globaldata->inputFileName;
				format = globaldata->getFormat();	
		
				if (format == "column") { read = new ReadColumnMatrix(distFileName); }	
				else if (format == "phylip") { read = new ReadPhylipMatrix(distFileName); }
				else if (format == "matrix") { 
					groupMap = new GroupMap(groupfile);
					int error = groupMap->readMap();
					if (error == 1) { delete groupMap; abort = true; }
					else {
						if (globaldata->gGroupmap != NULL) { delete globaldata->gGroupmap;  }
						globaldata->gGroupmap = groupMap;
					}
				}
		
				if (format != "matrix" ) {
					read->setCutoff(cutoff);
	
					if(namefile != ""){	
						nameMap = new NameAssignment(namefile);
						nameMap->readMap();
					}else{
						nameMap = NULL;
					}
				}
			}
*/
		}

	}
	catch(exception& e) {
		m->errorOut(e, "ReadDistCommand", "ReadDistCommand");
		exit(1);
	}
}
예제 #5
0
int main(int argc, char *argv[]) {
  unsigned char *pkt1 = NULL, buf[100];
  unsigned char *dst6 = NULL, *src6 = NULL, *multicast6, *target6, *neighbor6;
  int pkt1_len = 0, i = 0;
  char *interface;
  int ttl = 1, mode = -1, len = 0;

  if (argc < 3 || strncmp(argv[1], "-h", 2) == 0)
    help(argv[0]);

  while ((i = getopt(argc, argv, "t:s:d:")) >= 0) {
    switch (i) {
      case 't':
        ttl = atoi(optarg);
        break;
      case 's':
        src6 = thc_resolve6(optarg);
        break;
      case 'd':
        dst6 = thc_resolve6(optarg);
        break;
      default:
        fprintf(stderr, "Error: invalid option %c\n", i);
        exit(-1);
    }
  }

  interface = argv[optind];
  if (strncasecmp(argv[optind + 1], "hello", 3) == 0)
    mode = 0;
  if (strncasecmp(argv[optind + 1], "join", 3) == 0)
    mode = 1;
  if (strncasecmp(argv[optind + 1], "prune", 3) == 0) {
    mode = 2;
  }
  if (mode == -1) {
    fprintf(stderr, "Error: no mode defined, specify hello, join or prune\n");
    exit(-1);
  }
  if (mode != 0) {
    if (argc - optind != 5) {
      fprintf(stderr, "Error: join/prune mode need a multicast and target address\n");
      exit(-1);
    }
    neighbor6 = thc_resolve6(argv[optind + 2]);
    multicast6 = thc_resolve6(argv[optind + 3]);
    target6 = thc_resolve6(argv[optind + 4]);
    if (multicast6 == NULL || target6 == NULL || neighbor6 == NULL) {
      fprintf(stderr, "Error: unable to resolve addresses\n");
      exit(-1);
    }
  }

  if (dst6 == NULL)
    dst6 = thc_resolve6("ff02::d");
    
  if (thc_get_own_ipv6(interface, NULL, PREFER_LINK) == NULL) {
    fprintf(stderr, "Error: invalid interface %s\n", interface);
    exit(-1);
  }

  if ((pkt1 = thc_create_ipv6_extended(interface, PREFER_LINK, &pkt1_len, src6, dst6, ttl, 0, 0, 0, 0)) == NULL)
    return -1;
  memset(buf, 0, sizeof(buf));

  // here we set buf and len
  switch(mode) {
    case 0:
      buf[1] = 1;
      buf[3] = 2;
      buf[5] = 255;
      buf[7] = 19;
      buf[9] = 4;
      if (argc - optind >= 3) {
        i = atoi(argv[optind + 2]); 
        buf[10] = i / 256*256*256;
        buf[11] = (i / 65536) % 256;
        buf[12] = (i % 65536) / 256;
        buf[13] = i % 256;
      }
      len = 14;
      break;
    default:
      buf[0] = 2;
      memcpy(buf + 2, neighbor6, 16);
      buf[19] = 1;
      buf[21] = 255;
      buf[22] = 2;
      buf[25] = 128;
      memcpy(buf + 26, multicast6, 16);
      if (mode == 1)
        buf[43] = 1;
      else
        buf[45] = 1;
      buf[46] = 2;
      buf[48] = 7;
      buf[49] = 128;
      memcpy(buf + 50, target6, 16);
      len = 66;
      mode = 3;
  }

  if (thc_add_pim(pkt1, &pkt1_len, mode, buf, len) < 0)
    return -1;
  if (thc_generate_pkt(interface, NULL, NULL, pkt1, &pkt1_len) < 0) {
    fprintf(stderr, "Error: Can not generate packet, exiting ...\n");
    exit(-1);
  }

  while (thc_send_pkt(interface, pkt1, &pkt1_len) < 0)
    usleep(5);

  printf("Sent PIM %s message\n", mode == 0 ? "hello" : mode == 1 ? "join" : "prune");

  return 0;
}
int main(int argc, char **argv){

    std::string filename("");
	unsigned int scale = 5, dmst = 2, window = 3, detectorType = 0, descriptorType = 0, distanceType = 2, strategy = 0;
    double baseSigma = 0.2, sigmaStep = 1.4, minPeak = 0.34, minPeakDistance = 0.001, success = 0.95, inlier = 0.4, matchingThreshold = 0.4;
	bool useMaxRange = false;
	
	int i = 1;
	while(i < argc){
		if(strncmp("-filename", argv[i], sizeof("-filename")) == 0 ){
			filename = argv[++i];
			i++;
		} else if(strncmp("-detector", argv[i], sizeof("-detector")) == 0 ){
			detectorType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-descriptor", argv[i], sizeof("-descriptor")) == 0 ){
			descriptorType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-corresp", argv[i], sizeof("-corresp")) == 0 ){
			corresp = atoi(argv[++i]);
			i++;
		}  else if(strncmp("-distance", argv[i], sizeof("-distance")) == 0 ){
			distanceType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-baseSigma", argv[i], sizeof("-baseSigma")) == 0 ){
			baseSigma = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-sigmaStep", argv[i], sizeof("-sigmaStep")) == 0 ){
			sigmaStep = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-minPeak", argv[i], sizeof("-minPeak")) == 0 ){
			minPeak = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-minPeakDistance", argv[i], sizeof("-minPeakDistance")) == 0 ){
			minPeakDistance = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-scale", argv[i], sizeof("-scale")) == 0 ){
			scale = atoi(argv[++i]);
			i++;
		} else if(strncmp("-dmst", argv[i], sizeof("-dmst")) == 0 ){
			dmst = atoi(argv[++i]);
			i++;
		} else if(strncmp("-window", argv[i], sizeof("-window")) == 0 ){
			scale = atoi(argv[++i]);
			i++;
		} else if(strncmp("-acceptanceSigma", argv[i], sizeof("-acceptanceSigma")) == 0 ){
			acceptanceSigma = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-success", argv[i], sizeof("-success")) == 0 ){
			success = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-inlier", argv[i], sizeof("-inlier")) == 0 ){
			inlier = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-matchingThreshold", argv[i], sizeof("-matchingThreshold")) == 0 ){
			matchingThreshold = strtod(argv[++i], NULL);
			i++;
		} else {
			i++;
		}
    }
    
    if(!filename.size()){
		help();
		exit(-1);
    }
    
    CarmenLogWriter writer;
    CarmenLogReader reader;
    
    m_sensorReference = LogSensorStream(&reader, &writer);
    
    m_sensorReference.load(filename);
    
    SimpleMinMaxPeakFinder *m_peakMinMax = new SimpleMinMaxPeakFinder(minPeak, minPeakDistance);
    
    
    std::string detector("");
    switch(detectorType){
	case 0:
	    m_detectorCurvature = new CurvatureDetector(m_peakMinMax, scale, baseSigma, sigmaStep, dmst);
		m_detectorCurvature->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorCurvature;
	    detector = "curvature";
	    break;
	case 1:
	    m_detectorNormalEdge = new NormalEdgeDetector(m_peakMinMax, scale, baseSigma, sigmaStep, window);
	    m_detectorNormalEdge->setUseMaxRange(useMaxRange);
		m_detector = m_detectorNormalEdge;
	    detector = "edge";
	    break;
	case 2:
	    m_detectorNormalBlob = new NormalBlobDetector(m_peakMinMax, scale, baseSigma, sigmaStep, window);
		m_detectorNormalBlob->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorNormalBlob;
	    detector = "blob";
	    break;
	case 3:
	    m_detectorRange = new RangeDetector(m_peakMinMax, scale, baseSigma, sigmaStep);
		m_detectorRange->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorRange;
	    detector = "range";
	    break;
	default:
	    std::cerr << "Wrong detector type" << std::endl;
	    exit(-1);
    }
    
    HistogramDistance<double> *dist = NULL;
    
    std::string distance("");
    switch(distanceType){
	case 0:
	    dist = new EuclideanDistance<double>();
	    distance = "euclid";
	    break;
	case 1:
	    dist = new Chi2Distance<double>();
	    distance = "chi2";
	    break;
	case 2:
	    dist = new SymmetricChi2Distance<double>();
	    distance = "symchi2";
	    break;
	case 3:
	    dist = new BatthacharyyaDistance<double>();
	    distance = "batt";
	    break;
	case 4:
	    dist = new KullbackLeiblerDistance<double>();
	    distance = "kld";
	    break;
	case 5:
	    dist = new JensenShannonDistance<double>();
	    distance = "jsd";
	    break;
	default:
	    std::cerr << "Wrong distance type" << std::endl;
	    exit(-1);
    }
    
    std::string descriptor("");
    switch(descriptorType){
	case 0:
	    m_betaGenerator = new BetaGridGenerator(0.02, 0.5, 4, 12);
	    m_betaGenerator->setDistanceFunction(dist);
	    m_descriptor = m_betaGenerator;
	    descriptor = "beta";
	    break;
	case 1:
	    m_shapeGenerator = new ShapeContextGenerator(0.02, 0.5, 4, 12);
	    m_shapeGenerator->setDistanceFunction(dist);
	    m_descriptor = m_shapeGenerator;
	    descriptor = "shape";
	    break;
	default:
	    std::cerr << "Wrong descriptor type" << std::endl;
	    exit(-1);
    }
    
    std::cerr << "Processing file:\t" << filename << "\nDetector:\t\t" << detector << "\nDescriptor:\t\t" << descriptor << "\nDistance:\t\t" << distance << std::endl;
    
    switch(strategy){
	case 0:
	    m_ransac = new RansacFeatureSetMatcher(acceptanceSigma * acceptanceSigma * 5.99, success, inlier, matchingThreshold, acceptanceSigma * acceptanceSigma * 3.84, false);
	    break;
	case 1:
	    m_ransac = new RansacMultiFeatureSetMatcher(acceptanceSigma * acceptanceSigma * 5.99, success, inlier, matchingThreshold, acceptanceSigma * acceptanceSigma * 3.84, false);
	    break;
	default:
	    std::cerr << "Wrong strategy type" << std::endl;
	    exit(-1);
    }

    m_sensorReference.seek(0,END);
    unsigned int end = m_sensorReference.tell();
    m_sensorReference.seek(0,BEGIN);

    m_pointsReference.resize(end + 1);
    m_posesReference.resize(end + 1);
        
    computeBoundingBox();
    
    detectLog();
    describeLog();
    
    std::stringstream mapFile;
    mapFile << filename << "_map.png";
/*    cairo_surface_t * cairoMapSurface = cairo_pdf_surface_create(mapFile.str().c_str(), sizeX, sizeY);
    cairo_surface_t * cairoOutSurface = cairo_pdf_surface_create(outFile.str().c_str(), sizeX, sizeY);*/
    cairo_surface_t * cairoMapSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sizeX, sizeY);
//     cairo_surface_t * cairoMapSurface = cairo_svg_surface_create(mapFile.str().c_str(), sizeX, sizeY);
    cairoMap = cairo_create(cairoMapSurface);
    
    std::stringstream outDir;
    outDir << filename << "_" << detector << "_" << descriptor << "_" << distance << "/";
    mkdir(outDir.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    
    computeMap();

    std::string bar(50,' ');
    bar[0] = '#';
    unsigned int progress = 0;
    
    
    for(unsigned int i =0; i < m_pointsReference.size(); i++){
	unsigned int currentProgress = (i*100)/(m_pointsReference.size() - 1);
	if (progress < currentProgress){
	    progress = currentProgress;
	    bar[progress/2] = '#';
	    std::cout << "\rMatching  [" << bar << "] " << progress << "%" << std::flush;
	}
	std::stringstream outFile;
	outFile << outDir.str() << "frame_";
	outFile.width(4);
	outFile.fill('0');
	outFile << std::right << i << ".png";
	cairo_surface_t * cairoOutSurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sizeX, sizeY);
// 	cairo_surface_t * cairoOutSurface = cairo_svg_surface_create(outFile.str().c_str(), sizeX, sizeY);
	cairoOut = cairo_create(cairoOutSurface);
	cairo_translate(cairoOut, -offsetX, -offsetY);
	cairo_scale(cairoOut, scaleFactor, scaleFactor);
	cairo_set_line_width(cairoOut, 1./scaleFactor);
	match(i);
 	cairo_surface_write_to_png(cairoOutSurface, outFile.str().c_str());
	cairo_surface_destroy(cairoOutSurface);
	cairo_destroy(cairoOut);
    }
    std::cout << " done." << std::endl;
    
    cairo_surface_write_to_png(cairoMapSurface, mapFile.str().c_str());
    
    cairo_surface_destroy(cairoMapSurface);
    cairo_destroy(cairoMap);
//     cairo_show_page(cairoOut);
}
예제 #7
0
int
main(int argc, char *argv[])
{
  int i, j, k;
  int sets = 0, countsets = 0, minlen = 0, maxlen = MAXLENGTH, count = 0;
  int set_low = 0, set_up = 0, set_no = 0, set_print = 0, set_other = 0;
  FILE *in = stdin, *out = stdout;
  char buf[MAXLENGTH + 1];

  prg = argv[0];
  if (argc < 2)
    help();

  while ((i = getopt(argc, argv, "i:o:m:M:c:lunps")) >= 0) {
    switch (i) {
    case 'i':
      if ((in = fopen(optarg, "r")) == NULL) {
        fprintf(stderr, "Error: unable to open input file %s\n", optarg);
        exit(-1);
      }
      break;
    case 'o':
      if ((out = fopen(optarg, "w")) == NULL) {
        fprintf(stderr, "Error: unable to open output file %s\n", optarg);
        exit(-1);
      }
      break;
    case 'm':
      minlen = atoi(optarg);
      break;
    case 'M':
      maxlen = atoi(optarg);
      break;
    case 'c':
      countsets = atoi(optarg);
      break;
    case 'l':
      if (set_low == 0) {
        set_low = 1;
        sets++;
      }
      break;
    case 'u':
      if (set_up == 0) {
        set_up = 1;
        sets++;
      }
      break;
    case 'n':
      if (set_no == 0) {
        set_no = 1;
        sets++;
      }
      break;
    case 'p':
      if (set_print == 0) {
        set_print = 1;
        sets++;
      }
      break;
    case 's':
      if (set_other == 0) {
        set_other = 1;
        sets++;
      }
      break;
    default:
      help();
    }
  }
  if (minlen > maxlen) {
    fprintf(stderr, "Error: -m MINLEN is greater than -M MAXLEN\n");
    exit(-1);
  }
  if (countsets > sets) {
    fprintf(stderr, "Error: -c MINSETS is larger than the sets defined\n");
    exit(-1);
  }
  if (countsets == 0)
    countsets = sets;

  while (fgets(buf, sizeof(buf), in) != NULL) {
    i = -1;
    if (buf[0] == 0)
      continue;
    if (buf[strlen(buf) - 1] == '\n')
      buf[strlen(buf) - 1] = 0;
    if (strlen(buf) >= minlen && strlen(buf) <= maxlen) {
      i = 0;
      if (countsets > 0) {
        if (set_low)
          if (strpbrk(buf, "abcdefghijklmnopqrstuvwxyz") != NULL)
            i++;
        if (set_up)
          if (strpbrk(buf, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") != NULL)
            i++;
        if (set_no)
          if (strpbrk(buf, "0123456789") != NULL)
            i++;
        if (set_print) {
          j = 0;
          for (k = 0; k < strlen(buf); k++)
            if (isprint(buf[k]) && isalnum(buf[k]) == 0)
              j = 1;
          if (j)
            i++;
        }
        if (set_other) {
          j = 0;
          for (k = 0; k < strlen(buf); k++)
            if (isprint(buf[k]) == 0 && isalnum(buf[k]) == 0)
              j = 1;
          if (j)
            i++;
        }
      }
      if (i >= countsets) {
        fprintf(out, "%s\n", buf);
        count++;
      }
    }
    /* fprintf(stderr, "[DEBUG] i: %d  minlen: %d  maxlen: %d  len: %d\n", i, minlen, maxlen, strlen(buf)); */
  }

  return count;
}
예제 #8
0
int
main (int argc, char *argv[])
{
  char *newname, *path, *suffix;
  int add_random, add_suffix, add_wild, argo, create, directory, file_id,
    length, opt, path_ok, rc, user_dir, verbose;

  /* parse options */
  add_random = 1;
  add_suffix = 0;
  add_wild = 0;
  create = 1;
  directory = 0;
  path = "";
  user_dir = 0;
  suffix = "";
  verbose = 0;
  while ((opt = getopt (argc, argv, "cd:hnqs:vwD")) != OPTEND)
    switch (opt)
      {
      case 'c':
        create = 0;
        break;
      case 'd':
        user_dir = 1;
        path = optarg;
        break;
      case 'h':
        help (stdout);
        return (0);
      case 'n':
        add_random = 0;
        create = 0;
        break;
      case 'q':
        verbose = -1;
        break;
      case 's':
        add_suffix = 1;
        suffix = optarg;
        break;
      case 'v':
        verbose = 1;
        break;
      case 'w':
        add_wild = 1;
        add_random = 0;
        create = 0;
        break;
      case 'D':
        directory = 1;
        break;
      case '?':
        help (stderr);
        return (1);
      }

  /* if no arguments given, print help */
  argo = argc - optind;
  if (argo == 0)
    {
      help (stdout);
      return (0);
    }

  /* if incorrect number of arguments given, print help */
  if (argo != 1)
    {
      help (stderr);
      return (1);
    }

  /* find a writeable path */
  path_ok = 0;
  if (user_dir)
    {
      if (verbose == -1)
        path_ok = good_dir (path, 0);
      else
        path_ok = good_dir (path, 1);
    }
  if (!path_ok)
    {
      path = getenv ("TMPDIR");
      path_ok = good_dir (path, verbose);
    }
  if (!path_ok)
    {
      path = getenv ("TEMP");
      path_ok = good_dir (path, verbose);
    }
  if (!path_ok)
    {
      path = getenv ("TMP");
      path_ok = good_dir (path, verbose);
    }
  if (!path_ok)
    {
      path = "/tmp";
      path_ok = good_dir (path, verbose);
    }
  if (!path_ok)
    {
      path = "/var/tmp";
      path_ok = good_dir (path, verbose);
    }
  if (!path_ok)
    {
      path = ".";
      path_ok = good_dir (path, verbose);
    }
  if (!path_ok)
    {
      fprintf (stderr, "tempname error: can't find writeable directory\n");
      return (2);
    }

  /* append a filename prefix, unique letter block, and optional suffix */
  length = (int) strlen (path) + (int) strlen (argv[optind]) + (int) strlen(suffix) + 10;
  newname = (char *) malloc (length * sizeof (char));
  strcpy (newname, "");
  strcat (newname, path);
#if (defined(__MINGW32__) || defined(DJGPP))
  if (newname[strlen (newname) - 1] != '\\')
    strcat (newname, "\\");
#else
  if (newname[strlen (newname) - 1] != '/')
    strcat (newname, "/");
#endif
  strcat (newname, argv[optind]);
  if (add_wild)
    strcat (newname, "_*");
  else if (add_random)
    strcat (newname, "_XXXXXX");
  if (add_suffix)
    strcat (newname, suffix);

  /* scramble unique letter block and optionally create temporary file */
  if (add_random)
    {
      if (directory)
        {
          rc = mkstemp_custom (newname, GT_DIR);
          if (rc < 0)
            {
              fprintf (stderr, "tempname error: can't open a tempdir for writing\n");
              return (3);
            }
        }
      else if (create)
        {
          file_id = mkstemp_custom (newname, GT_FILE);
          if (file_id > 0)
            close (file_id);
          else
            {
              fprintf (stderr, "tempname error: can't open a tempfile for writing\n");
              return (3);
            }
        }
      else
        {
          rc = mkstemp_custom (newname, GT_NOCREATE);
          if (rc < 0)
            {
              fprintf (stderr, "tempname error: can't create a tempname for writing\n");
              return (3);
            }
        }
   }

  /* print out filename of temporary file */
  if (strlen (newname) == 0)
    {
      fprintf (stderr, "tempname error: can't form unique filename\n");
      free (newname);
      return (3);
    }
  else
    fprintf (stdout, "%s\n", newname);

  /* free memory and indicate successful finish */
  free (newname);
  return (0);
}
예제 #9
0
static int parse_argv(int argc, char **argv)
{

	int c, i, j;
	int uflag = 0;
	char *p;
	while ((!uflag) && (c = getopt(argc, argv, "t:r:f:p:u:F:hv?")) != -1)
	{
		switch (c)
		{
			case 't':
				time_alarm = atoi(optarg);
				break;
			case 'u':
				uflag = 1;
			case 'p':
				strncpy(status_dir, optarg, sizeof(status_dir) - 1);
				if (strlen(status_dir) < 1)
				{
					printf("bad status_dir: sub-string \"status/module_name\" is required.\n");
					return(-1);
				}
				p = &status_dir[strlen(status_dir) - 1];
				while(p - status_dir >= 0 &&  (*p == '/' || isblank((int)(*p))))
				{
					*p = '\0';
					p--;
				}
				if (NULL == (p = strstr(status_dir, "status/")))
				{
					printf("bad status_dir: sub-string \"status/module_name\" is required!\n");
					return(-1);
				}
				p += 7;
				while(*p && *p == '/')
					p++;
				if (*p == '\0' || snprintf(service, sizeof(service), "%s", p) < 1)
				{
					printf("bad status_dir: sub-string \"status/module_name\" is required!\n");
					return(-1);
				}
				break;
			case 'f':
				p = optarg;
				i = 0;
				while(*p && i < 512 - 1)
				{
					while (*p && isblank((int)(*p)))
					{
						p++;
					}
					j = 0;
					while (*p && !isblank((int)(*p)) && j < 1024 - 1)
					{
						cmd[i][j++] = *p++;
					}
					if (*p && !isblank((int)*p))
					{
						printf("arg is too long: %s\n", optarg);
						return(-1);
					}
					if (!cmd[i][0])
						break;
					cmdp[i] = cmd[i];
					i++;
				}
				break;
			case 'r':
				strncpy(restart_sh, optarg, sizeof(restart_sh) - 1);
				break;
			case 'F':
				bzero(conf_path, sizeof(conf_path));
				strncpy(conf_path, optarg, sizeof(conf_path) - 1);
				break;
			case 'v':
				printf("v 1.0.0\n");
				return(-1);
			case 'h':
			case '?':
			default:
				help(argv[0]);
				return(-1);
		}
	}
	if (!cmdp[0] && optind < argc)
	{
		i = 0;
		while (optind < argc &&  i < 512 - 1)
		{
			strncpy(cmd[i], argv[optind++], sizeof(cmd[i]) -1);
			cmdp[i] = cmd[i];
			i++;
		}	
	}
	
	if (!cmdp[0] || !status_dir[0])
	{
		printf("bad arg:\n");
		help(argv[0]);
		return(-1);
	}
	return(0);
}
예제 #10
0
SeqSummaryCommand::SeqSummaryCommand(string option)  {
	try {
		abort = false; calledHelp = false;   
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string,string> parameters = parser.getParameters();
			
			ValidParameters validParameter("summary.seqs");
			map<string,string>::iterator it;
			
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			//if the user changes the input directory command factory will send this info to us in the output parameter 
			string inputDir = validParameter.validFile(parameters, "inputdir", false);		
			if (inputDir == "not found"){	inputDir = "";		}
			else {
				string path;
				it = parameters.find("fasta");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["fasta"] = inputDir + it->second;		}
				}
				
				it = parameters.find("name");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["name"] = inputDir + it->second;		}
				}
                
                it = parameters.find("count");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["count"] = inputDir + it->second;		}
				}
			}
			
			//initialize outputTypes
			vector<string> tempOutNames;
			outputTypes["summary"] = tempOutNames;
			
			//check for required parameters
			fastafile = validParameter.validFile(parameters, "fasta", true);
			if (fastafile == "not open") { abort = true; }
			else if (fastafile == "not found") { 				
				fastafile = m->getFastaFile(); 
				if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
				else { 	m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
			}else { m->setFastaFile(fastafile); }	
			
			namefile = validParameter.validFile(parameters, "name", true);
			if (namefile == "not open") { namefile = ""; abort = true; }
			else if (namefile == "not found") { namefile = "";  }	
			else { m->setNameFile(namefile); }
            
            countfile = validParameter.validFile(parameters, "count", true);
			if (countfile == "not open") { abort = true; countfile = ""; }	
			else if (countfile == "not found") { countfile = ""; }
			else { m->setCountTableFile(countfile); }
			
            if ((countfile != "") && (namefile != "")) { m->mothurOut("You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
			
			//if the user changes the output directory command factory will send this info to us in the output parameter 
			outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found"){	
				outputDir = "";	
				outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it	
			}
			
			string temp = validParameter.validFile(parameters, "processors", false);	if (temp == "not found"){	temp = m->getProcessors();	}
			m->setProcessors(temp);
			m->mothurConvert(temp, processors);
			
            if (countfile == "") {
                if (namefile == "") {
                    vector<string> files; files.push_back(fastafile);
                    parser.getNameFile(files);
                }
            }
		}
	}
	catch(exception& e) {
		m->errorOut(e, "SeqSummaryCommand", "SeqSummaryCommand");
		exit(1);
	}
}
예제 #11
0
파일: mia_main.c 프로젝트: hjanime/mia
int main( int argc, char* argv[] ) {

  char mat_fn[MAX_FN_LEN+1];
  char maln_fn[MAX_FN_LEN+1];
  char fastq_out_fn[MAX_FN_LEN+1];
  char maln_root[MAX_FN_LEN+1];
  char ref_fn[MAX_FN_LEN+1];
  char frag_fn[MAX_FN_LEN+1];
  char adapter_code[2]; // place to keep the argument for -a (which adapter to trim)
  char* c_time; // place to keep asctime string
  char* test_id;

  int ich;
  int any_arg = 0;
  int Hard_cut = 0; // If 0 => use dynamic score cutoff, if > 0 use this instead
  int circular = 0; // Boolean, TRUE if reference sequence is circular
  int make_fastq = 0; // Boolean, TRUE if we should also output fastq database of seqs in assembly
  int seq_code = 0; // code to indicate sequence input format; 0 => fasta; 1 => fastq
  int do_adapter_trimming = 0; // Boolean, TRUE if we should try to trim
                               // adapter from input sequences
  int iterate = 0; //Boolean, TRUE means interate the assembly until convergence
  // on an assembled sequence
  int FINAL_ONLY = 0; //Boolean, TRUE means only write out the final assembly maln file
                      //         FALSE (default) means write out each one
  int ids_rest = 0; // Boolean, TRUE means restrict analysis to IDs in input file
  int repeat_filt = 0; //Boolean, TRUE means remove sequences that are repeats, 
                       // keeping best-scoring representative
  int repeat_qual_filt = 0; //Boolean, TRUE means remove sequences that are repeats,
                            // keeping best quality score sum representative
  int just_outer_coords = 1; // Boolean, TRUE means just use strand, start, and end to
                             // determine if sequences are redundant
  int SCORE_CUT_SET = 0; //Boolean, TRUE means user has set a length/score cutoff line
  int seen_seqs = 0;
  int hp_special = 0; // Boolean, TRUE means user wants hp gap special discount
  int distant_ref = 0; // Boolean, TRUE means the initial reference sequence is
                       // known to be distantly related so keep trying to align all
                       // sequences each round
  int kmer_filt_len = -1; // length of kmer filtering, if user wants it; otherwise
                          // special value of -1 indicates this is unset
  int soft_mask = 0; //Boolean; TRUE => do not use kmers that are all lower-case
                     //        FALSE => DO use all kmers, regardless of case
  int iter_num; // Number of iterations of assembly done
  int collapse = 0; // Boolean; TRUE => collapse input sequences in FSDB to improve
                    //                  sequence quality
                    //          FALSE => (default) keep all sequences
  double slope     = DEF_S; // Set these to default unless, until user changes
  double intercept = DEF_N; // them 
  MapAlignmentP maln, // Contains all fragments initially better
                      // than FIRST_ROUND_SCORE_CUTOFF
    culled_maln;      // Contains all fragments with scores
                      // better than SCORE_CUTOFF
  AlignmentP fw_align, rc_align, adapt_align;
  
  PSSMP ancsubmat   = init_flatsubmat();
  PSSMP rcancsubmat = revcom_submat(ancsubmat);
  const PSSMP flatsubmat  = init_flatsubmat();

  KPL* fkpa; // Place to keep forward kmer array if user requested kmer 
  KPL* rkpa; // Place to keep reverse kmer array if user requested kmer 
  IDsListP good_ids;
  FragSeqP frag_seq;
  PWAlnFragP front_pwaln, back_pwaln;
  FSDB fsdb; // Database to hold sequences to iterate over
  FILE* FF;
  time_t curr_time;


  char maln_root_def[] = "assembly.maln.iter";
  extern int optind;
  extern char* optarg;
  char neand_adapt[] = "GTCAGACACGCAACAGGGGATAGGCAAGGCACACAGGGGATAGG";
  char stand_adapt[] = "CTGAGACACGCAACAGGGGATAGGCAAGGCACACAGGGGATAGG";
  char user_def_adapt[128];
  char* adapter; // set to either neand_adapt or stand_adapt based on user preference
  adapter = neand_adapt; // Default is Neandertal
  char* assembly_cons;
  char* last_assembly_cons;
  int cc = 1; // consensus code for calling consensus base
  int i;

  /* Set the default output filename until the user overrides it */
  strcpy( maln_root, maln_root_def );


  /* Process command line arguments */
  while( (ich=getopt( argc, argv, "s:r:f:m:a:p:H:I:S:N:k:q:FTciuhDMUAC" )) != -1 ) {
    switch(ich) {
    case 'c' :
      circular = 1;
      break;
    case 'q' :
      make_fastq = 1;
      strcpy( fastq_out_fn, optarg );
    case 'C' :
      collapse = 1;
      break;
    case 'i' :
      iterate = 1;
      break;
    case 'h' :
      hp_special = 1;
      break;
    case 'u' :
      repeat_filt = 1;
      break;
    case 'A' :
      just_outer_coords = 0;
      break;
    case 'U' :
      repeat_qual_filt = 1;
      break;
    case 'D' :
      distant_ref = 1;
      break;
    case 'p' :
      cc = atoi( optarg );
      any_arg = 1;
      break;
    case 'I' :
      good_ids = parse_ids( optarg );
      ids_rest = 1;
      break;
    case 'H' :
      Hard_cut = atoi( optarg );
      if ( Hard_cut <= 0 ) {
	fprintf( stderr, "Hard cutoff (-H) must be positive\n" );
	help();
	exit( 0 );
      }
      any_arg = 1;
      break;
    case 'M' :
      soft_mask = 1;
      break;
    case 's' :
      strcpy( mat_fn, optarg );
      free( ancsubmat ); // trash the flat submat we initialized with
      ancsubmat   = read_pssm( mat_fn );
      free( rcancsubmat ); // trash the init rcsubmat, too
      rcancsubmat = revcom_submat( ancsubmat );
      any_arg = 1;
      break;
    case 'r' :
      strcpy( ref_fn, optarg );
      any_arg = 1;
      break;
    case 'k' :
      kmer_filt_len = atoi( optarg );
      any_arg = 1;
      break;
    case 'f' :
      strcpy( frag_fn, optarg );
      any_arg = 1;
      break;
    case 'm' :
      strcpy( maln_root, optarg );
      any_arg = 1;
      break;
    case 'T' :
      do_adapter_trimming = 1;
      break;
    case 'a' :
      if ( strlen( optarg ) > 127 ) {
	  fprintf( stderr, "That adapter is too big!\nMIA will use the standard adapter.\n" );
	  adapter = stand_adapt;
      }
      else {
	strcpy( user_def_adapt, optarg );
	  if ( strlen( user_def_adapt ) > 1 ) {
	    adapter = user_def_adapt;
	  }
	  else {
	    if ( !( (user_def_adapt[0] == 'n') ||
		    (user_def_adapt[0] == 'N') ) ) {
	      adapter = stand_adapt;
	    }
	    else {
	      adapter = neand_adapt;
	    }
	  }
      }
      break;
    case 'S' :
      slope = atof( optarg );
      SCORE_CUT_SET = 1;
      break;
    case 'N' :
      intercept = atof( optarg );
      SCORE_CUT_SET = 1;
      break;
    case 'F' :
      FINAL_ONLY = 1;
      break;
    default :
      help();
      exit( 0 );
    }
  }

  if ( !any_arg ) {
    help();
    exit( 0 );
  }

  if ( optind != argc ) {
    fprintf( stderr, "There seems to be some extra cruff on the command line that mia does not understand.\n" );
  }

  /* Start the clock... */
  curr_time = time(NULL);
  //  c_time = (char*)save_malloc(64*sizeof(char));
  //  c_time = asctime(localtime(&curr_time));

  /* Announce that we're starting */
  fprintf( stderr, 
	   "Starting assembly of %s\nusing %s\nas reference at %s\n", 
	   frag_fn, ref_fn, 
	   asctime(localtime(&curr_time)) );


  /* Set up the maln structure */
  maln = (MapAlignmentP)init_map_alignment();
  maln->cons_code = cc; 
  if ( maln == NULL ) {
    fprintf( stderr, "Not enough memories for this\n" );
    exit( 1 );
  }

  /* Set the distant_ref flag */
  maln->distant_ref = distant_ref;

  /* Set up the FSDB for keeping good-scoring sequence in memory */
  fsdb = init_FSDB();
  if ( fsdb == NULL ) {
    fprintf( stderr, "Not enough memories for holding sequences\n" );
    exit( 1 );
  }

  /* Read in the reference sequence and make reverse complement, too*/
  if ( read_fasta_ref( maln->ref, ref_fn ) != 1 ) {
    fprintf( stderr, "Problem reading reference sequence file %s\n", ref_fn );
    exit( 1 );
  }

  /* Add wrap-around sequence (rc, too) and set maln->ref->circular
     if it's circular */
  if ( circular ) {
    add_ref_wrap( maln->ref );
  }
  else {
    maln->ref->wrap_seq_len = maln->ref->seq_len;
  }
  /* Add space for the gaps array */
  maln->ref->gaps = (int*)save_malloc((maln->ref->wrap_seq_len+1) *
				      sizeof(int));
  for( i = 0; i <= maln->ref->wrap_seq_len; i++ ) {
    maln->ref->gaps[i] = 0;
  }

  /* Set up fkpa and rkpa for list of kmers in the reference (forward and
     revcom strand) if user wants kmer filtering */
  if ( kmer_filt_len > 0 ) {
    fprintf( stderr, "Making kmer list for k-mer filtering...\n" );
    fkpa = init_kpa(kmer_filt_len);
    rkpa = init_kpa(kmer_filt_len);
    /* 
    kmer_list = (KmersP)pop_kmers( maln->ref, kmer_filt_len );
    */
    populate_kpa( fkpa, maln->ref->seq, 
		  maln->ref->wrap_seq_len, kmer_filt_len, 
		  soft_mask );
    populate_kpa( rkpa, maln->ref->rcseq, 
		  maln->ref->wrap_seq_len, kmer_filt_len,
		  soft_mask );
  }

  /* Now kmer arrays have been made if requested. We can upper case
     the reference sequences. */
  make_ref_upper( maln->ref );

  /* Set up FragSeqP to point to a FragSeq */
  frag_seq = (FragSeqP)save_malloc(sizeof(FragSeq));

  /* Set up the alignment structures for forward and reverse
     complement alignments */
  fw_align = (AlignmentP)init_alignment( INIT_ALN_SEQ_LEN,
					 (maln->ref->wrap_seq_len + 
					  (2*INIT_ALN_SEQ_LEN)),
					 0, hp_special );
  rc_align = (AlignmentP)init_alignment( INIT_ALN_SEQ_LEN,
					 (maln->ref->wrap_seq_len + 
					  (2*INIT_ALN_SEQ_LEN)),
					 1, hp_special );

  /* Set up the alignment structure for adapter trimming, if user
     wants that */
  if ( do_adapter_trimming ) {
    adapt_align = (AlignmentP)init_alignment( INIT_ALN_SEQ_LEN,
					      INIT_ALN_SEQ_LEN,
					      0, hp_special );
    /* Setup the flatsubmat */
    //flatsubmat = init_flatsubmat();
    adapt_align->submat = flatsubmat;

    adapt_align->seq2   = adapter;
    adapt_align->len2   = strlen( adapt_align->seq2 );
    pop_s2c_in_a( adapt_align );
    if ( hp_special ) {
      pop_hpl_and_hps( adapt_align->seq2, adapt_align->len2,
		       adapt_align->hprl, adapt_align->hprs );
    }
    /* Set for a semi-global that pays a penalty for unaligning the
       beginning of the adapter, but not for the end of the adapter.
       This is because if the sequence read (align->seq1) ends, then
       we won't see any more of the adapter. When we search for the
       best alignment, we'll only look in the last column, requiring that
       all of align->seq1 is accounted for */
    adapt_align->sg5    = 1;
    adapt_align->sg3    = 0;
  }

  fw_align->seq1 = maln->ref->seq;
  rc_align->seq1 = maln->ref->rcseq;
  if ( circular ) {
    fw_align->len1 = maln->ref->wrap_seq_len;
    rc_align->len1 = maln->ref->wrap_seq_len;
  }
  else {
    fw_align->len1 = maln->ref->seq_len;
    rc_align->len1 = maln->ref->seq_len;
  }

  /* Now the reference sequence and its reverse complement are
     prepared, put the s1c lookup codes in */
  pop_s1c_in_a( fw_align );
  pop_s1c_in_a( rc_align );

  if ( hp_special ) {
    pop_hpl_and_hps( fw_align->seq1, fw_align->len1,
		     fw_align->hpcl, fw_align->hpcs );
    pop_hpl_and_hps( rc_align->seq1, rc_align->len1,
		     rc_align->hpcl, rc_align->hpcs );
  }

  /* One by one, go through the input file of fragments to be aligned.
     Align them to the reference. For each fragment generating an
     alignment score better than the cutoff, merge it into the maln
     alignment. Keep track of those that don't, too. */
  FF = fileOpen( frag_fn, "r" );
  seq_code = find_input_type( FF );

  //LOG = fileOpen( log_fn, "w" );
  front_pwaln = (PWAlnFragP)save_malloc( sizeof(PWAlnFrag));
  back_pwaln  = (PWAlnFragP)save_malloc( sizeof(PWAlnFrag));

  /* Give some space to remember the IDs as we see them */
  test_id = (char*)save_malloc(MAX_ID_LEN * sizeof(char));

  /* Announce we're strarting alignment of fragments */
  fprintf( stderr, "Starting to align sequences to the reference...\n" );

  while( read_next_seq( FF, frag_seq, seq_code ) ) {
    seen_seqs++;
    strcpy( test_id, frag_seq->id );
    if ( DEBUG ) {
      fprintf( stderr, "%s\n", frag_seq->id );
    }
    if ( !ids_rest ||
	 ( bsearch( &test_id, good_ids->ids, 
		    good_ids->num_ids,
		    sizeof(char*), idCmp ) 
	   != NULL ) ) {

      if ( do_adapter_trimming ) {
	/* Trim sequence (set frag_seg->trimmed and 
	   frag_seg->trim_point field) */
	trim_frag( frag_seq, adapter, adapt_align );
      }
      else {
	frag_seq->trimmed = 0;
      }

      /* Check if kmer filtering. If so, filter */
      if ( new_kmer_filter( frag_seq, fkpa, rkpa, kmer_filt_len,
			    fw_align, rc_align ) ) {
	/* Align this fragment to the reference and write 
	   the result into pwaln; use the ancsubmat, not the reverse
	   complemented rcsancsubmat during this first iteration because
	   all sequence is forward strand
	*/
	fw_align->submat = ancsubmat;
	rc_align->submat = ancsubmat;
	
	if ( sg_align( maln, frag_seq, fsdb, 
		       fw_align, rc_align,
		       front_pwaln, 
		       back_pwaln ) == 0 ) {
	  fprintf( stderr, "Problem handling %s\n", frag_seq->id );
	}
      }  
    }
    if ( seen_seqs % 1000 == 0 ) {
      fprintf( stderr, "." );
    }
    if ( seen_seqs % 80000 == 0 ) {
      fprintf( stderr, "\n" );
    }
  }

  /* Now, fsdb is complete and points to all the things in maln.
     So we can fill in the AlnSeqP->smp array for everything in the 
     maln->AlnSeqArray to know which matrices to use for *CALLING* 
     a consensus; Conveniently, there are pointers to all of these
     in the fss->fss[X]->front|back_asp */
  pop_smp_from_FSDB( fsdb, PSSM_DEPTH );

  //fprintf( LOG, "__Finished with initial alignments__" );
  //fflush( LOG );
  fprintf( stderr, "\n" );
  iter_num = 1;

  /* Now, we need a new MapAlignment, culled_maln, that is big
     enough to hold all the unique guys from maln */
  culled_maln = init_culled_map_alignment( maln );

  /* Filtering repeats announcement */
  fprintf( stderr, "Repeat and score filtering\n" );

  /* If user wants to filter against repeats by alignment score, do it */
  if ( repeat_filt ) {  
    /* Sort fsdb by fsdb->as */
    sort_fsdb( fsdb );
    
    /* Now, everything is sorted in fsdb, so I can easily see
       which guys are unique by as, ae, and rc fields */
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }

  /* If user wants to filter against repeats by q-score sum, do it */
  if ( repeat_qual_filt ) {  
    /* Sort fsdb by fsdb->as */
    sort_fsdb_qscore( fsdb );
    
    /* Now, everything is sorted in fsdb, so I can easily see
       which guys are unique by as, ae, and rc fields */
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }

  /* Now, we know which sequences are unique, so make a
     culled_maln with just the unique guys */
  cull_maln_from_fsdb( culled_maln, fsdb, Hard_cut, 
		       SCORE_CUT_SET, slope, intercept );

  fclose(FF);

  /* Tell the culled_maln which matrices to use for assembly */
  culled_maln->fpsm = ancsubmat;
  culled_maln->rpsm = rcancsubmat;

  sort_aln_frags( culled_maln ); //invalidates fsdb->front|back_asp fields!

  fw_align->submat = ancsubmat;
  fw_align->sg5 = 1;
  fw_align->sg3 = 1;

  last_assembly_cons = (char*)save_malloc((maln->ref->seq_len +1) * 
				     sizeof(char));
  strncpy( last_assembly_cons, maln->ref->seq, 
	   maln->ref->seq_len );
  last_assembly_cons[maln->ref->seq_len] = '\0';

  /* Re-align everything with revcomped
     sequence and substitution matrices, but first
     unmask all alignment positions and collapse sequences
     if requested
  */
  memset(fw_align->align_mask, 1, fw_align->len1);
  if ( collapse ) {
    collapse_FSDB( fsdb, Hard_cut, SCORE_CUT_SET, 
		   slope, intercept );
  }
  reiterate_assembly( last_assembly_cons, iter_num, maln, fsdb,
		      fw_align, front_pwaln, back_pwaln, 
		      ancsubmat, rcancsubmat );
  pop_smp_from_FSDB( fsdb, PSSM_DEPTH );
  fprintf( stderr, "Repeat and score filtering\n" );
  if ( repeat_filt ) {
    sort_fsdb( fsdb );
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }
  if ( repeat_qual_filt ) {  
    sort_fsdb_qscore( fsdb );
    set_uniq_in_fsdb( fsdb, just_outer_coords );
  }
  cull_maln_from_fsdb( culled_maln, fsdb, Hard_cut,
		       SCORE_CUT_SET, slope, intercept );
  
  
  /* Tell the culled_maln which matrices to use for assembly */
  culled_maln->fpsm = ancsubmat;
  culled_maln->rpsm = rcancsubmat;
  
  //invalidates fsdb->front|back_asp fields!
  sort_aln_frags( culled_maln );
  sprintf( maln_fn, "%s.%d", maln_root, iter_num );
  if ( !iterate || !FINAL_ONLY ) {
    write_ma( maln_fn, culled_maln );
    if ( make_fastq ) {
      write_fastq( fastq_out_fn, fsdb );
    }
  }

  /* Are we iterating (re-aligning to the a new consensus? */
  if (iterate) {
    /* New assembly consensus announcement */
    fprintf( stderr, "Generating new assembly consensus\n" );
    assembly_cons = consensus_assembly_string( culled_maln );

    while( ( strcmp( assembly_cons, last_assembly_cons ) != 0) &&
	   (iter_num < MAX_ITER) ) {
      /* Another round...*/
      iter_num++;
      free( last_assembly_cons );
      last_assembly_cons = assembly_cons;

      fprintf( stderr, "Starting assembly iteration %d\n", 
	       iter_num );

      /* If the user wants collapsed sequences, now is the time */
      if ( collapse ) {
	collapse_FSDB( fsdb, Hard_cut, SCORE_CUT_SET, 
		       slope, intercept );
      }

      reiterate_assembly( assembly_cons, iter_num, maln, fsdb, 
			  fw_align, front_pwaln, back_pwaln,
			  ancsubmat, rcancsubmat );

      pop_smp_from_FSDB( fsdb, PSSM_DEPTH );

      fprintf( stderr, "Repeat and score filtering\n" );
      if ( repeat_filt ) {
	sort_fsdb( fsdb );
	set_uniq_in_fsdb( fsdb, just_outer_coords );
      }
      if ( repeat_qual_filt ) {
	sort_fsdb_qscore( fsdb );
	set_uniq_in_fsdb( fsdb, just_outer_coords );
      }
      cull_maln_from_fsdb( culled_maln, fsdb, Hard_cut,
			   SCORE_CUT_SET, slope, intercept );

      
      /* Tell the culled_maln which matrices to use for assembly */
      culled_maln->fpsm = ancsubmat;
      culled_maln->rpsm = rcancsubmat;

      //invalidates fsdb->front|back_asp fields!
      sort_aln_frags( culled_maln );

      sprintf( maln_fn, "%s.%d", maln_root, iter_num );
      if ( !FINAL_ONLY ) {
	fprintf( stderr, "Writing maln file for iteration %d\n", 
		 iter_num );
	write_ma( maln_fn, culled_maln );
      }
      assembly_cons = consensus_assembly_string( culled_maln );
    }
  
    /* Convergence? */
    if ( strcmp( assembly_cons, last_assembly_cons ) == 0 ) {
      fprintf( stderr, "Assembly convergence - writing final maln\n" );
      write_ma( maln_fn, culled_maln );
    }
    else {
      fprintf( stderr, "Assembly did not converge after % rounds, quitting\n" );
      write_ma( maln_fn, culled_maln );
    }
    if ( make_fastq ) {
      write_fastq( fastq_out_fn, fsdb );
    }
  }

  /* No iteration, but we must still re-align everything with revcomped
     sequence and substitution matrices to keep scores comparable to what
     they would have been had we iterated */

  /* Announce we're finished */
  curr_time = time(NULL);
  //  c_time    = asctime(localtime(&curr_time));
  fprintf( stderr, "Assembly finished at %s\n",
	   asctime(localtime(&curr_time)) );

  exit( 0 );
}
예제 #12
0
//**********************************************************************************************************************
GetRAbundCommand::GetRAbundCommand(string option)  {
	try {
		abort = false; calledHelp = false;   
		allLines = 1;
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string,string> parameters = parser.getParameters();
			map<string,string>::iterator it;
			
			ValidParameters validParameter;
			
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			//initialize outputTypes
			vector<string> tempOutNames;
			outputTypes["rabund"] = tempOutNames;
			
			//if the user changes the input directory command factory will send this info to us in the output parameter 
			string inputDir = validParameter.validFile(parameters, "inputdir", false);		
			if (inputDir == "not found"){	inputDir = "";		}
			else {
				string path;
				it = parameters.find("list");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["list"] = inputDir + it->second;		}
				}
				
				it = parameters.find("sabund");
				//user has given a template file
				if(it != parameters.end()){ 
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["sabund"] = inputDir + it->second;		}
				}
			}
			
			
			//check for required parameters
			listfile = validParameter.validFile(parameters, "list", true);
			if (listfile == "not open") { listfile = ""; abort = true; }
			else if (listfile == "not found") { listfile = ""; }
			else {  format = "list"; inputfile = listfile; m->setListFile(listfile); }
			
			sabundfile = validParameter.validFile(parameters, "sabund", true);
			if (sabundfile == "not open") { sabundfile = ""; abort = true; }	
			else if (sabundfile == "not found") { sabundfile = ""; }
			else {  format = "sabund"; inputfile = sabundfile; m->setSabundFile(sabundfile); }
			
			
			//check for optional parameter and set defaults
			// ...at some point should added some additional type checking...
			string temp;
			temp = validParameter.validFile(parameters, "sorted", false);			if (temp == "not found") { temp = "T"; }
			sorted = m->isTrue(temp);
			
			label = validParameter.validFile(parameters, "label", false);			
			if (label == "not found") { label = ""; }
			else { 
				if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
				else { allLines = 1;  }
			}
			
			if ((listfile == "") && (sabundfile == "")) { 
				//is there are current file available for any of these?
				//give priority to shared, then list, then rabund, then sabund
				//if there is a current shared file, use it
				listfile = m->getListFile(); 
				if (listfile != "") { inputfile = listfile; format = "list"; m->mothurOut("Using " + listfile + " as input file for the list parameter."); m->mothurOutEndLine(); }
				else { 
					sabundfile = m->getSabundFile(); 
					if (sabundfile != "") { inputfile = sabundfile; format = "sabund"; m->mothurOut("Using " + sabundfile + " as input file for the sabund parameter."); m->mothurOutEndLine(); }
					else { 
						m->mothurOut("No valid current files. You must provide a list or sabund file."); m->mothurOutEndLine(); 
						abort = true;
					}
				}
			}
			
			
			//if the user changes the output directory command factory will send this info to us in the output parameter 
			outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found"){	outputDir = m->hasPath(inputfile); 	}			
			
		}
			

	}
	catch(exception& e) {
		m->errorOut(e, "GetRAbundCommand", "GetRAbundCommand");
		exit(1);
	}			
}
예제 #13
0
bool game::opening_screen()
{
    WINDOW* w_background = newwin(TERMY, TERMX, 0, 0);

    werase(w_background);
    wrefresh(w_background);

    WINDOW* w_open = newwin(25, 80, (TERMY > 25) ? (TERMY-25)/2 : 0, (TERMX > 80) ? (TERMX-80)/2 : 0);
    const int iMenuOffsetX = 2;
    int iMenuOffsetY = 22;

    std::vector<std::string> vSubItems;
    vSubItems.push_back("Custom Character");
    vSubItems.push_back("Preset Character");
    vSubItems.push_back("Random Character");

    print_menu(w_open, 0, iMenuOffsetX, iMenuOffsetY);

    std::vector<std::string> savegames, templates;
    std::string tmp;
    dirent *dp;
    DIR *dir = opendir("save");
    if (!dir) {
        #if (defined _WIN32 || defined __WIN32__)
            mkdir("save");
        #else
            mkdir("save", 0777);
        #endif
        dir = opendir("save");
    }
    if (!dir) {
        dbg(D_ERROR) << "game:opening_screen: Unable to make save directory.";
        debugmsg("Could not make './save' directory");
        endwin();
        exit(1);
    }
    while ((dp = readdir(dir))) {
        tmp = dp->d_name;
        if (tmp.find(".sav") != std::string::npos)
            savegames.push_back(tmp.substr(0, tmp.find(".sav")));
    }
    closedir(dir);
    dir = opendir("data");
    while ((dp = readdir(dir))) {
        tmp = dp->d_name;
        if (tmp.find(".template") != std::string::npos)
            templates.push_back(tmp.substr(0, tmp.find(".template")));
    }

    int sel1 = 1, sel2 = 1, layer = 1;
    InputEvent input;
    int chInput;
    bool start = false;

    // Load MOTD and store it in a string
    std::vector<std::string> motd;
    std::ifstream motd_file;
    motd_file.open("data/motd");
    if (!motd_file.is_open())
        motd.push_back("No message today.");
    else {
        while (!motd_file.eof()) {
            std::string tmp;
            getline(motd_file, tmp);
            if (tmp[0] != '#')
                motd.push_back(tmp);
        }
    }

    // Load Credits and store it in a string
    std::vector<std::string> credits;
    std::ifstream credits_file;
    credits_file.open("data/credits");
    if (!credits_file.is_open())
        credits.push_back("No message today.");
    else {
        while (!credits_file.eof()) {
            std::string tmp;
            getline(credits_file, tmp);
            if (tmp[0] != '#')
                credits.push_back(tmp);
        }
    }

    while(!start) {
        if (layer == 1) {
            print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY, (sel1 == 0 || sel1 == 7) ? false : true);

            if (sel1 == 0) {	// Print the MOTD.
                for (int i = 0; i < motd.size() && i < 16; i++)
                    mvwprintz(w_open, i + 7, 8, c_ltred, motd[i].c_str());

                wrefresh(w_open);
                refresh();
            } else if (sel1 == 7) {	// Print the Credits.
                for (int i = 0; i < credits.size() && i < 16; i++)
                    mvwprintz(w_open, i + 7, 8, c_ltred, credits[i].c_str());

                wrefresh(w_open);
                refresh();
            }

            chInput = getch();

            if (chInput == 'm' || chInput == 'M') {
                sel1 = 0;
                chInput = '\n';
            } else if (chInput == 'n' || chInput == 'N') {
                sel1 = 1;
                chInput = '\n';
            } else if (chInput == 'L') {
                sel1 = 2;
                chInput = '\n';
            } else if (chInput == 'r' || chInput == 'R') {
                sel1 = 3;
                chInput = '\n';
            } else if (chInput == 's' || chInput == 'S') {
                sel1 = 4;
                chInput = '\n';
            } else if (chInput == 'o' || chInput == 'O') {
                sel1 = 5;
                chInput = '\n';
            } else if (chInput == 'H') {
                sel1 = 6;
                chInput = '\n';
            } else if (chInput == 'c' || chInput == 'C') {
                sel1 = 7;
                chInput = '\n';
            } else if (chInput == 'q' || chInput == 'Q' || chInput == KEY_ESCAPE) {
                sel1 = 8;
                chInput = '\n';
            }

            if (chInput == KEY_LEFT || chInput == 'h') {
                if (sel1 > 0)
                    sel1--;
                else
                    sel1 = 8;
            } else if (chInput == KEY_RIGHT || chInput == 'l') {
                if (sel1 < 8)
                    sel1++;
                else
                    sel1 = 0;
            } else if ((chInput == KEY_UP || chInput == 'k' || chInput == '\n') && sel1 > 0 && sel1 != 7) {
                if (sel1 == 5) {
                    show_options();
                } else if (sel1 == 6) {
                    help();
                } else if (sel1 == 8) {
                    uquit = QUIT_MENU;
                    return false;
                } else {
                    sel2 = 0;
                    layer = 2;
                    print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY, (sel1 == 0 || sel1 == 7) ? false : true);
                }
            }
        } else if (layer == 2) {
            if (sel1 == 1) {	// New Character
                print_menu_items(w_open, vSubItems, sel2, iMenuOffsetY-2, iMenuOffsetX+7);
                wrefresh(w_open);
                refresh();
                chInput = getch();

                if (chInput == 'c' || chInput == 'C') {
                    sel2 = 0;
                    chInput = '\n'  ;
                } else if (chInput == 'p' || chInput == 'P') {
                    sel2 = 1;
                    chInput = '\n';
                } else if (chInput == 'r' || chInput == 'R') {
                    sel2 = 2;
                    chInput = '\n';
                }

                if (chInput == KEY_LEFT || chInput == 'h') {
                    if (sel2 > 0)
                        sel2--;
                    else
                        sel2 = 2;
                } if (chInput == KEY_RIGHT || chInput == 'l') {
                    if (sel2 < 2)
                        sel2++;
                    else
                        sel2 = 0;
                } else if (chInput == KEY_DOWN || chInput == 'j' || chInput == KEY_ESCAPE) {
                    layer = 1;
                    sel1 = 1;
                }
                if (chInput == KEY_UP || chInput == 'k' || chInput == '\n') {
                    if (sel2 == 0 || sel2 == 2) {
                        if (!u.create(this, (sel2 == 0) ? PLTYPE_CUSTOM : PLTYPE_RANDOM)) {
                            u = player();
                            delwin(w_open);
                            return (opening_screen());
                        }

                        werase(w_background);
                        wrefresh(w_background);
                        start_game();
                        start = true;
                    } else if (sel2 == 1) {
                        layer = 3;
                        sel1 = 0;
                        print_menu_items(w_open, vSubItems, sel2, iMenuOffsetY-2, iMenuOffsetX+7);
                    }
                }
            } else if (sel1 == 2) {	// Load Character
                if (savegames.size() == 0)
                    mvwprintz(w_open, iMenuOffsetY - 2, 19 + iMenuOffsetX, c_red, "No save games found!");
                else {
                    for (int i = 0; i < savegames.size(); i++) {
                        int line = iMenuOffsetY - 2 - i;
                        mvwprintz(w_open, line, 19 + iMenuOffsetX, (sel2 == i ? h_white : c_white), savegames[i].c_str());
                    }
                }
                wrefresh(w_open);
                refresh();
                input = get_input();
                if (savegames.size() == 0 && (input == DirectionS || input == Confirm)) {
                    layer = 1;
                } else if (input == DirectionS) {
                    if (sel2 > 0)
                        sel2--;
                    else
                        sel2 = savegames.size() - 1;
                } else if (input == DirectionN) {
                    if (sel2 < savegames.size() - 1)
                        sel2++;
                    else
                        sel2 = 0;
                } else if (input == DirectionW || input == Cancel) {
                    layer = 1;
                }
                if (input == DirectionE || input == Confirm) {
                    if (sel2 >= 0 && sel2 < savegames.size()) {
                        werase(w_background);
                        wrefresh(w_background);
                        load(savegames[sel2]);
                        start = true;
                    }
                }
            } else if (sel1 == 3) {  // Delete world
                if (query_yn("Delete the world and all saves?")) {
                    delete_save();
                    savegames.clear();
                    MAPBUFFER.reset();
                    MAPBUFFER.make_volatile();
                }

                layer = 1;
            } else if (sel1 == 4) {	// Special game
                for (int i = 1; i < NUM_SPECIAL_GAMES; i++) {
                    mvwprintz(w_open, iMenuOffsetY-i-1, 34 + iMenuOffsetX, (sel2 == i-1 ? h_white : c_white),
                    special_game_name( special_game_id(i) ).c_str());
                }
                wrefresh(w_open);
                refresh();
                input = get_input();
                if (input == DirectionS) {
                    if (sel2 > 0)
                        sel2--;
                    else
                        sel2 = NUM_SPECIAL_GAMES - 2;
                } else if (input == DirectionN) {
                    if (sel2 < NUM_SPECIAL_GAMES - 2)
                        sel2++;
                    else
                        sel2 = 0;
                } else if (input == DirectionW || input == Cancel) {
                    layer = 1;
                }
                if (input == DirectionE || input == Confirm) {
                    if (sel2 >= 0 && sel2 < NUM_SPECIAL_GAMES - 1) {
                        delete gamemode;
                        gamemode = get_special_game( special_game_id(sel2+1) );
                        if (!gamemode->init(this)) {
                            delete gamemode;
                            gamemode = new special_game;
                            u = player();
                            delwin(w_open);
                            return (opening_screen());
                        }
                        start = true;
                    }
                }
            }
        } else if (layer == 3) {	// Character Templates
            if (templates.size() == 0)
                mvwprintz(w_open, iMenuOffsetY-4, iMenuOffsetX+27, c_red, "No templates found!");
            else {
                for (int i = 0; i < templates.size(); i++) {
                    int line = iMenuOffsetY - 4 - i;
                    mvwprintz(w_open, line, 27 + iMenuOffsetX, (sel1 == i ? h_white : c_white), templates[i].c_str());
                }
            }
            wrefresh(w_open);
            refresh();
            input = get_input();
            if (input == DirectionS) {
                if (sel1 > 0)
                    sel1--;
                else
                    sel1 = templates.size() - 1;
            } else if (templates.size() == 0 && (input == DirectionN || input == Confirm)) {
                sel1 = 1;
                layer = 2;
                print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY);
            } else if (input == DirectionN) {
                if (sel1 < templates.size() - 1)
                    sel1++;
                else
                    sel1 = 0;
            } else if (input == DirectionW  || input == Cancel || templates.size() == 0) {
                sel1 = 1;
                layer = 2;
                print_menu(w_open, sel1, iMenuOffsetX, iMenuOffsetY);
            } else if (input == DirectionE || input == Confirm) {
                if (!u.create(this, PLTYPE_TEMPLATE, templates[sel1])) {
                    u = player();
                    delwin(w_open);
                    return (opening_screen());
                }

                werase(w_background);
                wrefresh(w_background);
                start_game();
                start = true;
            }
        }
    }
    delwin(w_open);
    if (start == false)
        uquit = QUIT_MENU;
    return start;
}
예제 #14
0
static int init(int argc, char **argv) {
  const char *str;
  int value;

  int hardware_mixer = 0;

  config.audio_backend_latency_offset = 0;           // this is the default for ALSA
  config.audio_backend_buffer_desired_length = 6615; // default for alsa with a software mixer
  
  

  // get settings from settings file first, allow them to be overridden by command line options

  if (config.cfg != NULL) {
    /* Get the desired buffer size setting. */
    if (config_lookup_int(config.cfg, "alsa.audio_backend_buffer_desired_length_software", &value)) {
      if ((value < 0) || (value > 66150))
        die("Invalid alsa audio backend buffer desired length (software) \"%d\". It should be between 0 and "
            "66150, default is 6615",
            value);
      else {
        config.audio_backend_buffer_desired_length = value;
      }
    }
    
    /* Get the latency offset. */
    if (config_lookup_int(config.cfg, "alsa.audio_backend_latency_offset", &value)) {
      if ((value < -66150) || (value > 66150))
        die("Invalid alsa audio backend buffer latency offset \"%d\". It should be between -66150 and +66150, default is 0",
            value);
      else
        config.audio_backend_latency_offset = value;
    }

    /* Get the Output Device Name. */
    if (config_lookup_string(config.cfg, "alsa.output_device", &str)) {
      alsa_out_dev = (char *)str;
    }


    /* Get the Mixer Type setting. */

    if (config_lookup_string(config.cfg, "alsa.mixer_type", &str)) {
      inform("The alsa mixer_type setting is deprecated and has been ignored. FYI, using the \"mixer_control_name\" setting automatically chooses a hardware mixer.");
    }
    

    /* Get the Mixer Device Name. */
    if (config_lookup_string(config.cfg, "alsa.mixer_device", &str)) {
      alsa_mix_dev = (char *)str;
    }

    /* Get the Mixer Control Name. */
    if (config_lookup_string(config.cfg, "alsa.mixer_control_name", &str)) {
      alsa_mix_ctrl = (char *)str;
      hardware_mixer = 1;
    }
  }

  optind = 1; // optind=0 is equivalent to optind=1 plus special behaviour
  argv--;     // so we shift the arguments to satisfy getopt()
  argc++;
  // some platforms apparently require optreset = 1; - which?
  int opt;
  while ((opt = getopt(argc, argv, "d:t:m:c:i:")) > 0) {
    switch (opt) {
    case 'd':
      alsa_out_dev = optarg;
      break;

    case 't':
      inform("The alsa backend -t option is deprecated and has been ignored. FYI, using the -c option automatically chooses a hardware mixer.");
      break;

    case 'm':
      alsa_mix_dev = optarg;
      break;
    case 'c':
      alsa_mix_ctrl = optarg;
      hardware_mixer = 1;
      break;
    case 'i':
      alsa_mix_index = strtol(optarg, NULL, 10);
      break;
    default:
      help();
      die("Invalid audio option -%c specified", opt);
    }
  }

  if (optind < argc)
    die("Invalid audio argument: %s", argv[optind]);
  
  debug(1,"Output device name is \"%s\".",alsa_out_dev);

  if (!hardware_mixer)
    return 0;

  if (alsa_mix_dev == NULL)
    alsa_mix_dev = alsa_out_dev;

  int ret = 0;
  
  snd_mixer_selem_id_alloca(&alsa_mix_sid);
  snd_mixer_selem_id_set_index(alsa_mix_sid, alsa_mix_index);
  snd_mixer_selem_id_set_name(alsa_mix_sid, alsa_mix_ctrl);

  if ((snd_mixer_open(&alsa_mix_handle, 0)) < 0)
    die("Failed to open mixer");
  debug(1,"Mixer device name is \"%s\".",alsa_mix_dev);
  if ((snd_mixer_attach(alsa_mix_handle, alsa_mix_dev)) < 0)
    die("Failed to attach mixer");
  if ((snd_mixer_selem_register(alsa_mix_handle, NULL, NULL)) < 0)
    die("Failed to register mixer element");

  ret = snd_mixer_load(alsa_mix_handle);
  if (ret < 0)
    die("Failed to load mixer element");
  
  debug(1,"Mixer Control name is \"%s\".",alsa_mix_ctrl);
    
  alsa_mix_elem = snd_mixer_find_selem(alsa_mix_handle, alsa_mix_sid);    
  if (!alsa_mix_elem)
    die("Failed to find mixer element");

 
  if (snd_mixer_selem_get_playback_volume_range(alsa_mix_elem, &alsa_mix_minv, &alsa_mix_maxv) < 0)
    debug(1, "Can't read mixer's [linear] min and max volumes.");
  else {
    if (snd_mixer_selem_get_playback_dB_range (alsa_mix_elem, &alsa_mix_mindb, &alsa_mix_maxdb) == 0) {

      audio_alsa.volume = &volume; // insert the volume function now we know it can do dB stuff
      audio_alsa.parameters = &parameters; // likewise the parameters stuff
      if (alsa_mix_mindb == SND_CTL_TLV_DB_GAIN_MUTE) {
        // Raspberry Pi does this
        debug(1, "Lowest dB value is a mute.");
        if (snd_mixer_selem_ask_playback_vol_dB(alsa_mix_elem, alsa_mix_minv + 1,
                                                &alsa_mix_mindb) == 0)
          debug(1, "Can't get dB value corresponding to a \"volume\" of 1.");
      }
      debug(1, "Hardware mixer has dB volume from %f to %f.", (1.0 * alsa_mix_mindb) / 100.0,
            (1.0 * alsa_mix_maxdb) / 100.0);
      if (config.volume_range_db) {
        long suggested_alsa_min_db = alsa_mix_maxdb - (long)trunc(config.volume_range_db*100);
        if (suggested_alsa_min_db > alsa_mix_mindb)
          alsa_mix_mindb = suggested_alsa_min_db;
        else
          inform("The volume_range_db setting, %f is greater than the native range of the mixer %f, so it is ignored.",config.volume_range_db,(alsa_mix_maxdb-alsa_mix_mindb)/100.0);
      }
    } else {
      // use the linear scale and do the db conversion ourselves
      debug(1, "note: the hardware mixer specified -- \"%s\" -- does not have a dB volume scale, so it can't be used.",alsa_mix_ctrl);
      /*
      debug(1, "Min and max volumes are %d and %d.",alsa_mix_minv,alsa_mix_maxv);
      alsa_mix_maxdb = 0;
      if ((alsa_mix_maxv!=0) && (alsa_mix_minv!=0))
        alsa_mix_mindb = -20*100*(log10(alsa_mix_maxv*1.0)-log10(alsa_mix_minv*1.0));
      else if (alsa_mix_maxv!=0)
        alsa_mix_mindb = -20*100*log10(alsa_mix_maxv*1.0);
      audio_alsa.volume = &linear_volume; // insert the linear volume function
      audio_alsa.parameters = &parameters; // likewise the parameters stuff
      debug(1,"Max and min dB calculated are %d and %d.",alsa_mix_maxdb,alsa_mix_mindb);
      */
     }
  }
  if (snd_mixer_selem_has_playback_switch(alsa_mix_elem)) {
    has_mute = 1;
    debug(1, "Has mute ability.");
  }
  return 0;
}
예제 #15
0
파일: cat.c 프로젝트: Keruspe/systemd
static int parse_argv(int argc, char *argv[]) {

        enum {
                ARG_VERSION = 0x100,
                ARG_STDERR_PRIORITY,
                ARG_LEVEL_PREFIX
        };

        static const struct option options[] = {
                { "help",            no_argument,       NULL, 'h'                 },
                { "version",         no_argument,       NULL, ARG_VERSION         },
                { "identifier",      required_argument, NULL, 't'                 },
                { "priority",        required_argument, NULL, 'p'                 },
                { "stderr-priority", required_argument, NULL, ARG_STDERR_PRIORITY },
                { "level-prefix",    required_argument, NULL, ARG_LEVEL_PREFIX    },
                {}
        };

        int c;

        assert(argc >= 0);
        assert(argv);

        while ((c = getopt_long(argc, argv, "+ht:p:", options, NULL)) >= 0)

                switch (c) {

                case 'h':
                        help();
                        return 0;

                case ARG_VERSION:
                        return version();

                case 't':
                        if (isempty(optarg))
                                arg_identifier = NULL;
                        else
                                arg_identifier = optarg;
                        break;

                case 'p':
                        arg_priority = log_level_from_string(optarg);
                        if (arg_priority < 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Failed to parse priority value.");
                        break;

                case ARG_STDERR_PRIORITY:
                        arg_stderr_priority = log_level_from_string(optarg);
                        if (arg_stderr_priority < 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Failed to parse stderr priority value.");
                        break;

                case ARG_LEVEL_PREFIX: {
                        int k;

                        k = parse_boolean(optarg);
                        if (k < 0)
                                return log_error_errno(k, "Failed to parse level prefix value.");

                        arg_level_prefix = k;
                        break;
                }

                case '?':
                        return -EINVAL;

                default:
                        assert_not_reached("Unhandled option");
                }

        return 1;
}
예제 #16
0
파일: main.c 프로젝트: JiannengSun/postgres
/*
 * Any Postgres server process begins execution here.
 */
int
main(int argc, char *argv[])
{
	bool		do_check_root = true;

	progname = get_progname(argv[0]);

	/*
	 * Platform-specific startup hacks
	 */
	startup_hacks(progname);

	/*
	 * Remember the physical location of the initially given argv[] array for
	 * possible use by ps display.  On some platforms, the argv[] storage must
	 * be overwritten in order to set the process title for ps. In such cases
	 * save_ps_display_args makes and returns a new copy of the argv[] array.
	 *
	 * save_ps_display_args may also move the environment strings to make
	 * extra room. Therefore this should be done as early as possible during
	 * startup, to avoid entanglements with code that might save a getenv()
	 * result pointer.
	 */
	argv = save_ps_display_args(argc, argv);

	/*
	 * If supported on the current platform, set up a handler to be called if
	 * the backend/postmaster crashes with a fatal signal or exception.
	 */
#if defined(WIN32) && defined(HAVE_MINIDUMP_TYPE)
	pgwin32_install_crashdump_handler();
#endif

	/*
	 * Fire up essential subsystems: error and memory management
	 *
	 * Code after this point is allowed to use elog/ereport, though
	 * localization of messages may not work right away, and messages won't go
	 * anywhere but stderr until GUC settings get loaded.
	 */
	MemoryContextInit();

	/*
	 * Set up locale information from environment.  Note that LC_CTYPE and
	 * LC_COLLATE will be overridden later from pg_control if we are in an
	 * already-initialized database.  We set them here so that they will be
	 * available to fill pg_control during initdb.  LC_MESSAGES will get set
	 * later during GUC option processing, but we set it here to allow startup
	 * error messages to be localized.
	 */

	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("postgres"));

#ifdef WIN32

	/*
	 * Windows uses codepages rather than the environment, so we work around
	 * that by querying the environment explicitly first for LC_COLLATE and
	 * LC_CTYPE. We have to do this because initdb passes those values in the
	 * environment. If there is nothing there we fall back on the codepage.
	 */
	{
		char	   *env_locale;

		if ((env_locale = getenv("LC_COLLATE")) != NULL)
			pg_perm_setlocale(LC_COLLATE, env_locale);
		else
			pg_perm_setlocale(LC_COLLATE, "");

		if ((env_locale = getenv("LC_CTYPE")) != NULL)
			pg_perm_setlocale(LC_CTYPE, env_locale);
		else
			pg_perm_setlocale(LC_CTYPE, "");
	}
#else
	pg_perm_setlocale(LC_COLLATE, "");
	pg_perm_setlocale(LC_CTYPE, "");
#endif

#ifdef LC_MESSAGES
	pg_perm_setlocale(LC_MESSAGES, "");
#endif

	/*
	 * We keep these set to "C" always, except transiently in pg_locale.c; see
	 * that file for explanations.
	 */
	pg_perm_setlocale(LC_MONETARY, "C");
	pg_perm_setlocale(LC_NUMERIC, "C");
	pg_perm_setlocale(LC_TIME, "C");

	/*
	 * Now that we have absorbed as much as we wish to from the locale
	 * environment, remove any LC_ALL setting, so that the environment
	 * variables installed by pg_perm_setlocale have force.
	 */
	unsetenv("LC_ALL");

	/*
	 * Catch standard options before doing much else, in particular before we
	 * insist on not being root.
	 */
	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			help(progname);
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("postgres (PostgreSQL) " PG_VERSION);
			exit(0);
		}

		/*
		 * In addition to the above, we allow "--describe-config" and "-C var"
		 * to be called by root.  This is reasonably safe since these are
		 * read-only activities.  The -C case is important because pg_ctl may
		 * try to invoke it while still holding administrator privileges on
		 * Windows.  Note that while -C can normally be in any argv position,
		 * if you wanna bypass the root check you gotta put it first.  This
		 * reduces the risk that we might misinterpret some other mode's -C
		 * switch as being the postmaster/postgres one.
		 */
		if (strcmp(argv[1], "--describe-config") == 0)
			do_check_root = false;
		else if (argc > 2 && strcmp(argv[1], "-C") == 0)
			do_check_root = false;
	}

	/*
	 * Make sure we are not running as root, unless it's safe for the selected
	 * option.
	 */
	if (do_check_root)
		check_root(progname);

	/*
	 * Dispatch to one of various subprograms depending on first argument.
	 */

#ifdef EXEC_BACKEND
	if (argc > 1 && strncmp(argv[1], "--fork", 6) == 0)
		SubPostmasterMain(argc, argv);	/* does not return */
#endif

#ifdef WIN32

	/*
	 * Start our win32 signal implementation
	 *
	 * SubPostmasterMain() will do this for itself, but the remaining modes
	 * need it here
	 */
	pgwin32_signal_initialize();
#endif

	if (argc > 1 && strcmp(argv[1], "--boot") == 0)
		AuxiliaryProcessMain(argc, argv);		/* does not return */
	else if (argc > 1 && strcmp(argv[1], "--describe-config") == 0)
		GucInfoMain();			/* does not return */
	else if (argc > 1 && strcmp(argv[1], "--single") == 0)
		PostgresMain(argc, argv,
					 NULL,		/* no dbname */
					 strdup(get_user_name_or_exit(progname)));	/* does not return */
	else
		PostmasterMain(argc, argv);		/* does not return */
	abort();					/* should not get here */
}
예제 #17
0
파일: editor.cpp 프로젝트: Fomka/ufo2000
// See also: Inventory::draw(), Soldier::draw_inventory()
// Called by: Connect::do_planner() via Units::execute and execute_main()
void Editor::show()
{
    reset_video();
    destroy_bitmap(screen2);
    screen2 = create_bitmap(640, 400); 
    clear(screen2);

    // Prepare background picture for editor screen to improve 
    // performance a bit (static image that is never changed)
    BITMAP *editor_bg = create_bitmap(640, 400);
    clear_to_color(editor_bg, COLOR_BLACK1);
    SPK *tac01 = new SPK("$(xcom)/ufograph/tac01.scr");  // Picture with buttons
    tac01->show(editor_bg, 0, 0); // draw buttons: OK, Next-Man, Prev-Man, Unload-clip, Scroll-right
    delete tac01;
    BITMAP *b5 = create_bitmap(32, 15); clear(b5);  // Button for Scroll-left
    blit(editor_bg, b5, 288, 137, 0, 0, 32, 15);
    draw_sprite_vh_flip(editor_bg, b5, 255, 137); // Button: Scroll-left
    destroy_bitmap(b5);
    rectfill(editor_bg, 288, 32, 319, 57, COLOR_GRAY15);    //hide unused "unload" button
    text_mode(-1);
    textout(editor_bg, g_small_font, _("Click-and-drop weapons from the armory to the soldier, right-click to remove"), 0, 364 + 22, COLOR_WHITE); 

    position_mouse(320, 200);
    MouseRange temp_mouse_range(0, 0, 639, 400);

    int DONE = 0;
    int mouse_leftr = 1, mouse_rightr = 1;
    int i;
    int color = COLOR_LT_OLIVE;
    int A1 = 0, A2 = 0;

    while (mouse_b & 3) rest(1);

    g_console->resize(SCREEN_W, SCREEN_H - 400);
    g_console->set_full_redraw();
    g_console->redraw(screen, 0, 400);

    while (!DONE) {

        net->check();

        rest(1); // Don't eat all CPU resources

        if (CHANGE) {
            g_console->redraw(screen, 0, 400);

            blit(editor_bg, screen2, 0, 0, 0, 0, editor_bg->w, editor_bg->h);
            man->showspk(screen2); // Show "bigpicture" of soldier in choosen armor

            color = COLOR_DK_GRAY;
            if (man->x != 0)   // ??? This soldier already selected for the mission ?
                color = COLOR_LT_OLIVE;
            text_mode(-1);
            textout(screen2, large, man->md.Name, 0, 0, color);

            for (i = 0; i < NUMBER_OF_PLACES; i++) //man->drawgrid();
                man->place(i)->drawgrid(screen2, i);
            m_armoury->drawgrid(screen2, P_ARMOURY);

            man->draw_unibord(1, 320, 0);  // Attribute-Barchart
            if (sel_item != NULL) {
                if (sel_item_place == P_ARMOURY)
                    sel_item->od_info(330, 235, COLOR_WHITE);
                else
                    sel_item->od_info(330, 235, COLOR_OLIVE);

                textprintf(screen2, g_small_font, 128, 140, COLOR_GREEN,  "%s", sel_item->name().c_str());

                if (sel_item->haveclip()) {
                    //textprintf(screen2, font, 272, 80, color, "%d", sel_item->roundsremain());
                    textout(screen2, g_small_font, _("AMMO:"),  272, 64, COLOR_LT_OLIVE);
                    textout(screen2, g_small_font, _("ROUNDS"), 272, 72, COLOR_LT_OLIVE);
                    textout(screen2, g_small_font, _("LEFT="),  272, 80, COLOR_LT_OLIVE);
                    textprintf(screen2, g_small_font,           299, 80, COLOR_ORANGE, "%d", sel_item->roundsremain());
                    rect(screen2, 272, 88, 303, 135, COLOR_DK_GRAY);      //clip
                    PCK::showpck(sel_item->clip()->obdata_pInv(), 272, 88 + 8);
                } else if (sel_item->obdata_isAmmo()) {
                    //textprintf(screen2, font, 272, 80, color, "%d", sel_item->rounds);
                    textout(screen2, g_small_font, _("AMMO:"),  272, 64, COLOR_LT_OLIVE);
                    textout(screen2, g_small_font, _("ROUNDS"), 272, 72, COLOR_LT_OLIVE);
                    textout(screen2, g_small_font, _("LEFT="),  272, 80, COLOR_LT_OLIVE);
                    textprintf(screen2, g_small_font,           299, 80, COLOR_ORANGE, "%d", sel_item->m_rounds);
                    rect(screen2, 272, 88, 303, 135, COLOR_DK_GRAY);      //clip
                    PCK::showpck(sel_item->obdata_pInv(), 272, 88 + 8);
                }
                PCK::showpck(sel_item->obdata_pInv(),
                                mouse_x - sel_item->obdata_width()  * 16 / 2,
                                mouse_y - sel_item->obdata_height() * 16 / 2 + 8);
            } else {
                Item *it = m_armoury->item_under_mouse(0, 0);
                if (it != NULL) {
                    if (is_item_allowed(it->m_type))
                        it->od_info(330, 235, COLOR_GRAY05);
                    else
                        it->od_info(330, 235, COLOR_GRAY10);
                } else {
                    //textprintf(screen2, large, 330, 220, COLOR_LT_BLUE, _("Click here to change equipment set"));
                    int ty = 235;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("       F1: Help")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("    F2/F3: Save/load team")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("       F4: Edit soldier attributes")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("       F5: Change weaponset")); ty += 15;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("       F6: Save as weapon set template")); ty += 15;

                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _(" Ctrl+Ins: Copy current soldier")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("Shift+Ins: Paste on current soldier")); ty += 15;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("      Del: Delete items of current man")); /*ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("Shift+Del: Drop items of current man"));*/ ty += 15;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("      F11: Cycle through appearences")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("      F12: Cycle through human armours")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("Shift+F12: Cycle through alien races")); ty += 15;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("      Tab: Next soldier")); ty += 10;
                    textprintf(screen2, font,  330, ty, COLOR_BLUE,     _("Shift+Tab: Previous soldier")); ty += 10;
                }
            }

            int wht = man->count_weight();
            int max_wht = man->md.Strength;
            color       = max_wht < wht ? COLOR_RED03 : COLOR_GRAY02;
            textprintf(screen2, g_small_font, 0, 20, color, _("Equipment weight: %2d/%2d"), wht, max_wht);
            char str1[64]; // to adjust position of translated string
          //int x1 = 120;
            int x2 = 236;
            sprintf(str1, "%s: %4d", _("Soldier cost"), man->calc_full_ammunition_cost() );
            int w1 = text_length(g_small_font, str1);  // right-justify string
            textprintf(screen2, g_small_font, x2-w1, 20, COLOR_GRAY02, "%s", str1);

            draw_alpha_sprite(screen2, mouser, mouse_x, mouse_y);
            blit(screen2, screen, 0, 0, 0, 0, screen2->w, screen2->h);
            CHANGE = 0;
        }

        if ((mouse_b & 1) && (mouse_leftr)) { //left mouseclick
            mouse_leftr = 0;
            CHANGE = 1;

            if (handle_mouse_leftclick())
                DONE = 1;
        }

        if ((mouse_b & 2) && (mouse_rightr)) { //right mouseclick: get & put items
            mouse_rightr = 0;
            CHANGE = 1;
            if (sel_item != NULL) {
                if (sel_item_place == P_ARMOURY) {
                    // If item was taken from the armoury - just delete it
                    delete sel_item;
                    sel_item = NULL;
                } else {
                    // If item was taken from the the soldier - put it back
                    man->putitem(sel_item, sel_item_place, sel_item->m_x, sel_item->m_y);
                    sel_item = NULL;
                }
            } else {
                // Delete item under mouse cursor
                for (i = 0; i < NUMBER_OF_PLACES; i++) {
                    Item *it = man->place(i)->mselect(0, 0);
                    if (it != NULL) delete(it);
                }
            }
        }

        if (!(mouse_b & 1)) {
            mouse_leftr = 1;
        }

        if (!(mouse_b & 2)) {
            mouse_rightr = 1;
        }

        if (keypressed()) {
            CHANGE = 1;
          //int c = readkey();
          //switch (c >> 8) {
            int scancode; int keycode = ureadkey(&scancode); 
            switch (scancode) { 
                case KEY_F1:
                    help( HELP_INVENTORY );
                    break;
                // Todo: Change from "Save&Load Team" to "Save&Load Soldier" 
                // Todo: move "Save&Load Team" to Mission-planner (connect.cpp)
                case KEY_F2:
                    //if (askmenu("SAVE DATA")) {
                    save();
                    //}
                    break;
                case KEY_F3:
                    //if (askmenu("LOAD DATA")) {
                    load();
                    //}
                    break;
                case KEY_F4:
                    edit_soldier();   // Edit Attributes+Armor
                    break;

                case KEY_F5:
                    change_equipment();
                    break;

                case KEY_F6:
                    export_weaponset();
                    break;

                case KEY_F10:
                    change_screen_mode();
                    break;

                case KEY_F11:  // cycle thru apperances:
                    A1 = man->md.Appearance;
                    A2 = man->md.fFemale;
                    if ((key[KEY_LSHIFT]) || (key[KEY_RSHIFT]) ) { // Shift-F11: 
                        A2++;
                        if (A2 >= 2) A2 = 0;
                        man->md.fFemale    = A2;
                    } else { // F11: 
                        A1 = A1 + (A2 ? 4 : 0);
                        A1++;
                        if (A1 >= 8) A1 = 0;
                        man->md.fFemale    = A1 >= 4;
                        man->md.Appearance = A1 % 4;
                    }
                    man->process_MANDATA();
                    break;
                case KEY_F12:  // cycle thru armor-types:
                    A1 = man->md.SkinType;
                    if ((key[KEY_LSHIFT]) || (key[KEY_RSHIFT]) ) // Shift-F12: Aliens
                        man->skin()->next_alien();
                    else // F12: Human Armor
                        man->skin()->next_human();
                    man->process_MANDATA();
                    break;
//
                case KEY_INSERT:  // Todo: Copy items from last DEL to current man
                    if ((key[KEY_LCONTROL]) || (key[KEY_RCONTROL])) {
                        copy_soldier(man);
                        break;
                    }
                    if ((key[KEY_LSHIFT]) || (key[KEY_RSHIFT])) {
                        paste_soldier(man);
                        break;
                    }
                    break;
                case KEY_DEL:  // Todo: store the deleted items (where?) for KEY_INSERT
                    if ((key[KEY_LSHIFT]) || (key[KEY_RSHIFT]) ) { // Shift-DEL:
                      // Drop all carried items:   // Todo: drop to common pool
                        Item * it;
                        for (int i = 0; i < NUMBER_OF_CARRIED_PLACES; i++) {
                            it = man->item(i);
                            if (it != NULL)
                                man->putitem(it, P_MAP);
                        }
                    } else { // DEL:
                        // Destroy items of current man, including those on the ground:
                        man->destroy_all_items();
                    }
                    break;

                case KEY_TAB:   // jump to next/prev. soldier
                    if ((key[KEY_LSHIFT]) || (key[KEY_RSHIFT]) ) { // Shift-TAB:
                        man = man->prevman();
                    } else { // TAB:
                        man = man->nextman();
                    }
                    break;
                case KEY_LEFT:
                    man = man->prevman();
                    break;
                case KEY_RIGHT:
                    man = man->nextman();
                    break;     

                 case KEY_PGUP:
                    scroll_equipment(-1);
                    break;
                 case KEY_PGDN:
                    scroll_equipment(+1);
                    break;
                case KEY_PRTSCR:
                    if (askmenu(_("SCREEN-SNAPSHOT"))) {
                        savescreen();
                    }
                    break;
                case KEY_ESC:
                    DONE = 1;
                    break;
                default: 
                    if (g_console->process_keyboard_input(keycode, scancode))
                        net->send_message((char *)g_console->get_text());
            }
        }
    }

    m_plt->save_FULLDATA("$(home)/squad.lua");

    destroy_bitmap(editor_bg);
    destroy_bitmap(screen2);
    screen2 = create_bitmap(SCREEN2W, SCREEN2H); clear(screen2);

    g_console->resize(SCREEN_W, SCREEN_H - SCREEN2H);
    g_console->set_full_redraw();

    clear(screen);
}
예제 #18
0
void
MisesMat :: give3dLSMaterialStiffnessMatrix(FloatMatrix &answer, MatResponseMode mode, GaussPoint *gp, TimeStep *atTime)
{
    MisesMatStatus *status = static_cast< MisesMatStatus * >( this->giveStatus(gp) );
    // start from the elastic stiffness

    FloatMatrix I(6, 6);
    I.at(1, 1) = I.at(2, 2) = I.at(3, 3) = 1;
    I.at(4, 4) = I.at(5, 5) = I.at(6, 6) = 0.5;
    FloatArray delta(6);
    delta.at(1) = delta.at(2) = delta.at(3) = 1;

    FloatMatrix F, F_Tr;
    F.beMatrixForm( status->giveTempFVector() );
    double J;
    J = F.giveDeterminant();

    StressVector trialStressDev(_3dMat);
    double trialStressVol;
    status->giveTrialStressVol(trialStressVol);
    status->giveTrialStressDev(trialStressDev);
    double trialS = trialStressDev.computeStressNorm();
    FloatArray n(6);
    n = trialStressDev;
    if ( trialS == 0 ) {
        n.resize(6);
    } else {
        n.times(1 / trialS);
    }


    FloatMatrix Cdev(6, 6);
    FloatMatrix C(6, 6);
    FloatMatrix help(6, 6);
    help.beDyadicProductOf(delta, delta);
    C = help;
    help.times(-1. / 3.);
    FloatMatrix C1 = I;
    C1.add(help);
    C1.times(2 * trialStressVol);

    FloatMatrix n1(6, 6), n2(6, 6);
    n1.beDyadicProductOf(n, delta);
    n2.beDyadicProductOf(delta, n);
    help = n1;
    help.add(n2);
    help.times(-2. / 3. * trialS);
    C1.add(help);
    Cdev = C1;
    C.times(K * J * J);

    help = I;
    help.times( -K * ( J * J - 1 ) );
    C.add(help);
    FloatMatrix Cvol = C;
    C.add(C1);
    //////////////////////////////////////////////////////////////////////////////////////////////////////////

    FloatMatrix invF(3, 3);
    FloatMatrix T(6, 6), tT(6, 6);

    invF.beInverseOf(F);
    //////////////////////////////////////////////////
    //first row of pull back transformation matrix
    T.at(1, 1) = invF.at(1, 1) * invF.at(1, 1);
    T.at(1, 2) = invF.at(1, 2) * invF.at(1, 2);
    T.at(1, 3) = invF.at(1, 3) * invF.at(1, 3);
    T.at(1, 4) = 2. * invF.at(1, 2) * invF.at(1, 3);
    T.at(1, 5) = 2. * invF.at(1, 1) * invF.at(1, 3);
    T.at(1, 6) = 2. * invF.at(1, 1) * invF.at(1, 2);
    //second row of pull back transformation matrix
    T.at(2, 1) = invF.at(2, 1) * invF.at(2, 1);
    T.at(2, 2) = invF.at(2, 2) * invF.at(2, 2);
    T.at(2, 3) = invF.at(2, 3) * invF.at(2, 3);
    T.at(2, 4) = 2. * invF.at(2, 2) * invF.at(2, 3);
    T.at(2, 5) = 2. * invF.at(2, 1) * invF.at(2, 3);
    T.at(2, 6) = 2. * invF.at(2, 1) * invF.at(2, 2);
    //third row of pull back transformation matrix
    T.at(3, 1) = invF.at(3, 1) * invF.at(3, 1);
    T.at(3, 2) = invF.at(3, 2) * invF.at(3, 2);
    T.at(3, 3) = invF.at(3, 3) * invF.at(3, 3);
    T.at(3, 4) = 2. * invF.at(3, 2) * invF.at(3, 3);
    T.at(3, 5) = 2. * invF.at(3, 1) * invF.at(3, 3);
    T.at(3, 6) = 2. * invF.at(3, 1) * invF.at(3, 2);
    //fourth row of pull back transformation matrix
    T.at(4, 1) = invF.at(2, 1) * invF.at(3, 1);
    T.at(4, 2) = invF.at(2, 2) * invF.at(3, 2);
    T.at(4, 3) = invF.at(2, 3) * invF.at(3, 3);
    T.at(4, 4) = ( invF.at(2, 2) * invF.at(3, 3) + invF.at(2, 3) * invF.at(3, 2) );
    T.at(4, 5) = ( invF.at(2, 1) * invF.at(3, 3) + invF.at(2, 3) * invF.at(3, 1) );
    T.at(4, 6) = ( invF.at(2, 1) * invF.at(3, 2) + invF.at(2, 2) * invF.at(3, 1) );
    //fifth row of pull back transformation matrix
    T.at(5, 1) = invF.at(1, 1) * invF.at(3, 1);
    T.at(5, 2) = invF.at(1, 2) * invF.at(3, 2);
    T.at(5, 3) = invF.at(1, 3) * invF.at(3, 3);
    T.at(5, 4) = ( invF.at(1, 2) * invF.at(3, 3) + invF.at(1, 3) * invF.at(3, 2) );
    T.at(5, 5) = ( invF.at(1, 1) * invF.at(3, 3) + invF.at(1, 3) * invF.at(3, 1) );
    T.at(5, 6) = ( invF.at(1, 1) * invF.at(3, 2) + invF.at(1, 2) * invF.at(3, 1) );
    //sixth row of pull back transformation matrix
    T.at(6, 1) = invF.at(1, 1) * invF.at(2, 1);
    T.at(6, 2) = invF.at(1, 2) * invF.at(2, 2);
    T.at(6, 3) = invF.at(1, 3) * invF.at(2, 3);
    T.at(6, 4) = ( invF.at(1, 2) * invF.at(2, 3) + invF.at(1, 3) * invF.at(2, 2) );
    T.at(6, 5) = ( invF.at(1, 1) * invF.at(2, 3) + invF.at(1, 3) * invF.at(2, 1) );
    T.at(6, 6) = ( invF.at(1, 1) * invF.at(2, 2) + invF.at(1, 2) * invF.at(2, 1) );
    ///////////////////////////////////////////

    if ( mode != TangentStiffness ) {
        help.beProductTOf(C, T);
        answer.beProductOf(T, help);
        return;
    }


    //StructuralCrossSection *crossSection = ( StructuralCrossSection * ) ( gp->giveElement()->giveCrossSection() );
    double kappa = status->giveCumulativePlasticStrain();
    // increment of cumulative plastic strain as an indicator of plastic loading
    double dKappa = sqrt(3. / 2.) * ( status->giveTempCumulativePlasticStrain() - kappa );
    //double dKappa = ( status->giveTempCumulativePlasticStrain() - kappa);
    if ( dKappa <= 0.0 ) { // elastic loading - elastic stiffness plays the role of tangent stiffness
        help.beProductTOf(C, T);
        answer.beProductOf(T, help);
        return;
    }

    // === plastic loading ===
    //dKappa = dKappa*sqrt(3./2.);
    // trial deviatoric stress and its norm


    double beta0, beta1, beta2, beta3, beta4;
    if ( trialS == 0 ) {
        beta1 = 0;
    } else {
        beta1 = 2 * trialStressVol * dKappa / trialS;
    }

    if ( trialStressVol == 0 ) {
        beta0 = 0;
        beta2 = 0;
        beta3 = beta1;
        beta4 = 0;
    } else {
        beta0 = 1 + H / 3 / trialStressVol;
        beta2 = ( 1 - 1 / beta0 ) * 2. / 3. * trialS * dKappa / trialStressVol;
        beta3 = 1 / beta0 - beta1 + beta2;
        beta4 = ( 1 / beta0 - beta1 ) * trialS / trialStressVol;
    }

    FloatMatrix N;
    N.beDyadicProductOf(n, n);
    N.times(-2 * trialStressVol * beta3);
    answer.resize(6, 6);

    C1.times(-beta1);
    FloatMatrix mN(3, 3);
    mN.at(1, 1) = n.at(1);
    mN.at(1, 2) = n.at(6);
    mN.at(1, 3) = n.at(5);
    mN.at(2, 1) = n.at(6);
    mN.at(2, 2) = n.at(2);
    mN.at(2, 3) = n.at(4);
    mN.at(3, 1) = n.at(5);
    mN.at(3, 2) = n.at(4);
    mN.at(3, 3) = n.at(3);
    FloatMatrix mN2(3, 3);
    mN2.beProductOf(mN, mN);

    double volN2 = 1. / 3. * ( mN2.at(1, 1) + mN2.at(2, 2) + mN2.at(3, 3) );
    FloatArray devN2(6);
    devN2.at(1) = mN2.at(1, 1) - volN2;
    devN2.at(2) = mN2.at(2, 2) - volN2;

    devN2.at(3) = mN2.at(3, 3) - volN2;
    devN2.at(4) = mN2.at(2, 3);
    devN2.at(5) = mN2.at(1, 3);
    devN2.at(6) = mN2.at(1, 2);
    FloatMatrix nonSymPart;
    nonSymPart.beDyadicProductOf(n, devN2);
    //symP.beTranspositionOf(nonSymPart);
    //symP.add(nonSymPart);
    //symP.times(1./2.);
    nonSymPart.times(-2 * trialStressVol * beta4);

    C.add(C1);
    C.add(N);
    C.add(nonSymPart);
    help.beProductTOf(C, T);
    answer.beProductOf(T, help);
}
예제 #19
0
파일: ngdumptest.c 프로젝트: aosm/libpcap
int
main(int argc, char * const argv[])
{
	int ch;
	const char *file_name = NULL;
	pcapng_block_t block;
	
	/*
	 * Loop through argument to build PCAP-NG block
	 * Optionally write to file
	 */
	while ((ch = getopt(argc, argv, "4:6:Cc:D:d:efhi:n:o:p:sw:x")) != -1) {
		switch (ch) {
			case 'C':
				copy_data_buffer = 1;
				break;
				
			case 'c':
				comment = optarg;
				break;
				
			case 'D': {
				int i;
				
				packet_length = strtoul(optarg, NULL, 0);
				packet_data = malloc(packet_length);
				for (i = 0; i < packet_length; i++) {
					packet_data[i] = i % 256;
				}
				
				block = pcap_ng_block_alloc(65536);
				make_data_block(block, packet_data, packet_length);
				pcap_ng_free_block(block);
				break;
			}
			case 'd':
				packet_length  = strlen(optarg);
				packet_data = (unsigned char *)optarg;
				block = pcap_ng_block_alloc(65536);
				make_data_block(block, packet_data, packet_length);
				pcap_ng_free_block(block);
				break;
				
			case 'e':
				type_of_packet = ENHANCED_PACKET;
				break;
				
			case 'f':
				first_comment = 1;
				break;

			case 'h':
				help(argv[0]);
				return (0);
				
			case 'i':
				if_name = optarg;
				
				block = pcap_ng_block_alloc(65536);
				make_interface_description_block(block, if_name);
				pcap_ng_free_block(block);
				
				break;
				
			case '4':
			case '6': {
				int af;
				int name_count = 0;
				char *ptr = strchr(optarg, ':');
				char **names = NULL;
				int i;
				struct in_addr ina;
				struct in6_addr in6a;
				int retval;
				
				
				if (ptr == NULL) {
					fprintf(stderr, "malformed arguments for option 'n'\n");
					help(argv[0]);
					return (0);
				}
				do {
					ptr++;
					name_count += 1;
				} while ((ptr = strchr(ptr, ':')) != NULL);
				
				names = calloc(name_count +1, sizeof(char *));
				
				ptr = strchr(optarg, ':');
				*ptr = '\0';
				
				if (ch == '4') {
					af = AF_INET;
					retval = inet_pton(af, optarg, &ina);
				} else {
					af = AF_INET6;
					retval = inet_pton(af, optarg, &in6a);
				}
				if (retval == 0)
					errx(1, "This is not an %s address: '%s'\n",
						 af == AF_INET ? "IPv4" : "IPv6",
						 optarg);
				else if (retval == -1)
					err(1, "inet_pton(%s) failed\n", optarg);
				
				for (i = 0; i < name_count; i++) {
					char *end;
					ptr++;
					end = strchr(ptr, ':');
					if (end != NULL)
						*end = '\0';
					
					names[i] = strdup(ptr);
					if (end != NULL)
						ptr = end;
				}

				block = pcap_ng_block_alloc(65536);
				if (af == AF_INET)
					make_name_resolution_record(block, af,  &ina, names);
				else
					make_name_resolution_record(block, af, &in6a, names);
				pcap_ng_free_block(block);
				break;
			}
				
			case 'n': {
				num_data_blocks = strtoul(optarg, NULL, 0);
				break;
			}
				
			case 'o':
				type_of_packet = OBSOLETE_PACKET;
				break;
				
			case 'p': {
				char *ptr = strchr(optarg, ':');
				char *endptr;
				
				if (ptr == NULL) {
					fprintf(stderr, "malformed arguments for option 'p'\n");
					help(argv[0]);
					return (0);
				}
				proc_name = strndup(optarg, (ptr - optarg));
				ptr += 1;
				if (*ptr == '\0') {
					fprintf(stderr, "malformed arguments for option 'p'\n");
					help(argv[0]);
					return (0);
				}
				proc_pid = (uint32_t)strtoul(ptr, &endptr, 0);
				if (endptr != NULL && *endptr != '\0') {
					fprintf(stderr, "malformed arguments for option 'p'\n");
					help(argv[0]);
					return (0);
				}
				proc_index += 1;
				
				block = pcap_ng_block_alloc(65536);
				make_process_information_block(block, proc_name, proc_pid);
				pcap_ng_free_block(block);
				break;
			}
			case 's':
				type_of_packet = SIMPLE_PACKET;
				break;
				
			case 'w':
				file_name = optarg;
				
				if (dumper != NULL)
					pcap_ng_dump_close(dumper);
				
				pcap_t *pcap = pcap_open_dead(DLT_PCAPNG, 65536);
				if (pcap == NULL)
					err(EX_OSERR, "pcap_open_dead(DLT_PCAPNG, 65536) failed\n");
				
				dumper = pcap_ng_dump_open(pcap, file_name);
				if (pcap == NULL)
					err(EX_OSERR,  "pcap_ng_dump_open(%s) failed\n", file_name);

				
				make_section_header_block();
				break;

			case 'x':
				if (optind < argc) {
					if (argv[optind][0] != '-') {
						char *endptr;
						unsigned long num = strtoul(argv[optind], &endptr, 0);
						if (endptr != NULL && *endptr == '\0') {
							optind++;
							ext_len = num;
						}
					}
				}
				ext_buffer = malloc(ext_len);
				if (ext_buffer == NULL)
					errx(EX_OSERR, "malloc(%lu) failed", ext_len);
				break;
			default:
				help(argv[0]);
				return (0);
		}
	}
		
	if (dumper != NULL)
		pcap_ng_dump_close(dumper);
	
	return (0);
}
예제 #20
0
int main(int argc, char*argv[]) {
    pid_t pid;
    int fd = -1;
    int ret = 1, i;
    struct sockaddr_un sa;
    char *ibuf = NULL;
    char *obuf = NULL;
    size_t buf_size, ibuf_size, ibuf_index, ibuf_length, obuf_size, obuf_index, obuf_length;
    char *cli;
    bool ibuf_eof, obuf_eof, ibuf_closed, obuf_closed;
    struct pollfd pollfd[3];
    struct pollfd *watch_socket, *watch_stdin, *watch_stdout;
    int stdin_type = 0, stdout_type = 0, fd_type = 0;

    char *bn = NULL;
    int c;

    static const struct option long_options[] = {
        {"version",     0, NULL, ARG_VERSION},
        {"help",        0, NULL, 'h'},
        {NULL,          0, NULL, 0}
    };

    setlocale(LC_ALL, "");
#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
#endif

    bn = pa_path_get_filename(argv[0]);

    while ((c = getopt_long(argc, argv, "h", long_options, NULL)) != -1) {
        switch (c) {
            case 'h' :
                help(bn);
                ret = 0;
                goto quit;
            case ARG_VERSION:
                printf(_("pacmd %s\n"
                         "Compiled with libpulse %s\n"
                         "Linked with libpulse %s\n"),
                       PACKAGE_VERSION,
                       pa_get_headers_version(),
                       pa_get_library_version());
                ret = 0;
                goto quit;
            default:
                goto quit;
        }
    }

    if (pa_pid_file_check_running(&pid, "pulseaudio") < 0) {
        pa_log(_("No PulseAudio daemon running, or not running as session daemon."));
        goto quit;
    }

    if ((fd = pa_socket_cloexec(PF_UNIX, SOCK_STREAM, 0)) < 0) {
        pa_log(_("socket(PF_UNIX, SOCK_STREAM, 0): %s"), strerror(errno));
        goto quit;
    }

    pa_zero(sa);
    sa.sun_family = AF_UNIX;

    if (!(cli = pa_runtime_path("cli")))
        goto quit;

    pa_strlcpy(sa.sun_path, cli, sizeof(sa.sun_path));
    pa_xfree(cli);

    for (i = 0; i < 5; i++) {
        int r;

        if ((r = connect(fd, (struct sockaddr*) &sa, sizeof(sa))) < 0 && (errno != ECONNREFUSED && errno != ENOENT)) {
            pa_log(_("connect(): %s"), strerror(errno));
            goto quit;
        }

        if (r >= 0)
            break;

        if (pa_pid_file_kill(SIGUSR2, NULL, "pulseaudio") < 0) {
            pa_log(_("Failed to kill PulseAudio daemon."));
            goto quit;
        }

        pa_msleep(300);
    }

    if (i >= 5) {
        pa_log(_("Daemon not responding."));
        goto quit;
    }

    buf_size = pa_pipe_buf(fd);
    ibuf_size = PA_MIN(buf_size, pa_pipe_buf(STDIN_FILENO));
    ibuf = pa_xmalloc(ibuf_size);
    obuf_size = PA_MIN(buf_size, pa_pipe_buf(STDOUT_FILENO));
    obuf = pa_xmalloc(obuf_size);
    ibuf_index = ibuf_length = obuf_index = obuf_length = 0;
    ibuf_eof = obuf_eof = ibuf_closed = obuf_closed = false;

    if (argc > 1) {
        for (i = 1; i < argc; i++) {
            size_t k;

            k = PA_MIN(ibuf_size - ibuf_length, strlen(argv[i]));
            memcpy(ibuf + ibuf_length, argv[i], k);
            ibuf_length += k;

            if (ibuf_length < ibuf_size) {
                ibuf[ibuf_length] = i < argc-1 ? ' ' : '\n';
                ibuf_length++;
            }
        }

        ibuf_eof = true;
    }

    if (!ibuf_eof && isatty(STDIN_FILENO)) {
        /* send hello to enable interactive mode (welcome message, prompt) */
        if (pa_write(fd, "hello\n", 6, &fd_type) < 0) {
            pa_log(_("write(): %s"), strerror(errno));
            goto quit;
        }
    }

    for (;;) {
        struct pollfd *p;

        if (ibuf_eof &&
            obuf_eof &&
            ibuf_length <= 0 &&
            obuf_length <= 0)
            break;

        if (ibuf_length <= 0 && ibuf_eof && !ibuf_closed) {
            shutdown(fd, SHUT_WR);
            ibuf_closed = true;
        }

        if (obuf_length <= 0 && obuf_eof && !obuf_closed) {
            shutdown(fd, SHUT_RD);
            obuf_closed = true;
        }

        pa_zero(pollfd);

        p = pollfd;

        if (ibuf_length > 0 || (!obuf_eof && obuf_length <= 0)) {
            watch_socket = p++;
            watch_socket->fd = fd;
            watch_socket->events =
                (ibuf_length > 0 ? POLLOUT : 0) |
                (!obuf_eof && obuf_length <= 0 ? POLLIN : 0);
        } else
            watch_socket = NULL;

        if (!ibuf_eof && ibuf_length <= 0) {
            watch_stdin = p++;
            watch_stdin->fd = STDIN_FILENO;
            watch_stdin->events = POLLIN;
        } else
            watch_stdin = NULL;

        if (obuf_length > 0) {
            watch_stdout = p++;
            watch_stdout->fd = STDOUT_FILENO;
            watch_stdout->events = POLLOUT;
        } else
            watch_stdout = NULL;

        if (pa_poll(pollfd, p-pollfd, -1) < 0) {

            if (errno == EINTR)
                continue;

            pa_log(_("poll(): %s"), strerror(errno));
            goto quit;
        }

        if (watch_stdin) {
            if (watch_stdin->revents & POLLIN) {
                ssize_t r;
                pa_assert(ibuf_length <= 0);

                if ((r = pa_read(STDIN_FILENO, ibuf, ibuf_size, &stdin_type)) <= 0) {
                    if (r < 0) {
                        pa_log(_("read(): %s"), strerror(errno));
                        goto quit;
                    }

                    ibuf_eof = true;
                } else {
                    ibuf_length = (size_t) r;
                    ibuf_index = 0;
                }
            } else if (watch_stdin->revents & POLLHUP)
                ibuf_eof = true;
        }

        if (watch_socket) {
            if (watch_socket->revents & POLLIN) {
                ssize_t r;
                pa_assert(obuf_length <= 0);

                if ((r = pa_read(fd, obuf, obuf_size, &fd_type)) <= 0) {
                    if (r < 0) {
                        pa_log(_("read(): %s"), strerror(errno));
                        goto quit;
                    }

                    obuf_eof = true;
                } else {
                    obuf_length = (size_t) r;
                    obuf_index = 0;
                }
            } else if (watch_socket->revents & POLLHUP)
                obuf_eof = true;
        }

        if (watch_stdout) {
            if (watch_stdout->revents & POLLHUP) {
                obuf_eof = true;
                obuf_length = 0;
            } else if (watch_stdout->revents & POLLOUT) {
                ssize_t r;
                pa_assert(obuf_length > 0);

                if ((r = pa_write(STDOUT_FILENO, obuf + obuf_index, obuf_length, &stdout_type)) < 0) {
                    pa_log(_("write(): %s"), strerror(errno));
                    goto quit;
                }

                obuf_length -= (size_t) r;
                obuf_index += obuf_index;
            }
        }

        if (watch_socket) {
            if (watch_socket->revents & POLLHUP) {
                ibuf_eof = true;
                ibuf_length = 0;
            } if (watch_socket->revents & POLLOUT) {
                ssize_t r;
                pa_assert(ibuf_length > 0);

                if ((r = pa_write(fd, ibuf + ibuf_index, ibuf_length, &fd_type)) < 0) {
                    pa_log(_("write(): %s"), strerror(errno));
                    goto quit;
                }

                ibuf_length -= (size_t) r;
                ibuf_index += obuf_index;
            }
        }
    }

    ret = 0;

quit:
    if (fd >= 0)
        pa_close(fd);

    pa_xfree(obuf);
    pa_xfree(ibuf);

    return ret;
}
예제 #21
0
파일: he_main.c 프로젝트: schwehr/hdf4
int
main(int argc, char *argv[])
{
    int         backup = YES;   /* Backup files when opening? */
    int i;
    char       *fileName = NULL;

    for (i = 1; i < argc; i++)
      {
          if (argv[i][0] == '-')
            {
                switch (findOpt(argv[i] + 1))
                  {
                      case HE_HELP:
                          printf("he [<file>] [-nobackup] [-batch]\n");
                          help();
                          quit(0);
                          break;
                      case HE_BATCH:
                          he_batch = YES;
                          break;
                      case HE_REMOTE:
                          he_remote = YES;
                          break;
                      case HE_NOBACKUP:
                          backup = NO;
                          break;
                      case HE_BACKUP:
                          backup = YES;
                          break;
                      case HE_NOTFOUND:
                          unkOpt(argv[i]);
                          quit(1);  /* does not return */
                          break;
                      case HE_AMBIG:
                          ambigOpt(argv[i]);
                          quit(1);
                          break;
                      default:
                          irrOpt(argv[i]);
                          quit(1);  /* does not return */
                          break;
                  }
            }
          else
            {
                /* Must be a filename */
                if (!fileName)
                    fileName = argv[i];
                else
                    fprintf(stderr, "Single file only. %s not open.\n", argv[i]);
            }
      }

    /* if there is a file name given in the command line, open it */

    if (fileName)
        he_status = openFile(fileName, backup);

    /* read, execute loop */
    cmdLoop();

    if (fileOpen())
        closeFile(YES);     /* close with keep */
    quit(0);
    return 0;
}
예제 #22
0
static void flag_help(void) { help(); }
예제 #23
0
//**********************************************************************************************************************
LefseCommand::LefseCommand(string option)  {
	try {
		abort = false; calledHelp = false;
        allLines = 1;
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			//valid paramters for this command
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string,string> parameters = parser.getParameters();
			
			ValidParameters validParameter;
			map<string,string>::iterator it;
			//check to make sure all parameters are valid for command
			for (it = parameters.begin(); it != parameters.end(); it++) {
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			vector<string> tempOutNames;
            outputTypes["summary"] = tempOutNames;
            outputTypes["kruskall-wallis"] = tempOutNames;
            outputTypes["wilcoxon"] = tempOutNames;
            
			//if the user changes the input directory command factory will send this info to us in the output parameter
			string inputDir = validParameter.validFile(parameters, "inputdir", false);
			if (inputDir == "not found"){	inputDir = "";		}
			else {
                
                string path;
				it = parameters.find("design");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["desing"] = inputDir + it->second;		}
				}
				
                it = parameters.find("shared");
				//user has given a template file
				if(it != parameters.end()){
					path = m->hasPath(it->second);
					//if the user has not given a path then, add inputdir. else leave path alone.
					if (path == "") {	parameters["shared"] = inputDir + it->second;		}
				}
            }
                    
            //get shared file, it is required
			sharedfile = validParameter.validFile(parameters, "shared", true);
			if (sharedfile == "not open") { sharedfile = ""; abort = true; }
			else if (sharedfile == "not found") {
				//if there is a current shared file, use it
				sharedfile = m->getSharedFile();
				if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
				else { 	m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
			}else { m->setSharedFile(sharedfile); }
            
            //get shared file, it is required
			designfile = validParameter.validFile(parameters, "design", true);
			if (designfile == "not open") { designfile = ""; abort = true; }
			else if (designfile == "not found") {
				//if there is a current shared file, use it
				designfile = m->getDesignFile();
				if (designfile != "") { m->mothurOut("Using " + designfile + " as input file for the design parameter."); m->mothurOutEndLine(); }
				else { 	m->mothurOut("You have no current design file and the design parameter is required."); m->mothurOutEndLine(); abort = true; }
			}else { m->setDesignFile(designfile); }
            
            //if the user changes the output directory command factory will send this info to us in the output parameter
			outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found"){
				outputDir = m->hasPath(sharedfile); //if user entered a file with a path then preserve it
			}
            
            string label = validParameter.validFile(parameters, "label", false);
			if (label == "not found") { label = ""; }
			else {
				if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
				else { allLines = 1;  }
			}
            
            mclass = validParameter.validFile(parameters, "class", false);
			if (mclass == "not found") { mclass = ""; }
			
            subclass = validParameter.validFile(parameters, "subclass", false);
			if (subclass == "not found") { subclass = ""; }
            
            classes = validParameter.validFile(parameters, "classes", false);
			if (classes == "not found") { classes = ""; }
            
            string temp = validParameter.validFile(parameters, "anova_alpha", false);
			if (temp == "not found") { temp = "0.05"; }
			m->mothurConvert(temp, anovaAlpha);
            
            temp = validParameter.validFile(parameters, "wilcoxon_alpha", false);
			if (temp == "not found") { temp = "0.05"; }
			m->mothurConvert(temp, wilcoxonAlpha);

		}
		
	}
	catch(exception& e) {
		m->errorOut(e, "LefseCommand", "LefseCommand");
		exit(1);
	}
}
예제 #24
0
int main(int argc, char ** args){
    char *flag_array[] = FLAG_ARRAY;
    int flags = process_flags(argc, args, FLAG_ARRAY_SIZE, flag_array);
    double * numeric_args = malloc(sizeof(double) * (argc - 1));
    int numeric_arg_count = process_numeric_args(argc, args, numeric_args);

    if(flags & FLAG_HELP){
        help();
        return 0;
    }

    if(flags & FLAG_RESUME){
        printf("Unimplemented. Sorry.\n");
        return 1;
    }

    // first argument should always be a file unless --stdout
    FILE * fout;
    if(flags & FLAG_STDOUT){
        // write to stdout. This is useful if we want to pipe the data somewhere (ie, for visualisation)
        fout = stdout;
    }else{
        fout = fopen(args[1], "w");
        if(fout == NULL){
            printf("Could not open file at %s for writing. No such directory or permission denied.\n", args[1]);
            return 1;
        }
    }

    if(flags & FLAG_ORBIT){
        if(flags & FLAG_SIMPLE){
            if(flags & FLAG_2D){
                if(numeric_arg_count == 8){
                    char *labels[8] = {"time", "xpos", "ypos", "xvel", "yvel", "object_mass", "time_limit", "total_energy"};
                    set_up_runge_kutta_4th(5, 2);
                    iterate_to_file(&simple_2d_orbit_runge_kutta_4th, 8, numeric_args, numeric_args[7], labels, fout);
                    free_runge_kutta_4th();
                }else{
                    printf("Invalid number of numerical arguments. Need 8, %d given.\n", numeric_arg_count);
                }
            }else{
                printf("Simple 3D simulation has not been implemented. Please specify --2D.\n");
            }
        }else if(flags & FLAG_FREE){
            if(flags & FLAG_2D){
                // make sure a valid number of args has been entered
                if(numeric_arg_count >= 8 && (numeric_arg_count - 3) % 5 == 0){
                    body_count = (numeric_arg_count - 3) / 5;
                    char ** labels = malloc(sizeof(char *) * (body_count * 5 + 2));
                    labels[0] = "time";
                    int i;
                    for(i=0;i<body_count;i++){
                        labels[i * 5 + 1] = malloc(8);
                        sprintf(labels[i * 5 + 1], "%d.xpos", i);
                        labels[i * 5 + 2] = malloc(8);
                        sprintf(labels[i * 5 + 2], "%d.ypos", i);
                        labels[i * 5 + 3] = malloc(8);
                        sprintf(labels[i * 5 + 3], "%d.xvel", i);
                        labels[i * 5 + 4] = malloc(8);
                        sprintf(labels[i * 5 + 4], "%d.yvel", i);
                        labels[i * 5 + 5] = malloc(8);
                        sprintf(labels[i * 5 + 5], "%d.mass", i);
                    }
                    labels[body_count * 5 + 1] = "time_limit";
                    set_up_runge_kutta_4th(5 * body_count + 1, 1);
                    iterate_to_file(&free_2d_orbit_runge_kutta_4th, 5 * body_count + 2, numeric_args, numeric_args[numeric_arg_count - 1], labels, fout);
                    free_runge_kutta_4th();
                }else{
                    printf("Invalid number of numerical arguments. Need at least 8 with 5 arguments for each body. %d given\n", numeric_arg_count);
                    help();
                    return 1;
                }
            }else if(flags & FLAG_3D){
                // make sure a valid number of args have been entered
                if(numeric_arg_count >= 10 && (numeric_arg_count - 3) % 7 == 0){
                    body_count = (numeric_arg_count - 3) / 7;
                    char ** labels = malloc(sizeof(char *) * (body_count * 7 + 2));
                    labels[0] = "time";
                    int i;
                    for(i=0;i<body_count;i++){
                        labels[i * 7 + 1] = malloc(8);
                        sprintf(labels[i * 7 + 1], "%d.xpos", i);
                        labels[i * 7 + 2] = malloc(8);
                        sprintf(labels[i * 7 + 2], "%d.ypos", i);
                        labels[i * 7 + 3] = malloc(8);
                        sprintf(labels[i * 7 + 3], "%d.zpos", i);
                        labels[i * 7 + 4] = malloc(8);
                        sprintf(labels[i * 7 + 4], "%d.xvel", i);
                        labels[i * 7 + 5] = malloc(8);
                        sprintf(labels[i * 7 + 5], "%d.yvel", i);
                        labels[i * 7 + 6] = malloc(8);
                        sprintf(labels[i * 7 + 6], "%d.zvel", i);
                        labels[i * 7 + 7] = malloc(8);
                        sprintf(labels[i * 7 + 7], "%d.mass", i);
                    }
                    labels[body_count * 7 + 1] = "time_limit";
                    set_up_runge_kutta_4th(7 * body_count + 1, 1);
                    iterate_to_file(&free_3d_orbit_runge_kutta_4th, 7 * body_count + 2, numeric_args, numeric_args[numeric_arg_count - 1], labels, fout);
                    free_runge_kutta_4th();
                }else{
                    printf("Invalid number of numerical arguments. Need at least 10 with 7 arguments for each body. %d given\n", numeric_arg_count);
                    help();
                    return 1;
                }
            }else{
                printf("Please specify either --2D or --3D\n");
                help();
                return 1;
            }
        }else{
            printf("Please specify either --simple or --free\n");
            help();
            return 1;
        }
    }

    return 0;
}
예제 #25
0
// decode用のmain関数
int main(int argc, char *argv[])
{
  //char input_filename[1024];
  char *input_filename, *output_filename, *dict_filename;
  FILE *input, *output, *dictfile;
  IBITFS input_stream, dict_stream;
  int result;

 /* オプションの解析 */
  while ((result = getopt(argc, argv, "r:w:d:")) != -1) {
    switch (result) {
    case 'r':
      input_filename = optarg;
      break;
      
    case 'w':
      output_filename = optarg;
      break;
      
    case 'd':
      dict_filename = optarg;
      break;
      
    case '?':
      help(argv);
      break;
    }
  }

  // 必要なオプションがそろっているかを確認する
  if (!(input_filename && output_filename && dict_filename)) {
    help(argv);
  }
  
  // 圧縮データファイルをオープンする
  input  = fopen(input_filename, "rb");
  if (input == NULL) {
    puts("Input file open error at the beginning.");
    exit(1);
  }
  
  // 出力用ファイルをオープンする
  output = fopen(output_filename, "wb");
  if (output == NULL) {
    puts("Output file open error at the beginning.");
    exit(1);
  }
  
  // 辞書ファイルをオープンする
  dictfile = fopen(dict_filename, "rb");
  if (!dictfile) {
    puts("Dictionary file open error at the beginning.");
    exit(EXIT_FAILURE);
  }

  ibitfs_init(&input_stream, input);
  ibitfs_init(&dict_stream, dictfile);
  

  DecodeCFG(output, &input_stream, &dict_stream);
  ibitfs_finalize(&input_stream);
  ibitfs_finalize(&dict_stream);
  fclose(input); fclose(output);
  exit(0);
}
예제 #26
0
int usage()
{
    help();
    return 1;
}
예제 #27
0
static void dohelp(void) {
    _dousage();
    help("overview.html");
exit(0);
}
예제 #28
0
int adb_commandline(int argc, char **argv)
{
    char buf[4096];
    int no_daemon = 0;
    int is_daemon = 0;
    int is_server = 0;
    int persist = 0;
    int r;
    int quote;
    transport_type ttype = kTransportAny;
    char* serial = NULL;
    char* server_port_str = NULL;

        /* If defined, this should be an absolute path to
         * the directory containing all of the various system images
         * for a particular product.  If not defined, and the adb
         * command requires this information, then the user must
         * specify the path using "-p".
         */
    gProductOutPath = getenv("ANDROID_PRODUCT_OUT");
    if (gProductOutPath == NULL || gProductOutPath[0] == '\0') {
        gProductOutPath = NULL;
    }
    // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint

    serial = getenv("ANDROID_SERIAL");

    /* Validate and assign the server port */
    server_port_str = getenv("ANDROID_ADB_SERVER_PORT");
    int server_port = DEFAULT_ADB_PORT;
    if (server_port_str && strlen(server_port_str) > 0) {
        server_port = (int) strtol(server_port_str, NULL, 0);
        if (server_port <= 0) {
            fprintf(stderr,
                    "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number. Got \"%s\"\n",
                    server_port_str);
            return usage();
        }
    }

    /* modifiers and flags */
    while(argc > 0) {
        if(!strcmp(argv[0],"server")) {
            is_server = 1;
        } else if(!strcmp(argv[0],"nodaemon")) {
            no_daemon = 1;
        } else if (!strcmp(argv[0], "fork-server")) {
            /* this is a special flag used only when the ADB client launches the ADB Server */
            is_daemon = 1;
        } else if(!strcmp(argv[0],"persist")) {
            persist = 1;
        } else if(!strncmp(argv[0], "-p", 2)) {
            const char *product = NULL;
            if (argv[0][2] == '\0') {
                if (argc < 2) return usage();
                product = argv[1];
                argc--;
                argv++;
            } else {
                product = argv[0] + 2;
            }
            gProductOutPath = find_product_out_path(product);
            if (gProductOutPath == NULL) {
                fprintf(stderr, "adb: could not resolve \"-p %s\"\n",
                        product);
                return usage();
            }
        } else if (argv[0][0]=='-' && argv[0][1]=='s') {
            if (isdigit(argv[0][2])) {
                serial = argv[0] + 2;
            } else {
                if(argc < 2 || argv[0][2] != '\0') return usage();
                serial = argv[1];
                argc--;
                argv++;
            }
        } else if (!strcmp(argv[0],"-d")) {
            ttype = kTransportUsb;
        } else if (!strcmp(argv[0],"-e")) {
            ttype = kTransportLocal;
        } else {
                /* out of recognized modifiers and flags */
            break;
        }
        argc--;
        argv++;
    }

    adb_set_transport(ttype, serial);
    adb_set_tcp_specifics(server_port);

    if (is_server) {
        if (no_daemon || is_daemon) {
            r = adb_main(is_daemon, server_port);
        } else {
            r = launch_server(server_port);
        }
        if(r) {
            fprintf(stderr,"* could not start server *\n");
        }
        return r;
    }

top:
    if(argc == 0) {
        return usage();
    }

    /* adb_connect() commands */

    if(!strcmp(argv[0], "devices")) {
        char *tmp;
        char *listopt;
        if (argc < 2)
            listopt = "";
        else if (argc == 2 && !strcmp(argv[1], "-l"))
            listopt = argv[1];
        else {
            fprintf(stderr, "Usage: adb devices [-l]\n");
            return 1;
        }
        snprintf(buf, sizeof buf, "host:%s%s", argv[0], listopt);
        tmp = adb_query(buf);
        if(tmp) {
            printf("List of devices attached \n");
            printf("%s\n", tmp);
            return 0;
        } else {
            return 1;
        }
    }

    if(!strcmp(argv[0], "connect")) {
        char *tmp;
        if (argc != 2) {
            fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
            return 1;
        }
        snprintf(buf, sizeof buf, "host:connect:%s", argv[1]);
        tmp = adb_query(buf);
        if(tmp) {
            printf("%s\n", tmp);
            return 0;
        } else {
            return 1;
        }
    }

    if(!strcmp(argv[0], "disconnect")) {
        char *tmp;
        if (argc > 2) {
            fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
            return 1;
        }
        if (argc == 2) {
            snprintf(buf, sizeof buf, "host:disconnect:%s", argv[1]);
        } else {
            snprintf(buf, sizeof buf, "host:disconnect:");
        }
        tmp = adb_query(buf);
        if(tmp) {
            printf("%s\n", tmp);
            return 0;
        } else {
            return 1;
        }
    }

    if (!strcmp(argv[0], "emu")) {
        return adb_send_emulator_command(argc, argv);
    }

    if(!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) {
        int r;
        int fd;

        char h = (argv[0][0] == 'h');

        if (h) {
            printf("\x1b[41;33m");
            fflush(stdout);
        }

        if(argc < 2) {
            D("starting interactive shell\n");
            r = interactive_shell();
            if (h) {
                printf("\x1b[0m");
                fflush(stdout);
            }
            return r;
        }

        snprintf(buf, sizeof buf, "shell:%s", argv[1]);
        argc -= 2;
        argv += 2;
        while(argc-- > 0) {
            strcat(buf, " ");

            /* quote empty strings and strings with spaces */
            quote = (**argv == 0 || strchr(*argv, ' '));
            if (quote)
                strcat(buf, "\"");
            strcat(buf, *argv++);
            if (quote)
                strcat(buf, "\"");
        }

        for(;;) {
            D("interactive shell loop. buff=%s\n", buf);
            fd = adb_connect(buf);
            if(fd >= 0) {
                D("about to read_and_dump(fd=%d)\n", fd);
                read_and_dump(fd);
                D("read_and_dump() done.\n");
                adb_close(fd);
                r = 0;
            } else {
                fprintf(stderr,"error: %s\n", adb_error());
                r = -1;
            }

            if(persist) {
                fprintf(stderr,"\n- waiting for device -\n");
                adb_sleep_ms(1000);
                do_cmd(ttype, serial, "wait-for-device", 0);
            } else {
                if (h) {
                    printf("\x1b[0m");
                    fflush(stdout);
                }
                D("interactive shell loop. return r=%d\n", r);
                return r;
            }
        }
    }

    if(!strcmp(argv[0], "kill-server")) {
        int fd;
        fd = _adb_connect("host:kill");
        if(fd == -1) {
            fprintf(stderr,"* server not running *\n");
            return 1;
        }
        return 0;
    }

    if(!strcmp(argv[0], "sideload")) {
        if(argc != 2) return usage();
        if(adb_download("sideload", argv[1], 1)) {
            return 1;
        } else {
            return 0;
        }
    }

    if(!strcmp(argv[0], "remount") || !strcmp(argv[0], "reboot")
            || !strcmp(argv[0], "reboot-bootloader")
            || !strcmp(argv[0], "tcpip") || !strcmp(argv[0], "usb")
            || !strcmp(argv[0], "root")) {
        char command[100];
        if (!strcmp(argv[0], "reboot-bootloader"))
            snprintf(command, sizeof(command), "reboot:bootloader");
        else if (argc > 1)
            snprintf(command, sizeof(command), "%s:%s", argv[0], argv[1]);
        else
            snprintf(command, sizeof(command), "%s:", argv[0]);
        int fd = adb_connect(command);
        if(fd >= 0) {
            read_and_dump(fd);
            adb_close(fd);
            return 0;
        }
        fprintf(stderr,"error: %s\n", adb_error());
        return 1;
    }

    if(!strcmp(argv[0], "bugreport")) {
        if (argc != 1) return usage();
        do_cmd(ttype, serial, "shell", "bugreport", 0);
        return 0;
    }

    /* adb_command() wrapper commands */

    if(!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
        char* service = argv[0];
        if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) {
            if (ttype == kTransportUsb) {
                service = "wait-for-usb";
            } else if (ttype == kTransportLocal) {
                service = "wait-for-local";
            } else {
                service = "wait-for-any";
            }
        }

        format_host_command(buf, sizeof buf, service, ttype, serial);

        if (adb_command(buf)) {
            D("failure: %s *\n",adb_error());
            fprintf(stderr,"error: %s\n", adb_error());
            return 1;
        }

        /* Allow a command to be run after wait-for-device,
            * e.g. 'adb wait-for-device shell'.
            */
        if(argc > 1) {
            argc--;
            argv++;
            goto top;
        }
        return 0;
    }

    if(!strcmp(argv[0], "forward")) {
        if(argc != 3) return usage();
        if (serial) {
            snprintf(buf, sizeof buf, "host-serial:%s:forward:%s;%s",serial, argv[1], argv[2]);
        } else if (ttype == kTransportUsb) {
            snprintf(buf, sizeof buf, "host-usb:forward:%s;%s", argv[1], argv[2]);
        } else if (ttype == kTransportLocal) {
            snprintf(buf, sizeof buf, "host-local:forward:%s;%s", argv[1], argv[2]);
        } else {
            snprintf(buf, sizeof buf, "host:forward:%s;%s", argv[1], argv[2]);
        }
        if(adb_command(buf)) {
            fprintf(stderr,"error: %s\n", adb_error());
            return 1;
        }
        return 0;
    }

    /* do_sync_*() commands */

    if(!strcmp(argv[0], "ls")) {
        if(argc != 2) return usage();
        return do_sync_ls(argv[1]);
    }

    if(!strcmp(argv[0], "push")) {
        if(argc != 3) return usage();
        return do_sync_push(argv[1], argv[2], 0 /* no verify APK */);
    }

    if(!strcmp(argv[0], "pull")) {
        if (argc == 2) {
            return do_sync_pull(argv[1], ".");
        } else if (argc == 3) {
            return do_sync_pull(argv[1], argv[2]);
        } else {
            return usage();
        }
    }

    if(!strcmp(argv[0], "install")) {
        if (argc < 2) return usage();
        return install_app(ttype, serial, argc, argv);
    }

    if(!strcmp(argv[0], "uninstall")) {
        if (argc < 2) return usage();
        return uninstall_app(ttype, serial, argc, argv);
    }

    if(!strcmp(argv[0], "sync")) {
        char *srcarg, *android_srcpath, *data_srcpath;
        int listonly = 0;

        int ret;
        if(argc < 2) {
            /* No local path was specified. */
            srcarg = NULL;
        } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
            listonly = 1;
            if (argc == 3) {
                srcarg = argv[2];
            } else {
                srcarg = NULL;
            }
        } else if(argc == 2) {
            /* A local path or "android"/"data" arg was specified. */
            srcarg = argv[1];
        } else {
            return usage();
        }
        ret = find_sync_dirs(srcarg, &android_srcpath, &data_srcpath);
        if(ret != 0) return usage();

        if(android_srcpath != NULL)
            ret = do_sync_sync(android_srcpath, "/system", listonly);
        if(ret == 0 && data_srcpath != NULL)
            ret = do_sync_sync(data_srcpath, "/data", listonly);

        free(android_srcpath);
        free(data_srcpath);
        return ret;
    }

    /* passthrough commands */

    if(!strcmp(argv[0],"get-state") ||
        !strcmp(argv[0],"get-serialno") ||
        !strcmp(argv[0],"get-devpath"))
    {
        char *tmp;

        format_host_command(buf, sizeof buf, argv[0], ttype, serial);
        tmp = adb_query(buf);
        if(tmp) {
            printf("%s\n", tmp);
            return 0;
        } else {
            return 1;
        }
    }

    /* other commands */

    if(!strcmp(argv[0],"status-window")) {
        status_window(ttype, serial);
        return 0;
    }

    if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
        return logcat(ttype, serial, argc, argv);
    }

    if(!strcmp(argv[0],"ppp")) {
        return ppp(argc, argv);
    }

    if (!strcmp(argv[0], "start-server")) {
        return adb_connect("host:start-server");
    }

    if (!strcmp(argv[0], "backup")) {
        return backup(argc, argv);
    }

    if (!strcmp(argv[0], "restore")) {
        return restore(argc, argv);
    }

    if (!strcmp(argv[0], "jdwp")) {
        int  fd = adb_connect("jdwp");
        if (fd >= 0) {
            read_and_dump(fd);
            adb_close(fd);
            return 0;
        } else {
            fprintf(stderr, "error: %s\n", adb_error());
            return -1;
        }
    }

    /* "adb /?" is a common idiom under Windows */
    if(!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
        help();
        return 0;
    }

    if(!strcmp(argv[0], "version")) {
        version(stdout);
        return 0;
    }

    usage();
    return 1;
}
예제 #29
0
WB_LONG main(WB_LONG argc, WB_TINY **argv)
{
    WB_UTINY *wbxml = NULL, *output = NULL, *xml = NULL;
    FILE *input_file = NULL, *output_file = NULL;
    WB_LONG count = 0, wbxml_len = 0, total = 0;
    WB_ULONG xml_len = 0;
    WB_TINY opt;
    WBXMLError ret = WBXML_OK;
    WB_UTINY input_buffer[INPUT_BUFFER_SIZE + 1];
    WBXMLGenXMLParams params;

    /* Init Default Parameters */
    params.lang = WBXML_LANG_UNKNOWN;
    params.gen_type = WBXML_GEN_XML_INDENT;
    params.indent = 1;
    params.keep_ignorable_ws = FALSE;

    while ((opt = (WB_TINY) getopt(argc, argv, "kh?o:m:i:l:")) != EOF)
    {
        switch (opt) {
        case 'k':
            params.keep_ignorable_ws = TRUE;
            break;
        case 'i':
            params.indent = (WB_UTINY) atoi((const WB_TINY*)optarg);
            break;
        case 'l':
            params.lang = get_lang((const WB_TINY*)optarg);
            break;
        case 'm':
            switch (atoi((const WB_TINY*)optarg)) {
            case 0:
                params.gen_type = WBXML_GEN_XML_COMPACT;
                break;
            case 1:
                params.gen_type = WBXML_GEN_XML_INDENT;
                break;
            case 2:
                params.gen_type = WBXML_GEN_XML_CANONICAL;
                break;
            default:
                params.gen_type = WBXML_GEN_XML_INDENT;
            }
            break;
        case 'o':
            output = (WB_UTINY*) optarg;
            break;
        case 'h':
        case '?':
        default:
            help();
            return 0;
        }
    }

    if (optind >= argc) {
        fprintf(stderr, "Missing arguments\n");
        help();
        return 0;
    }

#ifdef WBXML_USE_LEAKTRACKER
    lt_init_mem();
    lt_log_open_file("wbxml2xml.log");
    lt_log(0, "\n***************************\n Converting file: %s", argv[optind]);
#endif

    /**********************************
     *  Read the WBXML Document
     */

    if (WBXML_STRCMP(argv[optind], "-") == 0) {
        input_file = stdin;
    } else {
        /* Open WBXML document */
        input_file = fopen(argv[optind], "rb");
        if (input_file == NULL) {
            fprintf(stderr, "Failed to open %s\n", argv[optind]);
            goto clean_up;
        }
    }

    /* Read WBXML document */
    while(!feof(input_file))    {
        count = fread(input_buffer, sizeof(WB_UTINY), INPUT_BUFFER_SIZE, input_file);
        if (ferror(input_file))      {
            fprintf(stderr, "Error while reading from file %s\n", argv[optind]);
            if (input_file != stdin)
                fclose(input_file);
            if (wbxml != NULL)
                wbxml_free(wbxml);
            goto clean_up;
        }

        total += count;
        wbxml = wbxml_realloc(wbxml, total);
        if (wbxml == NULL) {
            fprintf(stderr, "Not enought memory\n");
            if (input_file != stdin)
                fclose(input_file);
            if (wbxml != NULL)
                wbxml_free(wbxml);
            goto clean_up;
        }

        memcpy(wbxml + wbxml_len, input_buffer, count);
        wbxml_len += count;
    }

    if (input_file != stdin)
        fclose(input_file);

    /* Convert WBXML document */
    ret = wbxml_conv_wbxml2xml_withlen(wbxml, wbxml_len, &xml, &xml_len, &params);
    if (ret != WBXML_OK) {
        fprintf(stderr, "wbxml2xml failed: %s\n", wbxml_errors_string(ret));
    }
    else {
        /* fprintf(stderr, "wbxml2xml succeded: \n%s\n", xml); */
        fprintf(stderr, "wbxml2xml succeded\n");

        if (output != NULL) {
            if (WBXML_STRCMP(output, "-") == 0) {
                output_file = stdout;
            } else {
                /* Open Output File */
                output_file = fopen((const WB_TINY*) output, "w");
            }

            if (output_file == NULL) {
                fprintf(stderr, "Failed to open output file: %s\n", output);
            }

            /* Write to Output File */
            if (fwrite(xml, sizeof(WB_UTINY), xml_len, output_file) < xml_len)
                fprintf(stderr, "Error while writing to file: %s\n", output);
            /*
            else
                fprintf(stderr, "Written %u bytes to file: %s\n", xml_len, output);
            */

            if (output_file != stdout)
                fclose(output_file);
        }

        /* Clean-up */
        wbxml_free(xml);
    }

    wbxml_free(wbxml);

clean_up:

#ifdef WBXML_USE_LEAKTRACKER
    lt_check_leaks();
    lt_shutdown_mem();
    lt_log_close_file();
#endif

    return 0;
}
예제 #30
0
void CmdThread::onClient(DebuggerClient &client) {
  if (DebuggerCommand::displayedHelp(client)) return;
  if (client.argCount() > 1) {
    help(client);
    return;
  }

  if (client.argCount() == 0) {
    m_body = "info";
    auto res = client.xend<CmdThread>(this);
    client.print(res->m_out);
  } else if (client.arg(1, "list")) {
    processList(client);
  } else if (client.arg(1, "normal")) {
    m_body = "normal";
    client.sendToServer(this);
    client.info("Thread is running in normal mode now. Other threads will "
                 "interleave when they hit breakpoints as well.");
  } else if (client.arg(1, "sticky")) {
    m_body = "sticky";
    client.sendToServer(this);
    client.info("Thread is running in sticky mode now. All other threads "
                 "will wait until this thread finishes, when they hit "
                 "breakpoints.");
  } else if (client.arg(1, "exclusive")) {
    m_body = "exclusive";
    client.sendToServer(this);
    client.info("Thread is running in exclusive mode now. All other threads "
                 "will not break, even when they hit breakpoints.");
  } else {
    std::string snum = client.argValue(1);
    if (!DebuggerClient::IsValidNumber(snum)) {
      client.error("'[t]hread {index}' needs a numeric argument.");
      client.tutorial(
        "You will have to run '[t]hread [l]ist' first to see a list of valid "
        "numbers or indices to specify. Thread 1 is always your current "
        "thread. If that's the only thread on the list, you do not have "
        "another thread at break to switch to."
      );
      return;
    }

    int num = atoi(snum.c_str());
    DThreadInfoPtr thread = client.getThread(num);
    if (!thread) {
      processList(client, false);
      thread = client.getThread(num);
      if (!thread) {
        client.error("\"%s\" is not a valid thread index. Choose one from "
                      "this list:", snum.c_str());
        processList(client);
        return;
      }
    }

    if (thread->m_id == client.getCurrentThreadId()) {
      client.info("This is your current thread already.");
      return;
    }

    m_body = "switch";
    m_threads.push_back(thread);
    client.sendToServer(this);
    throw DebuggerConsoleExitException();
  }
}