Esempio n. 1
0
int
main(int argc, char **argv)
{
	struct state state;

	if (initialize_state(&state)) {
		printf("ERROR in initialization\n");
		return 1;
	}

	if (parse_args(argc, argv, &state)) {
		printf("ERROR parsing arguments\n");
		return 1; // TODO: cleanup_state()
	}

	if (bmp_load(state.inf, state.inname, &state)) {
		printf("ERROR loading BMP!\n");
		return 1; // TODO: cleanup_state()
	}

	if (font_save(state.outf, state.outname, &state)) {
		printf("ERROR saving font!\n");
		return 1; // TODO: cleanup_state()
	}

	cleanup_state(&state);
	return 0;
}
Esempio n. 2
0
int main(int argc, char **argv)
{
  state *s = (state *)malloc(sizeof(state));

#ifndef __GLIBC__
  __progname  = strdup(basename(argv[0]));
#endif

  if (initialize_state(s))
    return EXIT_FAILURE;

  if (process_cmd_line(s,argc,argv))
    return EXIT_FAILURE;

  argv += optind;
      
  while (*argv != NULL) {
    make_bmp_from_file(s,*argv);
    ++argv;
  }

  // We don't bother cleaning up the state as we're about to exit. 
  // All of the memory we have
  // allocated is going to be returned to the operating system, so
  // there's no point in our explicitly free'ing it. 
  
  return EXIT_SUCCESS;
}
Esempio n. 3
0
int main()
{
	struct State current_state;
	initialize_state(&current_state);
	kalman_filter(&current_state);
	return 0;
}
Esempio n. 4
0
int main(int argc, char **argv)
{
  state *s = (state *)malloc(sizeof(state));

#ifndef __GLIBC__
  __progname  = strdup(basename(argv[0]));
#endif

  if (s == NULL)
      fatal_error("Unable to allocate state");

  if (initialize_state(s))
    fatal_error("Unable to initialize state");

  if (process_cmd_line(s,argc,argv))
    return EXIT_FAILURE;

  argv += optind;
  argc -= optind;

  /* We must have two files to compare */
  if (argc != 2)
    {
      usage();
      return EXIT_FAILURE;
    }

  if (compare_files(s,*argv,*(argv+1)))
    return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
Esempio n. 5
0
static void
key_setup(State *state, const unsigned char *key, size_t keylen)
{
    initialize_state(state);
    absorb(state, key, keylen);
    if (state->a > 0) {
        shuffle(state);
    }
}
Esempio n. 6
0
st_input *
st_input_new (const char *string)
{
    st_input *input;

    st_assert (string != NULL);

    input = st_new0 (st_input);

    initialize_state (input, strdup (string));    

    return input;
}
Esempio n. 7
0
int
spritz_stream(unsigned char *out, size_t outlen,
              const unsigned char *key, size_t keylen)
{
    State state;

    initialize_state(&state);
    absorb(&state, key, keylen);
    squeeze(&state, out, outlen);
    memzero(&state, sizeof state);

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

    initialize_state();

    initialize_timer();

    print_state(stdout, 1.0f);
    printf("Score: %d\n", game_state.score);

    char input;

    double dTime = 0;
    while (1)
    {
        dTime += get_elapsed_time();
        if (dTime > 1)
        {
            printf("Tick.\n");
            dTime -= 1;
        }
    }

    while (input = getchar())
    {
        switch (input)
        {
        case 'D':
            if (move_down()) return 0;
            break;
        case 'G':
            if (gravity_tick()) return 0;
            break;
        case 'L':
            move_left();
            break;
        case 'R':
            move_right();
            break;
        case 'U':
            rotate();
            break;
        }
        print_state(stdout, 1.0f);
        printf("Score: %d\n", game_state.score);
    }

    return 0;
}
Esempio n. 9
0
void get_kf(kf_t *kf, double phase_var, double code_var, double pos_var, double vel_var, double int_var,
            double pos_init_var, double vel_init_var, double int_init_var,
            u8 num_sdiffs, sdiff_t *sats_with_ref_first, double *dd_measurements, double ref_ecef[3], double dt)
{
  u32 state_dim = num_sdiffs + 5;
  u32 num_diffs = num_sdiffs-1;
  kf->state_dim = state_dim;
  kf->obs_dim = 2*num_diffs;
  assign_transition_mtx(state_dim, dt, &kf->transition_mtx[0]);
  assign_transition_cov(state_dim, pos_var, vel_var, int_var, &kf->transition_cov[0]);
  assign_decor_obs_cov(num_diffs, phase_var, code_var, &kf->decor_mtx[0], &kf->decor_obs_cov[0]);
  assign_decor_obs_mtx(num_sdiffs, sats_with_ref_first, &ref_ecef[0], &kf->decor_mtx[0], &kf->decor_obs_mtx[0]);
  initialize_state(kf, dd_measurements,
                   pos_init_var, vel_init_var, int_init_var);
}
Esempio n. 10
0
int ssl_proxy_new(int fd, struct ip_addr *ip)
{
        struct ssl_proxy *proxy;
	gnutls_session session;
	int sfd[2];

	if (!ssl_initialized) {
		i_error("SSL support not enabled in configuration");
		return -1;
	}

	session = initialize_state();
	gnutls_transport_set_ptr(session, fd);

	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sfd) == -1) {
		i_error("socketpair() failed: %m");
		gnutls_deinit(session);
		return -1;
	}

	net_set_nonblock(sfd[0], TRUE);
	net_set_nonblock(sfd[1], TRUE);
	net_set_nonblock(fd, TRUE);

	proxy = i_new(struct ssl_proxy, 1);
	proxy->refcount = 1;
	proxy->session = session;
	proxy->fd_ssl = fd;
	proxy->fd_plain = sfd[0];
	proxy->ip = *ip;

	hash_table_insert(ssl_proxies, proxy, proxy);

	proxy->refcount++;
	ssl_handshake(proxy);
	if (!ssl_proxy_destroy(proxy)) {
		/* handshake failed. return the disconnected socket anyway
		   so the caller doesn't try to use the old closed fd */
		return sfd[1];
	}

        main_ref();
	return sfd[1];
}
Esempio n. 11
0
/**
 * @todo Test whether the state is properly tracked when an input blocker is
 * used.
 */
