Exemplo n.º 1
0
/*******************************************************************************
 * Entry point
 ******************************************************************************/
int main(int argc, char *argv[argc]) {
    // We first parse command line switchs
    opt_t opt = opt_defaults;
    opt_parse(argc, argv, &opt);
    // Next we prepare the model
    rdr_t *rdr = rdr_new(opt.maxent);
    rdr->min_count = opt.min_count;
    mdl_t *mdl = mdl_new(rdr);
    mdl->opt = &opt;
    // And switch to requested mode
    switch (opt.mode) {
    case 0:
        dotrain(mdl);
        break;
    case 1:
        dolabel(mdl);
        break;
    case 2:
        dodump(mdl);
        break;
    case 3:
        doupdt(mdl);
        break;
    }
    // And cleanup
    mdl_free(mdl);
    return EXIT_SUCCESS;
}
Exemplo n.º 2
0
int main(int argc, char *argv[]){
    
    int i = 0;

    if(opt_parse(argc, argv, "d:f:u:p:n:o:csg")){
        fprintf(stderr, "bad cmdline arguments. please retry!\n");
        exit(2);
    }
    
    if(get_stdin_passwd)
        get_real_passwd(); 

    if(!conf_filepath)
        conf_filepath = AD_CONF_FILE;

    if(get_cond_from_file(conf_filepath) && !isvalid_ad_cond()){
        fprintf(stderr, "initialize from file failed. please retry!\n");
        exit(1);
    }

    if(!isvalid_ad_cond()){
        fprintf(stderr, "can't get fully informations to connect WIN_AD.\n"
                        "please specify it again on cmdline or conf_file and retry!\n");
        exit(2);
    }
    get_domain_info(&ad);

    dump_ad_cond();
    free_ad_cond();

    return 0;
}
Exemplo n.º 3
0
/** 
 * <JA>
 * jconf 設定ファイルを読み込んで解析し,対応するオプションを設定する.
 * オプション内の相対パスは、その jconf 設定ファイルからの相対となる.
 * 
 * @param conffile [in] jconf ファイルのパス名
 * @param jconf [out] 値をセットする jconf 設定データ
 * </JA>
 * <EN>
 * Read and parse a jconf file, and set the specified option values.
 * Relative paths in the file will be treated as relative to the file,
 * not the application current.
 * 
 * @param conffile [in] jconf file path name
 * @param jconf [out] global configuration data to be written.
 * </EN>
 *
 * @callgraph
 * @callergraph
 */
