Exemplo n.º 1
0
int read_args(int argc, char *argv[]){
	int ret = 0;
	global_args.args = (char *)malloc(ARGMAXNUM * sizeof(char));
	while((ret = getopt(argc, argv, opt_strings)) != -1){
		if(global_args.args_num >= ARGMAXNUM){ free(global_args.args); return -1; }
		if(global_args.last_index == optind) {free(global_args.args); return -1;}
		switch(ret){
			case 'd': if(read_options(&global_args.d_num, global_args.d_options, &global_args, optarg, ret) == -1) { return -1;} break;
			case 'i': ++global_args.i_num; if(global_args.i_num > 1){free(global_args.args); return -1;} global_args.args[global_args.args_num++] = ret; break;
			case 'l': ++global_args.l_num;  if(global_args.l_num > 1){free(global_args.args); return -1;}global_args.args[global_args.args_num++] = ret; break;
			case 'r': if(read_options(&global_args.r_num, global_args.r_options, &global_args, optarg, ret) == -1) {return -1;} break;
			case 'o': if(read_options(&global_args.o_num, global_args.o_options, &global_args, optarg, ret) == -1) {return -1;} break;
			case 'x': if(read_options(&global_args.x_num, global_args.x_options, &global_args, optarg, ret) == -1) {return -1;} break;
			default: free(global_args.args); return -1;
		}
		global_args.last_index = optind;
	}
	if(global_args.args_num <= 1 || global_args.args_num > 3){ free(global_args.args); return -1; }
	if(global_args.d_num == 0){free(global_args.args); return -1;}
	if((global_args.args_num == 3)){
		if(!(global_args.r_num & global_args.o_num)){free(global_args.args); printf("before return -1\n"); return -1;}
	}
	if(global_args.d_num > 1 || global_args.i_num > 1 || global_args.l_num > 1 || global_args.r_num > 1 || global_args.o_num > 1 || global_args.x_num > 1) {free(global_args.args); return -1;}
	if(global_args.r_num ^ global_args.o_num){free(global_args.args); return -1;}
	return 0;
}
/**
 * Main routine
 */
int main(int argc, char** argv)
{
    problem_t problem;
    read_options(argc, argv, &problem);

    clock_t start = clock(), diff; //Clocking

    if (problem.verbose) {
        for (int i = 0; i < problem.g; ++i) {
            printf("\nGeneration %d\n", i);
            print_board(&problem);
            advance_board(&problem, 1);
        }
    } else {
#ifdef WITH_TIMING
        double t0 = omp_get_wtime();
        advance_board(&problem, problem.g);
        double t1 = omp_get_wtime();
        printf("Cells / sec: %e\n",
               problem.g * problem.nboard * problem.nboard / (t1-t0));
#else
        advance_board(&problem, problem.g);
<<<<<<< HEAD

    diff = clock() - start; //get the time and print the result
    int msec = diff*1000/CLOCKS_PER_SEC;
    printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);

=======
#endif
    }
>>>>>>> upstream/master
Exemplo n.º 3
0
FC_nonp_variance_varselection::FC_nonp_variance_varselection(MASTER_OBJ * mp,
                 unsigned & enr, GENERAL_OPTIONS * o,
                 DISTR * lp, const ST::string & t,const ST::string & fp,
                 DESIGN * Dp,FC_nonp * FCn,vector<ST::string> & op,
                 vector<ST::string> & vn)
     : FC_nonp_variance(mp,enr,o,lp,t,fp,Dp,FCn,op,vn)
  {

  read_options(op,vn);

  FC_delta = FC(o,"",1,1,"");
  FC_delta.setbeta(1,1,1);

  FC_psi2 = FC(o,"",1,1,"");
  FC_psi2.setbeta(1,1,0.5);


  FC_omega = FC(o,"",1,1,"");

  FC_omega.setbeta(1,1,0.5);


  a_omega = 1;

  b_omega = 1;


  v = 5;

  Q = 25;


  }
Exemplo n.º 4
0
int
init_options(int no_config)
{
    // Custom user conf file
    char *userconf = NULL;
    char *rcfile;
    char pwd[MAX_SETTING_LEN];

    // Defualt savepath is current directory
    if (getcwd(pwd, MAX_SETTING_LEN)) {
        setting_set_value(SETTING_SAVEPATH, pwd);
    }

    // Initialize settings
    setting_set_value(SETTING_FILTER_METHODS, "REGISTER,INVITE,SUBSCRIBE,NOTIFY,OPTIONS,PUBLISH,MESSAGE");

    // Add Call list column options
    set_option_value("cl.column0", "index");
    set_option_value("cl.column1", "method");
    set_option_value("cl.column2", "sipfrom");
    set_option_value("cl.column3", "sipto");
    set_option_value("cl.column4", "msgcnt");
    set_option_value("cl.column5", "src");
    set_option_value("cl.column6", "dst");
    set_option_value("cl.column7", "state");

	// Done if config file should not be read
	if(no_config) {
		return 0;
	}

    // Read options from configuration files
    read_options("/etc/sngreprc");
    read_options("/usr/local/etc/sngreprc");
    // Get user configuration
    if ((rcfile = getenv("SNGREPRC"))) {
        read_options(rcfile);
    } else if ((rcfile = getenv("HOME"))) {
        if ((userconf = sng_malloc(strlen(rcfile) + RCFILE_EXTRA_LEN))) {
            sprintf(userconf, "%s/.sngreprc", rcfile);
            read_options(userconf);
            sng_free(userconf);
        }
    }

    return 0;
}
Exemplo n.º 5
0
SolverUnconstrained<Data,Problem>::SolverUnconstrained( Data const& __data )
    :
    M_prob( __data ),
    M_solver_stats ( this, true ),
    M_theta( M_prob.lowerBounds(), M_prob.upperBounds() )
{
    read_options();
}
Exemplo n.º 6
0
SolverUnconstrained<Data,Problem>::SolverUnconstrained( value_type x_definitions[_E_n][3] )
    :
    M_prob( x_definitions ),
    M_solver_stats ( this, true ),
    M_theta( _E_n )
{
    read_options();
}
Exemplo n.º 7
0
/*
 * main()
 *
 */