tdistributor::tdistributor(twidget& owner
		, const tdispatcher::tposition queue_position)
	: tmouse_motion(owner, queue_position)
	, tmouse_button_left("left"
			, owner
			, queue_position)
	, tmouse_button_middle("middle"
			, owner
			, queue_position)
	, tmouse_button_right("right"
			, owner
			, queue_position)
#if 0
	, hover_pending_(false)
	, hover_id_(0)
	, hover_box_()
	, had_hover_(false)
	, tooltip_(0)
	, help_popup_(0)
#endif
	, keyboard_focus_(0)
	, keyboard_focus_chain_()
{
	if(SDL_WasInit(SDL_INIT_TIMER) == 0) {
		if(SDL_InitSubSystem(SDL_INIT_TIMER) == -1) {
			assert(false);
		}
	}

	owner_.connect_signal<event::SDL_KEY_DOWN>(
			boost::bind(&tdistributor::signal_handler_sdl_key_down
				, this, _5, _6, _7));

	owner_.connect_signal<event::NOTIFY_REMOVAL>(
			boost::bind(
				  &tdistributor::signal_handler_notify_removal
				, this
				, _1
				, _2));

	initialize_state();
}
Esempio n. 12
0
int
spritz_hash(unsigned char *out, size_t outlen,
            const unsigned char *msg, size_t msglen)
{
    State         state;
    unsigned char r;

    if (outlen > 255) {
        return -1;
    }
    r = (unsigned char) outlen;
    initialize_state(&state);
    absorb(&state, msg, msglen);
    absorb_stop(&state);
    absorb(&state, &r, 1U);
    squeeze(&state, out, outlen);
    memzero(&state, sizeof state);

    return 0;
}
Esempio n. 13
0
bool SpikingOutput::allocateValues(){
    module::allocateValues(); // Use the allocateValues() method of the base class

    // Set parameters of distributions for random number generation
    normal_distribution<double>::param_type init_norm_dist_params(Min_period/1000.0, Min_period_std_dev/1000.0); // (mean=Min_period/1000.0, sigma=Min_period_std_dev/1000.0 seconds)
    norm_dist.param(init_norm_dist_params); // Set initial params of normal distribution

    gamma_distribution<double>::param_type init_gam_dist_params(Spike_dist_shape, 1.0/Spike_dist_shape); // Parameters of gamma distribution for spike: gam_k (alpha), gam_theta (beta)
    gam_dist.param(init_gam_dist_params); // Set params of uniform distribution

    // Resize initial image buffers
    inputImage->assign(sizeY, sizeX, 1, 1, 0.0);
    next_spk_time->assign(sizeY, sizeX, 1, 1, First_spk_delay);
    last_spk_time->assign(sizeY, sizeX, 1, 1, -numeric_limits<double>::infinity());
    curr_ref_period->assign(sizeY, sizeX, 1, 1, Min_period/1000.0);

    initialize_state(); // Set ref. period and unwarped first spike time

    if(Random_init != 0.0) // If parameter Random_init is differnt from 0, init the state of outputs randomly
        randomize_state();
    return(true);
}
void read_data(int rank, int max_rank)
{
    ap = (ASTRONOMY_PARAMETERS*)malloc(sizeof(ASTRONOMY_PARAMETERS));
    /********
        *   READ THE ASTRONOMY PARAMETERS
     ********/
    printf("[worker: %d] reading parameters...\n", rank);
    int retval = read_astronomy_parameters(astronomy_parameters_file, ap);
    if (retval)
    {
        fprintf(stderr, "APP: error reading astronomy parameters: %d\n", retval);
        exit(1);
    }
//  fwrite_astronomy_parameters(stdout, ap);
    printf("[worker: %d] splitting parameters...\n", rank);
    split_astronomy_parameters(ap, rank, max_rank);
    /********
        *   READ THE STAR POINTS
     ********/
    printf("[worker: %d] reading star points...\n", rank);
    sp = (STAR_POINTS*)malloc(sizeof(STAR_POINTS));
    retval = read_star_points(star_points_file, sp);
    if (retval)
    {
        fprintf(stderr, "APP: error reading star points: %d\n", retval);
        exit(1);
    }
    printf("[worker: %d] read %d stars.\n", rank, sp->number_stars);
    total_number_stars = sp->number_stars;
    split_star_points(sp, rank, max_rank);

    /********
        *   INITIALIZE THE EVALUATION STATE
     ********/
    printf("[worker: %d] initializing state...\n", rank);
    es = (EVALUATION_STATE*)malloc(sizeof(EVALUATION_STATE));
    initialize_state(es, ap->number_streams);
}
Esempio n. 15
0
/**
  * A função main é um ciclo que apenas termina quando o utilizador insere o comando "q".
  * Esta função vai então ser responsável iniciar o programa e receber os comandos que o utilizador lhe introduz.
  * Vai imprimir os resultados do jogo enquanto este decorrer. 
  */