boolean
config_file_parse(char *conffile, Jconf *jconf)
{
  int c_argc;
  char **c_argv;
  FILE *fp;
  int maxnum;
  char buf[BUFLEN];
  char *cdir;
  int i;
  boolean ret;

  jlog("STAT: include config: %s\n", conffile);
  
  /* set the content of jconf file into argument list c_argv[1..c_argc-1] */
  /* c_argv[0] will be the original conffile name */
  /* inside jconf file, quoting by ", ' and escape by '\' is supported */
  if ((fp = fopen(conffile, "r")) == NULL) {
    jlog("ERROR: m_jconf: failed to open jconf file: %s\n", conffile);
    return FALSE;
  }
  maxnum = 20;
  c_argv = (char **)mymalloc(sizeof(char *) * maxnum);
  c_argv[0] = strcpy((char *)mymalloc(strlen(conffile)+1), conffile);
  c_argc = 1;
  while (fgets_jconf(buf, BUFLEN, fp) != NULL) {
    if (buf[0] == '\0') continue;
    add_to_arglist(buf, &c_argv, &c_argc, &maxnum);
  }
  if (fclose(fp) == -1) {
    jlog("ERROR: m_jconf: cannot close jconf file\n");
    return FALSE;
  }

  /* env expansion */
  for (i=1;i<c_argc;i++) {
    c_argv[i] = expand_env(c_argv[i]);
  }

  if (debug2_flag) {		/* for debug */
    jlog("DEBUG: args:");
    for (i=1;i<c_argc;i++) jlog(" %s",c_argv[i]);
    jlog("\n");
  }

  /* now that options are in c_argv[][], call opt_parse() to process them */
  /* relative paths in jconf file are relative to the jconf file (not current) */
  cdir = strcpy((char *)mymalloc(strlen(conffile)+1), conffile);
  get_dirname(cdir);
  ret = opt_parse(c_argc, c_argv, (cdir[0] == '\0') ? NULL : cdir, jconf);
  free(cdir);

  /* free arguments */
  while (c_argc-- > 0) {
    free(c_argv[c_argc]);
  }
  free(c_argv);

  return(ret);
}
Exemplo n.º 4
0
int fuse_opt_parse(struct fuse_args *args, void *data,
		   const struct fuse_opt opts[], fuse_opt_proc_t proc)
{
	int res;
	struct fuse_opt_context ctx = {
		.data = data,
		.opt = opts,
		.proc = proc,
	};

	if (!args || !args->argv || !args->argc)
		return 0;

	ctx.argc = args->argc;
	ctx.argv = args->argv;

	res = opt_parse(&ctx);
	if (res != -1) {
		struct fuse_args tmp = *args;
		*args = ctx.outargs;
		ctx.outargs = tmp;
	}
	free(ctx.opts);
	fuse_opt_free_args(&ctx.outargs);
	return res;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	struct bitcoin_tx *tx;
	struct sha256_double txid;
	char str[hex_str_size(sizeof(txid))];

	err_set_progname(argv[0]);

	/* FIXME: Take update.pbs to adjust channel */
	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<tx>\n"
			   "Print txid of the transaction in the file",
			   "Print this message.");
	opt_register_version();

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc != 2)
		opt_usage_exit_fail("Expected 1 argument");

	tx = bitcoin_tx_from_file(ctx, argv[1]);
	bitcoin_txid(tx, &txid);

	if (!bitcoin_txid_to_hex(&txid, str, sizeof(str)))
		abort();

	/* Print it out. */
	if (!write_all(STDOUT_FILENO, str, strlen(str)))
		err(1, "Writing out txid");

	tal_free(ctx);
	return 0;
}
int main(int argc,char* argv[]){
	skl::OptParser options;
	std::vector<std::string> args;
	opt_parse(options,argc,argv,args);

	if(options.help()){
		options.usage();
		return EXIT_FAILURE;
	}

	skl::VideoCapture cam;
	skl::VideoCaptureParams params;

	if(!camera_setting.empty()){
		params.load(camera_setting);
	}
	// CAUTION: call opt_parse_cap_prop after opt_parse
	opt_parse_cap_prop(params);



	if(input_file.empty()){
		cam.open(dev);
	}
	else{
		cam.open(input_file);
	}

	// CAUTION: set params after open the camera.
	cam.set(params);

	std::cout << "Camera Parameter Settings" << std::endl;
	std::cout << cam.get();

	if(!cam.isOpened()){
		std::cerr << "ERROR: failed to open video." << std::endl;
		std::cerr << "       Maybe, camera is not connected to the PC??" << std::endl;
		return EXIT_FAILURE;
	}

	cv::namedWindow("image",0);
	int pos_frames;
	if(trackbar && !input_file.empty()){
		cv::createTrackbar("pos","image",&pos_frames, cam.get(skl::FRAME_COUNT)-1);
	}
	cv::Mat image;

	cv::VideoWriter writer;
	if(!output_file.empty()){
		cam >> image;
		if(!writer.open(
					output_file,
					CV_FOURCC('D','V','I','X'),
					cam.get(skl::FPS),
					image.size(),
					(cam.get(skl::MONOCROME)<=0))){
			std::cerr << "WARNING: failed to open " << output_file << ".";
		}
		writer << image;
	}
Exemplo n.º 7
0
/* config_string_parse with base dir */
boolean
config_string_parse_basedir(char *str, Jconf *jconf, char *dir)
{
  int c_argc;
  char **c_argv;
  int maxnum;
  int i;
  boolean ret;

  jlog("STAT: parsing option string: \"%s\"\n", str);
  
  /* set the content of jconf file into argument list c_argv[1..c_argc-1] */
  maxnum = 20;
  c_argv = (char **)mymalloc(sizeof(char *) * maxnum);
  c_argv[0] = strcpy((char *)mymalloc(7), "string");
  c_argc = 1;
  add_to_arglist(str, &c_argv, &c_argc, &maxnum);
  /* env expansion */
  for (i=1;i<c_argc;i++) {
    c_argv[i] = expand_env(c_argv[i]);
  }
  /* now that options are in c_argv[][], call opt_parse() to process them */
  ret = opt_parse(c_argc, c_argv, dir, jconf);

  /* free arguments */
  while (c_argc-- > 0) {
    free(c_argv[c_argc]);
  }
  free(c_argv);

  return(ret);
}
Exemplo n.º 8
0
void test2() {
	struct aug_conf c;
	int argc = 1;
	char *argv[] = {g_argv[0], NULL};
	const char *path = "/tmp/augrc";
	dictionary *ini;
	FILE *f = fopen(path, "w");
	if(f == NULL)
		err(1, "file: %s", path);
	fclose(f);

	diag("blank ini file and no args");
	ini = ciniparser_load(path);
	ok1(ini != NULL);

	conf_init(&c);
	ok1(opt_parse(argc, argv, &c) == 0);
	ok1(opt_set_amt(&c) == 0);
	conf_merge_ini(&c, ini);	
	ok1( compare_conf_vals(&c, &g_default_conf) == 0);

	conf_free(&c);
#define TEST2AMT 4
	
	ciniparser_freedict(ini);
	unlink(path);
}
Exemplo n.º 9
0
Arquivo: init.c Projeto: bysin/unitjs
int main(int argc, char **argv, char **envp) {
	unit_t n;
	int32_t rc, i;
	
	m_argc = argc;
	m_argv = argv;
	m_envp = envp;
	
	if ((rc = opt_parse(argc, argv)) < 0)
		return 1;
	
	if (opt_fastcgi)
		fcgi_start(opt_fastcgi);
	else if (opt_webserver)
		ws_start(opt_webserver);
	else {
		if (!(n = unit_new())) {
			printf("Unable to start UnitJS\n");
			return 1;
		}
		for (i = rc; i < argc; i++) {
			if (!unit_script(n, argv[i], NULL))
				break;
		}
		unit_free(n);
		unit_shutdown();
	}
	return m_exitstatus;
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	OpenAnchorScriptsigs *s;
	struct pkt *pkt;

	err_set_progname(argv[0]);

	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<open-anchor-sig-file>\n"
			   "Create LeakAnchorSigsAndPretendWeDidnt to stdout",
			   "Print this message.");
	opt_register_version();

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc != 2)
		opt_usage_exit_fail("Expected 1 argument");

	s = pkt_from_file(argv[1], PKT__PKT_OPEN_ANCHOR_SCRIPTSIGS)
		->open_anchor_scriptsigs;

	pkt = leak_anchor_sigs_and_pretend_we_didnt_pkt(ctx, s);
	if (!write_all(STDOUT_FILENO, pkt, pkt_totlen(pkt)))
		err(1, "Writing out packet");

	tal_free(ctx);
	return 0;
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
	bool pub = true, priv = true;

	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "[<seeds>...]\n"
			   "Generate (deterministic if seed) secp256k1 keys",
			   "Print this message.");
	opt_register_noarg("--pub",
			   opt_set_invbool, &priv,
			   "Generate only the public key");
	opt_register_noarg("--priv",
			   opt_set_invbool, &pub,
			   "Generate only the private key");
	opt_register_version();

 	opt_parse(&argc, argv, opt_log_stderr_exit);
	if (!priv && !pub)
		opt_usage_exit_fail("Can't use --pub and --priv");
	
	if (argc == 1) {
		srandom(time(NULL) + getpid());
		print_keypair(pub, priv);
	} else {
		int i;
		for (i = 1; i < argc; i++) {
			srandom(atoi(argv[i]));
			print_keypair(pub, priv);
		}
	}

	return 0;
}
Exemplo n.º 12
0
int opt_parse(char** carg)
{	
	struct argdef* a;
	
	if ( status == STATUS_NEWOPT )
	{
		if ( ++curarg >= argc ) return OPT_END;
		
		if ( argv[curarg][0] == '-' )
		{
			if ( argv[curarg][1] == '-' )
			{
				if ( !(a = _opt_find(0,&argv[curarg][2])) ) return OPT_ERROR_NOOPT;
				if ( a->autoset ) 
				{
					*a->autoset = 1;
					return opt_parse(carg);
				}
				if ( _opt_getarg(carg,a) ) return OPT_ERROR_NOPARAM;
				return a->retval;
			}
			
			curmulti = curarg;
			idmulti = 1;
			status = STATUS_CONTINUEOPT;
			goto CONTINUE_OPT;
		}
		return OPT_ERROR_NOOPT;
	}

	CONTINUE_OPT:
	
	if ( !(a = _opt_find(argv[curmulti][idmulti],NULL)) ) return OPT_ERROR_NOOPT;
	if ( a->autoset ) 
	{
		*a->autoset = 1;
		++idmulti;
		if ( !argv[curmulti][idmulti] )
			status = STATUS_NEWOPT;
		return opt_parse(carg);
	}
	if ( _opt_getarg(carg,a) ) return OPT_ERROR_NOPARAM;
	++idmulti;
	if ( !argv[curmulti][idmulti] )
			status = STATUS_NEWOPT;
	return a->retval;
}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
    struct timespec start, curr;
    struct timers timers;
    struct list_head expired;
    struct timer t[PER_CONN_TIME];
    unsigned int i, num;
    bool check = false;

    opt_register_noarg("-c|--check", opt_set_bool, &check,
                       "Check timer structure during progress");

    opt_parse(&argc, argv, opt_log_stderr_exit);

    num = argv[1] ? atoi(argv[1]) : (check ? 100000 : 100000000);

    list_head_init(&expired);
    curr = start = time_now();
    timers_init(&timers, start);

    for (i = 0; i < num; i++) {
        curr = time_add(curr, time_from_msec(1));
        if (check)
            timers_check(&timers, NULL);
        timers_expire(&timers, curr, &expired);
        if (check)
            timers_check(&timers, NULL);
        assert(list_empty(&expired));

        if (i >= PER_CONN_TIME) {
            timer_del(&timers, &t[i%PER_CONN_TIME]);
            if (check)
                timers_check(&timers, NULL);
        }
        timer_add(&timers, &t[i%PER_CONN_TIME],
                  time_add(curr, time_from_msec(CONN_TIMEOUT_MS)));
        if (check)
            timers_check(&timers, NULL);
    }
    if (num > PER_CONN_TIME) {
        for (i = 0; i < PER_CONN_TIME; i++)
            timer_del(&timers, &t[i]);
    }

    curr = time_sub(time_now(), start);
    if (check)
        timers_check(&timers, NULL);
    timers_cleanup(&timers);
    opt_free_table();

    for (i = 0; i < ARRAY_SIZE(timers.level); i++)
        if (!timers.level[i])
            break;

    printf("%u in %lu.%09lu (%u levels / %zu)\n",
           num, (long)curr.tv_sec, curr.tv_nsec,
           i, ARRAY_SIZE(timers.level));
    return 0;
}
Exemplo n.º 14
0
/**
 * <EN>
 * Load parameters from command argments, and set to each configuration
 * instances in jconf.
 * </EN>
 * <JA>
 * コマンド引数からパラメータを読み込み,jconf 内の各設定インスタンスに
 * 値を格納する.
 * </JA>
 *
 * @param jconf [i/o] global configuration instance
 * @param argc [in] number of arguments
 * @param argv [in] list of argument strings
 *
 * @return 0 on success, or -1 on failure.
 *
 * @callgraph
 * @callergraph
 * @ingroup jconf
 */
