static int hone_open(struct inode *inode, struct file *file)
{
	struct hone_reader *reader;
	int err = -ENOMEM;

	if ((file->f_flags & O_ACCMODE) != O_RDONLY)
		return -EINVAL;
	if (!(reader = alloc_hone_reader()))
		goto reader_failed;
	if (iminor(inode) == 1)
		reader->format = format_as_text;
	file->private_data = reader;
	getboottime(&reader->info.boot_time);
	ktime_get_ts(&reader->info.start_time);
	init_statistics(&reader->info.delivered);
	init_statistics(&reader->info.dropped);
	reader->nb.notifier_call = hone_event_handler;
	if ((err = hone_notifier_register(&reader->nb))) {
		printm(KERN_ERR, "hone_notifier_register() failed with error %d\n", err);
		goto register_failed;
	}
	__module_get(THIS_MODULE);
	return 0;

register_failed:
	free_hone_reader(reader);
reader_failed:
	return err;
}
Exemple #2
0
/* effects: creates and initializes the heap */
void marksweep_gc_init()
{
  size_t bytes_to_map;
  void *mapped;

  bytes_to_map = INITIAL_PAGES_TO_MAP*SYSTEM_PAGE_SIZE;

  // make sure we are allocating some amount of memory
  assert(bytes_to_map != 0);

  // reserve a large amount of memory in which to grow the heap
  fd = open("/dev/zero", O_RDONLY);
  mapped = mmap(0, bytes_to_map, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);

  // could not allocate memory. we really should throw an exception,  
  // but there are various problems with this. even if we pre-allocated
  // the exception object, throwing the exception would involve
  // allocating more memory.
  assert(mapped != MAP_FAILED);

  // initialize the heap data structure
  init_marksweep_heap(mapped,
		      INITIAL_PAGES_IN_HEAP*SYSTEM_PAGE_SIZE,
		      bytes_to_map,
		      &heap);

  init_statistics();
}
Exemple #3
0
void Tagger::_Tagging(FILE * infile, FILE * outfile)
{
	init_statistics();
	clear_trans_all(&c_newtrans);
	reset_corpus(infile);
	tag_corpus(infile, outfile, &dict, &skip_dict, &trans, 
				&c_newtrans, dbp, &dict, tranname);
}
FreeList::FreeList() :
    _head(NULL), _tail(NULL)
#ifdef ASSERT
    , _protecting_lock(NULL)
#endif
{
    _size		= 0;
    _count	= 0;
    _hint		= 0;
    init_statistics();
}
FreeList::FreeList(FreeChunk* fc) :
    _head(fc), _tail(fc)
#ifdef ASSERT
    , _protecting_lock(NULL)
#endif
{
    _size		= fc->size();
    _count	= 1;
    _hint		= 0;
    init_statistics();
#ifndef PRODUCT
    _allocation_stats.set_returnedBytes(size() * HeapWordSize);
#endif
}
FreeList::FreeList(HeapWord* addr, size_t size) :
    _head((FreeChunk*) addr), _tail((FreeChunk*) addr)
#ifdef ASSERT
    , _protecting_lock(NULL)