int main(int argc, char **argv)
{
	ocfs2_filesys *fs = NULL;
	errcode_t ret = 0;
	int i;

	initialize_ocfs_error_table();

#define INSTALL_SIGNAL(sig)					\
	do {							\
		if (signal(sig, handle_signal) == SIG_ERR) {	\
		    fprintf(stderr, "Could not set " #sig "\n");\
		    goto bail;					\
		}						\
	} while (0)

	INSTALL_SIGNAL(SIGTERM);
	INSTALL_SIGNAL(SIGINT);

	memset(corrupt, 0, sizeof(corrupt));

	ret = read_options(argc, argv);
	if (ret < 0)
		goto bail;

	print_version();

	ret = ocfs2_open(device, OCFS2_FLAG_RW, 0, 0, &fs);
	if (ret) {
		com_err(progname, ret, "while opening \"%s\"", device);
		goto bail;
	}

	for (i = 0; i < NUM_FSCK_TYPE; ++i) {
		if (corrupt[i]) {
			if (!prompt_codes[i].pc_func) {
				fprintf(stderr, "Unimplemented corrupt code "
					"= %s\n", prompt_codes[i].pc_codestr);
				continue;
			}
			fprintf(stdout, "%s: Corrupting %s with code %s (%d)\n",
				progname, device, prompt_codes[i].pc_codestr,
				prompt_codes[i].pc_codenum);
			prompt_codes[i].pc_func(fs, prompt_codes[i].pc_codenum,
						slotnum);
		}
	}

bail:
	if (fs) {
		ret = ocfs2_close(fs);
		if (ret)
			com_err(progname, ret, "while closing \"%s\"", device);
	}

	return ret;
}					/* main */
Exemplo n.º 8
0
int main (int argc, char **argv)
{
	ocfs2_filesys *fs = NULL;
	errcode_t ret = 1;

	initialize_ocfs_error_table();

#define INSTALL_SIGNAL(sig)					\
	do {							\
		if (signal(sig, handle_signal) == SIG_ERR) {	\
		    printf("Could not set " #sig "\n");		\
		    goto bail;					\
		}						\
	} while (0)

	INSTALL_SIGNAL(SIGTERM);
	INSTALL_SIGNAL(SIGINT);

	memset(&options, 0, sizeof(options));
	if (read_options(argc, argv)) {
		usage(progname);
		goto bail;
	}

	if (!device || !options.ops)
		goto bail;

	ret = ocfs2_open(device, OCFS2_FLAG_RW, 0, 0, &fs);
	if (ret) {
		com_err(progname, ret, "while opening \"%s\"", device);
		goto bail;
	}

	srand((unsigned long)fs);

	switch (options.ops) {
		case CREATE_LOCAL_ALLOC:
			ret = create_local_alloc(fs, options.slot);
			break;

		case CREATE_ORPHAN_FILE:
			ret = create_orphan_file(fs, options.slot);
			break;

		case CREATE_TRUNCATE_LOG:
			ret = create_truncate_log(fs, options.slot);
			break;
	}
bail:
	if (fs)
		ocfs2_close(fs);

	return ret;
}
Exemplo n.º 9
0
Arquivo: ebizzy.c Projeto: 1587/ltp
int main(int argc, char *argv[])
{
	read_options(argc, argv);

	allocate();

	write_pattern();

	start_threads();

	return 0;
}
Exemplo n.º 10
0
int main(int argc, char * argv[])
{
	VideoCapture capture;

	// Read options
	read_options(argc, argv,capture);
	Mat frame;
	Mat first;
	if (argc==1)
	{
		capture.open(0);
	}
	// Init camera
	if (!capture.isOpened())
	{
		cout<<"capture device failed to open!"<<endl;
		return -1;
	}

	//display video frame rate
	float rate=capture.get(CV_CAP_PROP_FPS);
	cout<<"rate="<<rate<<endl;

	//
	cout<<"totalframenumber="<<capture.get(CV_CAP_PROP_FRAME_COUNT)<<endl;

	//Register mouse callback to draw the bounding box
	cvNamedWindow("Tracker", CV_WINDOW_AUTOSIZE);
	cvSetMouseCallback("Tracker", mouseHandler, NULL );
	//save img path
	string imgFormat=".\\imgs\\img%05d.png";
	char image_name[256];

	if (fromfile)
	{
		capture.set(CV_CAP_PROP_POS_FRAMES,0*rate);
		capture >> frame;
		frameCount++;
		frame.copyTo(first);
		//show fame num
		stringstream buf;
		buf << frameCount;
		string num = buf.str();
		putText(frame, num, Point(15, 30), FONT_HERSHEY_SIMPLEX, 1, Scalar(100, 0, 255), 3);
		//show
		imshow("Tracker", frame);
		//save
		sprintf(image_name, imgFormat.c_str(), frameCount);
		imwrite(image_name,frame);
	}
	else
	{
Exemplo n.º 11
0
DESIGN_mrf::DESIGN_mrf(datamatrix & dm,datamatrix & iv,
                       GENERAL_OPTIONS * o,DISTR * dp,FC_linear * fcl,
                       const MAP::map & m,vector<ST::string> & op,
                       vector<ST::string> & vn)
                      : DESIGN(o,dp,fcl)
  {

  if (errors==false)
    {

    read_options(op,vn);

    discrete = true;

    ma = m;
    type = Mrf;

    nrpar = ma.get_nrregions();
    consecutive=true;

    Zout = datamatrix(nrpar,1,1);
    index_Zout = statmatrix<int>(Zout.rows(),1);
    index_Zout.indexinit();
    }

  if (errors==false)
    init_data(dm,iv);

  if (errors==false)
    {
    compute_penalty();

    XWX = envmatdouble(0,nrpar);
    XWres = datamatrix(nrpar,1);
    Wsum = datamatrix(nrpar,1,1);

    compute_precision(1.0);

    compute_basisNull();

    identity=true;
    }

/*
  ofstream out("c:\\bayesx\\trunk\\testh\\results\\dm.raw");
  dm.prettyPrint(out);

  ofstream out2("c:\\bayesx\\trunk\\testh\\results\\iv.raw");
  iv.prettyPrint(out2);
*/

  }
Exemplo n.º 12
0
/*----------------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
	STUFFS things;

	/* print tool info */
	printf("\n%s - 8085 Cross Assembler (version-%s)\n",PROGNAME,PROGVERS);
	printf("  => by [email protected]\n\n");

	/* initialize main data structure */
	initialize(&things);

	/* false do-while loop - for error exits */
	do
	{
		/* get parameters */
		if(read_options(&things,argc,argv)<0)
			break;

		/* first pass - build label db */
		things.pass = EXEC_PASS_1;
		if(process_asmfile(&things)>0)
			break;

		/* second pass - arrange code */
		things.pass = EXEC_PASS_2;
		if(process_asmfile(&things)>0)
			break;

		/* write HEX file */
		if(things.opt_flag&OPT_GENERATE_HEX)
			write_ihex(&things);

		/* write vmf file */
		if(things.opt_flag&OPT_GENERATE_VMF)
			write_vlog(&things);
	}
	while(0);

	/* reset error if showed usage */
	if(things.errc==ERROR_SHOW_USAGE) things.errc = 0;

	/* clean-up main data structure */
	cleanup(&things);

	/* print end indicator */
	printf("\n%s - Done! (%d)\n\n", PROGNAME, things.errc);

	return things.errc;
}
Exemplo n.º 13
0
int main(int argc, char** argv)
{
    //the options struct holds all run-time options. 
    options opt; 
    opt.overwrite = false ; 
    opt.gaussBool = false ; //Initialize --overwrite flag to false. Probably should handle 
                                //this in read_options. 
    opt.polyFit = false ; 

    vector<double> data ; 
    double avg, std ; 
    vector <vector<double> > hist ; 

    read_options(argc, argv, opt) ; 

    //Print run-time parameters
    cout << "inFile : " << opt.inFile << endl ; 
    cout << "outFile: " << opt.outFile << endl ; 
    cout << "numBins: " << opt.numBins << endl ; 
    cout << "overwrite : " ; 
    if (opt.overwrite) { cout << "True" << endl ; }
    else { cout << "False" << endl; }
    if ( opt.gaussBool ) {
        cout << "Gaussian fit file : " << opt.gaussFile << endl; 
    }
    if ( opt.polyFit ) {
        cout << "Polynomial fit file : " << opt.polyfitFile << endl; 
        cout << "Number of terms : " << opt.numTerms << endl ; 
    }

    //Begin program
    
    data = read_data(opt.inFile)  ; 

    cout << endl; 
    avg = average(data) ; 
    cout << "average = " << avg << endl; 

    std = stdDev(data,avg) ; 
    cout << "std     = " << std << endl ; 

    hist = histogram(data, opt.numBins) ; 
    print(hist,opt.outFile); 
    if (opt.gaussBool) 
        print_gauss(hist, opt.gaussFile, std, avg) ; 
    if (opt.polyFit) 
        fit_polynomial(hist,avg, opt.numTerms, opt.polyfitFile) ; 
    return 0; 
}
Exemplo n.º 14
0
FC_hrandom_variance_vec::FC_hrandom_variance_vec(MASTER_OBJ * mp,unsigned & enr,
        GENERAL_OPTIONS * o,DISTR * lp,
        DISTR * lpRE,
        const ST::string & t,const ST::string & fp,
        DESIGN * Dp,FC_nonp * FCn,vector<ST::string> & op,
        vector<ST::string> & vn)
    : FC_nonp_variance_vec(mp,enr,o,lp,t,fp,Dp,FCn,op,vn)
{
    read_options(op,vn);
    likepRE = lpRE;

    b_invgamma = masterp->level1_likep[equationnr]->trmult*b_invgamma_orig;

//  hyperLambda=rand_gamma(a_invgamma,b_invgamma);
    hyperLambda=0.1;
}
Exemplo n.º 15
0
int
main(int argc, char ** argv) {

  struct swift_context *c = NULL;
  struct client_options opts;
  swift_error e;

  if (!read_options(&opts, argc, argv)) {
    exit(EXIT_FAILURE);
  }
  if (!validate_options(&opts)) {
    exit(EXIT_FAILURE);
  }
  if (opts.filename) {
    opts.datahandle = setupio(&opts); 
  } else {
    if (opts.action == ACTION_OBJ_WRITE) {
      opts.datahandle = stdin;
    } else {
      opts.datahandle = stdout;
    }
  }
  if (!opts.datahandle) {
    exit(EXIT_FAILURE);
  }


  swift_init();
  e = swift_context_create(&c, opts.url, opts.username, opts.password);
  if (e) {
    fprintf(stderr, "Error: %s, line %d\n", swift_errormsg(e), __LINE__);
    exit(EXIT_FAILURE);
  }

  e = execute_action(&opts, c);
  if (e) {
    fprintf(stderr, "Error: %s, line %d\n", swift_errormsg(e), __LINE__);
    exit(EXIT_FAILURE);
  }

  swift_context_delete(&c);

  fclose(opts.datahandle);

  return 0;

}
Exemplo n.º 16
0
//==============================================================================
bool CC_Base::execute(int argc, char *argv[])
{
	po::options_description desc;
	init_options(desc);

	try
	{
		po::variables_map vm;
		po::store(po::parse_command_line(argc, argv, desc), vm);
		po::notify(vm);

		if (vm.count("log"))
			init_log(argc, argv, option_log_name_);

		if (!read_options(desc, vm))
			return false;

		if (init_programmer() && init_unit())
		{
			log_info("main, start task processing");
			process_tasks();
			log_info("main, finish task processing");
			programmer_.unit_close();
			return true;
		}
	}
	catch (std::runtime_error& e) // usb, file error
	{
		std::cout << "  Error occured";
		if (strlen(e.what()))
		{
			std::cout << ": " << e.what();
			log_info("%s", e.what());
		}
		std::cout << "\n";
	}
	catch (po::error& e) //command line error
	{
		std::cout << "  Bad command line options";
		if (strlen(e.what()))
			std::cout << " (" << e.what() << ")";
		std::cout << "\n  Try --help for more information\n";
	}
	return false;
}
Exemplo n.º 17
0
int main(int argc, char** argv)
{

    int grid_size_x;
    int grid_size_y;
    int max_iter;
    float xmin;
    float xmax;
    float ymin;
    float ymax;
    int **image;
    int rank;
//initialise a fn pointer
    in_set_fn_t fp; 
    MPI_Comm comm;
    comm = MPI_COMM_WORLD;

    MPI_Init(&argc, & argv);

    MPI_Comm_rank(comm, &rank); 

    read_options(argc, argv, &grid_size_x, &grid_size_y, &max_iter,
                 &xmin, &xmax, &ymin, &ymax);

    if(0 == rank)
    {
      initialise_image(&image, grid_size_x, grid_size_y);
    }


//set it to either julia or mandelbrot calculation
    fp = &point_in_julia;  

    compute_set(fp, image, xmin, xmax, ymin, ymax, grid_size_x, grid_size_y, max_iter, comm);

    if(0 == rank)
    {
      write_ppm("output.ppm", image, grid_size_x, grid_size_y, max_iter);
      free(image);
    }

    MPI_Finalize();
    return 0;
}
Exemplo n.º 18
0
int main (int argc, char **argv)
{
  botcfg.state = STATE_INIT;
   //piHiPri (45);
  if (setup () != 0)
  {
    fprintf (stderr, "Error setting up\n");
    return 1;
  }

  if (read_options (argc, argv) != 0)
  {
    fprintf (stderr, "Error reading options\n");
    return 1;
  }
  
  if (botcfg.state == STATE_INIT)
  {
    //User didn't chose either record or replay, falling back to passthrough
    botcfg.state = STATE_RUNNING;
  }
  
  if (joystick_setup () != 0)
  {
    fprintf (stderr, "Error setting up joysticks\n");
    return 1;
  }
  
  //drop_privs ();
  
  if (check_pid ())
  {
    fprintf (stderr, "Are we already running?\n");
    return 1;
  }
  
  main_loop ();
  clear_all_buttons (); 
  fprintf (stdout, "Exiting...\n");
  remove_pid ();
  return 0 ;
}
Exemplo n.º 19
0
int			get_arguments(options_t *options, int ac, char **av) {
	char	**rest;
	u_int	cnt;

	options->port = STARCRAFT_PORT;
	
	rest = read_options(options, ac, av, sov_arguments);
	if (!rest)
		return 0;
	
	if (!options->pcap_filter) {
		options->pcap_filter = malloc(SNAP_LEN);
		snprintf(options->pcap_filter, SNAP_LEN, PCAP_FILTER_FORMAT, options->port);
	}
	cnt = count_args(rest);
	if (cnt < 2) {
		fprintf(stderr, "Error: not enough arguments." EOL);
		print_use();
		return 0;
	}
	options->capture_device_name = *rest++;
	options->hosts = rest;
	options->host_count = cnt - 1;

	if (options->inject_device_name)
	{
		if (options->bind_udp_port) {
			fprintf(stderr, "Invalid arguments: cannot bind UDP and use injection" EOL);
			return 0;
		}
#ifdef WIN32
		if (!options->inject_ethernet_source || !options->inject_ethernet_destination) {
			fprintf(stderr, "Invalid arguments: source and destination MAC addresses" EOL
				"are required when using injection under windows." EOL);
			return 0;
		}
#endif
	}

	return 1;
}
Exemplo n.º 20
0
//int main(int argc, char *argv[], char *env[])
void main(void)
{
 int i, j;
 mvtype movemade;
 mousex=100;
 mousey=100;
 iconmenu=0;
 set_default_options();
 options=doptions;
 read_options();
 initialise(startbrd);
 initial_displays(current);
 no_more_openings=FALSE;
 quit=game_over=0;
 g_path.move[0].f=0;
 randomize();
 FLAGnewstart=1;
 while(!quit)
 {
   while(game.movenum<maxmoves && !quit)
   {
	 whites=0;
	 blacks=0;
	 if (FLAGnewstart) { starttime=time(NULL); FLAGnewstart=0; }
	 newtime=0;
	 if (!game_over && ((current.mvr=='w' && options.whiteplayer==PROGRAM) || (current.mvr=='b' && options.blackplayer==PROGRAM)))
	      movemade=get_computer_move(current); else
		 movemade=get_player_move(current, game_over);
	 if (kbhit()) { if (getch()==27) { options.whiteplayer=USER; options.blackplayer=USER; } }
	 if (current.mvr=='w') (whites=time(NULL)-starttime); else (blacks=time(NULL)-starttime);
	 if (movemade.t!=0) if (movemade.t<100) makemv(movemade); else {menu_option(movemade.t); game_over=0;}
	 regular_displays(current, movemade);
	 if (!game_over) game_over=over();
	 assert(game.lastmove<maxmoves);
   }
   options.whiteplayer=USER;
   options.blackplayer=USER;
 }
}
Exemplo n.º 21
0
int main(int argc, char** argv)
{

    int grid_size_x;
    int grid_size_y;
    int max_iter;
    float xmin;
    float xmax;
    float ymin;
    float ymax;
    int **image;
    int rank;
    MPI_Comm comm;
    comm = MPI_COMM_WORLD;

    MPI_Init(&argc, & argv);

    MPI_Comm_rank(comm, &rank); 

    read_options(argc, argv, &grid_size_x, &grid_size_y, &max_iter,
                 &xmin, &xmax, &ymin, &ymax);

    if(0 == rank)
    {
      initialise_image(&image, grid_size_x, grid_size_y);
    }

    compute_mandelbrot_set(image, xmin, xmax, ymin, ymax,
                           grid_size_x, grid_size_y, max_iter, comm);

    if(0 == rank)
    {
      write_ppm("output.ppm", image, grid_size_x, grid_size_y, max_iter);
      free(image);
    }

    MPI_Finalize();
    return 0;
}
Exemplo n.º 22
0
FC_nonp_variance::FC_nonp_variance(MASTER_OBJ * mp, unsigned & enr, GENERAL_OPTIONS * o,
                 DISTR * lp, const ST::string & t,const ST::string & fp,
                 DESIGN * Dp,FC_nonp * FCn,vector<ST::string> & op,
                 vector<ST::string> & vn)
     : FC(o,t,1,2,fp)
  {
  FCnonpp = FCn;
  likep = lp;
  designp = Dp;
  masterp = mp;
  equationnr = enr,
  lambdaconst = false;

  read_options(op,vn);

  datamatrix betanew(1,2);
  betanew(0,0) = likep->get_scale()/lambdastart;
  betanew(0,1) = lambdastart;
  setbeta(betanew);

  FCnonpp->tau2 = beta(0,0);
  FCnonpp->lambda = beta(0,1);

  }
Exemplo n.º 23
0
int main(int argc, char** argv)
{
    int grid_size_x;
    int grid_size_y;
    int max_iter;
    float xmin;
    float xmax;
    float ymin;
    float ymax;
    int **image;

    read_options(argc, argv, &grid_size_x, &grid_size_y, &max_iter,
                 &xmin, &xmax, &ymin, &ymax);

    initialise_image(&image, grid_size_x, grid_size_y);

    compute_mandelbrot_set(image, xmin, xmax, ymin, ymax,
                           grid_size_x, grid_size_y, max_iter);

    write_ppm("output.ppm", image, grid_size_x, grid_size_y, max_iter);

    free(image);
    return 0;
}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
    int n, fd, i;
    char *p;
    ne_test *testp;
    
    if ( read_options(argc, argv) == -1){
	Usage(argv[0]);
	exit(-1);	
    }

    if ( pget_option.outfile ){
	if ((fd=open(pget_option.outfile, O_CREAT | O_TRUNC | O_RDWR, 0660)) < 0){
	    perror("open() :");
	    return -1;
	}   

	close(STDOUT_FILENO);
	dup2(fd, STDOUT_FILENO);
    }


    test_argc = argc;
    test_argv = argv;


    if (tests[0].fn == NULL) {
	printf("-> no tests found in `%s'\n", test_suite);
	return -1;
    }

    if (ne_sock_init()) {
	COL("43;01"); printf("WARNING:"); NOCOL;
	printf(" Socket library initalization failed.\n");
    }

    printf("\n");	
    printf("\n");	
    i = 0;
    p = Result_Header[i];
    while (  p != NULL ){
    	printf("%s\n", p);
	i++;
    	p = Result_Header[i];
    }


   testp = &tests[0];
   if ( !strcmp(pget_option.methods, "WebFolder") )
    	testp = &tests2[0];

    for ( n=0; !aborted && testp[n].fn != NULL; n++) {
	int result;


	test_name = testp[n].name;
	have_context = 0;
	test_num = n;
	warned = 0;
	fflush(stdout);

	/* run the test. */
	result = testp[n].fn();


        if (testp[n].flags & T_EXPECT_FAIL) {
            if (result == OK) {
                t_context("test passed but expected failure");
                result = FAIL;
            } else if (result == FAIL)
                result = OK;
        }

	/* align the result column if we've had warnings. */
	if (warned) {
	    printf("    %s ", dots);
	}

    }

    /* discount skipped tests */
    if (skipped) {
	printf("-> %d %s.\n", skipped,
	       skipped==1?"test was skipped":"tests were skipped");
	n -= skipped;
	if (passes + fails != n) {
	    printf("-> ARGH! Number of test results does not match "
		   "number of tests.\n"
		   "-> ARGH! Test Results are INRELIABLE.\n");
	}
    }

    ne_sock_exit();
    
    return fails;
}
Exemplo n.º 25
0
int main(int argc, char **argv)
{
	errcode_t ret = 0;
	struct mount_options mo;
	ocfs2_filesys *fs = NULL;
	struct o2cb_cluster_desc cluster;
	struct o2cb_region_desc desc;
	int clustered = 1;
	int group_join = 0;
	struct stat statbuf;
	const char *spec;
	char *opts_string = NULL;

	initialize_ocfs_error_table();
	initialize_o2dl_error_table();
	initialize_o2cb_error_table();

	setbuf(stdout, NULL);
	setbuf(stderr, NULL);

	if (signal(SIGTERM, handle_signal) == SIG_ERR) {
		fprintf(stderr, "Could not set SIGTERM\n");
		exit(1);
	}

	if (signal(SIGINT, handle_signal) == SIG_ERR) {
		fprintf(stderr, "Could not set SIGINT\n");
		exit(1);
	}

	memset(&mo, 0, sizeof(mo));
	read_options (argc, argv, &mo);

	ret = process_options(&mo);
	if (ret)
		goto bail;

	ret = ocfs2_open(mo.dev, OCFS2_FLAG_RO, 0, 0, &fs); //O_EXCL?
	if (ret) {
		com_err(progname, ret, "while opening device %s", mo.dev);
		goto bail;
	}

	clustered = (0 == ocfs2_mount_local(fs));

	if (ocfs2_is_hard_readonly(fs) && (clustered ||
					   !(mo.flags & MS_RDONLY))) {
		ret = OCFS2_ET_IO;
		com_err(progname, ret,
			"while mounting read-only device in %s mode",
			(clustered ? "clustered" : "read-write"));
		goto bail;
	}

	if (verbose)
		printf("device=%s\n", mo.dev);

	ret = o2cb_setup_stack((char *)OCFS2_RAW_SB(fs->fs_super)->s_cluster_info.ci_stack);
	if (ret) {
		com_err(progname, ret, "while setting up stack\n");
		goto bail;
	}

	if (clustered) {
		ret = o2cb_init();
		if (ret) {
			com_err(progname, ret, "while trying initialize cluster");
			goto bail;
		}

		ret = ocfs2_fill_cluster_desc(fs, &cluster);
		if (ret) {
			com_err(progname, ret,
				"while trying to determine cluster information");
			goto bail;
		}

		ret = ocfs2_fill_heartbeat_desc(fs, &desc);
		if (ret) {
			com_err(progname, ret,
				"while trying to determine heartbeat information");
			goto bail;
		}
		desc.r_persist = 1;
		desc.r_service = OCFS2_FS_NAME;
	}

	ret = add_mount_options(fs, &cluster, &mo.xtra_opts);
	if (ret) {
		com_err(progname, ret, "while adding mount options");
		goto bail;
	}

	/* validate mount dir */
	if (lstat(mo.dir, &statbuf)) {
		com_err(progname, 0, "mount directory %s does not exist",
			mo.dir);
		goto bail;
	} else if (stat(mo.dir, &statbuf)) {
		com_err(progname, 0, "mount directory %s is a broken symbolic "
			"link", mo.dir);
		goto bail;
	} else if (!S_ISDIR(statbuf.st_mode)) {
		com_err(progname, 0, "mount directory %s is not a directory",
			mo.dir);
		goto bail;
	}

	block_signals (SIG_BLOCK);

	if (clustered && !(mo.flags & MS_REMOUNT)) {
		ret = o2cb_begin_group_join(&cluster, &desc);
		if (ret) {
			block_signals (SIG_UNBLOCK);
			com_err(progname, ret,
				"while trying to join the group");
			goto bail;
		}
		group_join = 1;
	}
	spec = canonicalize(mo.dev);
	ret = mount(spec, mo.dir, OCFS2_FS_NAME, mo.flags & ~MS_NOSYS,
		    mo.xtra_opts);
	if (ret) {
		ret = errno;
		if (group_join) {
			/* We ignore the return code because the mount
			 * failure is the important error.
			 * complete_group_join() will handle cleaning up */
			o2cb_complete_group_join(&cluster, &desc, errno);
		}
		block_signals (SIG_UNBLOCK);
		if (ret == -EROFS)
			com_err(progname, OCFS2_ET_RO_FILESYS, "while mounting %s "
				"on %s, please try fixing this by fsck.ocfs2 and then "
				"retry mounting", mo.dev, mo.dir);
		else
			com_err(progname, OCFS2_ET_INTERNAL_FAILURE,
				"while mounting %s on %s. Check 'dmesg' for more "
				"information on this error %d.", mo.dev, mo.dir,
				(int)ret);
		goto bail;
	}
	if (group_join) {
		ret = o2cb_complete_group_join(&cluster, &desc, 0);
		if (ret) {
			com_err(progname, ret,
				"while completing group join (WARNING)");
			/*
			 * XXX: GFS2 allows the mount to continue, so we
			 * will do the same.  I don't know how clean that
			 * is, but I don't have a better solution.
			 */
			ret = 0;
		}
	}

	change_local_hb_io_priority(fs, mo.dev);

	opts_string = fix_opts_string(((mo.flags & ~MS_NOMTAB) |
			(clustered ? MS_NETDEV : 0)),
			mo.xtra_opts, NULL);
	update_mtab_entry(mo.dev, mo.dir, OCFS2_FS_NAME, opts_string,
			mo.flags, 0, 0);

	block_signals (SIG_UNBLOCK);

bail:
	if (fs)
		ocfs2_close(fs);
	if (mo.dev)
		free(mo.dev);
	if (mo.dir)
		free(mo.dir);
	if (mo.opts)
		free(mo.opts);
	if (mo.xtra_opts)
		free(mo.xtra_opts);
	if (mo.type)
		free(mo.type);
	if (opts_string)
		free(opts_string);

	return ret ? 1 : 0;
}
Exemplo n.º 26
0
int main(int argc, char* argv[]){
  int i,j;
  
  // (0) leer parametros
  options opt;
  if (argc == 1) {print_help(argv[0]); return 0;}
  if(read_options(argc, argv, &opt))
  {printf("ERROR reading parameters\n"); return 1;}
  int len1 = strlen(opt.file1);
  int len2 = strlen(opt.file2);
  if( strcmp(&(opt.file1[len1-4]),".bmp") || strcmp(&(opt.file2[len2-4]),".bmp") )
  { printf("ERROR: nombre del archivo\n"); return -1;}
  
  // (0.1) siempre armo el summary
  opt.summary = (int*)malloc(sizeof(int)*256);
  for(i=0;i<256;i++) opt.summary[i]=0;
  
  // (1) leer imagenes
  BMP* bmp1 = bmp_read(opt.file1);
  BMP* bmp2 = bmp_read(opt.file2);
  if( bmp1==0 || bmp1==0 )
  { printf("ERROR: no se puede abrir el archivo\n"); return -1;}
  
  // (2) check tipo de archivo
  if( ((BMPIH*)(bmp1->ih))->biSize != ((BMPIH*)(bmp1->ih))->biSize )
  { printf("ERROR: tipo de archivo diferente\n"); return -1;}
  
  // (3) check tamaño del archivo
  int w1 = ((BMPIH*)(bmp1->ih))->biWidth;
  int h1 = ((BMPIH*)(bmp1->ih))->biHeight;
  int c1 = ((BMPIH*)(bmp1->ih))->biBitCount;
  int w2 = ((BMPIH*)(bmp2->ih))->biWidth;
  int h2 = ((BMPIH*)(bmp2->ih))->biHeight;
  int c2 = ((BMPIH*)(bmp2->ih))->biBitCount;
  if( w1!=w2 || h1!=h2 || c1!=c2 )
  { printf("ERROR: tamaño de archivo diferente\n"); return -1;}
  //printf("%i=%i %i=%i %i=%i\n",w1,w2,h1,h2,c1,c2);
  if(w1%4!=0) { printf("ERROR: padding no soportado\n"); return -1;} // TODO: soportar padding!
  
  // (3) check el bit count TODO: only 24 o 32
  if( c1!=24 && c1!=32 )
    { printf("ERROR: (%i) bitcount distinto de 24 o 32\n", c1); return -1;}
  
  // (4) crear imagenes de diferencias
  BMP *bmpDiffR, *bmpDiffG, *bmpDiffB, *bmpDiffA;
  bmpDiffR = bmp_copy(bmp1,0);
  bmpDiffG = bmp_copy(bmp1,0);
  bmpDiffB = bmp_copy(bmp1,0);
  if(c1 == 32)
    bmpDiffA = bmp_copy(bmp1,0);
  
  // (5) extraer data
  uint8_t *data1,*data2,*dataR,*dataG,*dataB,*dataA;
  data1 = bmp_get_data(bmp1);
  data2 = bmp_get_data(bmp2);
  dataR = bmp_get_data(bmpDiffR);
  dataG = bmp_get_data(bmpDiffG);
  dataB = bmp_get_data(bmpDiffB);
  if(c1 == 32)
    dataA = bmp_get_data(bmpDiffA);
  
  // (6) calcular diferencias
  if(c1 == 32)
  for(j=0;j<h1;j++) {
    for(i=0;i<w1;i++) {
      int pos = (j*w1+i)*4;
      uint8_t R1 = data1[pos+3];
      uint8_t G1 = data1[pos+2];
      uint8_t B1 = data1[pos+1];
      uint8_t A1 = data1[pos+0];
      uint8_t R2 = data2[pos+3];
      uint8_t G2 = data2[pos+2];
      uint8_t B2 = data2[pos+1];
      uint8_t A2 = data2[pos+0];
      
      dataR[pos+3] = cmp(R1,R2,i,j,"R",&opt);
      dataR[pos+2] = dataR[pos+3];
      dataR[pos+1] = dataR[pos+3];
      dataR[pos+0] = 255;
      
      dataG[pos+3] = cmp(G1,G2,i,j,"G",&opt);
      dataG[pos+2] = dataG[pos+3];
      dataG[pos+1] = dataG[pos+3];
      dataG[pos+0] = 255;
      
      dataB[pos+3] = cmp(B1,B2,i,j,"B",&opt);
      dataB[pos+2] = dataB[pos+3];
      dataB[pos+1] = dataB[pos+3];
      dataB[pos+0] = 255;

      dataA[pos+3] = cmp(A1,A2,i,j,"A",&opt);
      dataA[pos+2] = dataA[pos+3];
      dataA[pos+1] = dataA[pos+3];
      dataA[pos+0] = 255;
    }
  }
  if(c1 == 24)
  for(j=0;j<h1;j++) {
    for(i=0;i<w1;i++) {
      int pos = (j*w1+i)*3;
      uint8_t R1 = data1[pos+2];
      uint8_t G1 = data1[pos+1];
      uint8_t B1 = data1[pos+0];
      uint8_t R2 = data2[pos+2];
      uint8_t G2 = data2[pos+1];
      uint8_t B2 = data2[pos+0];
      
      dataR[pos+2] = cmp(R1,R2,i,j,"R",&opt);
      dataR[pos+1] = dataR[pos+2];
      dataR[pos+0] = dataR[pos+2];
      
      dataG[pos+2] = cmp(G1,G2,i,j,"G",&opt);
      dataG[pos+1] = dataG[pos+2];
      dataG[pos+0] = dataG[pos+2];
      
      dataB[pos+2] = cmp(B1,B2,i,j,"B",&opt);
      dataB[pos+1] = dataB[pos+2];
      dataB[pos+0] = dataB[pos+2];
    }
  }
  
  // (7) mostrar summary
  if(opt.summaryop) {
    for(i=1;i<256;i++)
      if(opt.summary[i]!=0)
      printf("%i\t%i\n",i,opt.summary[i]);
  }
  
  // (8) guardar resultados
  if(opt.image) {
    char* strX = "diffX.bmp";
    char* fileSto = malloc(strlen(opt.file1)+5+1);
    strcpy(fileSto,opt.file1);
    strcpy(fileSto+len1-4,strX);
    fileSto[len1]='R';
    bmp_save(fileSto,bmpDiffR);
    fileSto[len1]='G';
    bmp_save(fileSto,bmpDiffG);
    fileSto[len1]='B';
    bmp_save(fileSto,bmpDiffB);
    fileSto[len1]='A';
    if(c1 == 32)
      bmp_save(fileSto,bmpDiffA);
  
    // (8.1) borrar las imagenes
    bmp_delete(bmp1);
    bmp_delete(bmp2);
    bmp_delete(bmpDiffR);
    bmp_delete(bmpDiffG);
    bmp_delete(bmpDiffB);
    if(c1 == 32)
      bmp_delete(bmpDiffA);
  }
  
  // (9) retorno error si encontre una diferencia
  for(i=opt.epsilon;i<256;i++)
    if(opt.summary[i]>0)
      return -1;
  return 0;
}
Exemplo n.º 27
0
int
main(int argc, char * const argv[])
{
	char *buf;
	char *flag_str, *scale_str;
	size_t buflen, errcnt, i, skipped, tested;
	int r;
	int includeNegScale;
	int includeExabyteTests;
	int verbose;

	buflen = 4;
	includeNegScale = 0;
	includeExabyteTests = 0;
	verbose = 0;

	read_options(argc, argv, &buflen, &includeNegScale,
	    &includeExabyteTests, &verbose);

	buf = malloc(buflen);
	errcnt = 0;
	tested = 0;
	skipped = 0;

	if (buflen != 4)
		printf("Warning: buffer size %zu != 4, expect some results to differ.\n", buflen);

	printf("1..%zu\n", nitems(test_args));
	for (i = 0; i < nitems(test_args); i++) {
		/* KLUDGE */
		if (test_args[i].num == INT64_MAX && buflen == 4) {
		        /* Start final tests which require buffer of 6 */
		        free(buf);
		        buflen = 6;
                        buf = malloc(buflen);
                        if (verbose)
                                printf("Buffer length increased to %zu\n",
				    buflen);
		}

		if (test_args[i].scale < 0 && ! includeNegScale) {
			skipped++;
			testskipped(i + 1);
			continue;
		}
		if (test_args[i].num >= halfExabyte && ! includeExabyteTests) {
			skipped++;
			testskipped(i + 1);
			continue;
		}

		r = humanize_number(buf, buflen, test_args[i].num, "",
		    test_args[i].scale, test_args[i].flags);
		flag_str = str_flags(test_args[i].flags, "[no flags]");
		scale_str = str_scale(test_args[i].scale);

		if (r != test_args[i].retval) {
			if (verbose)
				printf("wrong return value on index %zu, "
				    "buflen: %zu, got: %d + \"%s\", "
				    "expected %d + \"%s\"; num = %jd, "
				    "scale = %s, flags= %s.\n",
				    i, buflen, r, buf, test_args[i].retval,
				    test_args[i].res,
				    (intmax_t)test_args[i].num,
				    scale_str, flag_str);
			else
				printf("not ok %zu # return %d != %d\n",
				    i + 1, r, test_args[i].retval);
			errcnt++;
		} else if (strcmp(buf, test_args[i].res) != 0) {
			if (verbose)
				printf("result mismatch on index %zu, got: "
				    "\"%s\", expected \"%s\"; num = %jd, "
				    "scale = %s, flags= %s.\n",
				    i, buf, test_args[i].res,
				    (intmax_t)test_args[i].num,
				    scale_str, flag_str);
			else
				printf("not ok %zu # buf \"%s\" != \"%s\"\n",
				    i + 1, buf, test_args[i].res);
			errcnt++;
		} else {
			if (verbose)
				printf("successful result on index %zu, "
				    "returned %d, got: \"%s\"; num = %jd, "
				    "scale = %s, flags= %s.\n",
				    i, r, buf,
				    (intmax_t)test_args[i].num,
				    scale_str, flag_str);
			else
				printf("ok %zu\n", i + 1);
		}
		tested++;
	}

	if (verbose)
		printf("total errors: %zu/%zu tests, %zu skipped\n", errcnt,
		    tested, skipped);

	if (errcnt)
		return 1;

	return 0;
}
Exemplo n.º 28
0
/** Instantiates an Environment and attaches an Interpreter to interact with the
    command line. */
int
main( int argc, char *argv[] )
{
    int status = EXIT_SUCCESS;

    Environment *env;
    Interpreter *itp;
    Parser *p;

    static char source_file[0x100];
    *source_file = '\0';

#if USE_NCURSES
    initscr();
#endif

    read_options( argc, argv, source_file );

    if ( !( env = environment__new() ) )
        status = EXIT_FAILURE;

    else
    {
        if ( ( itp = interpreter__new( env, quiet_flag, version_flag ) ) )
        {
            p = parser__new( itp );

            if ( *source_file )
            {
#if DEBUG__MAIN
                PRINT( "Loading namespace from file...\n" );
#endif

                interpreter__deserialize( itp, source_file );
            }

            if ( !quiet_flag )
            {
                print_version();
                print_copying();
                REFRESH;
            }

/*
parser__feed( p, "here;" );
parser__feed( p, "here;" );

            if ( interpreter__parse( itp ) )
                ERROR( "main: parse failed" );

parser__feed( p, "_size;" );

            if ( interpreter__parse( itp ) )
                ERROR( "main: parse failed" );

parser__feed( p, ";here;" );
*/
            if ( parser__parse( p ) )
                ERROR( "main: parse failed" );

            interpreter__delete( itp );

            parser__free( p );
        }

        else
            status = EXIT_FAILURE;

        environment__delete( env );
    }

#if USE_NCURSES
    endwin();
#endif

#if DEBUG__ALLOC
    debug__memcheck();
#endif

    /* See: http://www.jetcafe.org/~jim/c-style.html#Expressions */
    exit( status );
}
Exemplo n.º 29
0
int main(int argc, char* argv[])
{
	read_options(argc, argv);

	//loading image
	imgc = cvLoadImage(input_file,-1);
	
	if (imgc->nChannels > 1) {
		color = 1;		
		img = cvLoadImage(input_file,CV_LOAD_IMAGE_GRAYSCALE);
	} else {
		img = imgc;
	}

	if(!img) {
		printf("Could not load image file: %s\n",input_file);
		return 1;
	} else {
		if (verbose) printf("Loaded file: %s\n",input_file);
		if (verbose) printf("dimensions %dx%dpx, channels: %d\n",img->width,img->height,imgc->nChannels);
	}
	XS=img->width;
	YS=img->height;

	// different settings for small or large images
	if (YS > 512) {
		RY=RY_big;
		MO=MO_big;
		YO1=YO1_big;
		YO2=YO2_big;
	} else {
		RY=RY_small;
		MO=MO_small;
		YO1=YO1_small;
		YO2=YO2_small;
	}

	// generate image buffer according to image size
	IM = (uchar *) malloc (XS*YS * sizeof(uchar));
	IMV = (uchar *) malloc (XS*YS * sizeof(uchar));
	IM1 = (uchar *) malloc (XS*YS * sizeof(uchar));

	if (color) {
		IMB = (uchar *) malloc (XS*YS * sizeof(uchar));
		IMG = (uchar *) malloc (XS*YS * sizeof(uchar));
		IMR = (uchar *) malloc (XS*YS * sizeof(uchar));		
		IM1B = (uchar *) malloc (XS*YS * sizeof(uchar));
		IM1G = (uchar *) malloc (XS*YS * sizeof(uchar));
		IM1R = (uchar *) malloc (XS*YS * sizeof(uchar));
	}
	
	int x,y;

	//convert opencv image to array (in a really stupid way)	
	for(x=0;x<XS;x++) {
		for(y=0;y<YS;y++) {
			IM[x+y*XS] = ((uchar *)(img->imageData + y*img->widthStep))[x];
			if (color) {
				IMB[x+y*XS] = ((uchar *)(imgc->imageData + y*imgc->widthStep))[x*imgc->nChannels];
				IMG[x+y*XS] = ((uchar *)(imgc->imageData + y*imgc->widthStep))[x*imgc->nChannels+1];
				IMR[x+y*XS] = ((uchar *)(imgc->imageData + y*imgc->widthStep))[x*imgc->nChannels+2];
			}
		}
	}
	

	//---------- important algo begins here

	//vertical gradient
	if (verbose) printf("calculate vertical gradient..\n");
	for (x=0; x<XS; x++)
	{
		for (y=0; y<YS; y++)
		{
			if (y<2||y+1>=YS) IMV[x+y*XS]=128;
			else IMV[x+y*XS]=int(IM[x+(y-2)*XS])+int(IM[x+(y-1)*XS])-int(IM[x+(y-1)*XS])-int(IM[x+(y-1)*XS])+128;
		}
	}

	//calculating ydeltas
	if (verbose) printf("calculate x&ydeltas...\n");	
	maxn ms;
	int no, x2, mo, y1, y2;
	for (x=0; x<XS; x++)
	{
		for (no=0; no<NO; no++) if (in(x2=x+XO[no],XS))
		{
			minn md;//minimalizator
			for (mo=0; mo<MO; mo++)
			{
				int sumsq=0;
				for (y=RY; y+RY<YS; y++)
				{
					y1=y+YO1[mo];
					y2=y+YO2[mo];

					int deltasq=square(int(IMV[x+y1*XS])-int(IMV[x2+y2*XS]));
//					if (deltasq>=square(8))
						sumsq+=deltasq;
				}
				md.add(YO2[mo]-YO1[mo],sumsq);
//				GD.point(0, x, sumsq/XS/10, COLOR12[mo],1);
			}
//			GD.point(0, x, md.minv()/XS/10, COLOR12[md.mini()],1);
			dta[x][no]=md.mini();//best fit between verticals
			ssq[x][no]=md.minv();//distance
			ms.add(md.minv());
		}
	}

	memset(P, 0, sizeof P);

	const double F1=1.;//force to zero
	const double F2=4000.;//ofset force
//	const double F3=400.;//smoothing force

	int t;
	//applying ofsets
	if (verbose) printf("apply offsets...\n");		
	for (t=0; t<400; t++)
	{
		memset(Q, 0, sizeof Q);
		memset(W, 0, sizeof W);

		for (x=0; x<XS; x++)
		{
			W[x]+=F1;

			for (no=0; no<NO; no++) if (in(x2=x+XO[no],XS))
			{
				int d=dta[x][no];
				int s=ssq[x][no];

//				if (s>100000) continue;

				double f=F2*.5/NO*corrfn(s,0,100000);
				W[x]+=f;
				Q[x]+=f*(P[x2]-d);

				W[x2]+=f;
				Q[x2]+=f*(P[x]+d);
			}

#if 0//smoothing > later
			if (x>0)
			{
				W[x]+=F3;
				Q[x]+=F3*P[x-1];
			}
			if (x+1<XS)
			{
				W[x]+=F3;
				Q[x]+=F3*P[x+1];
			}
#endif
		}
		for (x=0; x<XS; x++)
		{
			P[x]=Q[x]/W[x];
		}
	}

	//smoothing
	if (verbose) printf("smoothing\n");
	const double F4=1.;//force to intermediate curve
	const double F5=1.;//smoothing force
	memcpy(R, P, sizeof R);
	for (t=0; t<100; t++)
	{
		memset(Q, 0, sizeof Q);
		memset(W, 0, sizeof W);

		for (x=0; x<XS; x++)
		{
			Q[x]+=F4*R[x];
			W[x]+=F4;

			if (x>0)
			{
				W[x]+=F5;
				Q[x]+=F5*P[x-1];
			}
			if (x+1<XS)
			{
				W[x]+=F5;
				Q[x]+=F5*P[x+1];
			}
		}

		for (x=0; x<XS; x++)
		{
			P[x]=Q[x]/W[x];
		}
	}

	
	/*
	//drawing out the red line
	for (x=0; x<XS; x++)
	{
		GD.point(0, fix(x), fix(135.+P[x]), 0xFF, 1);
	}
	*/
	
	//result image
	if (verbose)  printf("calculate result images...\n");

	for (x=0; x<XS; x++)
	{
		for (y=0; y<YS; y++)
		{
			
			int y1=y+int(P[x]+.5);
			if (color) {
				IM1B[x+y*XS] = bg_c;
				IM1G[x+y*XS] = bg_c;
				IM1R[x+y*XS] = bg_c;
			} else {
				IM1[x+y*XS]= bg_c;
			}
				
			if (in(y1,YS))
			{
				//IM1[x+y*XS]=IM[x+y1*XS];
				
				if (color) {
					IM1B[x+y*XS]=valfr1(IMB, XS, 16*x, int(16.*(y+P[x])), 4);
					IM1G[x+y*XS]=valfr1(IMG, XS, 16*x, int(16.*(y+P[x])), 4);
					IM1R[x+y*XS]=valfr1(IMR, XS, 16*x, int(16.*(y+P[x])), 4);
				} else {
					IM1[x+y*XS]=valfr1(IM, XS, 16*x, int(16.*(y+P[x])), 4);
				}
				//((uchar *)(out->imageData + y*img->widthStep))[x] = IM[x+y1*XS];
			}
		}
	}

	//---------- important algo ends here	


	// now convert back to opencv image (very stupid!)

	if (color)
		out = cvCreateImage(cvSize(XS,YS),IPL_DEPTH_8U,3);
	else
		out = cvCreateImage(cvSize(XS,YS),IPL_DEPTH_8U,1);		
	
	for(x=0;x<XS;x++) {
		for(y=0;y<YS;y++) {
			
			if (color) {
				((uchar *)(out->imageData + y*imgc->widthStep))[x*imgc->nChannels] = IM1B[x+y*XS];
				((uchar *)(out->imageData + y*imgc->widthStep))[x*imgc->nChannels+1] = IM1G[x+y*XS];
				((uchar *)(out->imageData + y*imgc->widthStep))[x*imgc->nChannels+2] = IM1R[x+y*XS];
			} else {
				((uchar *)(out->imageData + y*imgc->widthStep))[x] = IM1[x+y*XS];
			}			
		}
	}	

	//save file
	if (verbose) printf("saving file %s\n",output_file);
	if(!cvSaveImage(output_file, out)) {
		printf("Could not save: file\n");
		return 1;
	}

	return 0;

}
Exemplo n.º 30
0
/**
 * RHash program entry point.
 *
 * @param argc number of program arguments including the program path
 * @param argv program arguments
 * @return the program exit code, zero on success and 1 on error
 */
int main(int argc, char *argv[])
{
	find_file_options search_opt;
	timedelta_t timer;
	int sfv;

	i18n_initialize(); /* initialize locale and translation */

	memset(&rhash_data, 0, sizeof(rhash_data));
	rhash_data.out = stdout; /* set initial output streams */
	rhash_data.log = stderr; /* can be altered by options later */
	rhash_data.search_opt = &search_opt;

	init_hash_info_table();

	read_options(argc, argv); /* load config and parse command line options */
	prev_sigint_handler = signal(SIGINT, ctrl_c_handler); /* install SIGINT handler */
	rhash_library_init();

	/* in benchmark mode just run benchmark and exit */
	if(opt.mode & MODE_BENCHMARK) {
		unsigned flags = (opt.flags & OPT_BENCH_RAW ? RHASH_BENCHMARK_CPB | RHASH_BENCHMARK_RAW : RHASH_BENCHMARK_CPB);
		if((opt.flags & OPT_BENCH_RAW) == 0) {
			fprintf(rhash_data.out, _("%s v%s benchmarking...\n"), PROGRAM_NAME, VERSION);
		}
		rhash_run_benchmark(opt.sum_flags, flags, rhash_data.out);
		rsh_exit(0);
	}

	if(opt.n_files == 0) {
		if(argc > 1) {
			log_warning(_("no files/directories were specified at command line\n"));
		}

		/* print short usage help */
		log_msg(_("Usage: %s [OPTION...] <FILE>...\n\n"
			"Run `%s --help' for more help.\n"), CMD_FILENAME, CMD_FILENAME);
		rsh_exit(0);
	}

	/* setup printf formating string */
	rhash_data.printf_str = opt.printf_str;

	if(opt.template_file) {
		if(!load_printf_template()) rsh_exit(2);
	} else if(!rhash_data.printf_str && !(opt.mode & (MODE_CHECK | MODE_CHECK_EMBEDDED))) {
		/* initialize printf output format according to '--<hashname>' options */
		init_printf_format( (rhash_data.template_text = rsh_str_new()) );
		rhash_data.printf_str = rhash_data.template_text->str;

		if(opt.flags & OPT_VERBOSE) {
			char* str = rsh_strdup(rhash_data.printf_str);
			log_msg(_("Format string is: %s\n"), str_trim(str));
			free(str);
		}
	}

	if(rhash_data.printf_str) {
		rhash_data.print_list = parse_print_string(rhash_data.printf_str, &opt.sum_flags);
	}

	memset(&search_opt, 0, sizeof(search_opt));
	search_opt.max_depth = (opt.flags & OPT_RECURSIVE ? opt.find_max_depth : 0);
	search_opt.options = FIND_SKIP_DIRS;
	search_opt.call_back = find_file_callback;

	if((sfv = (opt.fmt == FMT_SFV && !opt.mode))) {
		print_sfv_banner(rhash_data.out);
	}

	/* pre-process files */
	if(sfv || opt.bt_batch_file) {
		/* note: errors are not reported on pre-processing */
		search_opt.call_back_data = (void*)1;
		process_files((const char**)opt.files, opt.n_files, &search_opt);

		fflush(rhash_data.out);
	}

	/* measure total processing time */
	rhash_timer_start(&timer);
	rhash_data.processed = 0;

	/* process files */
	search_opt.options |= FIND_LOG_ERRORS;
	search_opt.call_back_data = (void*)0;
	process_files((const char**)opt.files, opt.n_files, &search_opt);

	if((opt.mode & MODE_CHECK_EMBEDDED) && rhash_data.processed > 1) {
		print_check_stats();
	}

	if(!rhash_data.interrupted)
	{
		if(opt.bt_batch_file && rhash_data.rctx) {
			rhash_final(rhash_data.rctx, 0);
			save_torrent_to(opt.bt_batch_file, rhash_data.rctx);
		}

		if((opt.flags & OPT_SPEED) &&
			!(opt.mode & (MODE_CHECK | MODE_UPDATE)) &&
			rhash_data.processed > 1) {
			double time = rhash_timer_stop(&timer);
			print_time_stats(time, rhash_data.total_size, 1);
		}
	} else {
		/* check if interruption was not reported yet */
		if(rhash_data.interrupted == 1) report_interrupted();
	}

	options_destroy(&opt);
	rhash_destroy(&rhash_data);

	/* return non-zero error code if error occurred */
	return (rhash_data.error_flag ? 1 :
		search_opt.errors_count ? 2 :
		rhash_data.interrupted ? 3 : 0);
}