int main() {
	char *cmd = NULL;
	FUNCTION *fun = NULL;
	BOARD * brd = NULL;

	srand(time(NULL));
	brd = initialize_state();

	while(rl_gets() != NULL) {
		int i, j;

		/* Ignorar os espacos no inicio do comando */
		for(i = 0; line_read[i] && whitespace(line_read[i]); i++);

		/* Saltar a primeira palavra da linha */
		for(j = i; line_read[j] && !whitespace(line_read[j]); j++);

		/* Delimitar o nome do comando */
		if(line_read[j])
			line_read[j++] = 0;

		 /* Saltar os espacos mais uma vez */
		for(; line_read[j] && whitespace(line_read[j]); j++);

		cmd = line_read + i;

		fun = find_command(cmd);
		if(fun != NULL) {
			brd = fun(line_read + j, brd);
			print_state(brd);
		} else {
			mensagem_de_erro(E_COMMAND);
		}
	}

	return 0;
}
Esempio n. 16
0
// new_connection_cb: gets called when the listen socket for the
// server is ready to read (i.e. there's an incoming connection).
void new_connection_cb(uv_stream_t *server, int status)
{
  SSL *ssl;
  uv_tcp_t *client;
  connection_state *state;
  worker_data *worker = (worker_data *)server->data;
  int rc;

  if (status == -1) {
    // TODO: should we log this?
    return;
  }

  client = (uv_tcp_t *)malloc(sizeof(uv_tcp_t));
  client->data = NULL;
  rc = uv_tcp_init(server->loop, client);
  if (rc != 0) {
    write_log(1, "Failed to setup TCP socket on new connection: %s", 
              error_string(rc));
  } else {
    rc = uv_accept(server, (uv_stream_t *)client);
    if (rc != 0) {
      uv_close((uv_handle_t *)client, close_cb);
      write_log(1, "Failed to accept TCP connection: %s",
                error_string(rc));
      return;
    }
  }

  // The TCP connection has been accepted so now pass it off to a worker
  // thread to handle

  state = (connection_state *)malloc(sizeof(connection_state));
  initialize_state(&worker->active, state);
  state->tcp = client;
  set_get_header_state(state);

  ssl = SSL_new(worker->ctx);
  if (!ssl) {
    uv_close((uv_handle_t *)client, close_cb);
    write_log(1, "Failed to create SSL context");
    return;
  }

  state->ssl = ssl;

  // Set up OpenSSL to use a memory BIO. We'll read and write from this BIO
  // when the TCP connection has data or is writeable. The BIOs are set to
  // non-blocking mode.

  state->read_bio = BIO_new(BIO_s_mem());
  BIO_set_nbio(state->read_bio, 1);
  state->write_bio = BIO_new(BIO_s_mem());
  BIO_set_nbio(state->write_bio, 1);
  SSL_set_bio(ssl, state->read_bio, state->write_bio);

  client->data = (void *)state;

  rc = uv_read_start((uv_stream_t*)client, allocate_cb, read_cb);
  if (rc != 0) {
    uv_close((uv_handle_t *)client, close_cb);
    write_log(1, "Failed to start reading on client connection: %s", 
              error_string(rc));
    return;
  }

  // Start accepting the TLS connection. This will likely not
  // complete here and will be completed in the read_cb/do_ssl above.

  SSL_set_accept_state(ssl);
  SSL_do_handshake(ssl);
}
Esempio n. 17
0
int main(int argc, char **argv)
{
    int count, status = EXIT_SUCCESS;
    TCHAR *fn;
    state *s;

    /* Because the main() function can handle wchar_t arguments on Win32,
       we need a way to reference those values. Thus we make a duplciate
       of the argc and argv values. */

#ifndef __GLIBC__
    __progname  = basename(argv[0]);
#endif

    s = (state *)malloc(sizeof(state));
    if (NULL == s)
    {
        // We can't use fatal_error because it requires a valid state
        print_status("%s: Unable to allocate state variable", __progname);
        return EXIT_FAILURE;
    }

    if (initialize_state(s))
    {
        print_status("%s: Unable to initialize state variable", __progname);
        return EXIT_FAILURE;
    }

    process_command_line(s,argc,argv);

    if (initialize_hashing_algorithms(s))
        return EXIT_FAILURE;

    if (primary_audit == s->primary_function)
        setup_audit(s);

#ifdef _WIN32
    if (prepare_windows_command_line(s))
        fatal_error(s,"%s: Unable to process command line arguments", __progname);

    check_wow64(s);
#else
    s->argc = argc;
    s->argv = argv;
#endif

    MD5DEEP_ALLOC(TCHAR,s->cwd,PATH_MAX);
    s->cwd = _tgetcwd(s->cwd,PATH_MAX);
    if (NULL == s->cwd)
        fatal_error(s,"%s: %s", __progname, strerror(errno));

    /* Anything left on the command line at this point is a file
       or directory we're supposed to process. If there's nothing
       specified, we should tackle standard input */

    if (optind == argc)
        hash_stdin(s);
    else
    {
        MD5DEEP_ALLOC(TCHAR,fn,PATH_MAX);

        count = optind;

        while (count < s->argc)
        {
            generate_filename(s,fn,s->cwd,s->argv[count]);

#ifdef _WIN32
            status = process_win32(s,fn);
#else
            status = process_normal(s,fn);
#endif

            ++count;
        }

        free(fn);
    }

    if (primary_audit == s->primary_function)
        status = display_audit_results(s);

    return status;
}
Esempio n. 18
0
File: auto21-1.c Progetto: apqw/epi
int main(int argc, char *argv[])
{
  double u[NN], v[NN], p[NN], fat[NN], Vc[NN], w[NN][N2], a[NX+1][NY+1][NZ+1], B[NX+1][NY+1][NZ+1], u_ave[NN];
  double xx[NN], yy[NN], zz[NN], r[NN];
  double ageb[NN], agek[NN];
  int state[NN], div_times[NN], touch[NN];
  int lj[NN][N2];
  int indx[NN]; // lj[i][0...indx-1]
  int ljd[NN][N2];
  int ljd_indx[NN]; // ljd[i][0...ljd_indx-1]

  /* debug */
  int pair[NN], pair2[NN], pair_indx = 0;
  double L[NN]; 
  int other_cell[NN];
  int tb[NN];
  int ncell_var, num;
  int i, j, k;
  int KEY_INPUT_DATA;
  char celldata_name[100];
  char str[100], str_chem[100];
  FILE *finput, *fdebug;
  void checkstate(int [], int );
  void checkparam();

  int nmx = (int)(COMPRESS_FACTOR * LX/(2.0*R_memb));
  int nmy = (int)(COMPRESS_FACTOR * LY/(2.0*R_memb));

  printf("mkdir %s\n", OUTPUTDIR );
  sprintf(str, "mkdir -p %s", OUTPUTDIR);
  system(str);

  checkparam();

  if (fabs(dx-dh)>EPS || fabs(dy-dh)>EPS || fabs(dz-dh)>EPS) {
    printf("error: dx=%f dy=%f dz=%f.\n", dx, dy, dz);
    printf("grid size must be dh=%f.\n", dh);
    exit(1);
  }
  if (argc <= 1) { 
    printf("input file name required\n");
    exit(1);
  }

  strcpy(celldata_name, argv[1]);

  if((finput = fopen(celldata_name, "r")) == NULL) {
    printf("input file error2\n");
    exit(1);
  }

  if ((num = count_line(finput)) != NN) {
    printf(" error: input data file not consistent.\n");
    printf("input file lines = %d: NN = %d\n", num, NN);
    exit(5);
  }

  fclose(finput);
  if((finput = fopen(celldata_name, "r")) == NULL) {
    printf("input file error2\n");
    exit(1);
  }
  
  initialize_state(state, ageb, agek, fat, Vc);
  /* input vales, initialize gj, return first blank cell's index*/
  initialize_vars(finput, xx, yy, zz, lj, state, r, ageb, agek, div_times, fat, Vc, touch, L, other_cell, tb, &ncell_var, &NDER, &NMEMB);
  printf("variables initialized: NDER=%d NMEMB=%d ncell=%d NN=%d\n", NDER, NMEMB, ncell_var, NN);

  if (nmx != NMX || nmy != NMY) {
    printf("error: number of membrane particles inconsistent with parameter file\n");
    exit(1);
  }

  checkstate(state, ncell_var);
  
  connect_lj(lj, state, ncell_var, xx, yy, zz, r, indx);
  printf("lj connection initialized\n");  

  check_pair(ncell_var, xx, yy, zz, pair, pair2, &pair_indx, L, other_cell);
  
  fclose(finput);
  
  initial_u(u, v, p, a, B, w); // initialization

  KEY_INPUT_DATA = atoi(argv[2]);
  if (KEY_INPUT_DATA != 1 && KEY_INPUT_DATA != 0) {
    printf("error: 2nd argument must be 0 or 1\n");
    exit(3);
  }
  
  if (KEY_INPUT_DATA) {
    printf("chemical data read from recycled_data\n");
    
    sprintf(str_chem, "recycled_data");
    input_uvp(str_chem, u, v, p, a, B, w, ncell_var);
  }

  if (SYSTEM == WHOLE) {
    printf("computing the whole epidermis.\n");
    //    SYSTEM = WHOLE;
  }
  else if (SYSTEM == BASAL) {
    printf("computing only the basal layer and the dermis.\n");
    //    SYSTEM = BASAL;
  }
  else {
    printf("parameter SYSTEM must be 'WHOLE' or 'BASAL'\n");
    exit(1);
  }

  if (KEY_FORCED_SC) 
    printf("forced cornification enabled\n");
  else
    printf("forced cornification disabled\n");

  if (KEY_INPUT_DATA && KEY_FORCED_SC) {
    printf("error: forced cornification must be disabled\n");
    exit(1);
  }
  else if (!KEY_INPUT_DATA && !KEY_FORCED_SC) {
    printf("WARNING: sc formation would take longer without forced cornification.\n");
  }

  if (KEY_DERMAL_CHANGE)
    printf("computing dermal change\n");
  else 
    printf("fixed dermal shape\n");

  printf("divmax=%d, accel_div=%f MALIGNANT=%d\n", 
	 div_max, accel_div, MALIGNANT);
    printf("K_TOTAL=%f, K_DESMOSOME_RATIO=%f\n", K_TOTAL, K_DESMOSOME_RATIO);
  
  evolution(u, v, p, w, a, B, xx, yy, zz, r, ageb, agek, state, div_times, fat, 
	    Vc, touch, lj, indx, &ncell_var, u_ave, pair, pair2,  &pair_indx,  L, other_cell,
            ljd, ljd_indx, tb);  

  printf("finished\n");

  return 0;
}
static void worker(int argc, const char** argv)
{
    double* parameters;
    int ret1, ret2;
    int number_parameters, ap_number_parameters;
    ASTRONOMY_PARAMETERS ap = { 0 };
    STAR_POINTS sp = { 0 };
    EVALUATION_STATE es = { 0 };

    parameters = parse_parameters(argc, argv, &number_parameters);

    if (!parameters)
    {
        fprintf(stderr, "Could not parse parameters from the command line\n");
        mw_finish(EXIT_FAILURE);
    }

    ret1 = read_astronomy_parameters(astronomy_parameter_file, &ap);
    ret2 = read_star_points(star_points_file, &sp);

    MW_DEBUG("ap.number_stream_parameters = %d\n", ap.number_stream_parameters);

    if (ret1)
    {
        fprintf(stderr,
                "APP: error reading astronomy parameters from file %s: %d\n",
                astronomy_parameter_file,
                ret1);
    }

    if (ret2)
    {
        fprintf(stderr,
                "APP: error reading star points from file %s: %d\n",
                star_points_file,
                ret2);
    }

    if (ret1 | ret2)
    {
        free(parameters);
        cleanup_worker();
		mw_finish(EXIT_FAILURE);
    }

    initialize_state(&ap, &sp, &es);

    ap_number_parameters = get_optimized_parameter_count(&ap);

    if (number_parameters < 1 || number_parameters != ap_number_parameters)
    {
        fprintf(stderr,
                "Error reading parameters: number of parameters from the "
                "command line (%d) does not match the number of parameters "
                "to be optimized in %s (%d)\n",
                number_parameters,
                astronomy_parameter_file,
                ap_number_parameters);

        free(parameters);
        cleanup_worker();
        mw_finish(EXIT_FAILURE);
    }

    set_astronomy_parameters(&ap, parameters);

#if COMPUTE_ON_CPU
    init_constants(&ap);
    init_simple_evaluator(cpu_evaluate);
#elif USE_CUDA
    init_constants(&ap);
    init_simple_evaluator(cuda_evaluate);
#elif USE_OCL
    init_constants(&ap);
    init_simple_evaluator(ocl_evaluate);
#else
    #error "Must choose CUDA, OpenCL or CPU"
#endif /* COMPUTE_ON_CPU */

    /* CHECKME: What is this magic 3.0, and why was it being
     * subtracted from CPU and CUDA result, but not OpenCL? */
    double likelihood = evaluate(parameters, &ap, &es, &sp) - 3.0;

    fprintf(stderr, "<search_likelihood> %0.20f </search_likelihood>\n", likelihood);
    fprintf(stderr, "<search_application> %s %s </search_application>\n", BOINC_APP_VERSION, PRECISION);

    free(parameters);
	cleanup_worker();

    mw_finish(EXIT_SUCCESS);

}
Esempio n. 20
0
int main(int argc, char **argv) 
{
  TCHAR *fn, *cwd;
  state *s;
  int count, status = STATUS_OK;

  /* Because the main() function can handle wchar_t arguments on Win32,
     we need a way to reference those values. Thus we make a duplciate
     of the argc and argv values. */ 

#ifndef __GLIBC__
  __progname  = basename(argv[0]);
#endif

  
  s = (state *)malloc(sizeof(state));
  if (NULL == s)
  {
    // We can't use fatal_error because it requires a valid state
    print_status("%s: Unable to allocate state variable", __progname);
    return STATUS_INTERNAL_ERROR;
  }

  if (initialize_state(s))
  {
    print_status("%s: Unable to initialize state variable", __progname);
    return STATUS_INTERNAL_ERROR;
  }

  if (process_command_line(s,argc,argv))
  {
    print_status("%s: Unable to process command line arguments", __progname);
    return STATUS_INTERNAL_ERROR;
  }

#ifdef _WIN32
  if (prepare_windows_command_line(s))
    fatal_error(s,"%s: Unable to process command line arguments", __progname);
#else
  s->argc = argc;
  s->argv = argv;
#endif

  /* Anything left on the command line at this point is a file
     or directory we're supposed to process. If there's nothing
     specified, we should tackle standard input */
  if (optind == argc)
    hash_stdin(s);
  else
  {
    MD5DEEP_ALLOC(TCHAR,fn,PATH_MAX);
    MD5DEEP_ALLOC(TCHAR,cwd,PATH_MAX);

    cwd = _tgetcwd(cwd,PATH_MAX);
    if (NULL == cwd)
      fatal_error(s,"%s: %s", __progname, strerror(errno));

    count = optind;

    while (count < s->argc)
    {  
      generate_filename(s,fn,cwd,s->argv[count]);

#ifdef _WIN32
      status = process_win32(s,fn);
#else
      status = process_normal(s,fn);
#endif

      //      if (status != STATUS_OK)
      //	return status;

      ++count;
    }

    free(fn);
    free(cwd);
  }

  /* We only have to worry about checking for unused hashes if one 
     of the matching modes was enabled. We let the display_not_matched
     function determine if it needs to display anything. The function
     also sets our return values in terms of inputs not being matched
     or known hashes not being used */
  if ((s->mode & mode_match) || (s->mode & mode_match_neg))
    s->return_value = finalize_matching(s);

  return s->return_value;
}
Esempio n. 21
0
int main(int argc, char **argv)
{
  int count, status, goal = argc;
  state *s;
  TCHAR *fn, *cwd;

#ifndef __GLIBC__
  __progname  = basename(argv[0]);
#endif

  s = (state *)malloc(sizeof(state));
  if (NULL == s)
    fatal_error("%s: Unable to allocate state variable", __progname);

  if (initialize_state(s))
    fatal_error("%s: Unable to initialize state variable", __progname);

  process_cmd_line(s,argc,argv);

#ifdef _WIN32
  if (prepare_windows_command_line(s))
    fatal_error("%s: Unable to process command line arguments", __progname);
#else
  s->argc = argc;
  s->argv = argv;
#endif

  // Anything left on the command line at this point is a file
  // or directory we're supposed to process. If there's nothing
  // specified, we should tackle standard input 
  if (optind == argc)
  {
    status = process_stdin(s);
  }
  else
  {
    MD5DEEP_ALLOC(TCHAR,fn,PATH_MAX);
    MD5DEEP_ALLOC(TCHAR,cwd,PATH_MAX);
    
    cwd = _tgetcwd(cwd,PATH_MAX);
    if (NULL == cwd)
      fatal_error("%s: %s", __progname, strerror(errno));
  
    count = optind;
  
    // The signature comparsion mode needs to use the command line
    // arguments and argument count. We don't do wildcard expansion
    // on it on Win32 (i.e. where it matters). The setting of 'goal'
    // to the original argc occured at the start of main(), so we just
    // need to update it if we're *not* in signature compare mode.
    if (!(s->mode & mode_sigcompare))
    {
      goal = s->argc;
    }
    
    while (count < goal)
    {
      if (MODE(mode_sigcompare))
	match_load(s,argv[count]);
      else if (MODE(mode_compare_unknown))
	match_compare_unknown(s,argv[count]);
      else
      {
	generate_filename(s,fn,cwd,s->argv[count]);

#ifdef _WIN32
	status = process_win32(s,fn);
#else
	status = process_normal(s,fn);
#endif
      }
      
      ++count;
    }

    // If we processed files, but didn't find anything large enough
    // to be meaningful, we should display a warning message to the user.
    // This happens mostly when people are testing very small files
    // e.g. $ echo "hello world" > foo && ssdeep foo
    if ( ! s->found_meaningful_file && s->processed_file)
    {
      print_error(s,"%s: Did not process files large enough to produce meaningful results", __progname);
    }
  }


  // If the user has requested us to compare signature files, use
  // our existng code to pretty-print directory matching to do the
  // work for us.
  if (s->mode & mode_sigcompare)
    s->mode |= mode_match_pretty;
  if (s->mode & mode_match_pretty)
    match_pretty(s);
  
  return (EXIT_SUCCESS);
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
  int verbose = 0;
  int iterations = 1;
  int iterating = 0;
  int self_terminate = 0;
  double total_prob = 0.00000001;
  double total_prob_prev = 0.0;
	char c;
  if (argc > 1){
    if (!strcmp(argv[1], "-v")){
      verbose = 1;
      printf("VERBOSE OUTPUT\n");
    } else if (!strcmp(argv[1], "-i")){
    		if (argc == 2){
    			fprintf(stderr, "enter number of iterations\n");
    			exit(1);
    		} else if (argc == 3){
    			iterations = atoi(argv[2]);
    			iterating = 1;
    			printf ("Running %d iterations\n", iterations);
			}
    	} else if (!strcmp(argv[1], "-st")){
    		self_terminate = 1;
    } else {
    		fprintf(stderr, "Invalid arguments\n");
    		exit(1);
    }
	}
  
  puts("Enter input file name:");
  char file_name[64];
  scanf("%s", file_name);
  FILE *file;
  file = fopen(file_name, "r");
  list_t alphabet;
  list_init(& alphabet);
  if (file == NULL){
    fprintf(stderr, "%s: No such file\n", file_name);
    exit(1);
  }
  // Get the list of letters from the file.
  alphabet = parse_file(file);
  
  // Randomly generate initial probabilities.
  srand((unsigned)time(NULL));
  
  int num_letters;
  num_letters = list_size(&alphabet);
  state *state_0 = (state*)malloc(sizeof(state));
  state *state_1 = (state*)malloc(sizeof(state));
  
  state_0 = initialize_state(0, alphabet, 1);
  state_1 = initialize_state(1, alphabet, 0);
  
    printf("---------------------------------\n- Initialization -\n---------------------------------\n");
  
    print_state(state_0, alphabet);
    print_state(state_1, alphabet);
  
    printf("\n---------------------------------\n");
  
  
  double *Pi = (double*)malloc(2*sizeof(double));
  // Pi[0] = ((double)rand()/(double)RAND_MAX);
  Pi[0] = 0.5;
  Pi[1] = 1 - Pi[0];
  printf("Pi:\n\tState\t0\t%lf\n\tState\t1\t%lf\n", Pi[0], Pi[1]);
  
  // Max word size 32
  int i=0;
  char *buffer = (char*)malloc(32);
  list_t words;
  list_init(&words);
  fclose(file);
  file = fopen(file_name, "r");
  while (fscanf(file, "%s ", buffer) != EOF){
  strcat(buffer, "#");
    list_prepend(& words, strdup(buffer));
  }
	//shuffle_list(words, list_size(&words));
  
// Display word list
//  char *temp;
//  for (i=0; i<list_size(&words); i++){
//    temp = (char*)list_get_at(&words, i);
//			printf("%s\n", temp);
//  }
  int iteration = 0;
  if (!self_terminate){
  		while(iteration < iterations){
  			printf("Running iteration number %d\n", iteration);
  			if (!iterating){
   			iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
 		   	printf("\n\n\n\n");
  	  		} else if (iteration == iterations - 1){
   		 	iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
 	 	  } else {
    			iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
    		}
    		iteration++;
    }
  } else {
  		while((iteration < 10) || total_prob_prev < total_prob){
			printf("%lf %lf\n", total_prob_prev, total_prob);
  			printf("Running iteration number %d\n", iteration);
  			total_prob_prev = total_prob;
  			total_prob = iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
  			iteration++;
  			/* If total probability is not increasing much, return that iteration's information.
  			It doesn't make a big difference if we run one more information after the maximum,
  			so I don't output the previous iteration */
 	 	}
		printf("%lf %lf\n", total_prob_prev, total_prob);
		iterate_hmm(alphabet, words, Pi, state_0, state_1, verbose, 1);
  }
//	for (i=0; i<list_size(&alphabet); i++){
//		c = ((letter_count*)list_get_at(&alphabet, i))->letter;
//		printf("Log probability of %c: %lf\n", c, log(ep(state_0, c)/ep(state_1, c)));
//	}
	list_t freq0;
	list_t freq1;
	list_init(&freq0);
	list_init(&freq1);
	letter_double* ld;
	for (i=0; i<list_size(&alphabet); i++){
		c = ((letter_count*)list_get_at(&alphabet, i))->letter;
		ld = (letter_double*)malloc(sizeof(letter_double));
		ld->letter = c;
		ld->d = log(ep(state_0, c)/ep(state_1, c));
		if (log(ep(state_0, c)/ep(state_1, c)) > 0){
			list_append(&freq0, ld);
		}
	}
	list_attributes_comparator(&freq0, compare_log_prob);
	list_sort(&freq0, 1);
	printf("Letters most preferred by State 0:\n");
	for (i=0; i<list_size(&freq0); i++){
		ld = ((letter_double*)list_get_at(&freq0, i));
			printf("%c: %lf\n", ld->letter, ld->d);
	}
	for (i=0; i<list_size(&alphabet); i++){
		c = ((letter_count*)list_get_at(&alphabet, i))->letter;
		ld = (letter_double*)malloc(sizeof(letter_double));
		ld->letter = c;
		ld->d = log(ep(state_0, c)/ep(state_1, c));
		if (log(ep(state_0, c)/ep(state_1, c)) < 0){
			list_append(&freq1, ld);
		}
	}
	list_attributes_comparator(&freq1, compare_log_prob);
	list_sort(&freq1, 1);
	printf("\nLetters most preferred by State 1:\n");
	for (i=0; i<list_size(&freq1); i++){
		ld = ((letter_double*)list_get_at(&freq1, i));
			printf("%c: %lf\n", ld->letter, ld->d);
	}
	printf("\n");
  
  fclose(file);
  return 0;
}