#endif
{
    assert(size > sizeof(FreeChunk), "size is too small");
    head()->setSize(size);
    _size		= size;
    _count	= 1;
    init_statistics();
#ifndef PRODUCT
    _allocation_stats.set_returnedBytes(_size * HeapWordSize);
#endif
}
int
main(int argc, char **argv)
{
	const char *av = NULL;
	int func_total, file_total;
        char arg_dbpath[MAXPATHLEN];
	const char *index = NULL;
	int optchar;
        int option_index = 0;
	STATISTICS_TIME *tim;

	arg_dbpath[0] = 0;
	basic_check();
	/*
	 * Setup GTAGSCONF and GTAGSLABEL environment variable
	 * according to the --gtagsconf and --gtagslabel option.
	 */
	preparse_options(argc, argv);
	/*
	 * Load configuration values.
	 */
	if (!vgetcwd(cwdpath, sizeof(cwdpath)))
		die("cannot get current directory.");
	openconf(cwdpath);
	configuration();
	/*
	 * setup_langmap() is needed to use decide_lang().
	 */
	setup_langmap(langmap);
	save_environment(argc, argv);
	/*
	 * insert htags_options at the head of argv.
	 */
	setenv_from_config();
	{
		char *env = getenv("HTAGS_OPTIONS");
		if (env && *env)
			argv = prepend_options(&argc, argv, env);
	}
	while ((optchar = getopt_long(argc, argv, "acd:DfFghIm:nNoqst:Tvwx", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_AUTO_COMPLETION:
			auto_completion = 1;
			if (optarg) {
				if (atoi(optarg) > 0)
					auto_completion_limit = optarg;
				else
					die("The option value of --auto-completion must be numeric.");
			}
			break;
		case OPT_CFLOW:
			call_file = optarg;
			break;
		case OPT_CALL_TREE:
			call_file = optarg;
			break;
		case OPT_CALLEE_TREE:
			callee_file = optarg;
			break;
		case OPT_CVSWEB:
			cvsweb_url = optarg;
			break;
		case OPT_CVSWEB_CVSROOT:
			cvsweb_cvsroot = optarg;
			break;
		case OPT_GTAGSCONF:
		case OPT_GTAGSLABEL:
			/* These options are already parsed in preparse_options() */
			break;
		case OPT_INSERT_FOOTER:
			insert_footer = optarg;
			break;
		case OPT_INSERT_HEADER:
			insert_header = optarg;
			break;
		case OPT_HTML_HEADER:
			{
				STATIC_STRBUF(sb);
				if (!test("r", optarg))
					die("file '%s' not found.", optarg);
				strbuf_clear(sb);
				loadfile(optarg, sb);
				html_header = strbuf_value(sb);
			}
			break;
		case OPT_ITEM_ORDER:
			item_order = optarg;
			break;
		case OPT_TABS:
			if (atoi(optarg) > 0)
				tabs = atoi(optarg);
			else
				die("--tabs option requires numeric value.");
                        break;
		case OPT_NCOL:
			if (atoi(optarg) > 0)
				ncol = atoi(optarg);
			else
				die("--ncol option requires numeric value.");
                        break;
		case OPT_TREE_VIEW:
			tree_view = 1;
			if (optarg)
				tree_view_type = optarg;
			break;
                case 'a':
                        aflag++;
                        break;
                case 'd':
			strlimcpy(arg_dbpath, optarg, sizeof(arg_dbpath));
                        break;
                case 'D':
			dynamic = 1;
                        break;
                case 'f':
                        fflag++;
                        break;
                case 'F':
                        Fflag++;
                        break;
                case 'g':
                        gflag++;
                        break;
                case 'h':
			definition_header = AFTER_HEADER;
			if (optarg) {
				if (!strcmp(optarg, "before"))
					definition_header = BEFORE_HEADER;
				else if (!strcmp(optarg, "right"))
					definition_header = RIGHT_HEADER;
				else if (!strcmp(optarg, "after"))
					definition_header = AFTER_HEADER;
				else
					die("The option value of --func-header must be one of 'before', 'right' and 'after'.");
			}
                        break;
                case 'I':
                        Iflag++;
                        break;
                case 'm':
			main_func = optarg;
                        break;
                case 'n':
                        nflag++;
			if (optarg) {
				if (atoi(optarg) > 0)
					ncol = atoi(optarg);
				else
					die("The option value of --line-number must be numeric.");
			}
                        break;
                case 'o':
			other_files = 1;
                        break;
                case 's':
			symbol = 1;
                        break;
                case 'T':
			table_flist = 1;
			if (optarg) {
				if (atoi(optarg) > 0)
					flist_fields = atoi(optarg);
				else
					die("The option value of the --table-flist must be numeric.");
			}
                        break;
                case 't':
			title = optarg;
                        break;
                case 'q':
                        qflag++;
			setquiet();
                        break;
                case 'v':
                        vflag++;
			setverbose();
                        break;
                case 'w':
                        wflag++;
                        break;
                default:
                        usage();
                        break;
		}
	}
	/*
	 * Leaving everything to htags.
	 * Htags selects popular options for you.
	 */
	if (suggest2)
		suggest = 1;
	if (suggest) {
		int gtags_not_found = 0;
		char dbpath[MAXPATHLEN];

		aflag = Iflag = nflag = vflag = 1;
		setverbose();
		definition_header = AFTER_HEADER;
		other_files = symbol = show_position = table_flist = fixed_guide = 1;
		if (arg_dbpath[0]) {
			if (!test("f", makepath(arg_dbpath, dbname(GTAGS), NULL)))
				gtags_not_found = 1;
		} else if (gtagsexist(".", dbpath, sizeof(dbpath), 0) == 0) {
			gtags_not_found = 1;
		}
		if (gtags_not_found)
			gflag = 1;
	}
	if (suggest2) {
		Fflag = 1;				/* uses frame */
		fflag = dynamic = 1;			/* needs a HTTP server */
		auto_completion = tree_view = 1;	/* needs javascript */
	}
	if (call_file && !test("fr", call_file))
		die("cflow file not found. '%s'", call_file);
	if (callee_file && !test("fr", callee_file))
		die("cflow file not found. '%s'", callee_file);
	if (insert_header && !test("fr", insert_header))
		die("page header file '%s' not found.", insert_header);
	if (insert_footer && !test("fr", insert_footer))
		die("page footer file '%s' not found.", insert_footer);
	if (!fflag)
		auto_completion = 0;
        argc -= optind;
        argv += optind;
        if (!av)
                av = (argc > 0) ? *argv : NULL;

	if (debug)
		setdebug();
	settabs(tabs);					/* setup tab skip */
        if (qflag) {
                setquiet();
		vflag = 0;
	}
        if (show_version)
                version(av, vflag);
        if (show_help)
                help();
	/*
	 * Invokes gtags beforehand.
	 */
	if (gflag) {
		STRBUF *sb = strbuf_open(0);

		strbuf_puts(sb, gtags_path);
		if (vflag)
			strbuf_puts(sb, " -v");
		if (wflag)
			strbuf_puts(sb, " -w");
		if (suggest2 && enable_idutils && usable("mkid"))
			strbuf_puts(sb, " -I");
		if (arg_dbpath[0]) {
			strbuf_putc(sb, ' ');
			strbuf_puts(sb, arg_dbpath);
		}
		if (system(strbuf_value(sb)))
			die("cannot execute gtags(1) command.");
		strbuf_close(sb);
	}
	/*
	 * get dbpath.
	 */
	if (arg_dbpath[0]) {
		strlimcpy(dbpath, arg_dbpath, sizeof(dbpath));
	} else {
		int status = setupdbpath(0);
		if (status < 0)
			die_with_code(-status, "%s", gtags_dbpath_error);
		strlimcpy(dbpath, get_dbpath(), sizeof(dbpath));
	}
	if (!title) {
		char *p = strrchr(cwdpath, sep);
		title = p ? p + 1 : cwdpath;
	}
	if (cvsweb_url && test("d", "CVS"))
		use_cvs_module = 1;
	/*
	 * decide directory in which we make hypertext.
	 */
	if (av) {
		char realpath[MAXPATHLEN];

		if (!test("dw", av))
			die("'%s' is not writable directory.", av);
		if (chdir(av) < 0)
			die("directory '%s' not found.", av);
		if (!vgetcwd(realpath, sizeof(realpath)))
			die("cannot get current directory");
		if (chdir(cwdpath) < 0)
			die("cannot return to original directory.");
		snprintf(distpath, sizeof(distpath), "%s/HTML", realpath);
	} else {
		snprintf(distpath, sizeof(distpath), "%s/HTML", cwdpath);
	}
	/*
	 * Existence check of tag files.
	 */
	{
		int i;
		const char *path;
		GTOP *gtop;

		for (i = GPATH; i < GTAGLIM; i++) {
			path = makepath(dbpath, dbname(i), NULL);
			gtags_exist[i] = test("fr", path);
		}
		/*
		 * Real GRTAGS includes virtual GSYMS.
		 */
		gtags_exist[GSYMS] = symbol ? 1 : 0;
		if (!gtags_exist[GPATH] || !gtags_exist[GTAGS] || !gtags_exist[GRTAGS])
			die("GPATH, GTAGS and/or GRTAGS not found. Please reexecute htags with the -g option.");
		/*
		 * version check.
		 * Do nothing, but the version of tag file will be checked.
		 */
		gtop = gtags_open(dbpath, cwdpath, GTAGS, GTAGS_READ, 0);
		gtags_close(gtop);
		/*
		 * Check whether GRTAGS is empty.
		 */
		gtop = gtags_open(dbpath, cwdpath, GRTAGS, GTAGS_READ, 0);
		if (gtags_first(gtop, NULL, 0) == NULL)
			grtags_is_empty = 1;
		gtags_close(gtop);
	}
	/*
	 * make dbpath absolute.
	 */
	{
		char buf[MAXPATHLEN];
		if (realpath(dbpath, buf) == NULL)
			die("cannot get realpath of dbpath.");
		strlimcpy(dbpath, buf, sizeof(dbpath));
	}
	/*
	 * The older version (4.8.7 or former) of GPATH doesn't have files
         * other than source file. The oflag requires new version of GPATH.
	 */
	if (other_files) {
		GFIND *gp = gfind_open(dbpath, NULL, 0, 0);
		if (gp->version < 2)
			die("GPATH is old format. Please remake it by invoking gtags(1).");
		gfind_close(gp);
	}
	/*
	 * for global(1) and gtags(1).
	 */
	set_env("GTAGSROOT", cwdpath);
	set_env("GTAGSDBPATH", dbpath);
	set_env("GTAGSLIBPATH", "");
	/*------------------------------------------------------------------
	 * MAKE FILES
	 *------------------------------------------------------------------
	 *       HTML/cgi-bin/global.cgi ... CGI program (1)
	 *       HTML/cgi-bin/ghtml.cgi  ... unzip script (1)
	 *       HTML/.htaccess          ... skeleton of .htaccess (1)
	 *       HTML/help.html          ... help file (2)
	 *       HTML/R/                 ... references (3)
	 *       HTML/D/                 ... definitions (3)
	 *       HTML/search.html        ... search index (4)
	 *       HTML/defines.html       ... definitions index (5)
	 *       HTML/defines/           ... definitions index (5)
	 *       HTML/files/             ... file index (6)
	 *       HTML/index.html         ... index file (7)
	 *       HTML/mains.html         ... main index (8)
	 *       HTML/null.html          ... main null html (8)
	 *       HTML/S/                 ... source files (9)
	 *       HTML/I/                 ... include file index (9)
	 *       HTML/rebuild.sh         ... rebuild script (10)
	 *       HTML/style.css          ... style sheet (11)
	 *------------------------------------------------------------------
	 */
	/* for clean up */
	signal_setup();
	sethandler(clean);

        HTML = normal_suffix;

	message("[%s] Htags started", now());
	init_statistics();
	/*
	 * (#) check if GTAGS, GRTAGS is the latest.
	 */
	if (get_dbpath())
		message(" Using %s/GTAGS.", get_dbpath());
	if (grtags_is_empty)
		message(" GRTAGS is empty.");
	if (gpath_open(dbpath, 0) < 0)
		die("GPATH not found.");
	if (!w32) {
		/* UNDER CONSTRUCTION */
	}
	if (auto_completion || tree_view) {
		STATIC_STRBUF(sb);
		strbuf_clear(sb);
		strbuf_puts_nl(sb, "<script type='text/javascript' src='js/jquery.js'></script>");
		if (auto_completion)
			loadfile(makepath(datadir, "gtags/jscode_suggest", NULL), sb);
		if (tree_view)
			loadfile(makepath(datadir, "gtags/jscode_treeview", NULL), sb);
		jscode = strbuf_value(sb);
	}
	/*
	 * (0) make directories
	 */
	message("[%s] (0) making directories ...", now());
	if (!test("d", distpath))
		if (mkdir(distpath, 0777) < 0)
			die("cannot make directory '%s'.", distpath);
	make_directory_in_distpath("files");
	make_directory_in_distpath("defines");
	make_directory_in_distpath(SRCS);
	make_directory_in_distpath(INCS);
	make_directory_in_distpath(INCREFS);
	if (!dynamic) {
		make_directory_in_distpath(DEFS);
		make_directory_in_distpath(REFS);
		if (symbol)
			make_directory_in_distpath(SYMS);
	}
	if (fflag || dynamic)
		make_directory_in_distpath("cgi-bin");
	if (Iflag)
		make_directory_in_distpath("icons");
	if (auto_completion || tree_view)
		 make_directory_in_distpath("js");
	/*
	 * (1) make CGI program
	 */
	if (fflag || dynamic) {
		char cgidir[MAXPATHLEN];

		snprintf(cgidir, sizeof(cgidir), "%s/cgi-bin", distpath);
		message("[%s] (1) making CGI program ...", now());
		if (fflag || dynamic)
			makeprogram(cgidir, "global.cgi", 0755);
		if (auto_completion)
			makeprogram(cgidir, "completion.cgi", 0755);
		makehtaccess(cgidir, ".htaccess", 0644);
	} else {
		message("[%s] (1) making CGI program ...(skipped)", now());
	}
	if (av) {
		const char *path = makepath(distpath, "GTAGSROOT", NULL);
		FILE *op = fopen(path, "w");
		if (op == NULL)
			die("cannot make file '%s'.", path);
		fputs(cwdpath, op);
		fputc('\n', op);
		fclose(op);
	}
	/*
	 * (2) make help file
	 */
	message("[%s] (2) making help.html ...", now());
	makehelp("help.html");
	/*
	 * (#) load GPATH
	 */
	load_gpath(dbpath);

	/*
	 * (3) make function entries (D/ and R/)
	 *     MAKING TAG CACHE
	 */
	message("[%s] (3) making tag lists ...", now());
	cache_open();
	tim = statistics_time_start("Time of making tag lists");
	func_total = makedupindex();
	statistics_time_end(tim);
	message("Total %d functions.", func_total);
	/*
	 * (4) search index. (search.html)
	 */
	if (Fflag && fflag) {
		message("[%s] (4) making search index ...", now());
		makesearchindex("search.html");
	}
	{
		STRBUF *defines = strbuf_open(0);
		STRBUF *files = strbuf_open(0);

		/*
		 * (5) make definition index (defines.html and defines/)
		 *     PRODUCE @defines
		 */
		message("[%s] (5) making definition index ...", now());
		tim = statistics_time_start("Time of making definition index");
		func_total = makedefineindex("defines.html", func_total, defines);
		statistics_time_end(tim);
		message("Total %d functions.", func_total);
		/*
		 * (6) make file index (files.html and files/)
		 *     PRODUCE @files, %includes
		 */
		message("[%s] (6) making file index ...", now());
		init_inc();
		tim = statistics_time_start("Time of making file index");
		file_total = makefileindex("files.html", files);
		statistics_time_end(tim);
		message("Total %d files.", file_total);
		html_count += file_total;
		/*
		 * (7) make call tree using cflow(1)'s output (cflow.html)
		 */
		if (call_file || callee_file) {
			message("[%s] (7) making cflow index ...", now());
			tim = statistics_time_start("Time of making cflow index");
			if (call_file)
				if (makecflowindex("call.html", call_file) < 0)
					call_file = NULL;
			if (callee_file)
				if (makecflowindex("callee.html", callee_file) < 0)
					callee_file = NULL;
			statistics_time_end(tim);
		}
		/*
		 * [#] make include file index.
		 */
		message("[%s] (#) making include file index ...", now());
		tim = statistics_time_start("Time of making include file index");
		makeincludeindex();
		statistics_time_end(tim);
		/*
		 * [#] make a common part for mains.html and index.html
		 *     USING @defines @files
		 */
		message("[%s] (#) making a common part ...", now());
		index = makecommonpart(title, strbuf_value(defines), strbuf_value(files));

		strbuf_close(defines);
		strbuf_close(files);
	}
	/*
	 * (7)make index file (index.html)
	 */
	message("[%s] (7) making index file ...", now());
	makeindex("index.html", title, index);
	/*
	 * (8) make main index (mains.html)
	 */
	message("[%s] (8) making main index ...", now());
	makemainindex("mains.html", index);
	/*
	 * (9) make HTML files (SRCS/)
	 *     USING TAG CACHE, %includes and anchor database.
	 */
	message("[%s] (9) making hypertext from source code ...", now());
	tim = statistics_time_start("Time of making hypertext");
	makehtml(file_total);
	statistics_time_end(tim);
	/*
	 * (10) rebuild script. (rebuild.sh)
	 *
	 * Don't grant execute permission to rebuild script.
	 */
	makerebuild("rebuild.sh");
	if (chmod(makepath(distpath, "rebuild.sh", NULL), 0640) < 0)
		die("cannot chmod rebuild script.");
	/*
	 * (11) style sheet file (style.css)
	 */
	if (enable_xhtml) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];
		snprintf(src, sizeof(src), "%s/gtags/style.css", datadir);
		snprintf(dist, sizeof(dist), "%s/style.css", distpath);
		copyfile(src, dist);
	}
	if (auto_completion || tree_view) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];

		snprintf(src, sizeof(src), "%s/gtags/jquery", datadir);
		snprintf(dist, sizeof(dist), "%s/js", distpath);
		copydirectory(src, dist);
		snprintf(src, sizeof(src), "%s/gtags/jquery/images", datadir);
		snprintf(dist, sizeof(dist), "%s/js/images", distpath);
		copydirectory(src, dist);
	}
	message("[%s] Done.", now());
	if (vflag && (fflag || dynamic || auto_completion)) {
		message("\n[Information]\n");
		message(" o Htags was invoked with the -f, -c, -D or --auto-completion option. You should");
		message("   start http server so that cgi-bin/*.cgi is executed as a CGI script.");
 		message("\n If you are using Apache, 'HTML/.htaccess' might be helpful for you.\n");
		message(" Good luck!\n");
	}
	if (Iflag) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];

		snprintf(src, sizeof(src), "%s/gtags/icons", datadir);
		snprintf(dist, sizeof(dist), "%s/icons", distpath);
		copydirectory(src, dist);
	}
	gpath_close();
	/*
	 * Print statistics information.
	 */
	print_statistics(statistics);
	clean();
	return 0;
}
/* Estimate entropy and Markov models */
void get_statistics(struct Statistics *stats, FILE* fp)
{
  unsigned char *buffer;
  unsigned char old_buffer[BUFFER_SIZE+2];
  int total = 0;
  double sum = 0.0;
  double probability;
  size_t i, bytes_read;

  init_statistics(stats);
  rewind(fp);
  buffer = old_buffer+2;

  /* Read the first two characters */
  old_buffer[0] = (unsigned char)fgetc(fp);
  stats->occurrence.single[old_buffer[0]]++;
  old_buffer[1] = (unsigned char)fgetc(fp);
  stats->occurrence.single[old_buffer[1]]++;
  increment_count(2, old_buffer, stats->occurrence.multi[0]);
  total += 2;
  while(!feof(fp))
  {
    /* Fill buffer */
    bytes_read = fread(buffer, 1, BUFFER_SIZE, fp);

    for(i=0; i<bytes_read; i++)
    {
      /* Count occurrence of the byte */
      stats->occurrence.single[buffer[i]]++;
      /* Count occurrence of the latest two bytes */
      increment_count(2, buffer+i-1, stats->occurrence.multi[0]);
      /* Count occurrence of the latest three bytes */
      increment_count(3, buffer+i-2, stats->occurrence.multi[1]);
      /* Count total number of bytes */
      total++;
    }
  }

  /* Report occurrences */
  for(i=0; i<256; i++)
    printf("occurrence[%3d] = %d\n", i, stats->occurrence.single[i]);
  /* Report file size */
  printf("total = %d\n", total);

  /* Estimate memoryless entropy */
  for(i=0; i<256; i++)
  {
    if(stats->occurrence.single[i] > 0)
    {
      /* Calculate probability of the byte */
      probability = stats->occurrence.single[i] / (double)total;
      /* Add to sum */
      sum = sum - (probability * log2(probability));
    }
  }
  stats->entropy.memoryless = sum;

  /* Calculate entropy rate of first-order Markov model */
  sum = 0;
  for(i=0; i<256*256; i++)
  {
    if(stats->occurrence.multi[0]->mem[i] > 0)
    {
      /* Calculate probability of the sequence */
      probability = stats->occurrence.multi[0]->mem[i] / (double)(total-1);
      /* Add to sum */
      sum = sum - (probability * log2(probability));
    }
  }
  stats->entropy.markov1 = sum - stats->entropy.memoryless;

  /* Calculate entropy rate of second-order Markov model */
  sum = 0;
  for(i=0; i<256*256*256; i++)
  {
    if(stats->occurrence.multi[1]->mem[i] > 0)
    {
      /* Calculate probability of the sequence */
      probability = stats->occurrence.multi[1]->mem[i] / (double)(total-2);
      /* Add to sum */
      sum = sum - (probability * log2(probability));
    }
  }
  stats->entropy.markov2 = sum
    - stats->entropy.markov1
    - stats->entropy.memoryless;

  /* Report memoryless entropy */
  printf("Memoryless entropy: %f bit(s)\n", stats->entropy.memoryless);
  /* Report entropy rate of first-order Markov model */
  printf("Markov model (Order 1) entropy rate: %f bit(s)\n", stats->entropy.markov1);
  /* Report entropy rate of second-order Markov model */
  printf("Markov model (Order 2) entropy rate: %f bit(s)\n", stats->entropy.markov2);

  free_statistics(stats);
  return;
}
Exemple #9
0
/* ********************************************************************
 * MAIN PROGRAM
 *
 * We use HIGE timers in order to see system performance with vmstat
 *
 * ********************************************************************	*/  