int
j_config_load_args(Jconf *jconf, int argc, char *argv[])
{
    /* parse options and set variables */
    if (opt_parse(argc, argv, NULL, jconf) == FALSE) {
        return -1;
    }
    /* if multiple instances defined from init, remove initial one (id=0) */
    j_config_remove_initial(jconf);

    return 0;
}
Exemplo n.º 15
0
void test5() {
	struct aug_conf c;
	char *argv[] = {g_argv[0], "--no-color", NULL};
	int argc = AUG_ARRAY_SIZE(argv) - 1;

	diag("does the no color flag work?");
	conf_init(&c);
	ok1(opt_parse(argc, argv, &c) == 0);
	ok1(c.nocolor != false);
	ok1(opt_set_amt(&c) == 1);
	
#define TEST5AMT 3
	conf_free(&c);
}
Exemplo n.º 16
0
void test1() {
	struct aug_conf c;
	int argc = 1;
	char *argv[] = {g_argv[0], NULL};

	conf_init(&c);
	diag("no ini file and no args");
	ok1(opt_parse(argc, argv, &c) == 0);
	ok1(opt_set_amt(&c) == 0);
	ok1( compare_conf_vals(&c, &g_default_conf) == 0);

	conf_free(&c);
#define TEST1AMT 3
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	OpenChannel *o1, *o2;
	OpenAnchorScriptsigs *ss1, *ss2;
	struct bitcoin_tx *anchor;
	struct sha256_double txid;
	u8 *tx_arr;
	size_t *inmap, *outmap;
	char *tx_hex;

	err_set_progname(argv[0]);

	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<open-channel-file1> <open-channel-file2> <anchor-sig2-1> <anchor-sigs2>\n"
			   "Output the anchor transaction by merging the scriptsigs",
			   "Print this message.");

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc != 5)
		opt_usage_exit_fail("Expected 6 arguments");

	o1 = pkt_from_file(argv[1], PKT__PKT_OPEN)->open;
	o2 = pkt_from_file(argv[2], PKT__PKT_OPEN)->open;
	ss1 = pkt_from_file(argv[3], PKT__PKT_OPEN_ANCHOR_SCRIPTSIGS)
		->open_anchor_scriptsigs;
	ss2 = pkt_from_file(argv[4], PKT__PKT_OPEN_ANCHOR_SCRIPTSIGS)
		->open_anchor_scriptsigs;

	anchor = anchor_tx_create(ctx, o1, o2, &inmap, &outmap);
	if (!anchor)
		errx(1, "Failed transaction merge");
	if (!anchor_add_scriptsigs(anchor, ss1, ss2, inmap))
		errx(1, "Wrong number of scriptsigs");

	bitcoin_txid(anchor, &txid);

	/* Print it out in hex. */
	tx_arr = linearize_tx(ctx, anchor);
	tx_hex = tal_arr(tx_arr, char, hex_str_size(tal_count(tx_arr)));
	hex_encode(tx_arr, tal_count(tx_arr), tx_hex, tal_count(tx_hex));

	if (!write_all(STDOUT_FILENO, tx_hex, strlen(tx_hex)))
		err(1, "Writing out anchor transaction");

	tal_free(ctx);
	return 0;
}
Exemplo n.º 18
0
/* Main: parse arguments and call IRVM entry function */
int
main (int argc, char ** argv)
{
  opt_register_table (opts, NULL);
  if (!opt_parse (&argc, argv, opt_log_stderr))
    exit (1);

  if (argc != 2)
    opt_usage_and_exit ("[OPTIONS] INPUT-FILE");
  input_fn = argv[1];
  opt_free_table ();

  if (!(yyin = fopen (input_fn, "r")))
    err (1, "could not open %s", input_fn);

  irvm ();

  return 0;
}
Exemplo n.º 19
0
void test3() {
	struct aug_conf c;
	int argc = 1;
	char *argv[] = {g_argv[0], NULL};
	const char *path = "/tmp/augrc";
	dictionary *ini;
	const char *ncterm;
	FILE *f = fopen(path, "w");
	if(f == NULL)
		err(1, "file: %s", path);

	fprintf(f, "[" CONF_CONFIG_SECTION_CORE "]\n\n");
	fprintf(f, "ncterm = screen ;\n");
	fclose(f);
	diag("ini file overrides default");
	ini = ciniparser_load(path);
	ok1(ini != NULL);

	conf_init(&c);
	ok1(opt_parse(argc, argv, &c) == 0);
	ok1(opt_set_amt(&c) == 0);
	ok1( compare_conf_vals(&c, &g_default_conf) == 0);
	ncterm = NULL;
	ncterm = ciniparser_getstring(ini, CONF_CONFIG_SECTION_CORE ":ncterm", NULL);
	ok1( ncterm != NULL);
	if(ncterm == NULL)
		return;
	ok1( strcmp(ncterm, "screen") == 0 );

	conf_merge_ini(&c, ini);
	ok1( c.ncterm != NULL );
	if(c.ncterm == NULL)
		return;
	ok1( strcmp(c.ncterm, "screen") == 0 );
	c.ncterm = CONF_NCTERM_DEFAULT;
	ok1( compare_conf_vals(&c, &g_default_conf) == 0);
	
	conf_free(&c);
#define TEST3AMT 9

	ciniparser_freedict(ini);
	unlink(path);
}
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	struct sha256 seed, revocation_hash, rval;
	struct pkt *pkt;
	unsigned update_num;

	err_set_progname(argv[0]);

	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<seed> <update-number> <r-value>\n"
			   "Create a new HTLC complete message",
			   "Print this message.");
	opt_register_version();

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc != 4)
		opt_usage_exit_fail("Expected 3 arguments");

	if (!hex_decode(argv[1], strlen(argv[1]), &seed, sizeof(seed)))
		errx(1, "Invalid seed '%s' - need 256 hex bits", argv[1]);
	update_num = atoi(argv[2]);
	if (!update_num)
		errx(1, "Update number %s invalid", argv[2]);

	if (!hex_decode(argv[3], strlen(argv[3]), &rval, sizeof(rval)))
		errx(1, "Invalid rvalue '%s' - need 256 hex bits", argv[3]);

	/* Get next revocation hash. */
	shachain_from_seed(&seed, update_num, &revocation_hash);
	sha256(&revocation_hash,
	       revocation_hash.u.u8, sizeof(revocation_hash.u.u8));

	pkt = update_htlc_complete_pkt(ctx, &revocation_hash, &rval);
	if (!write_all(STDOUT_FILENO, pkt, pkt_totlen(pkt)))
		err(1, "Writing out packet");

	tal_free(ctx);
	return 0;
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *pcap_src = NULL;

	opt_register_table(opts, NULL);

	if (!opt_parse(&argc, argv, opt_log_stderr))
		return 1;

	if (!g_ifc_name && !g_file_name)
		return err_ret("No packet source specified\n");
	if (g_ifc_name && g_file_name)
		return err_ret("Both file and interface source specified\n");

	if (g_ifc_name)
		pcap_src = pcap_open_live(g_ifc_name, PCAP_SNAPLEN_ALL,
					  1, -1, errbuf);
	else if (g_file_name)
		pcap_src = pcap_open_offline(g_file_name, errbuf);

	if (!pcap_src) {
		fprintf(stderr, "Couldn't open packet source: %s\n", errbuf);
		return 1;
	}

	pcap_loop(pcap_src, PCAP_CNT_INF, packet_cb, NULL);

	pcap_close(pcap_src);

	if (g_dump)
		dist_dump(dist1, dist2, dist_min);

	if (g_hm)
		hm_dump();

	return 0;
}
Exemplo n.º 22
0
bool parse_args(int *argc, char ***argv, ...)
{
	char **a;
	va_list ap;

	va_start(ap, argv);
	*argc = 1;
	a = malloc(sizeof(*a) * (*argc + 1));
	a[0] = (*argv)[0];
	while ((a[*argc] = va_arg(ap, char *)) != NULL) {
		(*argc)++;
		a = realloc(a, sizeof(*a) * (*argc + 1));
	}

	if (allocated)
		free(*argv);

	*argv = a;
	allocated = true;
	/* Re-set before parsing. */
	optind = 0;

	return opt_parse(argc, *argv, save_err_output);
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	OpenChannel *o1, *o2;
	OpenAnchor *a;
	struct bitcoin_tx *close_tx;
	struct bitcoin_signature sig1, sig2;
	struct pubkey pubkey1, pubkey2;
	u8 *redeemscript;
	CloseChannel *close;
	CloseChannelComplete *closecomplete;
	uint64_t our_amount, their_amount;

	err_set_progname(argv[0]);

	/* FIXME: Take update.pbs to adjust channel */
	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<open-channel-file1> <open-channel-file2> <open-anchor-file> <close-protobuf> <close-complete-protobuf> [update-protobuf]...\n"
			   "Create the close transaction from the signatures",
			   "Print this message.");

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc < 6)
		opt_usage_exit_fail("Expected 5+ arguments");

	o1 = pkt_from_file(argv[1], PKT__PKT_OPEN)->open;
	o2 = pkt_from_file(argv[2], PKT__PKT_OPEN)->open;
	a = pkt_from_file(argv[3], PKT__PKT_OPEN_ANCHOR)->open_anchor;
	close = pkt_from_file(argv[4], PKT__PKT_CLOSE)->close;
	closecomplete = pkt_from_file(argv[5], PKT__PKT_CLOSE_COMPLETE)->close_complete;

	/* Pubkeys well-formed? */
	if (!proto_to_pubkey(o1->commit_key, &pubkey1))
		errx(1, "Invalid o1 commit_key");
	if (!proto_to_pubkey(o2->commit_key, &pubkey2))
		errx(1, "Invalid o2 commit_key");
	
	/* Get delta by accumulting all the updates. */
	gather_updates(o1, o2, a, close->close_fee, argv + 6,
		       &our_amount, &their_amount,
		       NULL, NULL, NULL);

	/* This is what the anchor pays to; figure out which output. */
	redeemscript = bitcoin_redeem_2of2(ctx, &pubkey1, &pubkey2);

	/* Now create the close tx to spend 2/2 output of anchor. */
	close_tx = create_close_tx(ctx, o1, o2, a, our_amount, their_amount);

	/* Signatures well-formed? */
	sig1.stype = sig2.stype = SIGHASH_ALL;
	if (!proto_to_signature(close->sig, &sig1.sig))
		errx(1, "Invalid close-packet");
	if (!proto_to_signature(closecomplete->sig, &sig2.sig))
		errx(1, "Invalid closecomplete-packet");

	/* Combined signatures must validate correctly. */
	if (!check_2of2_sig(close_tx, 0, redeemscript, tal_count(redeemscript),
			    &pubkey1, &pubkey2, &sig1, &sig2))
		errx(1, "Signature failed");

	/* Create p2sh input for close_tx */
	close_tx->input[0].script = scriptsig_p2sh_2of2(close_tx, &sig1, &sig2,
						      &pubkey1, &pubkey2);
	close_tx->input[0].script_length = tal_count(close_tx->input[0].script);

	/* Print it out in hex. */
	if (!bitcoin_tx_write(STDOUT_FILENO, close_tx))
		err(1, "Writing out transaction");

	tal_free(ctx);
	return 0;
}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
	OpenChannel *o1, *o2;
	struct bitcoin_tx *anchor;
	const tal_t *ctx = tal_arr(NULL, char, 0);
	u64 anchor_fee, amount, total_in, change;
	struct input *in;
	u8 *redeemscript;
	size_t i;
	struct pubkey pubkey1, pubkey2;

	err_set_progname(argv[0]);

	anchor_fee = 10000;
	
	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<open-channel-file1> <open-channel-file2> <amount> <changepubkey> <txid>/<outnum>/<satoshis>/<script-in-hex>/<privkey>...\n"
			   "A test program to create an anchor tx on stdout.",
			   "Print this message.");
	opt_register_arg("--anchor-fee=<bits>",
			 opt_set_bits, opt_show_bits, &anchor_fee,
			 "100's of satoshi to pay for anchor");
	opt_register_version();

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc < 6)
		opt_usage_exit_fail("Expected 5 or more arguments");

	o1 = pkt_from_file(argv[1], PKT__PKT_OPEN)->open;
	o2 = pkt_from_file(argv[2], PKT__PKT_OPEN)->open;
	if (!proto_to_pubkey(o1->commit_key, &pubkey1))
		errx(1, "Invalid o1 commit_key");
	if (!proto_to_pubkey(o2->commit_key, &pubkey2))
		errx(1, "Invalid o2 commit_key");

	amount = atol(argv[3]);
	if (!amount)
		errx(1, "Invalid total: must be > 0");

	in = tal_arr(ctx, struct input, argc - 5);

	total_in = 0;
	for (i = 0; i < tal_count(in); i++) {
		parse_anchor_input(argv[5+i], &in[i]);
		total_in += in[i].in.input_amount;
	}

	if (total_in < amount + anchor_fee)
		errx(1, "Only %llu satoshi in, and %llu out (+%llu fee)",
		     (unsigned long long)total_in,
		     (unsigned long long)amount,
		     (unsigned long long)anchor_fee);

	change = total_in - (amount + anchor_fee);

	/* If there's change, we have an extra output. */
	anchor = bitcoin_tx(ctx, tal_count(in), change ? 2 : 1);
	anchor->fee = anchor_fee;

	/* Commitment redeems this via 2 of 2 payment. */
	redeemscript = bitcoin_redeem_2of2(ctx, &pubkey1, &pubkey2);

	/* Set up outputs. */
	anchor->output[0].amount = amount;
	anchor->output[0].script = scriptpubkey_p2sh(anchor, redeemscript);
	anchor->output[0].script_length = tal_count(anchor->output[0].script);

	if (change) {
		struct pubkey change_key;

		if (!pubkey_from_hexstr(argv[4], &change_key))
			errx(1, "Invalid change key %s", argv[3]);

		redeemscript = bitcoin_redeem_single(anchor, &change_key);
		anchor->output[1].amount = change;
		anchor->output[1].script = scriptpubkey_p2sh(anchor,
							     redeemscript);
		anchor->output[1].script_length
			= tal_count(anchor->output[1].script);
	}

	/* Set up inputs (leaving scripts empty for signing) */
	for (i = 0; i < tal_count(in); i++) {
		anchor->input[i].input_amount = in[i].in.input_amount;
		anchor->input[i].txid = in[i].in.txid;
		anchor->input[i].index = in[i].in.index;
	}
	
	/* Now, sign each input. */
	for (i = 0; i < tal_count(in); i++) {
		in[i].sig.stype = SIGHASH_ALL;
		if (!sign_tx_input(ctx, anchor, i, in[i].in.script,
				   in[i].in.script_length,
				   &in[i].privkey, &in[i].pubkey,
				   &in[i].sig.sig))
			errx(1, "Error signing input %zi", i);
	}

	/* Finally, complete inputs using signatures. */
	for (i = 0; i < tal_count(in); i++) {
		if (!is_pay_to_pubkey_hash(in[i].in.script,
					   in[i].in.script_length))
			errx(1, "FIXME: Don't know how to handle input %zi", i);
		anchor->input[i].script
			= scriptsig_pay_to_pubkeyhash(anchor, &in[i].pubkey,
						      &in[i].sig);
		anchor->input[i].script_length
			= tal_count(anchor->input[i].script);
	}

	/* Print it out in hex. */
	if (!bitcoin_tx_write(STDOUT_FILENO, anchor))
		err(1, "Writing out transaction");

	tal_free(ctx);
	return 0;
}
Exemplo n.º 25
0
int main(int argc, const char **argv) {
  srand (time(NULL));
  try {
    string command = argv[0];
    bool help_info = false;
    for (int i = 1; i < argc; i++) {
      command += " ";
      command += argv[i];
      if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-about") == 0
          || strcmp(argv[i], "-?") == 0) {
        help_info = true;
      }
    }

    if (argc > 1 && help_info == false) {
      /* show the command line one the screen */
      fprintf(stderr, "[WELCOME TO WALT v%s]\n", walt_version);
      fprintf(stderr, "[%s", argv[0]);
      for (int i = 1; i < argc; i++) {
        fprintf(stderr, " %s", argv[i]);
      }
      fprintf(stderr, "]\n");
    }

    /* singled-end reads file, comma-separated list of files */
    string reads_file_s;
    vector<string> v_reads_file_s;

    /* paired-end reads files, comma-separated list of files*/
    string reads_file_p1;
    string reads_file_p2;
    vector<string> v_reads_file_p1;
    vector<string> v_reads_file_p2;

    /* index file*/
    string index_file;

    /* output file */
    string output_file;
    vector<string> v_output_file;

    /* WALT supports Tab-delimited SAM and MR output formats.
     * By default, WALT produces SAM format output files. To
     * get MR format, the suffix of the output file should be
     * ".mr". */
    bool SAM = true;

    /* trimming adaptor sequence */
    string adaptor;

    /* paired-end or single-end mapping */
    bool is_paired_end_reads = false;

    /* output ambiguous or unmapped reads or not, both are false by default */
    bool ambiguous = false;
    bool unmapped = false;

    /* AG_WILDCARD is false by default, which means that all Cs
     * in the reads and genome are converted to Ts.
     * If AG_WILDCARD is true, all Gs in the reads and genome
     * are converted to As. If option is only for single-end mapping */
    bool AG_WILDCARD = false;

    /* maximum allowed mismatches */
    uint32_t max_mismatches = 6;

    /* number of reads to map at one loop */
    uint32_t n_reads_to_process = 1000000;

    /* paired-end reads: keep top k genome positions for each in the pair */
    uint32_t top_k = 50;

    /* max fragment length for paired end reads */
    int frag_range = 1000;

    /* number of threads for mapping */
    int num_of_threads = 1;

    /****************** COMMAND LINE OPTIONS ********************/
    OptionParser opt_parse(strip_path(argv[0]), "map Illumina BS-seq reads",
                           "");
    opt_parse.add_opt(
        "index",
        'i',
        "index file created by makedb command \
        (the suffix of the index file should be '.dbindex')",
        true, index_file);
    opt_parse.add_opt(
        "reads",
        'r',
        "comma-separated list of read files for singled-end mapping \
         (the suffix of read files should be '.fastq' or '.fq')",
        false, reads_file_s);
    opt_parse.add_opt(
        "reads1",
        '1',
        "comma-separated list of read files for mate 1 \
         (the suffix of read files should be '.fastq' or '.fq')",
        false, reads_file_p1);
    opt_parse.add_opt(
        "reads2",
        '2',
        "comma-separated list of read files for mate 2 \
        (the suffix of read files should be '.fastq' or '.fq')",
        false, reads_file_p2);
    opt_parse.add_opt("output", 'o', "output file name", true, output_file);
    opt_parse.add_opt("mismatch", 'm', "maximum allowed mismatches", false,
                      max_mismatches);
    opt_parse.add_opt("number", 'N', "number of reads to map at one loop",
                      false, n_reads_to_process);
    opt_parse.add_opt(
        "ambiguous",
        'a',
        "randomly output one mapped position for ambiguous \
        reads in a separated file",
        false, ambiguous);
    opt_parse.add_opt("unmapped", 'u',
                      "output unmapped reads in a separated file", false,
                      unmapped);
    opt_parse.add_opt("clip", 'C', "clip the specified adaptor", false,
                      adaptor);
    opt_parse.add_opt("ag-wild", 'A',
                      "map using A/G bisulfite wildcards (single-end)", false,
                      AG_WILDCARD);
    opt_parse.add_opt("topk", 'k',
                      "maximum allowed mappings for a read (paired-end)", false,
                      top_k);
    opt_parse.add_opt("fraglen", 'L', "max fragment length (paired-end)", false,
                      frag_range);
    opt_parse.add_opt("thread", 't', "number of threads for mapping", false,
                      num_of_threads);

    vector<string> leftover_args;
    opt_parse.parse(argc, argv, leftover_args);
    if (argc == 1 || opt_parse.help_requested()) {
      fprintf(stderr, "%s\n", opt_parse.help_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.about_requested()) {
      fprintf(stderr, "%s\n", opt_parse.about_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.option_missing()) {
      fprintf(stderr, "%s\n", opt_parse.option_missing_message().c_str());
      return EXIT_SUCCESS;
    }

    if (!is_valid_filename(index_file, "dbindex")) {
      fprintf(stderr, "The suffix of the index file should be '.dbindex'\n");
      return EXIT_FAILURE;
    }

    if (!reads_file_s.empty() && reads_file_p1.empty()
        && reads_file_p2.empty()) {
      is_paired_end_reads = false;
    } else if (reads_file_s.empty() && !reads_file_p1.empty()
        && !reads_file_p2.empty()) {
      is_paired_end_reads = true;
    } else {
      fprintf(stderr, "Please use -r option to set singled-end reads, \n"
              "-1 and -2 options to set paired-end reads\n");
      return EXIT_FAILURE;
    }
    /****************** END COMMAND LINE OPTIONS *****************/

    bool get_empty_fields = false;
    if (!is_paired_end_reads) {
      v_reads_file_s = smithlab::split(reads_file_s, ",", get_empty_fields);
      for (uint32_t i = 0; i < v_reads_file_s.size(); ++i) {
        if (!is_valid_filename(v_reads_file_s[i], "fastq")
            && !is_valid_filename(v_reads_file_s[i], "fq")) {
          fprintf(stderr,
                  "The suffix of the reads file should be '.fastq', '.fq'\n");
          return EXIT_FAILURE;
        }
      }
    } else {
      v_reads_file_p1 = smithlab::split(reads_file_p1, ",", get_empty_fields);
      v_reads_file_p2 = smithlab::split(reads_file_p2, ",", get_empty_fields);
      if (v_reads_file_p1.size() != v_reads_file_p2.size()) {
        fprintf(
            stderr,
            "For paired-end mapping, mate 1 and mate 2 should \n\
                have the same number of files, and the paired files \n\
                should be in the same order.");
        return EXIT_FAILURE;
      }
      for (uint32_t i = 0; i < v_reads_file_p1.size(); ++i) {
        if (!is_valid_filename(v_reads_file_p1[i], "fastq")
            && !is_valid_filename(v_reads_file_p1[i], "fq")) {
          fprintf(stderr,
                  "The suffix of the reads file should be '.fastq', '.fq'\n");
          return EXIT_FAILURE;
        }
      }
    }

    if (!is_paired_end_reads) {
      if (v_reads_file_s.size() == 1) {
        v_output_file.push_back(output_file);
      } else {
        char output_filename[1000];
        for (uint32_t i = 0; i < v_reads_file_s.size(); ++i) {
          sprintf(output_filename, "%s_s%u", output_file.c_str(), i);
          v_output_file.push_back(output_filename);
        }
      }
    } else {
      if (v_reads_file_p1.size() == 1) {
        v_output_file.push_back(output_file);
      } else {
        char output_filename[1000];
        for (uint32_t i = 0; i < v_reads_file_p1.size(); ++i) {
          sprintf(output_filename, "%s_p%u", output_file.c_str(), i);
          v_output_file.push_back(output_filename);
        }
      }
    }

    for (uint32_t i = 0; i < v_reads_file_p2.size(); ++i) {
      if (!is_valid_filename(v_reads_file_p2[i], "fastq")
          && !is_valid_filename(v_reads_file_p2[i], "fq")) {
        fprintf(stderr,
                "The suffix of the reads file should be '.fastq', '.fq'\n");
        return EXIT_FAILURE;
      }
    }

    size_t suffix_pos = output_file.find_last_of(".");
    if (suffix_pos == string::npos) {
      SAM = true;
    } else if (".mr" == output_file.substr(suffix_pos)) {
      SAM = false;
    }
    /****************** END COMMAND LINE OPTIONS *****************/

    //////////////////////////////////////////////////////////////
    // CHECK OPTIONS
    fprintf(stderr, "[MAXIMUM NUMBER OF MISMATCHES IS %u]\n", max_mismatches);
    fprintf(stderr, "[NUMBER OF THREADS FOR MAPPING IS %d]\n", num_of_threads);

    if (n_reads_to_process > 5000000) {
      n_reads_to_process = 5000000;
    }

    if (is_paired_end_reads && top_k < 2) {
      fprintf(stderr, "-k option should be at least 2 for paired-end reads\n");
      return EXIT_FAILURE;
    }

    if (is_paired_end_reads && top_k > 300) {
      fprintf(stderr,
              "-k option should be less than 300 for paired-end reads\n");
      return EXIT_FAILURE;
    }
    ShowGenomeInfo(index_file);

    //////////////////////////////////////////////////////////////
    // Mapping
    if (!is_paired_end_reads) {
      for (uint32_t i = 0; i < v_reads_file_s.size(); ++i) {
        ProcessSingledEndReads(command, index_file, v_reads_file_s[i],
                               v_output_file[i], n_reads_to_process,
                               max_mismatches, adaptor, AG_WILDCARD, ambiguous,
                               unmapped, SAM, num_of_threads);
      }
    } else {
      for (uint32_t i = 0; i < v_reads_file_p1.size(); ++i) {
        ProcessPairedEndReads(command, index_file, v_reads_file_p1[i],
                              v_reads_file_p2[i], v_output_file[i],
                              n_reads_to_process, max_mismatches, adaptor,
                              top_k, frag_range, ambiguous, unmapped, SAM,
                              num_of_threads);
      }
    }
  } catch (const SMITHLABException &e) {
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	struct sha256 seed, revocation_hash, their_rhash;
	OpenChannel *o1, *o2;
	Update *update;
	struct bitcoin_tx *anchor, *commit;
	struct sha256_double anchor_txid;
	struct pkt *pkt;
	struct bitcoin_signature sig;
	EC_KEY *privkey;
	bool testnet;
	struct pubkey pubkey1, pubkey2;
	u8 *redeemscript;
	int64_t delta;
	size_t i, p2sh_out;

	err_set_progname(argv[0]);

	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<seed> <anchor-tx> <open-channel-file1> <open-channel-file2> <commit-privkey> <update-protobuf> [previous-updates]\n"
			   "Accept a new update message",
			   "Print this message.");

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc < 6)
		opt_usage_exit_fail("Expected 5+ arguments");

	if (!hex_decode(argv[1], strlen(argv[1]), &seed, sizeof(seed)))
		errx(1, "Invalid seed '%s' - need 256 hex bits", argv[1]);
	
	anchor = bitcoin_tx_from_file(ctx, argv[2]);
	bitcoin_txid(anchor, &anchor_txid);
	o1 = pkt_from_file(argv[3], PKT__PKT_OPEN)->open;
	o2 = pkt_from_file(argv[4], PKT__PKT_OPEN)->open;

	privkey = key_from_base58(argv[5], strlen(argv[5]), &testnet, &pubkey1);
	if (!privkey)
		errx(1, "Invalid private key '%s'", argv[5]);
	if (!testnet)
		errx(1, "Private key '%s' not on testnet!", argv[5]);

	update = pkt_from_file(argv[6], PKT__PKT_UPDATE)->update;
	
	/* Figure out cumulative delta since anchor. */
	delta = update->delta;
	for (i = 7; i < argc; i++) {
		Update *u = pkt_from_file(argv[i], PKT__PKT_UPDATE)->update;
		delta += u->delta;
	}

	/* Get next revocation hash. */
	shachain_from_seed(&seed, argc - 6, &revocation_hash);
	sha256(&revocation_hash,
	       revocation_hash.u.u8, sizeof(revocation_hash.u.u8));
	
	/* Get pubkeys */
	if (!proto_to_pubkey(o1->anchor->pubkey, &pubkey2))
		errx(1, "Invalid o1 commit pubkey");
	if (pubkey_len(&pubkey1) != pubkey_len(&pubkey2)
	    || memcmp(pubkey1.key, pubkey2.key, pubkey_len(&pubkey2)) != 0)
		errx(1, "o1 pubkey != this privkey");
	if (!proto_to_pubkey(o2->anchor->pubkey, &pubkey2))
		errx(1, "Invalid o2 final pubkey");

	/* This is what the anchor pays to; figure out whick output. */
	redeemscript = bitcoin_redeem_2of2(ctx, &pubkey1, &pubkey2);
	p2sh_out = find_p2sh_out(anchor, redeemscript);

	/* Now create THEIR new commitment tx to spend 2/2 output of anchor. */
	proto_to_sha256(update->revocation_hash, &their_rhash);
	commit = create_commit_tx(ctx, o2, o1, &their_rhash, delta,
				  &anchor_txid, p2sh_out);

	/* If contributions don't exceed fees, this fails. */
	if (!commit)
		errx(1, "Delta too large");

	/* Sign it for them. */
	sign_tx_input(ctx, commit, 0, redeemscript, tal_count(redeemscript),
		      privkey, &pubkey1, &sig.sig);

	pkt = update_accept_pkt(ctx, &sig.sig, &revocation_hash);
	if (!write_all(STDOUT_FILENO, pkt, pkt_totlen(pkt)))
		err(1, "Writing out packet");

	tal_free(ctx);
	return 0;
}
Exemplo n.º 27
0
int main(int argc, char **argv) {
    static bool show_series = false, show_all = false, use_cache = true;
    static int i_sid = 0;
    static char usage_str[] = "[SID[:PID]]";
    static struct opt_table opts[] = {
        OPT_WITH_ARG("--items-list|-i", opt_set_intval, NULL, &i_sid,
                "List episodes in a series. Requires a SID as a parameter."),
        OPT_WITHOUT_ARG("--series-list|-s", opt_set_bool, &show_series,
                "List the series available. The first element is the SID."),
        OPT_WITHOUT_ARG("--all|-a", opt_set_bool, &show_all,
                "List all items in all non-empty series."),
        OPT_WITHOUT_ARG("--force|-f", opt_set_invbool, &use_cache,
                "Force bypass the cached metadata."),
        OPT_WITHOUT_ARG("--help|-h", opt_usage_and_exit,
                usage_str, "Show this message."),
        OPT_ENDTABLE
    };
    opt_register_table(opts, NULL);
    if(!opt_parse(&argc, argv, opt_log_stderr)) {
        /* opt_parse will print an error to stderr. */
        exit(1);
    }
    if (!show_all && !show_series && !i_sid && (argc == 1)) {
        opt_usage_and_exit(usage_str);
    }

    struct iv_series *index;
    struct iv_config *config;
    int return_val = 0;
    cache_dir = xdg_user_dir_lookup_with_fallback("CACHE", "/tmp");
    if(NULL == (config = iviewiir_configure())) {
        fprintf(stderr, "Couldn't configure iviewiir, exiting\n");
        return 1;
    }
    int index_len = iviewiir_index(config, &index);
    if(0 >= index_len) {
        fprintf(stderr, "No items in index, exiting\n");
        return_val = 1;
        goto config_cleanup;
    }
    /* Check if they want everything listed */
    if(show_all) {
        list_all(config, index, index_len);
        return_val = 0;
        goto index_cleanup;
    }
    /* Check if they wanted a series list. */
    if(show_series) {
        int i;
        for(i=0; i<index_len; i++) {
            /* Heuristic to trim out empty series. */
            if((int)9e6 < index[i].id) {
                continue;
            }
            printf("%d - %s\n", index[i].id, index[i].title);
        }
        return_val = 0;
        goto index_cleanup;
    }
    /* Check if they want an episode list. */
    if(i_sid) {
        return_val = list_items(config, index, index_len, i_sid);
        goto index_cleanup;
    }
    /* If we've reached here and there are no arguments, print help message. */
    if (argc == 1) {
        opt_usage_and_exit(usage_str);
    }
    /* Otherwise, if they supplied a SID or SID:PID tuple, download the PID */
    int i = 1;
    while(i < argc) {
        if(NULL != strchr(argv[i], ':')) {
            // SID:PID
            const unsigned long sid = strtoul(strtok(argv[i], ":"), NULL, 10);
            const unsigned int pid = strtoul(strtok(NULL, ":"), NULL, 10);
            return_val += download_item(config, index, index_len, sid, pid);
        } else {
            // Check if it's a valid SID
            const unsigned int sid = strtoul(argv[i], NULL, 10);
            struct iv_episode *items;
            // Fetch episode lists for the SID
            debug("sid: %d\n", sid);
            int series_index;
            if(-1 == (series_index =
                        iv_find_series(sid, index, index_len, NULL))) {
                printf("No such series");
                return_val += 1;
                continue;
            }
            // Fetch items in series
            ssize_t items_len =
                iv_easy_series(config, &index[series_index], &items);
            if(1 > items_len) {
                printf("No items in series.\n");
                return_val += 1;
                continue;
            }
            for(i=0; i<items_len; i++) {
                return_val += download_item(config, index, index_len, sid,
                        items[i].id);
            }
            iv_destroy_series(items, items_len);
        }
        i++;
    }
index_cleanup:
    iv_destroy_index(index, index_len);
config_cleanup:
    iv_destroy_config(config);
    free(cache_dir);
    return return_val;
}
Exemplo n.º 28
0
int main(int argc, const char **argv) {
  srand (time(NULL));
  try {
    string chrom_file;
    string outfile;
    /****************** COMMAND LINE OPTIONS ********************/
    OptionParser opt_parse(strip_path(argv[0]),
                           "build index for reference genome", "");
    opt_parse.add_opt(
        "chrom",
        'c',
        "chromosomes in FASTA file or dir \
        (the suffix of the chromosome file should be '.fa')",
        true, chrom_file);
    opt_parse.add_opt(
        "output", 'o',
        "output file name (the suffix of the file should be '.dbindex')", true,
        outfile);

    vector<string> leftover_args;
    opt_parse.parse(argc, argv, leftover_args);
    if (argc == 1 || opt_parse.help_requested()) {
      fprintf(stderr, "%s\n", opt_parse.help_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.about_requested()) {
      fprintf(stderr, "%s\n", opt_parse.about_message().c_str());
      return EXIT_SUCCESS;
    }
    if (opt_parse.option_missing()) {
      fprintf(stderr, "%s\n", opt_parse.option_missing_message().c_str());
      return EXIT_SUCCESS;
    }
    if (!is_valid_filename(outfile, "dbindex")) {
      fprintf(stderr, "The suffix of the output file should be '.dbindex'\n");
      return EXIT_FAILURE;
    }
    if (outfile.size() > 1000) {
      fprintf(stderr, "The output file name is too long, "
          "please select a shorter name\n");
      return EXIT_FAILURE;;
    }
    /****************** END COMMAND LINE OPTIONS *****************/

    //////////////////////////////////////////////////////////////
    // READ GENOME
    //
    vector<string> chrom_files;
    IdentifyChromosomes(chrom_file, chrom_files);

    //////////////////////////////////////////////////////////////
    // BUILD  INDEX
    //
    uint32_t size_of_index = 0;
    ////////// BUILD INDEX FOR FORWARD STRAND (C->T)
    BuildIndex(chrom_files, 0, outfile + "_CT00", size_of_index);

    ////////// BUILD INDEX FOR REVERSE STRAND (C->T)
    BuildIndex(chrom_files, 1, outfile + "_CT01", size_of_index);

    ////////// BUILD INDEX FOR FORWARD STRAND (G->A)
    BuildIndex(chrom_files, 2, outfile + "_GA10", size_of_index);

    ////////// BUILD INDEX FOR REVERSE STRAND (G->A)
    BuildIndex(chrom_files, 3, outfile + "_GA11", size_of_index);

    Genome genome;
    ReadGenome(chrom_files, genome);
    WriteIndexHeadInfo(outfile, genome, size_of_index);
  } catch (const SMITHLABException &e) {
    fprintf(stderr, "%s\n", e.what().c_str());
    return EXIT_FAILURE;
  } catch (std::bad_alloc &ba) {
    fprintf(stderr, "ERROR: could not allocate memory\n");
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
Exemplo n.º 29
0
/** 
 * <JA>
 * メイン関数
 * 
 * @param argc [in] 引数列の長さ
 * @param argv [in] 引数列
 * 
 * @return 
 * </JA>エラー時 1,通常終了時 0 を返す.
 * <EN>
 * Main function.
 * 
 * @param argc [in] number of argument.
 * @param argv [in] array of arguments.
 * 
 * @return 1 on error, 0 on success.
 * </EN>
 */
int
main(int argc, char *argv[])
{
  int silence_cut = 1;	/* 0=disabled, 1=enabled, 2=undef */

  /* parse option */
  opt_parse(argc, argv);

  /* select microphone input */
  if (adin_select(SP_MIC) == FALSE) {
    j_printerr("Error: microphone input is not supported\n");
    return(1);
  }
  
  /* ready the microphone (arg is dummy) */
  if (use_48to16) {
    if (sfreq != 16000) {
      j_printerr("Error: in 48kHz mode, required rate should be 16kHz!\n");
      return(1);
    }
    /* setup for down sampling */
    adin_setup_48to16();
    /* set device sampling rate to 48kHz */
    if (adin_standby(48000, NULL) == FALSE) { /* fail */
      j_printerr("Error: failed to ready input device to 48kHz\n");
      return(1);
    }
  } else {
    if (adin_standby(sfreq, NULL) == FALSE) {
      j_printerr("Error: failed to standby input\n");
      return(1);
    }
  }
  /* set device-independent param */
  adin_setup_param(silence_cut, strip_zero_sample, level_thres, zero_cross_num, margin, margin, sfreq, TRUE, use_zmean);/* use same margin for head and tail */

  /* file check */
  if (!stout) {
    if (access(filename, F_OK) == 0) {
      if (access(filename, W_OK) == 0) {
	fprintf(stderr, "Warning: overwriting file \"%s\"\n", filename);
      } else {
	perror("adinrec");
	return(1);
      }
    }
  } /* output file will be opened when triggered (not here) */

  /* set interrupt signal handler to properly close output file */
  if (signal(SIGINT, interrupt_record) == SIG_ERR) {
    fprintf(stderr, "Warning: signal intterupt may collapse output\n");
  }
  
  /* do recoding */
  speechlen = 0;
  
  adin_begin();
  j_printerr("<<< please speak >>>"); /* moved from adin-cut.c */
  adin_go(adin_callback_file, NULL);
  adin_end();

  /* close file and output status */
  close_file();

  return 1;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
    int camera = 0;
    SDL_Joystick *joy = NULL;

    if (!fs_init(argv[0]))
    {
        fprintf(stderr, "Failure to initialize virtual file system: %s\n",
                fs_error());
        return 1;
    }

    srand((int) time(NULL));

    lang_init("neverball");

    opt_parse(argc, argv);

    config_paths(opt_data);
    fs_mkdir("Screenshots");

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == 0)
    {
        config_init();
        config_load();

        /* Cache Neverball's camera setting. */

        camera = config_get_d(CONFIG_CAMERA);

        /* Initialize the joystick. */

        if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
        {
            joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
            if (joy)
            {
                SDL_JoystickEventState(SDL_ENABLE);
                set_joystick(joy);
            }
        }

        /* Initialize the audio. */

        audio_init();

        /* Initialize the video. */

        if (video_init(TITLE, ICON))
        {
            int t1, t0 = SDL_GetTicks();

            /* Run the main game loop. */

            init_state(&st_null);

            if (opt_hole)
            {
                const char *path = fs_resolve(opt_hole);
                int loaded = 0;

                if (path)
                {
                    hole_init(NULL);

                    if (hole_load(0, path) &&
                        hole_load(1, path) &&
                        hole_goto(1, 1))
                    {
                        goto_state(&st_next);
                        loaded = 1;
                    }
                }

                if (!loaded)
                    goto_state(&st_title);
            }
            else
                goto_state(&st_title);

            while (loop())
                if ((t1 = SDL_GetTicks()) > t0)
                {
                    st_timer((t1 - t0) / 1000.f);
                    st_paint(0.001f * t1);
                    shot_take();
                    SDL_GL_SwapWindow(video_get_window());

                    t0 = t1;

                    if (config_get_d(CONFIG_NICE))
                        SDL_Delay(1);
                }
        }

        /* Restore Neverball's camera setting. */

        config_set_d(CONFIG_CAMERA, camera);
        config_save();

        SDL_Quit();
    }
    else fprintf(stderr, "%s: %s\n", argv[0], SDL_GetError());

    return 0;
}