int main(int argc, char **argv)  
{  
	int i,c;
	int errflg = 0;
	int iflg = 0;
	int wflg = 0;							// WIringPI
	int repeats = 1;						// We can repeat readings
	int attempts = 0;						// How many attempts were necessary to be successful
	int fake = 0;
	
    extern char *optarg;
    extern int optind, optopt;
	
	mode = SOCK_STREAM;						// default Socket mode

	// ------------------------- COMMANDLINE OPTIONS SETTING ----------------------
	// Valid options are:
	// -h <hostname> ; hostname or IP address of the daemon
	// -p <port> ; Portnumber for daemon socket
	// -b ; Broadcast mode
	// -v ; Verbose, Give detailed messages
	// -w ; WiringPi mode
	//
    while ((c = getopt(argc, argv, ":bc:dfh:ip:r:stvw")) != -1) {
        switch(c) {
		case 'b':
			mode = SOCK_DGRAM;			// UDP Datagram Mode, broadcastoing
		break;
		case 'c':
			cflg = 1;					// Checks
			checks = atoi(optarg);
		break;
		case 'd':						// Daemon mode, cannot be together with test?
			dflg = 1;
		break;
		case 'f':
			fake = 1;
		break;
		case 'h':						// Socket communication
            dflg++;						// Need daemon flag too, (implied)
			hostname = optarg;
		break;
		case 'i':						// Interrupt (instead of waiting out).
			iflg=1;
			if (wflg) errflg++;
		break;
		case 'p':						// Port number
            port = optarg;
           dflg++;						// Need daemon flag too, (implied)
        break;
		case 'r':						// repeats
			repeats = atoi(optarg);
		break;
		case 's':						// Statistics
			sflg = 1;
		break;
		case 't':						// Test Mode, do debugging
			debug=1;
		break;
		case 'v':						// Verbose, output long timing/bit strings
			verbose = 1;
		break;
		case 'w':						// wiringpi library used
			wflg = 1;
			if (iflg) errflg++;
		break;
		case ':':       				// -f or -o without operand
			fprintf(stderr,"Option -%c requires an operand\n", optopt);
			errflg++;
		break;
		case '?':
			fprintf(stderr, "Unrecognized option: -%c\n", optopt);
            errflg++;
        }
    }
	
	// -------------------- PRINT ERROR ---------------------------------------
	// Print error message if parsing the commandline
	// was not successful
	
    if (errflg) {
        fprintf(stderr, "usage: argv[0] (options) \n\n");
		fprintf(stderr, "-b\t\t; Broadcast mode. Use UDP broadcasting\n");
		fprintf(stderr, "-d\t\t; Daemon mode. Codes received will be sent to another host at port 5000\n");
		fprintf(stderr, "-i\t\t; Interrupt based sensor processing\n");
		fprintf(stderr, "-w\t\t; WiringPI libs used for sensor processing\n");
		fprintf(stderr, "-s\t\t; Statistics, will gather statistics from remote\n");
		fprintf(stderr, "-r\t\t; Repeats, will gather statistics #repeats times\n");
		fprintf(stderr, "-t\t\t; Test mode, will output received code from remote\n");
		fprintf(stderr, "-v\t\t; Verbose, will output more information about the received codes\n");
        exit (2);
    }
	
	// ------------------ SETUP WIRINGPI --------------------------------------------
	// Now start with setup wiringPI
	//
	
	wiringPiSetup();

	//	------------------ PRINTING Parameters ------------------------------
	//
	if (verbose == 1) {
		printf("The following options have been set:\n\n");
		printf("-v\t; Verbose option\n");
		if (statistics>0)	printf("-s\t; Statistics option\n");
		if (dflg>0)			printf("-d\t; Daemon option\n");
		if (iflg>0)			printf("-i\t; Interrupt processing\n");
		if (wflg>0)			printf("-w\t; WIringPI library processing\n");
		if (debug)			printf("-t\t; Test and Debug option\n");
		if (repeats>=1)		printf("-r\t; Repeats: %d\n",repeats);
		if (mode != SOCK_STREAM) printf("-b\t; UDP Broadcasting option\n");
		printf("\n");						 
	}//if verbose
	
	// If we are in daemon mode, initialize sockets etc.
	//
	if (dflg) {
		daemon_mode(hostname, port, mode);
	}
	
	if (sflg) {
		fprintf(stderr,"init statistics\n");
		init_statistics(statistics);			// Make cells 0
	}
	
	// ------------------------
	// MAIN LOOP
	// 
	delay(500);								// Wait 2 secs before starting
	
	// We will initialize the interrupt handler to only react to a falling edge.
	// SO as every bit consists of a high pulse of 50 and a low pulse of either 28 or 75 usec
	// when we measure the falling edge only a 50+28 means a 0 and a 50+75usec flank means 1
	//
	if (iflg) {
		wiringPiISR (DHT22PIN, INT_EDGE_FALLING, &sensor_interrupt);
	}
	
	for (i=0; i<repeats; i++)  
	{  
		if (iflg) {
		// Use an interrupt routing, less resource consuming
			attempts = dht22_read_int(i);
		}
		else if (wflg) {
		// Make use of the special library for these devices in wiringPI
			attempts = dht22_read_wiring(i);
		}
		else if (fake) {
			attempts = 1;
			send_2_server(sockfd, 50, 10);
		}
		else {
		// Use the brute force method and wait all reads out
			attempts = dht22_read_old(i); 
		}
		
		if (attempts <= 100) {
			printf(" It took %d attempts to read\n",attempts);
		}
		else {
			printf(" dht22: Unable to read a value in 100 attempts\n");
		}
		delay(2000);							// wait 2.0 secs
	}
	
	// Close the socket to the daemon
	if (close(sockfd) == -1) {
		perror("Error closing socket to daemon");
	}
	exit(EXIT_SUCCESS); 
}  
Exemple #10
0
void init_vars()
{
  Stage=STAGE_INIT;
  opts.Abort_Test_Counter = Abort_Test_Every ;
  Abort_Test_Every = 1;
  opts.AntialiasDepth = 3;
  opts.Antialias_Threshold = 0.3;
  opts.BBox_Threshold = 25;
  Color_Bits = 8;
  opts.DisplayFormat = '0';
  Display_Started = false;
  opts.First_Column = 0;
  opts.First_Column_Percent = 0.0;
  opts.First_Line = 0;
  opts.First_Line_Percent = 0.0;
  Frame.Screen_Height = 100;
  Frame.Screen_Width  = 100;
  Root_Object = NULL;
  free_istack = NULL;
  opts.JitterScale = 1.0;
  opts.Language_Version = OFFICIAL_VERSION_NUMBER;
  opts.Last_Column = -1;
  opts.Last_Column_Percent = 1.0;
  opts.Last_Line = -1;
  opts.Last_Line_Percent = 1.0;
  opts.PreviewGridSize_Start = 1;
  opts.PreviewGridSize_End   = 1;
  opts.Library_Paths[0] = NULL;
  opts.Library_Path_Index = 0;
  Max_Intersections = 64; /*128*/
  Number_Of_Files = 0;
  Number_of_istacks = 0;

  opts.Options = USE_VISTA_BUFFER + USE_LIGHT_BUFFER + JITTER +
                 DISKWRITE + REMOVE_BOUNDS;
  opts.OutputFormat = DEFAULT_OUTPUT_FORMAT;
  opts.OutputQuality = 8;
  Output_File = NULL;
  opts.Output_Numbered_Name[0]='\0';
  opts.Output_File_Name[0]='\0';
  opts.Output_Path[0]='\0';
  opts.Output_File_Type=0;
  opts.PaletteOption = '3';
  opts.Quality = 9;
  opts.Quality_Flags = QUALITY_9;
  opts.DisplayGamma = DEFAULT_DISPLAY_GAMMA;

  opts.Header_File_Name[0] = '\0';

  /* 
   * If DisplayGamma == 2.2, then GammaFactor == .45, which is what we want.
   */
  opts.GammaFactor = DEFAULT_ASSUMED_GAMMA/opts.DisplayGamma;

  opts.FrameSeq.FrameType = FT_SINGLE_FRAME;
  opts.FrameSeq.Clock_Value = 0.0;
  opts.FrameSeq.InitialFrame = 1;
  opts.FrameSeq.InitialClock = 0.0;
  opts.FrameSeq.FinalFrame = INT_VALUE_UNSET;
  opts.FrameSeq.FrameNumWidth = 0;
  opts.FrameSeq.FinalClock = 1.0;
  opts.FrameSeq.SubsetStartFrame = INT_VALUE_UNSET;
  opts.FrameSeq.SubsetStartPercent = DBL_VALUE_UNSET;
  opts.FrameSeq.SubsetEndFrame = INT_VALUE_UNSET;
  opts.FrameSeq.SubsetEndPercent = DBL_VALUE_UNSET;
  opts.FrameSeq.Field_Render_Flag = false;
  opts.FrameSeq.Odd_Field_Flag = false;

  /* NK rad - these default settings are low quality
  for relatively high quality, use

  opts.Radiosity_Nearest_Count = 8;
  opts.Radiosity_Count = 100;
  opts.Radiosity_Recursion_Limit = 5;

  Only these variables should need adjustment
  */

  opts.Radiosity_Brightness = 1.0;
  opts.Radiosity_Count = 35;
  opts.Radiosity_Dist_Max = 0.0;   /* NK rad - dist_max is always computed on the fly now - FYI */
  opts.Radiosity_Error_Bound = 1.8;
  opts.Radiosity_Gray = 0.0;       /* degree to which gathered light is grayed */
  opts.Radiosity_Low_Error_Factor = 0.5;
  opts.Radiosity_Min_Reuse = 0.015;
  opts.Radiosity_Nearest_Count = 5;
  opts.Radiosity_Recursion_Limit = 3;
  opts.Radiosity_Quality = 6;     /* Q-flag value for light gathering */
  opts.Radiosity_File_ReadOnContinue = 1;
  opts.Radiosity_File_SaveWhileRendering = 1;
  opts.Radiosity_File_AlwaysReadAtStart = 0;
  opts.Radiosity_File_KeepOnAbort = 1;
  opts.Radiosity_File_KeepAlways = 0;
  opts.Maximum_Sample_Brightness = -1.0;  /* default max brightness allows any */
  opts.Radiosity_ADC_Bailout = 0.01;     /* use a fairly high default adc_bailout for rad */
  opts.Radiosity_Use_Normal = false;
  opts.Radiosity_Use_Media = false;
  opts.radPretraceStart = 0.08;
  opts.radPretraceEnd = 0.04;
  opts.Radiosity_Load_File_Name = NULL;
  opts.Radiosity_Save_File_Name = NULL;
  opts.Radiosity_Add_On_Final_Trace = true;
  opts.Radiosity_Enabled = false;

  Current_Line_Number = 0;

  init_statistics(stats);
  init_statistics(totalstats);

  strcpy (opts.Input_File_Name, "OBJECT.POV");
  opts.Scene_Name[0]='\0';
  opts.Ini_Output_File_Name[0]='\0';
  opts.Use_Slabs=true;
  Num_Echo_Lines = POV_NUM_ECHO_LINES;   /* May make user setable later - CEY*/

  closed_flag = false;
  Stop_Flag = false;

  trender = trender_frame = trender_total = 0.0;
  tparse  = tparse_frame  = tparse_total  = 0.0;
  tphoton = tphoton_frame = tphoton_total = 0.0;

  histogram_grid = NULL;
  opts.histogram_on = false;
  opts.histogram_type = NONE;
  opts.histogram_file_type=0;
  opts.Histogram_File_Name[0] = '\0';
  Histogram_File = NULL;
  /*
   * Note that late initialization of the histogram_x and histogram_y
   * variables is done in fix_up_rendering_window, if they aren't specified
   * on the command line.  This is because they are based on the image
   * dimensions, and we can't be certain that we have this info at the
   * time we parse the histogram options in optin.c. [AED]
   */
  opts.histogram_x = opts.histogram_y = 0;
  max_histogram_value = 0;

  opts.Tracing_Method = 1;
  Experimental_Flag = 0;
  Make_Pigment_Entries();

  opts.Preview_RefCon = 0;

  opts.Warning_Level = 10; // all warnings

  opts.String_Encoding = 0; // ASCII

  (void)POVMSAttrList_New(&opts.Declared_Variables); // we have to be careful... [trf]

  /* NK phmap */
  backtraceFlag=0;
  photonOptions.photonsEnabled = 0;
  InitBacktraceWasCalled=false;

  photonOptions.photonMap.head = NULL;
  photonOptions.photonMap.numPhotons  = 0;
  photonOptions.photonMap.numBlocks  = 0;

  photonOptions.photonMap.gatherNumSteps = 2;
  photonOptions.photonMap.minGatherRad = -1.0;
  photonOptions.photonMap.minGatherRadMult = 1.0;
#ifdef GLOBAL_PHOTONS
  photonOptions.globalPhotonMap.gatherNumSteps = 1;
  photonOptions.globalPhotonMap.minGatherRad = -1.0;
  photonOptions.globalPhotonMap.minGatherRadMult = 1.0;
#endif
  photonOptions.mediaPhotonMap.gatherNumSteps = 1;
  photonOptions.mediaPhotonMap.minGatherRad = -1.0;
  photonOptions.mediaPhotonMap.minGatherRadMult = 1.0;

  photonOptions.minGatherCount = 20;
  photonOptions.maxGatherCount = 100;

  photonOptions.ADC_Bailout = -1;  /* use the normal adc bailout */
  photonOptions.Max_Trace_Level = -1; /* use the normal max_trace_level */

  photonOptions.jitter = 0.4;
  photonOptions.autoStopPercent = 0.5;

  photonOptions.expandTolerance = 0.2;
  photonOptions.minExpandCount = 35;

  photonOptions.fileName = NULL;
  photonOptions.loadFile = false;

  disp_elem = 0; /* for dispersion */
  disp_nelems = 0;   /* reset this for next pixel's tracing */

  photonOptions.photonGatherList = NULL;
  photonOptions.photonDistances = NULL;

#ifdef GLOBAL_PHOTONS
  /* global photon map */
  photonOptions.globalGatherRad = 10.0;
  photonOptions.globalPhotonsToShoot = 0;
#endif

  photonOptions.surfaceSeparation = 1.0;
  photonOptions.globalSeparation = 1.0;

  photonOptions.photonMap.head = NULL;
  photonOptions.photonMap.numPhotons = 0;
  photonOptions.photonMap.numBlocks = 0;
#ifdef GLOBAL_PHOTONS
  photonOptions.globalPhotonMap.head = NULL;
  photonOptions.globalPhotonMap.numPhotons = 0;
  photonOptions.globalPhotonMap.numBlocks = 0;
#endif
  photonOptions.mediaPhotonMap.head = NULL;
  photonOptions.mediaPhotonMap.numPhotons = 0;
  photonOptions.mediaPhotonMap.numBlocks = 0;

  photonOptions.maxMediaSteps = 0;  /* disable media photons by default */
  photonOptions.mediaSpacingFactor = 1.0;

  photonOptions.photonReflectionBlur = false; /* off by default */

  photonOptions.surfaceCount = 0;
  photonOptions.globalCount = 0;

  Highest_Trace_Level = 0 ;

  /* NK 1999 - bugfix */
  Trace_Level = 0;
  // [trf] Total_Depth = 0.0;
  Radiosity_Trace_Level = 1;

  warpNormalTextures = 0;

  opts.Noise_Generator = 2; /* default is the range-corrected noise, since the perlin noise (gen 3) seems buggy */

  ADC_Bailout = 1.0/255.0;

  SuperSampleCount = 0;
  RadiosityCount = 0;
  MosaicPreviewSize = 0;
}
Exemple #11
0
void FrameRender()
{
   // Store start time for parse.
   START_TIME

   Current_Token_Count = 0;
   tparse_frame = tphoton_frame = trender_frame = 0.0;

   // Parse the scene file.
   Send_Progress("Parsing", PROGRESS_PARSING);

   opts.Do_Stats = false;

   // Set up noise-tables
   Initialize_Noise();

   // Set up function VM
   POVFPU_Init();

   // Init module specific stuff.
   Initialize_Mesh_Code();

   Parse();

   opts.Do_Stats = true;

   if (opts.Radiosity_Enabled)
      Experimental_Flag |= EF_RADIOS;

   if (Experimental_Flag)
   {
      char str[512] = "" ;

      if (Experimental_Flag & EF_SPLINE)
        strcat (str, str [0] ? ", spline" : "spline") ;
      if (Experimental_Flag & EF_RADIOS)
        strcat (str, str [0] ? ", radiosity" : "radiosity") ;
      if (Experimental_Flag & EF_SLOPEM)
        strcat (str, str [0] ? ", slope pattern" : "slope pattern") ;
      if (Experimental_Flag & EF_ISOFN) 
        strcat (str, str [0] ? ", function '.hf'" : "function '.hf'") ;
      if (Experimental_Flag & EF_TIFF) 
        strcat (str, str [0] ? ", TIFF image support" : "TIFF image support") ;

      Warning(0, "This rendering uses the following experimental feature(s): %s.\n"
                 "The design and implementation of these features is likely to change in future versions\n"
                 "of POV-Ray. Full backward compatibility with the current implementation is NOT guaranteed.",
                 str);
   }

   Experimental_Flag = 0;

   // Switch off standard anti-aliasing.

   if((Frame.Camera->Aperture != 0.0) && (Frame.Camera->Blur_Samples > 0))
   {
      opts.Options &= ~ANTIALIAS;

      Warning(0, "Focal blur is used. Standard antialiasing is switched off.");
   }

   // Create the bounding box hierarchy.

   Stage = STAGE_SLAB_BUILDING;

   if(opts.Use_Slabs)
      Send_Progress("Creating bounding slabs", PROGRESS_CREATING_BOUNDING_SLABS);

   // Init module specific stuff.
   Initialize_Atmosphere_Code();
   Initialize_BBox_Code();
   Initialize_Lighting_Code();
   Initialize_VLBuffer_Code();
   Initialize_Radiosity_Code();

   // Always call this to print number of objects.
   Build_Bounding_Slabs(&Root_Object);

   // Create the vista buffer.
   Build_Vista_Buffer();

   // Create the light buffers.
   Build_Light_Buffers();

   // Save variable values.
   variable_store(STORE);

   // Get the parsing time.
   STOP_TIME
   tparse = TIME_ELAPSED
   Send_ProgressUpdate(PROGRESS_PARSING, 0);

   // Output parsing statistics.
   Send_ParseStatistics();

   if (photonOptions.photonsEnabled)
   {
     /* Store start time for photons. */
     START_TIME

     /* now backwards-trace the scene and build the photon maps */
     InitBacktraceEverything();
     BuildPhotonMaps();

     /* Get the photon-shooting time. */
     STOP_TIME
     tphoton = TIME_ELAPSED

     /* Get total parsing time. */
     tphoton_total += tphoton;
     tphoton_frame = tphoton;
     tphoton = 0;
   }

   /* Store start time for the rest of parsing. */
   START_TIME
   Stage = STAGE_INIT;

   // Open output file and if we are continuing an interrupted trace,
   // read in the previous file settings and any data there.  This has to
   // be done before any image-size related allocations, since the settings
   // in a resumed file take precedence over that specified by the user. [AED]
   open_output_file();

   // Start the display.
   if(opts.Options & DISPLAY)
   {
      Send_Progress("Displaying", PROGRESS_DISPLAYING);

      Display_Started = POV_DISPLAY_INIT(opts.Preview_RefCon, Frame.Screen_Width, Frame.Screen_Height);

      // Display vista tree.
      Draw_Vista_Buffer();
   }
   else
   {
      Display_Started = false;
   }

   // Get things ready for ray tracing (misc init, mem alloc)
   Initialize_Renderer();

   // This had to be taken out of open_output_file() because we don't have
   // the final image size until the output file has been opened, so we can't
   // initialize the display until we know this, which in turn means we can't
   // read the rendered part before the display is initialized. [AED]
   if((opts.Options & DISKWRITE) && (opts.Options & CONTINUE_TRACE))
   {
      Read_Rendered_Part(Actual_Output_Name);

      if (opts.Last_Line > Frame.Screen_Height)
         opts.Last_Line = Frame.Screen_Height;

      if (opts.Last_Column > Frame.Screen_Width)
         opts.Last_Column = Frame.Screen_Width;
   }

   // Get the rest of the parsing time.
   STOP_TIME
   tparse += TIME_ELAPSED

   // Store start time for trace.
   START_TIME

   // Get total parsing time.
   tparse_total += tparse;
   tparse_frame = tparse;
   tparse = 0;

   // Start tracing.
   Stage = STAGE_RENDERING;

   POV_PRE_RENDER

   Send_Progress("Rendering", PROGRESS_RENDERING);

   // Macro for setting up any special FP options
   CONFIG_MATH

   // Ok, go for it - trace the picture.

   // If radiosity preview has been done, we are continuing a trace, so it
   // is important NOT to do the preview, even if the user requests it, as it
   // will cause discontinuities in radiosity shading by (probably) calculating
   // a few more radiosity values.

   // Note that radiosity REQUIRES a mosaic preview prior to main scan
   if ( opts.Radiosity_Enabled && !opts.Radiosity_Preview_Done)
      Start_Tracing_Radiosity_Preview(opts.PreviewGridSize_Start, opts.PreviewGridSize_End);

   else if((opts.Options & PREVIEW) && (opts.Options & DISPLAY))
      Start_Tracing_Mosaic_Preview(opts.PreviewGridSize_Start, opts.PreviewGridSize_End);

   switch(opts.Tracing_Method)
   {
      case 2:
         Start_Adaptive_Tracing();
         break;
      case 1:
      default:
         Start_Non_Adaptive_Tracing();
   }

   // Record time so well spent before file close so it can be in comments
   STOP_TIME
   trender = TIME_ELAPSED

   // shutdown (freeing memory) does not get included in the time!

   // Get total render time.
   trender_total += trender;
   trender_frame = trender;
   trender = 0;

   // Close out our file
   if(Output_File != NULL)
   {
      delete Output_File;
      Output_File = NULL;
   }

   // For all those who never rtfm [trf]
   if((Highest_Trace_Level >= Max_Trace_Level) && (Had_Max_Trace_Level == false))
      PossibleError("Maximum trace level reached! If your scene contains black spots\nread more about the max_trace_level setting in the documentation!");

   Stage = STAGE_SHUTDOWN;

   POV_PRE_SHUTDOWN

   // DESTROY lots of stuff
   /* NK phmap */
   FreeBacktraceEverything();
   Deinitialize_Atmosphere_Code();
   Deinitialize_BBox_Code();
   Deinitialize_Lighting_Code();
   Deinitialize_Mesh_Code();
   Deinitialize_VLBuffer_Code();
   Deinitialize_Radiosity_Code();
   Destroy_Light_Buffers();
   Destroy_Vista_Buffer();
   Destroy_Bounding_Slabs();
   Destroy_Frame();
   Terminate_Renderer();
   FreeFontInfo();
   Free_Iteration_Stack();
   Free_Noise_Tables();

   POVFPU_Terminate();

   POV_POST_SHUTDOWN

   if((opts.Options & DISPLAY) && Display_Started)
   {
      POV_DISPLAY_FINISHED(opts.Preview_RefCon);

      POV_DISPLAY_CLOSE(opts.Preview_RefCon);

      Display_Started = false;
   }

   if(opts.histogram_on)
      write_histogram(opts.Histogram_File_Name);

   Send_Progress("Done Tracing", PROGRESS_DONE_TRACING);

   // Print stats ...
   Send_RenderStatistics();

   if(opts.FrameSeq.FrameType == FT_MULTIPLE_FRAME)
   {
      // Add them up
      sum_statistics(totalstats, stats);

      // ... and then clear them for the next frame
      init_statistics(stats);
   }

   // Restore variable values.
   variable_store(RESTORE);
}
int main(int argc, char** argv){
  struct sockaddr_in sock;
  int my_sock_fd, i;
  unsigned short port = 57843;
  char is_sink = false;

  if(argc < 3){
    printf("Usage: %s -i <interface> [-r samples_per_second | -sp sink_port | -p port | -e] [-s]\n",argv[0]);
    exit(-1);
  }

  for(i = 1; i < argc;){
    if(strcmp(argv[i], "-e") == 0){
      emulate_ts = true;
      i++;
      continue;
    }
    if(strcmp(argv[i], "-s") == 0){
      is_sink = true;
      i++;
      continue;
    }
    if(strcmp(argv[i], "-r") == 0){
      samples_per_second = parse_samples_per_second(argv[i + 1]);
      i+=2;
      continue;
    }
    if(strcmp(argv[i], "-i") == 0){
      iface = argv[i + 1];
      i+=2;
      continue;
    }
    if(strcmp(argv[i], "-p") == 0){
      port = atoi(argv[i + 1]);
      i+=2;
      continue;
    }
    if(strcmp(argv[i], "-sp") == 0){
      sink_dport = atoi(argv[i + 1]);
      i+=2;
      continue;
    }
  }

  if(is_sink)
    printf("Acting as sink.\n");

  my_sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if(my_sock_fd == -1){
    log(E, "Cannot open my socket\n");
    exit(-1);
  }

  memset(& sock, 0, sizeof(sock));
  sock.sin_family = AF_INET;
  sock.sin_port = htons(port);
  sock.sin_addr = get_ip_from_iface();

  if(bind(my_sock_fd, (struct sockaddr *) &sock, sizeof(sock)) == -1){
    log(E, "Unnable to bind socket\n");
    exit(-1);
  }

  printf("Bound to %s:%u\n", inet_ntoa(sock.sin_addr), port);

  init_statistics();
  signal(SIGINT,(void*) cleanup);
  if(is_sink){
    serve(my_sock_fd);
  }
  else{
    init_destination();
    if(emulate_ts)
      printf("Emulating timestamp.\n");
    printf("Sampling at %u\n", samples_per_second);
    collect(my_sock_fd);
  }
  return 0;
}
AdaptiveFreeList<Chunk>::AdaptiveFreeList() : FreeList<Chunk>(), _hint(0) {
  init_statistics();
}
Exemple #14
0
int
main(int argc, char **argv)
{
	char dbpath[MAXPATHLEN];
	char cwd[MAXPATHLEN];
	STRBUF *sb = strbuf_open(0);
	int optchar;
	int option_index = 0;
	STATISTICS_TIME *tim;

	while ((optchar = getopt_long(argc, argv, "cd:f:iuIn:oOqvwse", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_CONFIG:
			show_config = 1;
			if (optarg)
				config_name = optarg;
			break;
		case OPT_GTAGSCONF:
			gtagsconf = optarg;
			break;
		case OPT_GTAGSLABEL:
			gtagslabel = optarg;
			break;
		case OPT_PATH:
			do_path = 1;
			if (!strcmp("absolute", optarg))
				convert_type = PATH_ABSOLUTE;
			else if (!strcmp("relative", optarg))
				convert_type = PATH_RELATIVE;
			else if (!strcmp("through", optarg))
				convert_type = PATH_THROUGH;
			else
				die("Unknown path type.");
			break;
		case OPT_SINGLE_UPDATE:
			iflag++;
			single_update = optarg;
			break;
		case OPT_ENCODE_PATH:
			if (strlen(optarg) > 255)
				die("too many encode chars.");
			if (strchr(optarg, '/') || strchr(optarg, '.'))
				die("cannot encode '/' and '.' in the path.");
			set_encode_chars((unsigned char *)optarg);
			break;
		case 'c':
			cflag++;
			break;
		case 'd':
			dump_target = optarg;
			break;
		case 'f':
			file_list = optarg;
			break;
		case 'i':
			iflag++;
			break;
		case 'u':
			uflag++;
			iflag++;
			break;
		case 'I':
			Iflag++;
			break;
		case 'o':
			/*
			 * Though the -o(--omit-gsyms) was removed, this code
			 * is left for compatibility.
			 */
			break;
		case 'O':
			Oflag++;
			break;
		case 'q':
			qflag++;
			setquiet();
			break;
		case 'w':
			wflag++;
			break;
		case 'v':
			vflag++;
			setverbose();
			break;
		default:
			usage();
			break;
		}
	}
	if (gtagsconf) {
		char path[MAXPATHLEN];

		if (realpath(gtagsconf, path) == NULL)
			die("%s not found.", gtagsconf);
		set_env("GTAGSCONF", path);
	}
	if (gtagslabel) {
		set_env("GTAGSLABEL", gtagslabel);
	}
	if (qflag)
		vflag = 0;
	if (show_version)
		version(NULL, vflag);
	if (show_help)
		help();

	argc -= optind;
        argv += optind;

	/* If dbpath is specified, -O(--objdir) option is ignored. */
	if (argc > 0)
		Oflag = 0;
	if (show_config) {
		if (config_name)
			printconf(config_name);
		else
			fprintf(stdout, "%s\n", getconfline());
		exit(0);
	} else if (do_path) {
		/*
		 * This is the main body of path filter.
		 * This code extract path name from tag line and
		 * replace it with the relative or the absolute path name.
		 *
		 * By default, if we are in src/ directory, the output
		 * should be converted like follws:
		 *
		 * main      10 ./src/main.c  main(argc, argv)\n
		 * main      22 ./libc/func.c   main(argc, argv)\n
		 *		v
		 * main      10 main.c  main(argc, argv)\n
		 * main      22 ../libc/func.c   main(argc, argv)\n
		 *
		 * Similarly, the --path=absolute option specified, then
		 *		v
		 * main      10 /prj/xxx/src/main.c  main(argc, argv)\n
		 * main      22 /prj/xxx/libc/func.c   main(argc, argv)\n
		 */
		STRBUF *ib = strbuf_open(MAXBUFLEN);
		CONVERT *cv;
		char *ctags_x;

		if (argc < 3)
			die("gtags --path: 3 arguments needed.");
		cv = convert_open(convert_type, FORMAT_CTAGS_X, argv[0], argv[1], argv[2], stdout);
		while ((ctags_x = strbuf_fgets(ib, stdin, STRBUF_NOCRLF)) != NULL)
			convert_put(cv, ctags_x);
		convert_close(cv);
		strbuf_close(ib);
		exit(0);
	} else if (dump_target) {
		/*
		 * Dump a tag file.
		 */
		DBOP *dbop = NULL;
		const char *dat = 0;
		int is_gpath = 0;

		char* target_file = NULL;
		if (!test("f", dump_target)) {
			target_file = strchr(dump_target, ':');
			if (target_file == NULL) 
				die("file '%s' not found", dump_target);

			*target_file++ = 0; //move to the next char, which starts the target file.
			if (!test("f", dump_target)) {
				die("file '%s' not found.", dump_target);
			}
		}

		if ((dbop = dbop_open(dump_target, 0, 0, DBOP_RAW)) == NULL)
			die("file '%s' is not a tag file.", dump_target);
		/*
		 * The file which has a NEXTKEY record is GPATH.
		 */
		if (dbop_get(dbop, NEXTKEY))
			is_gpath = 1;

		if (target_file && !is_gpath) {
			die("dump target_file can only be used with GPATH");
		}

		if (target_file) {
			dat = dbop_get(dbop, target_file);
			if (dat == NULL) {
				die("target_file %s not found in GPATH", target_file);
			}
			time_t t = gpath_mtime(dbop, target_file);
			printf("%d\n", t);
		} else {
			for (dat = dbop_first(dbop, NULL, NULL, 0); dat != NULL; dat = dbop_next(dbop)) {
				const char *flag = is_gpath ? dbop_getflag(dbop) : "";

				if (*flag)
					if (is_gpath) {
						time_t t = gpath_mtime(dbop, dbop->lastkey);
						printf("%s\t%s\t%s\t%s\n", dbop->lastkey, dat, flag, ctime(&t));
					} else
						printf("%s\t%s\t%s\n", dbop->lastkey, dat, flag);
				else
					printf("%s\t%s\n", dbop->lastkey, dat);
			}
		}
		dbop_close(dbop);
		exit(0);
	} else if (Iflag) {
		if (!usable("mkid"))
			die("mkid not found.");
	}

	/*
	 * If 'gtags.files' exists, use it as a file list.
	 * If the file_list other than "-" is given, it must be readable file.
	 */
	if (file_list == NULL && test("f", GTAGSFILES))
		file_list = GTAGSFILES;
	if (file_list && strcmp(file_list, "-")) {
		if (test("d", file_list))
			die("'%s' is a directory.", file_list);
		else if (!test("f", file_list))
			die("'%s' not found.", file_list);
		else if (!test("r", file_list))
			die("'%s' is not readable.", file_list);
	}
	/*
	 * Regularize the path name for single updating (--single-update).
	 */
	if (single_update) {
		static char regular_path_name[MAXPATHLEN];
		char *p = single_update;
		
		if (!test("f", p))
			die("'%s' not found.", p);
		if (isabspath(p))
			die("--single-update requires relative path name.");
		if (!(p[0] == '.' && p[1] == '/')) {
			snprintf(regular_path_name, MAXPATHLEN, "./%s", p);
			p = regular_path_name;
		}
		single_update = p;
	}
	if (!getcwd(cwd, MAXPATHLEN))
		die("cannot get current directory.");
	canonpath(cwd);
	/*
	 * Decide directory (dbpath) in which gtags make tag files.
	 *
	 * Gtags create tag files at current directory by default.
	 * If dbpath is specified as an argument then use it.
	 * If the -i option specified and both GTAGS and GRTAGS exists
	 * at one of the candidate directories then gtags use existing
	 * tag files.
	 */
	if (iflag) {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (!gtagsexist(cwd, dbpath, MAXPATHLEN, vflag))
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	} else {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (Oflag) {
			char *objdir = getobjdir(cwd, vflag);

			if (objdir == NULL)
				die("Objdir not found.");
			strlimcpy(dbpath, objdir, sizeof(dbpath));
		} else
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	}
	if (iflag && (!test("f", makepath(dbpath, dbname(GTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GRTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GPATH), NULL)))) {
		if (wflag)
			warning("GTAGS, GRTAGS or GPATH not found. -i option ignored.");
		iflag = 0;
	}
	if (!test("d", dbpath))
		die("directory '%s' not found.", dbpath);
	if (vflag)
		fprintf(stderr, "[%s] Gtags started.\n", now());
	/*
	 * load configuration file.
	 */
	openconf();
	if (getconfb("extractmethod"))
		extractmethod = 1;
	strbuf_reset(sb);
	if (getconfs("langmap", sb))
		langmap = check_strdup(strbuf_value(sb));
	strbuf_reset(sb);
	if (getconfs("gtags_parser", sb))
		gtags_parser = check_strdup(strbuf_value(sb));
	/*
	 * initialize parser.
	 */
	if (vflag && gtags_parser)
		fprintf(stderr, " Using plug-in parser.\n");
	parser_init(langmap, gtags_parser);
	if (vflag && file_list)
		fprintf(stderr, " Using '%s' as a file list.\n", file_list);
	/*
	 * Start statistics.
	 */
	init_statistics();
	/*
	 * incremental update.
	 */
	if (iflag) {
		/*
		 * Version check. If existing tag files are old enough
		 * gtagsopen() abort with error message.
		 */
		GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
		gtags_close(gtop);
		/*
		 * GPATH is needed for incremental updating.
		 * Gtags check whether or not GPATH exist, since it may be
		 * removed by mistake.
		 */
		if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
			die("Old version tag file found. Please remake it.");
		(void)incremental(dbpath, cwd);
		print_statistics(statistics);
		exit(0);
	}
	/*
	 * create GTAGS and GRTAGS
	 */
	createtags(dbpath, cwd);
	/*
	 * create idutils index.
	 */
	if (Iflag) {
		tim = statistics_time_start("Time of creating ID");
		if (vflag)
			fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
		strbuf_reset(sb);
		strbuf_puts(sb, "mkid");
		if (vflag)
			strbuf_puts(sb, " -v");
		strbuf_sprintf(sb, " --file='%s/ID'", dbpath);
		if (vflag) {
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 1>&2");
		} else {
			strbuf_puts(sb, " >/dev/null");
		}
		if (debug)
			fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
		if (system(strbuf_value(sb)))
			die("mkid failed: %s", strbuf_value(sb));
		if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
			die("cannot chmod ID file.");
		statistics_time_end(tim);
	}
	if (vflag)
		fprintf(stderr, "[%s] Done.\n", now());
	closeconf();
	strbuf_close(sb);
	print_statistics(statistics);

	return 0;
}
Exemple #15
0
int
main(int argc, char **argv)
{
    char dbpath[MAXPATHLEN];
    char cwd[MAXPATHLEN];
    STRBUF *sb = strbuf_open(0);
    int optchar;
    int option_index = 0;
    STATISTICS_TIME *tim;

    /*
     * Setup GTAGSCONF and GTAGSLABEL environment variable
     * according to the --gtagsconf and --gtagslabel option.
     */
    preparse_options(argc, argv);
    /*
     * Get the project root directory.
     */
    if (!vgetcwd(cwd, MAXPATHLEN))
        die("cannot get current directory.");
    canonpath(cwd);
    /*
     * Load configuration file.
     */
    openconf(cwd);
    configuration();
    setenv_from_config();
    {
        char *env = getenv("GTAGS_OPTIONS");
        if (env && *env)
            argv = prepend_options(&argc, argv, env);
    }
    logging_arguments(argc, argv);
    while ((optchar = getopt_long(argc, argv, "cd:f:iIn:oOqvwse", long_options, &option_index)) != EOF) {
        switch (optchar) {
        case 0:
            /* already flags set */
            break;
        case OPT_CONFIG:
            show_config = 1;
            if (optarg)
                config_name = optarg;
            break;
        case OPT_GTAGSCONF:
        case OPT_GTAGSLABEL:
            /* These options are already parsed in preparse_options() */
            break;
        case OPT_SINGLE_UPDATE:
            iflag++;
            single_update = optarg;
            break;
        case OPT_ACCEPT_DOTFILES:
            set_accept_dotfiles();
            break;
        case 'c':
            cflag++;
            break;
        case 'd':
            dump_target = optarg;
            break;
        case 'f':
            file_list = optarg;
            break;
        case 'i':
            iflag++;
            break;
        case 'I':
            Iflag++;
            break;
        case 'o':
            /*
             * Though the -o(--omit-gsyms) was removed, this code
             * is left for compatibility.
             */
            break;
        case 'O':
            Oflag++;
            break;
        case 'q':
            qflag++;
            setquiet();
            break;
        case 'w':
            wflag++;
            break;
        case 'v':
            vflag++;
            setverbose();
            break;
        default:
            usage();
            break;
        }
    }
    if (qflag)
        vflag = 0;
    if (show_version)
        version(NULL, vflag);
    if (show_help)
        help();

    argc -= optind;
    argv += optind;

    /* If dbpath is specified, -O(--objdir) option is ignored. */
    if (argc > 0)
        Oflag = 0;
    if (show_config) {
        openconf(setupdbpath(0) == 0 ? get_root() : NULL);
        if (config_name)
            printconf(config_name);
        else
            fprintf(stdout, "%s\n", getconfline());
        exit(0);
    } else if (dump_target) {
        /*
         * Dump a tag file.
         */
        DBOP *dbop = NULL;
        const char *dat = 0;
        int is_gpath = 0;

        if (!test("f", dump_target))
            die("file '%s' not found.", dump_target);
        if ((dbop = dbop_open(dump_target, 0, 0, DBOP_RAW)) == NULL)
            die("file '%s' is not a tag file.", dump_target);
        /*
         * The file which has a NEXTKEY record is GPATH.
         */
        if (dbop_get(dbop, NEXTKEY))
            is_gpath = 1;
        for (dat = dbop_first(dbop, NULL, NULL, 0); dat != NULL; dat = dbop_next(dbop)) {
            const char *flag = is_gpath ? dbop_getflag(dbop) : "";

            if (*flag)
                printf("%s\t%s\t%s\n", dbop->lastkey, dat, flag);
            else
                printf("%s\t%s\n", dbop->lastkey, dat);
        }
        dbop_close(dbop);
        exit(0);
    } else if (Iflag) {
#define REQUIRED_MKID_VERSION "4.5"
        char *p;

        if (!usable("mkid"))
            die("mkid not found.");
        if (read_first_line("mkid --version", sb))
            die("mkid cannot executed.");
        p = strrchr(strbuf_value(sb), ' ');
        if (p == NULL)
            die("invalid version string of mkid: %s", strbuf_value(sb));
        switch (check_version(p + 1, REQUIRED_MKID_VERSION)
#ifdef _WIN32
                || strcmp(p + 1, "3.2.99") == 0
#endif
               )  {
        case 1:
            break;	/* OK */
        case 0:
            die("mkid version %s or later is required.", REQUIRED_MKID_VERSION);
        default:
            die("invalid version string of mkid: %s", strbuf_value(sb));
        }
    }

    /*
     * If 'gtags.files' exists, use it as a file list.
     * If the file_list other than "-" is given, it must be readable file.
     */
    if (file_list == NULL && test("f", GTAGSFILES))
        file_list = GTAGSFILES;
    if (file_list && strcmp(file_list, "-")) {
        if (test("d", file_list))
            die("'%s' is a directory.", file_list);
        else if (!test("f", file_list))
            die("'%s' not found.", file_list);
        else if (!test("r", file_list))
            die("'%s' is not readable.", file_list);
    }
    /*
     * Regularize the path name for single updating (--single-update).
     */
    if (single_update) {
        static char regular_path_name[MAXPATHLEN];
        char *p = single_update;

        if (!test("f", p))
            die("'%s' not found.", p);
#if _WIN32 || __DJGPP__
        for (; *p; p++)
            if (*p == '\\')
                *p = '/';
        p = single_update;
#define LOCATEFLAG MATCH_AT_FIRST|IGNORE_CASE
#else
#define LOCATEFLAG MATCH_AT_FIRST
#endif
        if (isabspath(p)) {
            char *q = locatestring(p, cwd, LOCATEFLAG);

            if (q && *q == '/')
                snprintf(regular_path_name, MAXPATHLEN, "./%s", q + 1);
            else
                die("path '%s' is out of the project.", p);

        } else {
            if (p[0] == '.' && p[1] == '/')
                snprintf(regular_path_name, MAXPATHLEN, "%s", p);
            else
                snprintf(regular_path_name, MAXPATHLEN, "./%s", p);
        }
        single_update = regular_path_name;
    }
    /*
     * Decide directory (dbpath) in which gtags make tag files.
     *
     * Gtags create tag files at current directory by default.
     * If dbpath is specified as an argument then use it.
     * If the -i option specified and both GTAGS and GRTAGS exists
     * at one of the candidate directories then gtags use existing
     * tag files.
     */
    if (iflag) {
        if (argc > 0)
            realpath(*argv, dbpath);
        else if (!gtagsexist(cwd, dbpath, MAXPATHLEN, vflag))
            strlimcpy(dbpath, cwd, sizeof(dbpath));
    } else {
        if (argc > 0)
            realpath(*argv, dbpath);
        else if (Oflag) {
            char *objdir = getobjdir(cwd, vflag);

            if (objdir == NULL)
                die("Objdir not found.");
            strlimcpy(dbpath, objdir, sizeof(dbpath));
        } else
            strlimcpy(dbpath, cwd, sizeof(dbpath));
    }
    if (iflag && (!test("f", makepath(dbpath, dbname(GTAGS), NULL)) ||
                  !test("f", makepath(dbpath, dbname(GRTAGS), NULL)) ||
                  !test("f", makepath(dbpath, dbname(GPATH), NULL)))) {
        if (wflag)
            warning("GTAGS, GRTAGS or GPATH not found. -i option ignored.");
        iflag = 0;
    }
    if (!test("d", dbpath))
        die("directory '%s' not found.", dbpath);
    if (vflag)
        fprintf(stderr, "[%s] Gtags started.\n", now());
    /*
     * initialize parser.
     */
    if (vflag && gtags_parser)
        fprintf(stderr, " Using plug-in parser.\n");
    parser_init(langmap, gtags_parser);
    if (vflag && file_list)
        fprintf(stderr, " Using '%s' as a file list.\n", file_list);
    /*
     * Start statistics.
     */
    init_statistics();
    /*
     * incremental update.
     */
    if (iflag) {
        /*
         * Version check. If existing tag files are old enough
         * gtagsopen() abort with error message.
         */
        GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
        gtags_close(gtop);
        /*
         * GPATH is needed for incremental updating.
         * Gtags check whether or not GPATH exist, since it may be
         * removed by mistake.
         */
        if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
            die("Old version tag file found. Please remake it.");
        (void)incremental(dbpath, cwd);
        print_statistics(statistics);
        exit(0);
    }
    /*
     * create GTAGS and GRTAGS
     */
    createtags(dbpath, cwd);
    /*
     * create idutils index.
     */
    if (Iflag) {
        FILE *op;
        GFIND *gp;
        const char *path;

        tim = statistics_time_start("Time of creating ID");
        if (vflag)
            fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
        strbuf_reset(sb);
        /*
         * Since idutils stores the value of PWD in ID file, we need to
         * force idutils to follow our style.
         */
#if _WIN32 || __DJGPP__
        strbuf_puts(sb, "mkid --files0-from=-");
#else
        strbuf_sprintf(sb, "PWD=%s mkid --files0-from=-", quote_shell(cwd));
#endif
        if (vflag)
            strbuf_puts(sb, " -v");
        strbuf_sprintf(sb, " --file=%s/ID", quote_shell(dbpath));
        if (vflag) {
#ifdef __DJGPP__
            if (is_unixy())	/* test for 4DOS as well? */
#endif
                strbuf_puts(sb, " 1>&2");
        } else {
            strbuf_puts(sb, " >" NULL_DEVICE);
#ifdef __DJGPP__
            if (is_unixy())	/* test for 4DOS as well? */
#endif
                strbuf_puts(sb, " 2>&1");
        }
        if (debug)
            fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
        op = popen(strbuf_value(sb), "w");
        if (op == NULL)
            die("cannot execute '%s'.", strbuf_value(sb));
        gp = gfind_open(dbpath, NULL, GPATH_BOTH);
        while ((path = gfind_read(gp)) != NULL) {
            fputs(path, op);
            fputc('\0', op);
        }
        gfind_close(gp);
        if (pclose(op) != 0)
            die("terminated abnormally '%s' (errno = %d).", strbuf_value(sb), errno);
        if (test("f", makepath(dbpath, "ID", NULL)))
            if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
                die("cannot chmod ID file.");
        statistics_time_end(tim);
    }
    if (vflag)
        fprintf(stderr, "[%s] Done.\n", now());
    closeconf();
    strbuf_close(sb);
    print_statistics(statistics);

    return 0;
}
Exemple #16
0
static rational lass(rational *A, int LastPlane_, int d)
/* A has exact dimension (LastPlane_+1)*(d+1). The function returns
   the volume; an underscore is appended to LastPlane_ and d */

{   rational * redA;            /* A reduced by one dimension and constraint */
    int i, j;
    T_LassInt baserow = 0, basecol = 0, col;
    int dimdiff, row;         /* dimension difference */
    boolean store_volume;
    boolean i_balance = FALSE;
    rational ma, mi, *volume, *realp1, *realp2;
    int Index_needed;         /* Boolean, if index operations are needed */
    T_LassInt * Del_index = NULL; /* contains the indices of the deleted planes */

    /* test if volume is already known and return it if so */

    dimdiff = G_d-d;
    if ((G_Storage > (dimdiff-2)) && (dimdiff >= 2)) {
        tree_out (&tree_volumes, &i_balance, key, &volume, &keyfound, KEY_PLANES_VAR);
        if ((*volume)>=0)  {  /* this volume has already been computed */
	    #ifdef STATISTICS
		Stat_CountRetrieved [d] ++;
	    #endif
	    return (*volume)*scale(dimdiff, 
	                           keyfound->hypervar.variables,
				   key.hypervar.variables);
	}
        (*volume)=0;      /* initialize */
        store_volume=TRUE;
        #ifdef STATISTICS
           Stat_CountStored [d] ++;
        #endif
    }
    else store_volume=FALSE;

    /* if d==1 compute the volume and give it back */

    if (d == 1) {
	ma=-MAXIMUM;
	mi= MAXIMUM;
	for (i=0; i<=LastPlane_; i++,A+=2) { 
	    if (*A>EPSILON_LASS) { if ((*(A+1)/ *A)<mi) mi=(*(A+1)/ *A); }
	    else if (*A<-EPSILON_LASS) { if ((*(A+1)/ *A)>ma) ma=*(A+1)/ *A; } 
            else if ((*(A+1))<-(100000*EPSILON_LASS)) return 0; 
	}
	if ((ma<-.5*MAXIMUM)||(mi>.5*MAXIMUM)) {
	    printf("\nVolume is unbounded!\n");
	    exit(0);
	}
	if ((mi-ma)>EPSILON_LASS) {
	    if (store_volume) (*volume)=mi-ma;
	    return mi-ma;
	}
	return 0;
    }

    /* if d>1 apply the recursive scheme by fixing constraints. */

    Index_needed = (G_Storage>(G_d-d-1));
    if (Index_needed){
	if (!(Del_index = (T_LassInt *) my_malloc ((LastPlane_ + 2) * sizeof (T_LassInt)))){
	    fprintf (stderr, "\n***** ERROR/WARNING: Out of memory in 'lass'\n");
	    exit(0);
	};
        Del_index[0]=G_m+2;   /* initialize: mark end */
    }
    ma=0;                                         /* used to sum up the summands */
    if (norm_and_clean_constraints(A, &LastPlane_, d, Del_index, Index_needed)!=0)
        goto label2;

    /* if appropriate shift polytope */

    if (d>=LaShiftLevel) {
	realp1=A+d;
	realp2=realp1+LastPlane_*(d+1);
	j=0;
	while (realp1<=realp2) {
	    if (fabs(*realp1)<EPSILON_LASS) j++;
	    realp1+=d+1;
	}
	if (d-j>=LaShift) shift_P(A, LastPlane_, d);
    }


    redA = (rational *) my_malloc (LastPlane_* d*sizeof(rational));
    if (redA == NULL) {
	fprintf (stderr, "\n***** ERROR/WARNING: Out of memory in 'lass.*redA'\n");
	exit(0);
    }
#ifdef ReverseLass
    for (row=LastPlane_; row>=0; row--) {
#else
    for (row=0; row<=LastPlane_; row++) {
#endif
	if (fabs(*(A+row*(d+1)+d))<EPSILON_LASS) 
            continue;                        /* skip this constraint if b_row == 0 */
	if (Index_needed)
	{  baserow=add_reduced_index(row, NULL, All_index);
           p2c[G_d-d][1] = baserow;
	   add_hypervar (baserow, G_d+1, &key);
	}	
	memcpy(&pivotrow[0], A+row*(d+1), sizeof(rational)*(d+1));
	col=0;                               /* search for pivot column */
	for (i=0; i<d; i++) {        
#if PIVOTING_LASS == 0
	    if (fabs(pivotrow[i])>=MIN_PIVOT_LASS) {col=i; break;};
#endif
	    if (fabs(pivotrow[i])>fabs(pivotrow[col])) col=i;
	};
	if (G_Storage>(G_d-d-1))
	{  basecol=add_reduced_index(col, NULL, Pivot);
           p2c[G_d-d][0] = basecol;
	   add_hypervar (G_m+1, basecol, &key);
	}

        /* copy A onto redA and at the same time perform pivoting */
	 
	mi=1.0/pivotrow[col];
	for (i=0; i<=d; i++) pivotrow[i]*=mi;
	realp1=A;
	realp2=redA;
	for (i=0; i<=LastPlane_; i++) {
	    if (i==row) {
		realp1+=d+1;
		continue;
	    };
	    mi=*(A+(i*(d+1))+col);
	    for (j=0; j<=d; j++) {
		if (j==col) {
		    realp1++;
		    continue;
		};
		*realp2=(*realp1)-pivotrow[j]*mi;
		realp1++;
		realp2++;
	    };
	};
	ma+= *(A+row*(d+1)+d)/(d*fabs(*(A+row*(d+1)+col)))
	     *lass(redA, LastPlane_-1, d-1);
        if (Index_needed)
        {  rm_original_inElAll_index(baserow);
           delete_hypervar (baserow, G_d+1, &key);
        }
	if (G_Storage>(G_d-d-1))
	{  del_original(basecol, Pivot);
	   delete_hypervar (G_m+1, basecol, &key);
	}
        #ifdef verboseFirstLevel
            if (d==G_d) 
	        printf("\nVolume accumulated to iteration %i is %20.12f",row,ma );
        #endif
    };
    my_free (redA, LastPlane_* d * sizeof (rational));
    label2: 
    if (Index_needed) {
	del_original_indices(Del_index, All_index);
        my_free (Del_index, (LastPlane_ + 2) * sizeof (T_LassInt));
    };
    if (store_volume)(*volume)=ma;
    return ma;
}

/****************************************************************************************/

void volume_lasserre_file (rational *volume, char *planesfile)

{  int i;

   read_hyperplanes (planesfile);
   if (G_m > 254)
   {  fprintf (stderr, "\n***** ERROR: Trying to use 'rlass' with more than 254 hyperplanes.");
      fprintf (stderr, "\nThis restriction can be changed, though. Please contact the authors.\n");
      exit (0);
   }
   if (G_Storage > G_d - 3)
      G_Storage = G_d - 3;
      /* necessary to prevent memory waste because in the tree arrays of length         */
      /* G_Storage + 2 are allocated                                                    */

   pivotrow = (rational *) my_malloc ((G_d + 1) * sizeof (rational));
   All_index = (T_LassInt *) my_malloc ((G_m + 1) * sizeof (T_LassInt));
   Pivot = (T_LassInt *) my_malloc ((G_d + 1) * sizeof (T_LassInt));
   p2c = (int **) my_malloc (G_d * sizeof (int *));
   for (i=0; i<G_d; i++){
       p2c[i] = (int *) my_malloc (2 * sizeof (int));
   }
   A=compact();
   planescopy=compact();
   tree_volumes = NULL;
   create_key (&key, KEY_PLANES_VAR);
   key.hypervar.hyperplanes [0] = G_m + 1;
   key.hypervar.variables [0] = G_d + 1;
   All_index[0]=G_m+2;  /* initialization (end mark) */
   Pivot[0]=G_m+2;	/* initialization (end mark) */
#ifdef STATISTICS
   init_statistics ();
#endif
   *volume = lass (A, G_m-1, G_d);

/*
   free_key (key, KEY_PLANES_VAR);
*/
}
Exemple #17
0
/* ********************************************************************
 * MAIN PROGRAM
 *
 * Read the user option of the commandline and either print to stdout
 * or return the value over the socket. 
 *
 * ********************************************************************	*/  
int main(int argc, char **argv)  
{  
	int i,c;
	int errflg = 0;
	int repeats = 1;
	int temp = 0;
	int temp_int, temp_frac;				// interger and fracture part for temperature
	
	char *hostname = "localhost";			// Default setting for our host == this host
	char *port = PORT;						// default port, 5000
	char snd_buf[256];
	
    extern char *optarg;
    extern int optind, optopt;

	// ------------------------- COMMANDLINE OPTIONS SETTING ----------------------
	// Valid options are:
	// -h <hostname> ; hostname or IP address of the daemon
	// -p <port> ; Portnumber for daemon socket
	// -v ; Verbose, Give detailed messages
	//
    while ((c = getopt(argc, argv, ":c:dh:p:r:stvx")) != -1) {
        switch(c) {

		case 'c':
			cflg = 1;					// Checks
			checks = atoi(optarg);
		break;
		case 'd':						// Daemon mode, cannot be together with test?
			dflg = 1;
		break;
		case 'h':						// Socket communication
            dflg++;						// Need daemon flag too, (implied)
			hostname = optarg;
		break;
		case 'p':						// Port number
            port = optarg;
           dflg++;						// Need daemon flag too, (implied)
        break;
		case 'r':						// repeats
			repeats = atoi(optarg);
		break;
		case 's':						// Statistics
			sflg = 1;
		break;
		case 't':						// Test Mode, do debugging
			debug=1;
		break;
		case 'v':						// Verbose, output long timing/bit strings
			verbose = 1;
		break;
		case ':':       				// -f or -o without operand
			fprintf(stderr,"Option -%c requires an operand\n", optopt);
			errflg++;
		break;
		case '?':
			fprintf(stderr, "Unrecognized option: -%c\n", optopt);
            errflg++;
        }
    }
	
	// -------------------- PRINT ERROR ---------------------------------------
	// Print error message if parsing the commandline
	// was not successful
	
    if (errflg) {
        fprintf(stderr, "usage: argv[0] (options) \n\n");
		
		fprintf(stderr, "-d\t\t; Daemon mode. Codes received will be sent to another host at port 5000\n");
		fprintf(stderr, "-s\t\t; Statistics, will gather statistics from remote\n");
		fprintf(stderr, "-t\t\t; Test mode, will output received code from remote\n");
		fprintf(stderr, "-v\t\t; Verbose, will output more information about the received codes\n");
        exit (2);
    }
	

	//	------------------ PRINTING Parameters ------------------------------
	//
	if (verbose == 1) {
		printf("The following options have been set:\n\n");
		printf("-v\t; Verbose option\n");
		if (statistics>0)	printf("-s\t; Statistics option\n");
		if (dflg>0)			printf("-d\t; Daemon option\n");
		if (debug)			printf("-t\t; Test and Debug option");
		printf("\n");						 
	}//if verbose
	
	// If we are in daemon mode, initialize sockets etc.
	//
	if (dflg) {
		daemon_mode(hostname, port);
	}
	
	if (sflg) {
		fprintf(stderr,"init statistics\n");
		init_statistics(statistics);			// Make cells 0
	}
	
	chdir (SPATH);
	
	// ------------------------
	// MAIN LOOP
	// 

	if (verbose) printf("\nRepeats: %d::\n",repeats);
	for (i=0; i<repeats; i++)  
	{  
		// For every directory found in SPATH
		DIR *dir;
		struct dirent *ent;
		if ((dir = opendir (SPATH)) != NULL) {
			/* print all the files and directories within directory */
			while ((ent = readdir (dir)) != NULL) {
				if (verbose) printf ("%s\n", ent->d_name);
				// 28 is the prefix for ds18b20
				if (strncmp(ent->d_name,"28",2) == 0)
				{
					temp = ds18b20_read(ent->d_name);
					temp_int = temp/1000;
					temp_frac = temp%1000;
					
					if (dflg) {
					// Daemon, output to socket
						sprintf(snd_buf, 					 "{\"tcnt\":\"%d\",\"action\":\"weather\",\"brand\":\"ds18b20\",\"type\":\"json\",\"address\":\"%s\",\"channel\":\"%d\",\"temperature\":\"%d.%d\",\"humidity\":\"%d\",\"windspeed\":\"%d\",\"winddirection\":\"%d\"}", 
						socktcnt%1000,
						ent->d_name,
						0,
						temp_int,
						temp_frac,
						0,
						0,
						0);
					
						// Do NOT use check_n_write_socket as weather stations will not
						// send too many repeating messages (1 or 2 will come in one trasmission)
						//
						if (write(sockfd, snd_buf, strlen(snd_buf)) == -1) {
							fprintf(stderr,"socket write error\n");
						}	
						socktcnt++;
						delay(200);
						
						if (verbose) printf("Buffer sent to Socket: %s\n",snd_buf);
					}
					else {
					// Commandline
						if (temp > 0) {
							printf("Temperature for dev %s: %d.%d\n",
								ent->d_name, temp/1000,temp%1000);
						}
						else {
							temp = -temp;
							printf("Temperature for dev %s: -%d.%d\n",
								ent->d_name, temp/1000,temp%1000);
						}
					}
				}
			}
			closedir (dir);
		} else {
  			/* could not open directory */
 			 perror ("No such directory ");
			return EXIT_FAILURE;
		}
	}
	delay(1500);
	// Should wait for confirmation of the daemon before closing
	
	exit(EXIT_SUCCESS); 
}  
void AdaptiveFreeList<Chunk>::initialize() {
  FreeList<Chunk>::initialize();
  set_hint(0);
  init_statistics(true /* split_birth */);
}
Exemple #19
0
void                    classifyDatasetTT(dataset *train, dataset *test, distances *distanceSet, criteria *criterias, mParameters *param)
{
    char                *outputStr;
    FILE                *distFile, **outputFile;
    int                 t1, t2, i, k, c, l = 0;
    float               ***distSet, **tmpSet;
    float               *bestScores, *spaceScores;
    int                 *trueCompute, *curCompute;
    int                 classFound, nbDist, nbComb = 0;
    statistics          **criteriaStats, **bestStats, **spaceStats;
    series              *ts1, *ts2;
    
    distSet = malloc(test->cardinality * sizeof(float **));
    tmpSet = malloc(train->cardinality * sizeof(float *));
    trueCompute = distanceSet->compute;
    curCompute = calloc(distanceSet->nb_distances, sizeof(int));
    outputStr = calloc(1024, sizeof(char));
    outputFile = calloc(criterias->nb_criteria + 1, sizeof(FILE *));
    criteriaStats = calloc(criterias->nb_criteria, sizeof(statistics *));
    bestStats = calloc(criterias->nb_criteria, sizeof(statistics *));
    spaceStats = calloc(criterias->nb_criteria, sizeof(statistics *));
    bestScores = calloc(criterias->nb_criteria, sizeof(float));
    spaceScores = calloc(criterias->nb_criteria, sizeof(float));
    for (i = 0; i < criterias->nb_criteria; i++)
    {
        bestScores[i] = 1.0;
        spaceScores[i] = 1.0;
        criteriaStats[i] = init_statistics(train->nb_classes);
        sprintf(outputStr, "%s/%s/results/%s.txt", param->output, train->name, criterias->name[i]);
        outputFile[i] = fopen(outputStr, "w");
    }
    sprintf(outputStr, "%s/%s/results/globalResults.txt", param->output, train->name);
    outputFile[criterias->nb_criteria] = fopen(outputStr, "w");
    for (t1 = 0; t1 < test->cardinality; t1++)
    {
        distSet[t1] = calloc(train->cardinality, sizeof(float *));
        for (t2 = 0; t2 < train->cardinality; t2++)
            distSet[t1][t2] = calloc(distanceSet->nb_distances, sizeof(float));
        for (i = 0; i < distanceSet->nb_distances; i++)
            if (distanceSet->compute[i])
            {
                #pragma omp parallel for
                for (t2 = 0; t2 < train->cardinality; t2++)
                {
                    ts1 = test->data[t1];
                    ts2 = train->data[t2];
                    distSet[t1][t2][i] = distanceSet->functions[i](ts1, ts2, distanceSet->best[i]);
                }
            }
    }
    for (i = 0; i < distanceSet->nb_distances; i++)
        if (distanceSet->compute[i])
        {
            sprintf(outputStr, "%s/%s/distances/test_%s.txt", param->output, train->name, distanceSet->name[i]);
            distFile = fopen(outputStr, "w");
            for (t1 = 0; t1 < test->cardinality; t1++)
            {
                for (t2 = 0; t2 < train->cardinality; t2++)
                    fprintf(distFile, "%f ", distSet[t1][t2][i]);
                fprintf(distFile, "\n");
            }
            fclose(distFile);
        }
    if (param->combineAll)
    {
        for (i = 0; i < distanceSet->nb_distances; i++)
            if (distanceSet->compute[i])
                nbComb++;
        nbComb = pow(2, nbComb);
    }
    for (c = 1; c < nbComb; c++)
    {
        for (k = c, l = 0, nbDist = 0; l < distanceSet->nb_distances; l++)
            if (trueCompute[l]) { curCompute[l] = (k & 0x1); k >>= 1; nbDist += curCompute[l];}
        for (i = 0; i < criterias->nb_criteria; i++)
            empty_statistics(criteriaStats[i]);
        for (t1 = 0; t1 < test->cardinality; t1++)
        {
            for (t2 = 0; t2 < train->cardinality; t2++)
            {
                tmpSet[t2] = calloc(nbDist, sizeof(float));
                for (l = 0, k = 0; l < distanceSet->nb_distances; l++)
                    if (curCompute[l])
                        tmpSet[t2][k++] = distSet[t1][t2][l];
            }
            normalize_distance(tmpSet, nbDist, train->cardinality);
            for (i = 0; i < criterias->nb_criteria; i++)
                if (criterias->compute[i])
                {
                    classFound = criterias->functions[i](tmpSet, train->classes, train->cardinality, nbDist, -1, train->nb_classes);
                    criteriaStats[i]->confusionMatrix[test->classes[t1]][classFound]++;
                    if (classFound != test->classes[t1])
                    {
                        criteriaStats[i]->classesErrors[test->classes[t1]]++;
                        criteriaStats[i]->nbErrors++;
                    }
                }
            for (t2 = 0; t2 < train->cardinality; t2++)
                free(tmpSet[t2]);
        }
        for (k = 0; k < (criterias->nb_criteria + 1); k++)
        {
            for (i = 0; i < distanceSet->nb_distances; i++)
                if (curCompute[i])
                    fprintf(outputFile[k], "%s ", distanceSet->name[i]);
            fprintf(outputFile[k], ":\n");
            if (k < criterias->nb_criteria)
            {
                criteriaStats[k]->error = (float)criteriaStats[k]->nbErrors / (float)test->cardinality;
                export_statistics(outputFile[k], criteriaStats[k]);
                if (criteriaStats[k]->error < bestScores[k])
                {
                    bestScores[k] = criteriaStats[k]->error;
                    if (bestStats[k] != NULL)
                        free(bestStats[k]);
                    bestStats[k] = duplicate_statistics(criteriaStats[k]);
                }
                if (c == criterias->bestSpaceID[k])
                {
                    spaceStats[k] = duplicate_statistics(criteriaStats[k]);
                    spaceScores[k] = criteriaStats[k]->error;
                }
                continue;
            }
            for (i = 0; i < criterias->nb_criteria; i++)
                fprintf(outputFile[k], "%f ", criteriaStats[i]->error);
            fprintf(outputFile[k], "\n");
        }
    }
    fprintf(outputFile[criterias->nb_criteria], "Best statistics :\n");
    for (i = 0; i < criterias->nb_criteria; i++)
        fprintf(outputFile[criterias->nb_criteria], "%f ", bestStats[i]->error);
    fprintf(outputFile[criterias->nb_criteria], "\n");
    fprintf(outputFile[criterias->nb_criteria], "Space statistics :\n");
    for (i = 0; i < criterias->nb_criteria; i++)
        fprintf(outputFile[criterias->nb_criteria], "%f ", spaceStats[i]->error);
    fprintf(outputFile[criterias->nb_criteria], "\n");
    for (i = 0; i < criterias->nb_criteria; i++)
    {
        fprintf(outputFile[i], "Best statistics :\n");
        export_statistics(outputFile[i], bestStats[i]);
        fprintf(outputFile[i], "Space statistics :\n");
        export_statistics(outputFile[i], spaceStats[i]);
        free_statistics(criteriaStats[i]);
        free_statistics(bestStats[i]);
        free_statistics(spaceStats[i]);
        fclose(outputFile[i]);
    }
    fclose(outputFile[i]);
    for (t1 = 0; t1 < test->cardinality; t1++)
    {
        for (t2 = 0; t2 < train->cardinality; t2++)
            free(distSet[t1][t2]);
        free(distSet[t1]);
    }
    free(bestScores);
    free(spaceScores);
    free(bestStats);
    free(spaceStats);
    free(criteriaStats);
    free(tmpSet);
    free(curCompute);
    free(outputStr);
    free(outputFile);
    free(distSet);
    return;
}