Exemple #1
0
VOL_problem::VOL_problem(const char *filename) : 
   alpha_(-1),
   lambda_(-1),
   iter_(0),
  value(-1),
    psize(-1),
   dsize(-1)
{
   set_default_parm();
   read_params(filename);
}
Exemple #2
0
void CvGBTrees::read( CvFileStorage* fs, CvFileNode* node )
{

    CV_FUNCNAME( "CvGBTrees::read" );

    __BEGIN__;

    CvSeqReader reader;
    CvFileNode* trees_fnode;
    CvMemStorage* storage;
    int i, ntrees;
    cv::String s;

    clear();
    read_params( fs, node );

    if( !data )
        EXIT;

    base_value = (float)cvReadRealByName( fs, node, "base_value", 0.0 );
    class_count = cvReadIntByName( fs, node, "class_count", 1 );

    weak = new pCvSeq[class_count];


    for (int j=0; j<class_count; ++j)
    {
        s = cv::format("trees_%d", j);

        trees_fnode = cvGetFileNodeByName( fs, node, s.c_str() );
        if( !trees_fnode || !CV_NODE_IS_SEQ(trees_fnode->tag) )
            CV_ERROR( CV_StsParseError, "<trees_x> tag is missing" );

        cvStartReadSeq( trees_fnode->data.seq, &reader );
        ntrees = trees_fnode->data.seq->total;

        if( ntrees != params.weak_count )
            CV_ERROR( CV_StsUnmatchedSizes,
            "The number of trees stored does not match <ntrees> tag value" );

        CV_CALL( storage = cvCreateMemStorage() );
        weak[j] = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvDTree*), storage );

        for( i = 0; i < ntrees; i++ )
        {
            CvDTree* tree = new CvDTree();
            CV_CALL(tree->read( fs, (CvFileNode*)reader.ptr, data ));
            CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
            cvSeqPush( weak[j], &tree );
        }
    }

    __END__;
}
Exemple #3
0
void BaseTest::safe_run( int start_from )
{
    CV_TRACE_FUNCTION();
    read_params( ts->get_file_storage() );
    ts->update_context( 0, -1, true );
    ts->update_context( this, -1, true );

    if( !::testing::GTEST_FLAG(catch_exceptions) )
        run( start_from );
    else
    {
        try
        {
        #if !defined _WIN32
        int _code = setjmp( tsJmpMark );
        if( !_code )
            run( start_from );
        else
            throw TS::FailureCode(_code);
        #else
            run( start_from );
        #endif
        }
        catch (const cv::Exception& exc)
        {
            const char* errorStr = cvErrorStr(exc.code);
            char buf[1 << 16];

            const char* delim = exc.err.find('\n') == cv::String::npos ? "" : "\n";
            sprintf( buf, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d",
                    errorStr, delim, exc.err.c_str(), exc.func.size() > 0 ?
                    exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
            ts->printf(TS::LOG, "%s\n", buf);

            ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
        }
        catch (const TS::FailureCode& fc)
        {
            std::string errorStr = TS::str_from_code(fc);
            ts->printf(TS::LOG, "General failure:\n\t%s (%d)\n", errorStr.c_str(), fc);

            ts->set_failed_test_info( fc );
        }
        catch (...)
        {
            ts->printf(TS::LOG, "Unknown failure\n");

            ts->set_failed_test_info( TS::FAIL_EXCEPTION );
        }
    }

    ts->set_gtest_status();
}
Exemple #4
0
Diffusion::Diffusion(Amr* Parent, BCRec* _phys_bc)
  : 
    parent(Parent),
    LevelData(MAX_LEV),
    phi_flux_reg(MAX_LEV, PArrayManage),
    grids(MAX_LEV),
    volume(MAX_LEV),
    area(MAX_LEV),
    phys_bc(_phys_bc)
{
    read_params();
    make_mg_bc();
}
Exemple #5
0
int main(int argc, char* argv[])
{
    if (argc > 1)
    {
        if (strcmp(argv[1], "est")==0)
        {
            read_params(argv[6]);
            print_params();
            em(argv[2], atoi(argv[3]), argv[4], argv[5]);
            return(0);
        }
        if (strcmp(argv[1], "inf")==0)
        {
            read_params(argv[5]);
            print_params();
            inference(argv[2], argv[3], argv[4]);
            return(0);
        }
    }
    printf("usage : ctm est <dataset> <# topics> <rand/seed/model> <dir> <settings>\n");
    printf("        ctm inf <dataset> <model-prefix> <results-prefix> <settings>\n");
    return(0);
}
gboolean
cpufreq_pstate_read (void)
{
  /* gather intel pstate parameters */
  if (!read_params ())
    return FALSE;

  /* now read the number of cpus and the remaining cpufreq info
     for each of them from sysfs */
  if (!cpufreq_sysfs_read ())
    return FALSE;

  return TRUE;
}
/**
 * Entry point
 */
int main(int argc, char *argv[]) {
	s_parameters params;
	DltClient client;
	params.client_ref = &client;
	int err = read_params(&params, argc, argv);

	if (err != 0) {
		usage(argv[0]);
		return err;
	}

	dlt_client_init(&client, params.verbose);
	dlt_client_register_message_callback(receive);

	err = init_dlt_connect(&client, &params, argc, argv);
	if (err != 0) {
		usage(argv[0]);
		return err;
	}

	err = dlt_client_connect(&client, params.verbose);
	if (err != 0) {
			printf("Failed to connect %s.\n", client.serial_mode > 0 ? client.serialDevice : client.servIP);
		return err;
	}

    if(params.output)
    {
        params.output_handle = open(params.output,O_WRONLY|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

        if (params.output_handle == -1)
        {
            fprintf(stderr,"Failed to open %s for writing.\n",params.output);
            return -1;
        }
    }

    params.messages_left = params.max_messages;

	dlt_client_main_loop(&client, &params, params.verbose);

	if(params.output_handle > 0)
	{
		close(params.output_handle);
	}
	return 0;
}
Exemple #8
0
int main() {
    unsigned int i=0;
    unsigned int num_pages;
    // Initial state: flash is insactive, and the big guy just pulled down the
    // MISO pin. 
    last_f = 1;
    if (READ_MISO_PIN())
	last_b = 0;
    else 
	last_b = 1;
    if (last_b == 0) {
	CLR_BIG_GUY_RESET_PIN();
	MAKE_BIG_GUY_RESET_OUTPUT();
	spi_init();
	CLR_SCK_PIN();
	MAKE_BIG_GUY_RESET_OUTPUT();
       	pulse_flash_cs();
	wait_ms(20);
	// read the program legth
	num_pages = read_params();
	//num_pages=575;
	num_pages += 0xff;
	num_pages >>= 8;
	error_code(num_pages);
	if (program_enable()) {
	    program_erase();
	} else {
	    error_code(0x10);
	    hibernate();
	}
	// wait a little bit
	wait_ms(120);
	pulse_flash_cs();
	// pulse the reset pin
	//wait_ms(20);
	// upload the program
	if (program_enable()) {
	    for (i=0; i < num_pages; i++) {
	    program_page(i);
	    wait_ms(56);
	    }
	} else {
	    error_code(0x20);
	}
	
    }
Exemple #9
0
    void read(const FileNode& fn)
    {
        clear();
        read_params(fn["training_params"]);

        fn["weights"] >> weights;
        fn["means"] >> means;

        FileNode cfn = fn["covs"];
        FileNodeIterator cfn_it = cfn.begin();
        int i, n = (int)cfn.size();
        covs.resize(n);

        for( i = 0; i < n; i++, ++cfn_it )
            (*cfn_it) >> covs[i];

        decomposeCovs();
        computeLogWeightDivDet();
    }
Exemple #10
0
int _tmain(int argc, _TCHAR* argv[])
{
    // read_params(); // закоментировать для использования параметров по умолчанию

    InitializeCriticalSection( &crit_sect );

    read_params ();

    // Проверяем параметр количества процессов
    check_proc_count ();

    create_random_bagaj ();

    linear_process ();

    weight = 0;

    semaphore = CreateSemaphore(NULL, 1,1, NULL);

    if (pa == 1)
        thr_process ();
    else if (pa == 2)
        petry_process ();
    else if (pa == 3)
        thr_apc ();
    else if (pa == 4)
        thr_pool_petry (); // */

    FILE *f_out = fopen( output_name, "wt" );

    fprintf( f_out, "Linear time: %d\n", l_time );
    fprintf( f_out, "Multithreaded time: %d", t_time );

    fprintf( f_out, "Total weight of %s is %d\n", name_for, weight );

    fclose(f_out);

    printf( "Press any key to quit\n" );
    getch ();

    return 0;
}
Exemple #11
0
void main(){
	set_mode();

	tick_duration=DEF_TICK_DURATION;

	tick_counter=melody_counter=0;
	tick_started=tick_occured=melody_started=melody_played=false;

	print_color("Lab 2", YELLOW);
	read_params();
	//disable_int();
	//outb(0x43, 0x36);
	//outb(0x40, 0xFF);
	//outb(0x40, 0xFF);
	set_int_addr_func(0x1C, (uint32_t)int1C_handler);
	enable_int();
	while(1){
		read_char();
	}
}
Exemple #12
0
int main(int argc, char **argv) {
    printf("Minimum Bayes Risk Reranker for Dependency Parsing\n");
    if (argc < 3) {
        print_usage();
    }
   
    char *mode = argv[1];
    char *set_fname = argv[2];
    
    APPROX_PARAMS *ap = read_params(set_fname);
    rewrite_parameters(ap, argc, argv, 3);
    
    char *sap = get_params_string(ap);
    printf("Parameters used\n===============\n%s===============\n", sap);
    free(sap);
            
    printf("MP_SIZE: %d\n", sizeof(MODEL_PARAMS));
    DEF_ALLOC(mp, MODEL_PARAMS);
    read_io_spec(ap->io_spec_file, mp);
    
    if (ap->mbr_coeff <= 0.) {
        fprintf(stderr, "Error: MBR_COEFF should be positive (now: MBR_COEFF = %f)\n", ap->mbr_coeff);
        exit(1);
    }
    
    if (strcmp(mode, "-rerank") == 0) {
        process_mbr_rerank(ap, mp);
    } else if (strcmp(mode, "-pred-tree") == 0) {
        fprintf(stderr, "Error: MBR tree prediction is not yet supported.");
    } else if (strcmp(mode, "-pred-str") == 0) {
        process_mbr_pred_str(ap, mp);
    } else {
        fprintf(stderr, "Error: mode '%s' is not supported\n", mode);
        print_usage();
    }
    
    free(ap);
    free(mp);
    mp = NULL;
    return 0; 
}    
void launch(
  int argc, char ** argv,
  unsigned long num_gang_0, unsigned long num_worker_0, unsigned long vector_length_0,
  unsigned long num_gang_1, unsigned long num_worker_1, unsigned long vector_length_1,
  acc_timer_t data_timer, acc_timer_t comp_timer
) {
  unsigned long n;
  float offset;

  read_params(argc, argv, &n, &offset);

  float * a;

  init_datas(n, &a);

  kernel_501(n, a, offset, num_gang_0, num_worker_0, vector_length_0, num_gang_1, num_worker_1, vector_length_1, data_timer, comp_timer);

  acc_timer_delta(data_timer);
  acc_timer_delta(comp_timer);

  free(a);
}
Exemple #14
0
/* module initialization and cleanup */
static int __init init(void)
{
	int i, err;

	printk(KERN_INFO PFX "reading parameters\n");
	err = read_params(DRIVER_NAME, &config);
	if (err != 0)
		return -1;
	printk(KERN_INFO PFX
		"initializing driver for %d (max %d) cards\n",
		config.num_modules, VMOD_MAX_BOARDS);

	/* fill in config data and semaphore */
	for (i = 0; i < config.num_modules; i++) {
		device_list[i].config = &config.module[i];
		init_MUTEX(&device_list[i].sem);
	}

	err = alloc_chrdev_region(&devno, 0, VMOD12E16_MAX_MODULES, DRIVER_NAME);
	if (err != 0)
		goto fail_chrdev;
	printk(KERN_INFO PFX "allocated device %d\n", MAJOR(devno));

	cdev_init(&cdev, &fops);
	cdev.owner = THIS_MODULE;
	if (cdev_add(&cdev, devno, VMOD12E16_MAX_MODULES) != 0) {
		printk(KERN_ERR PFX
			"failed to create chardev %d with err %d\n",
				MAJOR(devno), err);
		goto fail_cdev;
	}
	return 0;

fail_cdev:	
	unregister_chrdev_region(devno, VMOD12E16_MAX_MODULES);
fail_chrdev:	
	return -1;
}
Exemple #15
0
int
main (int argc, char **argv)
{
	size_t		n;
	size_t		p;
	double		*y;
	double		*x;

	if (!read_params (argc, argv)) usage (argv[0]);
	fprintf_params ();

	read_data (fn, skipheaders, &n, &p, &y, &x);

	larsen_centering (n, 1, y);
	larsen_centering (n, p, x);
	larsen_normalizing (n, p, x);

	example_elasticnet (n, p, x, y, start, dt, stop, lambda2, gamma_bic, maxiter);

	free (y);
	free (x);

	return EXIT_SUCCESS;
}
Exemple #16
0
int main(int argc, char ** argv){
    int uid, flags;
    char filename[PATH_MAX + 5];
    int ret;
    uid_t ruid, euid, suid;
    char buffer[STDIN_BUFFER_SIZE];
    char * caret = buffer;
    int read_params_ret;
    while(!(read_params_ret = read_params(&uid, &flags, filename, buffer, &caret))){
        if((ret = change_uids(&ruid, &euid, &suid, uid)) != EXIT_SUCCESS_STATUS)
            return ret; 
        if((ret = try_open(filename, flags)) != EXIT_SUCCESS_STATUS)
            return ret;
        if((ret = restore_uids(ruid, euid, suid)) != EXIT_SUCCESS_STATUS)
            return ret;
    }
    if(read_params_ret & READ_PARAMS_INVALID_ARGS){
        return EXIT_INVALID_ARGS_STATUS;
    }
    if(read_params_ret & READ_PARAMS_OTHER){
        return EXIT_OTHER_ERROR_STATUS;
    }
    return EXIT_SUCCESS_STATUS;
}
Exemple #17
0
int 
interface (
    int nvtxs,		/* number of vertices in full graph */
    int *start,		/* start of edge list for each vertex */
    int *adjacency,		/* edge list data */
    int *vwgts,		/* weights for all vertices */
    float *ewgts,		/* weights for all edges */
    float *x,
    float *y,
    float *z,		/* coordinates for inertial method */
    char *outassignname,	/* name of assignment output file */
    char *outfilename,		/* output file name */
    int *assignment,		/* set number of each vtx (length n) */
    int architecture,		/* 0 => hypercube, d => d-dimensional mesh */
    int ndims_tot,		/* total number of cube dimensions to divide */
    int mesh_dims[3],		/* dimensions of mesh of processors */
    double *goal,			/* desired set sizes for each set */
    int global_method,	/* global partitioning algorithm */
    int local_method,		/* local partitioning algorithm */
    int rqi_flag,		/* should I use RQI/Symmlq eigensolver? */
    int vmax,			/* how many vertices to coarsen down to? */
    int ndims,		/* number of eigenvectors (2^d sets) */
    double eigtol,		/* tolerance on eigenvectors */
    long seed			/* for random graph mutations */
)
{
    extern char *PARAMS_FILENAME;	/* name of file with parameter updates */
    extern int MAKE_VWGTS;	/* make vertex weights equal to degrees? */
    extern int MATCH_TYPE;      /* matching routine to use */
    extern int FREE_GRAPH;	/* free graph data structure after reformat? */
    extern int DEBUG_PARAMS;	/* debug flag for reading parameters */
    extern int DEBUG_TRACE;	/* trace main execution path */
    extern double start_time;	/* time routine is entered */
    extern double reformat_time;/* time spent reformatting graph */
    FILE     *params_file=NULL;	/* file for reading new parameters */
    struct vtx_data **graph;	/* graph data structure */
    double    vwgt_sum;		/* sum of vertex weights */
    double    time;		/* timing variable */
    float   **coords;		/* coordinates for vertices if used */
    int      *vptr;		/* loops through vertex weights */
    int       flag;		/* return code from balance */
    int       nedges;		/* number of edges in graph */
    int       using_vwgts;	/* are vertex weights being used? */
    int       using_ewgts;	/* are edge weights being used? */
    int       nsets_tot=0;	/* total number of sets being created */
    int       igeom;		/* geometric dimension for inertial method */
    int       default_goal;	/* using default goals? */
    int       i;		/* loop counter */
    double    seconds();
    int       reformat();
    void      free_graph(), read_params(), strout();

    if (DEBUG_TRACE > 0) {
	printf("<Entering interface>\n");
    }

    flag = 0;
    graph = NULL;
    coords = NULL;

    if (!Using_Main) {		/* If not using main, need to read parameters file. */
	start_time = seconds();
	params_file = fopen(PARAMS_FILENAME, "r");
	if (params_file == NULL && DEBUG_PARAMS > 1) {
	    printf("Parameter file `%s' not found; using default parameters.\n",
		   PARAMS_FILENAME);
	}
	read_params(params_file);
    }

    if (goal == NULL) {	/* If not passed in, default goals have equal set sizes. */
	default_goal = TRUE;
	if (architecture == 0)
	    nsets_tot = 1 << ndims_tot;
	else if (architecture == 1) 
	    nsets_tot = mesh_dims[0];
	else if (architecture == 2) 
	    nsets_tot = mesh_dims[0] * mesh_dims[1];
	else if (architecture > 2) 
	    nsets_tot = mesh_dims[0] * mesh_dims[1] * mesh_dims[2];

	if (MAKE_VWGTS && start != NULL) {
	    vwgt_sum = start[nvtxs] - start[0] + nvtxs;
	}
	else if (vwgts == NULL) {
	    vwgt_sum = nvtxs;
	}
	else {
	    vwgt_sum = 0;
	    vptr = vwgts;
	    for (i = nvtxs; i; i--)
		vwgt_sum += *(vptr++);
	}

	vwgt_sum /= nsets_tot;
	goal = smalloc_ret(nsets_tot * sizeof(double));
	if (goal == NULL) {
	    strout("\nERROR: No room to make goals.\n");
	    flag = 1;
	    goto skip;
	}
	for (i = 0; i < nsets_tot; i++)
	    goal[i] = vwgt_sum;
    }
    else {
	default_goal = FALSE;
    }

    if (MAKE_VWGTS) {
	/* Generate vertex weights equal to degree of node. */
	if (vwgts != NULL) {
	    strout("WARNING: Vertex weights being overwritten by vertex degrees.");
	}
	vwgts = smalloc_ret(nvtxs * sizeof(int));
	if (vwgts == NULL) {
	    strout("\nERROR: No room to make vertex weights.\n");
	    flag = 1;
	    goto skip;
	}
	if (start != NULL) {
	    for (i = 0; i < nvtxs; i++)
	        vwgts[i] = 1 + start[i + 1] - start[i];
	}
	else {
	    for (i = 0; i < nvtxs; i++)
	        vwgts[i] = 1;
	}
    }

    using_vwgts = (vwgts != NULL);
    using_ewgts = (ewgts != NULL);

    if (start != NULL || vwgts != NULL) {	/* Reformat into our data structure. */
	time = seconds();
	flag = reformat(start, adjacency, nvtxs, &nedges, vwgts, ewgts, &graph);

	if (flag) {
	    strout("\nERROR: No room to reformat graph.\n");
	    goto skip;
	}

	reformat_time += seconds() - time;
    }
    else {
	nedges = 0;
    }

    if (FREE_GRAPH) {		/* Free old graph data structures. */
        free(start);
	free(adjacency);
	if (vwgts != NULL)
	    free(vwgts);
	if (ewgts != NULL)
	    free(ewgts);
	start = NULL;
	adjacency = NULL;
	vwgts = NULL;
	ewgts = NULL;
    }


    if (global_method == 3 ||
        (MATCH_TYPE == 5 && (global_method == 1 || 
			     (global_method == 2 && rqi_flag)))) {
	if (x == NULL) {
	    igeom = 0;
	}
	else {			/* Set up coordinate data structure. */
	    coords = smalloc_ret(3 * sizeof(float *));
	    if (coords == NULL) {
		strout("\nERROR: No room to make coordinate array.\n");
		flag = 1;
		goto skip;
	    }
	    /* Minus 1's are to allow remainder of program to index with 1. */
	    coords[0] = x - 1;
	    igeom = 1;
	    if (y != NULL) {
		coords[1] = y - 1;
		igeom = 2;
		if (z != NULL) {
		    coords[2] = z - 1;
		    igeom = 3;
		}
	    }
	}
    }
    else {
	igeom = 0;
    }

    /* Subtract from assignment to allow code to index from 1. */
    assignment = assignment - 1;
    flag = submain(graph, nvtxs, nedges, using_vwgts, using_ewgts, igeom, coords,
		   outassignname, outfilename,
		   assignment, goal,
		   architecture, ndims_tot, mesh_dims,
		   global_method, local_method, rqi_flag, vmax, ndims,
		   eigtol, seed);

skip:
    if (coords != NULL)
	sfree(coords);

    if (default_goal)
	sfree(goal);

    if (graph != NULL)
	free_graph(graph);

    if (flag && FREE_GRAPH) {
	sfree(start);
	sfree(adjacency);
	sfree(vwgts);
	sfree(ewgts);
    }

    if (!Using_Main && params_file != NULL)
	fclose(params_file);

    return (flag);
}
Exemple #18
0
int main(int argc, char* argv[])
{
  int i, j;
  gaspi_number_t gsize;
  int comm_state = WORKING;
  int num_failures = 0;
  int timesteps = 0;
  
  ASSERT (gaspi_proc_init(GASPI_BLOCK));
  ASSERT (gaspi_proc_rank(&myrank));
  ASSERT (gaspi_proc_num(&numprocs));

  read_params(argc, argv, &timesteps, &numprocs_idle);
	
  numprocs_working = numprocs - numprocs_idle;
  numprocs_working_and_idle = numprocs_working + numprocs_idle;
  gaspi_rank_t *comm_main_ranks = malloc( numprocs_idle * sizeof(gaspi_rank_t));
  init_array_2(comm_main_ranks, numprocs_working);

  /* contains info of all processes:
     which are working(0), broken(1) and idle(2).
     keeps updated all the time(iterations) */
  int * status_processes = (int *) malloc(numprocs * sizeof(int));
	
  init_array_3(status_processes, numprocs, WORKING);
  for(i = numprocs-1, j=0; j < numprocs_idle;--i,++j)
    {
      status_processes[i] = IDLE; // putting last processes to IDLE
    }
	
  // ===== GASPI group creation =====
  if(status_processes[myrank]==WORKING)
    {
      ASSERT(gaspi_group_create(&COMM_MAIN));

      gaspi_number_t i;
      for(i=0; i<numprocs; i++)
	{
	  if(status_processes[i]==WORKING)
	    {
	      ASSERT(gaspi_group_add(COMM_MAIN, i));
	      ASSERT(gaspi_group_size(COMM_MAIN, &gsize));
	    }
	}
      ASSERT(gaspi_group_ranks (COMM_MAIN, comm_main_ranks));
      ASSERT(gaspi_group_commit (COMM_MAIN, GASPI_BLOCK));
    }

  /* ====== Init a SYNC FLAGS Segment ====== */
  /* used to communicate the WORKING, BROKEN, or FINISHED_WORK status between the working and idle processes. */

  gaspi_size_t SYNC_global_mem_size;
  SYNC_global_mem_size = numprocs * sizeof(int);

  gaspi_pointer_t gm_ptr_sync=NULL;
  ASSERT(init_segment (gm_seg_sync_flags_id, SYNC_global_mem_size));
  ASSERT(gaspi_segment_ptr (gm_seg_sync_flags_id, &gm_ptr_sync));

  int * sync_flags = (int *) gm_ptr_sync;
  init_array_3(sync_flags, numprocs, WORKING);
	
  /* ====== Init a health check write FLAGS Segment ====== */
  /* This array is used to send the gaspi_write message write before health_chk routine,
     which will then update the gaspi internal health vector */

  gaspi_size_t health_chk_global_mem_size;
  health_chk_global_mem_size = numprocs*sizeof(int);
  gaspi_pointer_t gm_ptr_health_chk=NULL;
  ASSERT(init_segment (gm_seg_health_chk_array_id, health_chk_global_mem_size));
  ASSERT(gaspi_segment_ptr (gm_seg_health_chk_array_id, &gm_ptr_health_chk));
	
  gaspi_state_vector_t health_vec = (gaspi_state_vector_t) malloc(numprocs);
  ASSERT(gaspi_state_vec_get(health_vec));

  gaspi_rank_t * avoid_list= (gaspi_rank_t *) malloc(numprocs * sizeof(gaspi_rank_t));
  for(i = 0;i < numprocs; ++i)
    avoid_list[i] = (gaspi_rank_t) 0;
	
  gaspi_barrier(GASPI_GROUP_ALL, GASPI_BLOCK);

  /* ===== TIME-STEP LOOP =====  */
  if(status_processes[myrank]==IDLE)
    {
      /* IDLE processes remain in this loop */
      while(1)
	{
	  gaspi_printf("%d.", myrank);
	  if(sync_flags[0] == WORKING)
	    {
	      /*  NO FAILURE REPORTED  */
	      usleep(1000000);
	    }
	  if(sync_flags[0] == BROKEN)
	    {
	      /* FAILURE REPORTED */
	      gaspi_printf("myrank: %d Broken reported\n", myrank);
	      comm_state=BROKEN;
	      break;
	    }
	  if(sync_flags[0] == WORKFINISHED)
	    {
	      /* WORKFINISHED REPORTED */
	      gaspi_printf("myrank: %d WorkFinished reported\n", myrank);
	      comm_state = WORKFINISHED;
	      break;
	    }
	}
    }

  int time_step;
  for(time_step=1; time_step <= timesteps && comm_state!=WORKFINISHED; time_step++)
    {
      gaspi_printf("== time_step: %d ==\n", time_step);
      if(comm_state==WORKING && status_processes[myrank]==WORKING)
	{
	  gaspi_barrier(COMM_MAIN, GASPI_TIMEOUT_TIME);
	  sleep(1); // NOTE: this is the work section.
	  if(time_step == 5 && myrank== 1)
	    {
	      exit (-1);
	    }
	}
      
      if(time_step<timesteps )
	{
	  send_global_msg_to_check_state(health_vec, avoid_list);
	  num_failures = check_comm_health(status_processes, health_vec);

	  gaspi_printf("%d NUM_FAILURES at timestep %d = %d\n", myrank, time_step, num_failures);

	  if( num_failures != 0 )
	    {
	      rescue_process = numprocs_working;
	      if(myrank==0)
		{
		  // message the IDLE process
		  sync_flags[0]=BROKEN;
		  
		  for(i = 0 ; i < num_failures ; ++i)
		    {
		      /* TODO: multiple failures at the same time. */
		      gaspi_printf("messaging rescue_process: %d\n", rescue_process);
		      ASSERT(gaspi_write(gm_seg_sync_flags_id, 0, rescue_process, gm_seg_sync_flags_id, 0, sizeof(int), 0, GASPI_BLOCK));
		      rescue_process++;
		    }
		}

	      if(myrank==0 || myrank==rescue_process)
		gaspi_printf("%d REPAIRING COMM_MAIN FLAG 1\n", myrank);

	      update_status_processes_array(status_processes, health_vec);
	      numprocs_working_and_idle = refresh_numprocs_working_and_idle(status_processes);
	      
	      if(myrank != rescue_process)
		{
		  ASSERT(gaspi_group_delete(COMM_MAIN));
		  ASSERT(recover());
		}
	  
	      ASSERT(gaspi_group_create(&COMM_MAIN_NEW));

	      for(i = 0; i < numprocs; i++)
		{
		  if(status_processes[i]==WORKING)
		    {
		      ASSERT(gaspi_group_add(COMM_MAIN_NEW, i));
		      ASSERT(gaspi_group_size(COMM_MAIN_NEW, &gsize));
		      if(gsize == numprocs_working)
			break;
		    }
		}
	  
	      gaspi_printf("%d: COMM_MAIN_NEW size is: %hi\n", myrank, gsize);

	      ASSERT(gaspi_group_commit (COMM_MAIN_NEW, GASPI_BLOCK));
	  
	      init_array_2(comm_main_ranks, numprocs_working);
	  
	      ASSERT(gaspi_group_ranks (COMM_MAIN_NEW, comm_main_ranks));

	      gaspi_printf("printing group_ranks_main: \n");
	      gaspi_printf_array(comm_main_ranks, numprocs_working);

	      comm_state = WORKING;
	      gaspi_printf("%d REPAIRING COMM_MAIN_NEW FLAG 2\n", myrank);
				
	      if(status_processes[myrank] == WORKING)
		{
		  ASSERT(gaspi_barrier(COMM_MAIN_NEW, GASPI_BLOCK));
		  ASSERT(gaspi_barrier(COMM_MAIN_NEW, GASPI_BLOCK));
		}

	      /* set things to work again */
	      COMM_MAIN = COMM_MAIN_NEW;
	      time_step = 5;
	    }
	}
    }
  
  if(myrank == 0)
    {
      gaspi_printf("finished successfully\n");
    }
  
  gaspi_proc_term(10000);

  return EXIT_SUCCESS;
}
Exemple #19
0
/*--------------------------------------------------------*/
int main(int argc, char *argv[])
{
        char    *inp1name, *inp2name, *parfname, *outfname,
                *corrname;
        short   *sat1, *sat2;
        int     i,
                nobj1, nobj2,
                nsub1, nsub2,
                nmatch,
                maxobj,
                *index;
        float   *x1, *y1, *x2, *y2,
                *mag1, *mag2,
                *xs1, *ys1, *xs2, *ys2,
                *xm1, *ym1, *xm2, *ym2,
                coeffx[3], coeffy[3];
        FILE    *outf;
        PARAMS  par;

/* IO stuff */
  if (argc != 6) usage();

  parfname = argv[1];
  inp1name = argv[2];
  inp2name = argv[3];
  outfname = argv[4];
  corrname = argv[5];

  read_params(parfname, &par);

  nobj1=read_objects(inp1name, &x1, &y1, &mag1, &sat1);
  if (par.verbose) printf("%d objects read from %s\n", nobj1, inp1name);
  if (par.nsub > nobj1) par.nsub = nobj1;
  nsub1=bright_end(nobj1, x1, y1, mag1, par.nsub, &xs1, &ys1, par.verbose);

  nobj2=read_objects(inp2name, &x2, &y2, &mag2, &sat2);
  if (par.verbose) printf("%d objects read from %s\n", nobj2, inp2name);
  if (par.nsub > nobj2) par.nsub = nobj2;
  nsub2=bright_end(nobj2, x2, y2, mag2, par.nsub, &xs2, &ys2, par.verbose);

printf("nsub1= %d\n", nsub1);
printf("nsub2= %d\n", nsub2);

  par.nsub=(nsub1 < nsub2 ? nsub1 : nsub2);
  if (par.verbose > 1) printf("par.nsub= %d\n", par.nsub);

  free(mag1);
  free(mag2);

  if (par.verbose > 2)
  {
    printf("Coordinates of the brighest objects:\n");
    printf("  X1    Y1      X2    Y2\n");
    printf("--------------------------\n");
    for (i=0; i<par.nsub; i++)
      printf("%8.2f %8.2f    %8.2f %8.2f\n", xs1[i], ys1[i], xs2[i], ys2[i]);
    printf("--------------------------\n\n");
  }

/* match nsub brightest stars for approximate transformation */
  maxobj=(nobj1 > nobj2 ? nobj1 : nobj2);
  if (par.verbose > 2) printf("maxobj= %d\n", maxobj);

  if (!(index=(int *)calloc(maxobj, sizeof(int)))) errmess("calloc(index)");

  triangles(xs1, ys1, xs2, ys2, par.nsub, par.nsub, index, par);

  if (!(xm1=(float *)malloc(sizeof(float)))) errmess("malloc(xm1)");
  if (!(ym1=(float *)malloc(sizeof(float)))) errmess("malloc(ym1)");
  if (!(xm2=(float *)malloc(sizeof(float)))) errmess("malloc(xm2)");
  if (!(ym2=(float *)malloc(sizeof(float)))) errmess("malloc(ym2)");

  nmatch=0;
  for (i=0; i<par.nsub; i++)
  {
    if (index[i] != -1)
    {
      if (!(xm1=(float *)realloc(xm1, (nmatch+1)*sizeof(float))))
        errmess("realloc(xm1)");
      if (!(ym1=(float *)realloc(ym1, (nmatch+1)*sizeof(float))))
        errmess("realloc(ym1)");
      if (!(xm2=(float *)realloc(xm2, (nmatch+1)*sizeof(float))))
        errmess("realloc(xm2)");
      if (!(ym2=(float *)realloc(ym2, (nmatch+1)*sizeof(float))))
        errmess("realloc(ym2)");

      xm1[nmatch]=xs1[i];
      ym1[nmatch]=ys1[i];
      xm2[nmatch]=xs2[index[i]];
      ym2[nmatch]=ys2[index[i]];
      nmatch++;
    }
  }

  free(xs1);
  free(ys1);
  free(xs2);
  free(ys2);

  if (nmatch < 2)
  {
    printf("ERROR: nmatch < 2\n");
    exit(2);
  }
  if (par.verbose) printf("%d objects matched by triangles()\n", nmatch);

/* linear fit to nmatch stars indentified by triangles */
  xy_lin(xm1, ym1, xm2, ym2, nmatch, coeffx, coeffy);

  free(xm1);
  free(ym1);
  free(xm2);
  free(ym2);

  if (par.verbose > 1)
  {
    printf("Linear transformation data:\n");
    printf("----------------------\n");
    for (i=0; i<3; i++)
      printf("coeffx[%d]= %12g   coeffy[%d]= %12g\n",
        i, coeffx[i], i, coeffy[i]);
    printf("----------------------\n");
  }

  nobj1=reject_saturated(nobj1, &x1, &y1, sat1);
  nobj2=reject_saturated(nobj2, &x2, &y2, sat2);
  if (par.verbose > 1)
  {
    printf("%d objects from %s left after reject_saturated()\n",
      nobj1, inp1name);
    printf("%d objects from %s left after reject_saturated()\n",
      nobj2, inp2name);
  }

  free(sat1);
  free(sat2);

/* using linear fit transform one list and look for close neighbors */
  for (i=0; i<nobj1; i++)
    maxobj=refine(coeffx, coeffy, x1, y1, x2, y2, nobj1, nobj2, index,
      par.ptol);
  if (par.verbose)
  {
    printf("%d objects left in the template list after refine()\n", maxobj);
    printf("Writing matched list to %s\n\n", outfname);
  }

  if (!(outf=fopen(outfname, "w"))) errmess("outfname");
  for (i=0; i<nobj1; i++)
    if (index[i] != -1)
      fprintf(outf, "%9.3f %10.3f %10.3f %10.3f\n",
                    x1[i], y1[i], x2[index[i]], y2[index[i]]);
  fclose(outf);

  free(index);
  free(x1); free(y1);
  free(x2); free(y2);

  if (!(outf=fopen(corrname, "w"))) errmess(corrname);

  fprintf(outf, "%d  %d  %s",
          (int)(coeffx[2]+0.5), (int)(coeffy[2]+0.5), inp2name);

  fclose(outf);

  return(0);
}
Exemple #20
0
int 
main (void)
{
    extern int Using_Main;	/* is main routine being called? */
    extern char *Graph_File_Name;	/* name of graph input file */
    extern char *Geometry_File_Name;	/* name of coordinate input file */
    extern char *Assign_In_File_Name;	/* name of assignment input input file */
    extern char *PARAMS_FILENAME;	/* name of file with parameter updates */
    extern double EIGEN_TOLERANCE;	/* tolerance for eigen calculations */
    extern int OUTPUT_ASSIGN;	/* whether to write assignment to file */
    extern int DEBUG_MEMORY;	/* debug memory allocation and freeing? */
    extern int DEBUG_TRACE;	/* trace main execution path */
    extern int DEBUG_PARAMS;	/* debug flag for reading parameters */
    extern long RANDOM_SEED;	/* seed for random number generators */
    extern int ECHO;		/* controls amount of output */
    extern int PROMPT;		/* prompt for input or not? */
    extern int PRINT_HEADERS;	/* print lines for output sections? */
    extern int MATCH_TYPE;      /* matching routine to call */
    extern double input_time;	/* times data file input */
    extern double start_time;	/* time partitioning starts */
    FILE     *fin;		/* input file */
    FILE     *fingeom;		/* geometry input file (for inertial method) */
    FILE     *finassign;	/* assignment file if reading in */
    FILE     *params_file;	/* file with parameter value updates */
    double   *goal;		/* desired set sizes */
    float    *x, *y, *z;	/* coordinates for inertial method */
    int      *start;		/* start of edge list for each vertex */
    int      *adjacency;	/* edge list data */
    float    *ewgts;		/* weights for all edges */
    int      *vwgts;		/* weights for all vertices */
    int       global_method;	/* global partitioning method */
    int       local_method;	/* local partitioning method */
    int    *assignment;	/* set number of each vtx (length nvtxs+1) */
    double    eigtol;		/* tolerance in eigenvector calculation */
    int       nvtxs;		/* number of vertices in graph */
    int       ndims;		/* dimension of recursive partitioning */
    int       architecture;	/* 0 => hypercube, d => d-dimensional mesh */
    int       ndims_tot;	/* total number of cube dimensions to divide */
    int       mesh_dims[3];	/* dimensions of mesh of processors */
    long      seed;		/* for random graph mutations */
    int       rqi_flag;		/* use RQI/Symmlq eigensolver? */
    int       vmax;		/* if so, how many vertices to coarsen down to? */
    int       igeom;		/* geometry dimension if inertial method */
    char      graphname[NAME_LENGTH];	/* name of graph input file */
    char      geomname[NAME_LENGTH];	/* name of geometry input file */
    char      inassignname[NAME_LENGTH];	/* assignment input file name */
    char      outassignname[NAME_LENGTH];	/* assignment output file name */
    char      outfilename[NAME_LENGTH];	/* name of output file */
    char     *outassignptr;	/* name or null pointer for output assignment */
    char     *outfileptr;	/* name or null pointer for output file */
    int       another;		/* run another problem? */
    double    time;		/* timing marker */
    int       flag;		/* return code from input routines */
    double    seconds();	/* returns elapsed time in seconds */
    int       affirm();
    int       input_graph(), input_geom();
    void      input_queries(), read_params(), clear_timing();

/*malloc_debug(2);*/

    if (DEBUG_TRACE > 0) {
	printf("<Entering main>\n");
    }

    if (PRINT_HEADERS) {
        printf("\n                    Chaco 2.0\n");
        printf("          Sandia National Laboratories\n\n");
    }

    Using_Main = TRUE;
    another = TRUE;
    params_file = fopen(PARAMS_FILENAME, "r");
    if (params_file == NULL && DEBUG_PARAMS > 1) {
	printf("Parameter file `%s' not found; using default parameters.\n",
	       PARAMS_FILENAME);
    }

    while (another) {

	start_time = time = seconds();

	x = y = z = NULL;
	goal = NULL;
	assignment = NULL;

	read_params(params_file);

	input_queries(&fin, &fingeom, &finassign, graphname, geomname, inassignname,
		      outassignname, outfilename,
		      &architecture, &ndims_tot, mesh_dims,
		      &global_method, &local_method, &rqi_flag, &vmax, &ndims);

	if (global_method == 7)
	    Assign_In_File_Name = inassignname;
	else
	    Assign_In_File_Name = NULL;

	if (OUTPUT_ASSIGN > 0)
	    outassignptr = outassignname;
	else
	    outassignptr = NULL;

	if (ECHO < 0)
	    outfileptr = outfilename;
	else
	    outfileptr = NULL;

	flag = input_graph(fin, graphname, &start, &adjacency, &nvtxs, &vwgts, &ewgts);
	if (flag) {
	    sfree(ewgts);
	    sfree(vwgts);
	    sfree(adjacency);
	    sfree(start);
	    goto skip;
	}

	Graph_File_Name = graphname;

	assignment = smalloc(nvtxs * sizeof(int));
	if (global_method == 7) {
	    flag = input_assign(finassign, inassignname, nvtxs, assignment);
	    if (flag)
		goto skip;
	    Assign_In_File_Name = inassignname;
	}

	if (global_method == 3 ||
	    (MATCH_TYPE == 5 && (global_method == 1 || 
				 (global_method == 2 && rqi_flag)))) {
	    /* Read in geometry data. */
	    flag = input_geom(fingeom, geomname, nvtxs, &igeom, &x, &y, &z);
	    if (flag)
		goto skip;
	    Geometry_File_Name = geomname;
	}
	else {
	    x = y = z = NULL;
	}

	input_time += seconds() - time;

	eigtol = EIGEN_TOLERANCE;
	seed = RANDOM_SEED;

	interface(nvtxs, start, adjacency, vwgts, ewgts, x, y, z,
		  outassignptr, outfileptr,
		  assignment,
		  architecture, ndims_tot, mesh_dims, goal,
		  global_method, local_method, rqi_flag, vmax, ndims,
		  eigtol, seed);

skip:
	if (global_method == 3) {
	    if (z != NULL)
		sfree(z);
	    if (y != NULL)
		sfree(y);
	    if (x != NULL)
		sfree(x);
	}
	sfree(assignment);

	if (DEBUG_MEMORY > 0) {
	    printf("\n");
	}

	if (PROMPT) {
	    another = affirm("\nRun Another Problem");
	}
	else {
	    another = affirm("");
	}
	if (another) {
	    clear_timing();
	    printf("\n------------------------------------------------\n\n");
	    fflush(stdout);
	}
    }
    if (params_file != NULL)
	fclose(params_file);

    if (DEBUG_TRACE > 1) {
	printf("<Leaving main>\n");
    }
    
    return(0);
}
Exemple #21
0
int main (int argc, char *argv[])
{
  /* check that we were given at least one argument
   * (the transfer file name) */
  if (argc != 2) {
    printf("Usage: scr_transfer <transferfile>\n");
    return 1;
  }

  /* record the name of the transfer file */
  scr_transfer_file = strdup(argv[1]);
  if (scr_transfer_file == NULL) {
    scr_err("scr_transfer: Copying transfer file name @ %s:%d",
            __FILE__, __LINE__
    );
    return 1;
  }

  /* initialize our tracking variables */
  read_params();

  /* get file io mode */
  mode_t mode_file = scr_getmode(1, 1, 0);

  /* we cache the opened file descriptors to avoid extra opens,
   * seeks, and closes */
  int fd_src = -1;
  int fd_dst = -1;

  char* new_file_src = NULL;
  char* old_file_src = NULL;
  char* new_file_dst = NULL;
  char* old_file_dst = NULL;

  off_t new_position = 0;
  off_t old_position = 0;

  /* start in the stopped state */
  state = STOPPED;
  set_transfer_file_state(SCR_TRANSFER_KEY_STATE_STOP, 0);

  /* TODO: enable this value to be set from config file */
  /* TODO: page-align this buffer for faster performance */
  /* allocate our file copy buffer */
  size_t bufsize = scr_file_buf_size;
  char* buf = malloc(bufsize);
  if (buf == NULL) {
    scr_err("scr_transfer: Failed to allocate %llu bytes for file copy buffer @ %s:%d",
            (unsigned long long) bufsize, __FILE__, __LINE__
    );
    return 1;
  }

  int nread = 0;
  double secs_run   = 0.0;
  double secs_slept = 0.0;
  double secs_run_start  = scr_seconds();
  double secs_run_end    = secs_run_start;
  double secs_last_write = secs_run_start;
  scr_hash* hash = scr_hash_new();
  while (keep_running) {
    /* loop here sleeping and checking transfer file periodically
     * until state changes and / or some time elapses */
    /* reset our timer for our last write */
    double secs_remain = scr_transfer_secs;
    while (keep_running && (state == STOPPED || secs_remain > 0.0)) {
      /* remember our current state before reading transfer file */
      int old_state = state;

      /* read the transfer file, which fills in our hash and
       * also updates state and bytes_per_second */
      scr_hash_delete(&hash);
      hash = read_transfer_file();

      /* compute time we should sleep before writing more data based
       * on bandwidth and percent of runtime limits */
      if (state == RUNNING) {
        /* get the current time */
        double secs_now = scr_seconds();

        /* based on the amount we last wrote and our allocated bandwidth,
         * compute time we need to sleep before attempting our next write */
        double secs_remain_bw = 0.0;
        if (nread > 0 && bytes_per_second > 0.0) {
          double secs_to_wait_bw = (double) nread / bytes_per_second;
          double secs_waited_bw = secs_now - secs_last_write;
          secs_remain_bw = secs_to_wait_bw - secs_waited_bw;
        }

        /* based on the percentage of time we are allowed to be running,
         * compute time we need to sleep before attempting our next write */
        double secs_remain_runtime = 0.0;
        if (percent_runtime > 0.0) {
          /* stop the run clock, add to the run time,
           * and restart the run clock */
          secs_run_end = secs_now;
          secs_run += secs_run_end - secs_run_start;
          secs_run_start = secs_run_end;

          /* compute our total time, and the time we need to sleep */
          double secs_total = secs_run + secs_slept;
          secs_remain_runtime = secs_run / percent_runtime - secs_total;
        }

        /* take the maximum of these two values */
        secs_remain = secs_remain_bw;
        if (secs_remain_runtime > secs_remain) {
          secs_remain = secs_remain_runtime;
        }
      }

      /* check for a state transition */
      if (state != old_state) {
        if (state == RUNNING) {
          /* if we switched to RUNNING, kick out without sleeping and
           * reset the total run and sleep times */
          secs_remain = 0.0;
          secs_run    = 0.0;
          secs_slept  = 0.0;
        } else if (state == STOPPED) {
          /* if we switched to STOPPED, close our files if open */
          close_files(new_file_src, &fd_src, new_file_dst, &fd_dst);
          clear_parameters(&new_file_src, &new_file_dst, &new_position);
          clear_parameters(&old_file_src, &old_file_dst, &old_position);

          /* after closing our files, update our state in the transfer file */
          set_transfer_file_state(SCR_TRANSFER_KEY_STATE_STOP, 0);
        }
      }

      /* assume we can sleep for the full remainder of the time */
      double secs = secs_remain;

      /* if we're not running, always sleep for the full time */
      if (state != RUNNING) {
        secs = scr_transfer_secs;
      }

      /* set a maximum time to sleep before we read the hash file again
       * (ensures some responsiveness) */
      if (secs > scr_transfer_secs) {
        secs = scr_transfer_secs;
      }

      /* sleep if we need to */
      if (secs > 0.0) {
        /* stop the run clock and add to the total run time */
        secs_run_end = scr_seconds();
        secs_run += secs_run_end - secs_run_start;

        /* sleep */
        usleep((unsigned long) (secs * 1000000.0));
        secs_slept += secs;
        secs_remain -= secs;

        /* restart the run clock */
        secs_run_start = scr_seconds();
      }
    }

    /* write data out */
    if (state == RUNNING) {
      /* look for a new file to transfer */
      off_t filesize = 0;
      find_file(hash, &new_file_src, &new_file_dst, &new_position, &filesize);

      /* if we got a new file, close the old one (if open),
       * open the new file */
      if (bool_diff_files(new_file_src, old_file_src)) {
        /* close the old descriptor if it's open */
        if (fd_src >= 0) {
          scr_close(old_file_src, fd_src);
          fd_src = -1;
        }

        /* delete the old file name if we have one */
        if (old_file_src != NULL) {
          free(old_file_src);
          old_file_src = NULL;
        }

        /* reset our position counter */
        old_position = 0;

        /* open the file and remember the filename if we have one */
        if (new_file_src != NULL) {
          fd_src = scr_open(new_file_src, O_RDONLY);
          /* TODO: check for errors here */
          old_file_src = strdup(new_file_src);
          /* TODO: check for errors here */
        }
      }

      /* if we got a new file, close the old one (if open),
       * open the new file */
      if (bool_diff_files(new_file_dst, old_file_dst)) {
        /* close the old descriptor if it's open */
        if (fd_dst >= 0) {
          scr_close(old_file_dst, fd_dst);
          fd_dst = -1;
        }

        /* delete the old file name if we have one */
        if (old_file_dst != NULL) {
          free(old_file_dst);
          old_file_dst = NULL;
        }

        /* reset our position counter */
        old_position = 0;

        /* open the file and remember the filename if we have one */
        if (new_file_dst != NULL) {
          fd_dst = scr_open(new_file_dst, O_RDWR | O_CREAT, mode_file);
          /* TODO: check for errors here */
          old_file_dst = strdup(new_file_dst);
          /* TODO: check for errors here */
        }
      }

      /* we may have the same file, but perhaps the position changed
       * (may need to seek) */
      if (new_position != old_position) {
        if (fd_src >= 0) {
          lseek(fd_src, new_position, SEEK_SET);
          /* TODO: check for errors here */
        }

        if (fd_dst >= 0) {
          lseek(fd_dst, new_position, SEEK_SET);
          /* TODO: check for errors here */
        }

        /* remember the new position */
        old_position = new_position;
      }

      /* if we have two open files,
       * copy a chunk from source file to destination file */
      nread = 0;
      if (fd_src >= 0 && fd_dst >= 0) {
        /* compute number of bytes to read from file */
        size_t count = (size_t) (filesize - new_position);
        if (count > bufsize) {
          count = bufsize;
        }

        /* read a chunk */
        nread = scr_read(new_file_src, fd_src, buf, count);

        /* if we read data, write it out */
        if (nread > 0) {
          /* record the time of our write */
          secs_last_write = scr_seconds();

          /* write the chunk and force it out with an fsync */
          scr_write(new_file_dst, fd_dst, buf, nread);
          fsync(fd_dst);

          /* update our position */
          new_position += (off_t) nread;
          old_position = new_position;

          /* record the updated position in the transfer file */
          update_transfer_file(new_file_src, new_file_dst, new_position);
        }

        /* if we've written all of the bytes, close the files */
        if (new_position == filesize) {
          close_files(new_file_src, &fd_src, new_file_dst, &fd_dst);
          clear_parameters(&new_file_src, &new_file_dst, &new_position);
          clear_parameters(&old_file_src, &old_file_dst, &old_position);
        }
      } else {
        /* TODO: we may have an error
         * (failed to open the source or dest file) */
        /* if we found no file to transfer, move to a STOPPED state */
        if (new_file_src == NULL) {
          state = STOPPED;
          set_transfer_file_state(SCR_TRANSFER_KEY_STATE_STOP, 1);
        }
      }
    }
  }

  /* free our file copy buffer */
  if (buf != NULL) {
    free(buf);
    buf = NULL;
  }

  /* free the strdup'd tranfer file name */
  if (scr_transfer_file != NULL) {
    free(scr_transfer_file);
    scr_transfer_file = NULL;
  }

  return 0;
}
Exemple #22
0
int load_filter(FILTERCHAIN* fc, CONFIG* cnf)
{
	FILTER_PARAMETER** fparams = NULL;
	int i, paramc = -1;
	int sess_err = 0;
	int x;
	if(cnf == NULL){
   
		fparams = read_params(&paramc);
 
	}else{

		CONFIG* iter = cnf;
		CONFIG_ITEM* item;
		while(iter){
			paramc = -1;
			item = iter->item;
      
			while(item){

				/**Matching configuration found*/
				if(!strcmp(item->name,"module") && !strcmp(item->value,fc->name)){
					paramc = 0;
					item = iter->item;
	  
					while(item){
						if(strcmp(item->name,"module") && strcmp(item->name,"type")){
							paramc++;
						}
						item = item->next;
					}
					item = iter->item;
					fparams = calloc((paramc + 1),sizeof(FILTER_PARAMETER*));
					if(fparams){
	    
						int i = 0;
						while(item){
							if(strcmp(item->name,"module") != 0 &&
							   strcmp(item->name,"type") != 0){
								fparams[i] = malloc(sizeof(FILTER_PARAMETER));
								if(fparams[i]){
									fparams[i]->name = strdup(item->name);
									fparams[i]->value = strdup(item->value);
									i++;
								}
							}
							item = item->next;
						}

					}

				}

				if(paramc > -1){
					break;
				}else{
					item = item->next;
				}

			}

			if(paramc > -1){
				break;
			}else{
				iter = iter->next;
			}

		}
	}


	if(cnf && fc && fc->instance){


		fc->filter = (FILTER*)fc->instance->createInstance(NULL,fparams);
		if(fc->filter == NULL){
			printf("Error loading filter:%s: createInstance returned NULL.\n",fc->name);
			sess_err = 1;
			goto error;
		}
		for(i = 0;i<instance.session_count;i++){

			if((fc->session[i] = fc->instance->newSession(fc->filter, instance.session)) &&
			   (fc->down[i] = calloc(1,sizeof(DOWNSTREAM))) &&
			   (fc->up[i] = calloc(1,sizeof(UPSTREAM)))){

				fc->up[i]->session = NULL;
				fc->up[i]->instance = NULL;
				fc->up[i]->clientReply = (void*)clientReply;

				if(fc->instance->setUpstream && fc->instance->clientReply){
					fc->instance->setUpstream(fc->filter, fc->session[i], fc->up[i]);
				}else{
                                    MXS_WARNING("The filter %s does not support client replies.\n",fc->name);
				}

				if(fc->next && fc->next->next){ 

					fc->down[i]->routeQuery = (void*)fc->next->instance->routeQuery;
					fc->down[i]->session = fc->next->session[i];
					fc->down[i]->instance = fc->next->filter;
					fc->instance->setDownstream(fc->filter, fc->session[i], fc->down[i]);

					fc->next->up[i]->clientReply = (void*)fc->instance->clientReply;
					fc->next->up[i]->session = fc->session[i];
					fc->next->up[i]->instance = fc->filter;

					if(fc->instance->setUpstream && fc->instance->clientReply){
						fc->next->instance->setUpstream(fc->next->filter,fc->next->session[i],fc->next->up[i]);
					}

				}else{ /**The dummy router is the next one*/

					fc->down[i]->routeQuery = (void*)routeQuery;
					fc->down[i]->session = NULL;
					fc->down[i]->instance = NULL;
					fc->instance->setDownstream(fc->filter, fc->session[i], fc->down[i]);

				}

			}


			if(!fc->session[i] || !fc->down[i] || !fc->up[i]){

				sess_err = 1;
				break;

			}

		}
    
		if(sess_err){
			for(i = 0;i<instance.session_count;i++){
				if(fc->filter && fc->session[i]){
					fc->instance->freeSession(fc->filter, fc->session[i]);
				}
				free(fc->down[i]);
			}
			free(fc->session);
			free(fc->down);
			free(fc->name);
			free(fc);
		}
    
	}
	error:  


	if(fparams){
		for(x = 0;x<paramc;x++){
			free(fparams[x]->name);
			free(fparams[x]->value);
		}
	}

	free(fparams);

	return sess_err ? 0 : 1;
}
int main(int argc, char *argv[])
{
  lprec *lp = NULL;
  char *filen, *wlp = NULL, *wmps = NULL, *wfmps = NULL, plp = FALSE;
  int i;
  int verbose = IMPORTANT /* CRITICAL */;
  int debug = -1;
  MYBOOL report = FALSE;
  MYBOOL nonames = FALSE, norownames = FALSE, nocolnames = FALSE;
  MYBOOL write_model_after = FALSE;
  MYBOOL noint = FALSE;
  int print_sol = -1;
  MYBOOL print_stats = FALSE;
  int floor_first = -1;
  MYBOOL do_set_bb_depthlimit = FALSE;
  int bb_depthlimit = 0;
  MYBOOL do_set_solutionlimit = FALSE;
  int solutionlimit = 0;
  MYBOOL break_at_first = FALSE;
  int scaling = 0;
  double scaleloop = 0;
  MYBOOL tracing = FALSE;
  short filetype = filetypeLP;
  int anti_degen1 = -1;
  int anti_degen2 = -1;
  short print_timing = FALSE;
  short parse_only = FALSE;
  int do_presolve = -1;
  short objective = 0;
  short PRINT_SOLUTION = 2;
  int improve = -1;
  int pivoting1 = -1;
  int pivoting2 = -1;
  int bb_rule1 = -1;
  int bb_rule2 = -1;
  int max_num_inv = -1;
  int scalemode1 = -1;
  int scalemode2 = -1;
  int crashmode = -1;
  char *guessbasis = NULL;
  /* short timeoutok = FALSE; */
  long sectimeout = -1;
  int result;
  MYBOOL preferdual = AUTOMATIC;
  int simplextype = -1;
  MYBOOL do_set_obj_bound = FALSE;
  REAL obj_bound = 0;
  REAL mip_absgap = -1;
  REAL mip_relgap = -1;
  REAL epsperturb = -1;
  REAL epsint = -1;
  REAL epspivot = -1;
  REAL epsd = -1;
  REAL epsb = -1;
  REAL epsel = -1;
  MYBOOL do_set_break_at_value = FALSE;
  REAL break_at_value = 0;
  REAL accuracy_error0, accuracy_error = -1;
  FILE *fpin = stdin;
  char *bfp = NULL;
  char *rxliname = NULL, *rxli = NULL, *rxlidata = NULL, *rxlioptions = NULL, *wxliname = NULL, *wxlisol = NULL, *wxli = NULL, *wxlioptions = NULL, *wxlisoloptions = NULL;
  char *rbasname = NULL, *wbasname = NULL;
  char *debugdump_before = NULL;
  char *debugdump_after = NULL;
  char *rparname = NULL;
  char *rparoptions = NULL;
  char *wparname = NULL;
  char *wparoptions = NULL;
  char obj_in_basis = -1;
  char mps_ibm = FALSE;
  char mps_negobjconst = FALSE;
  char mps_free = FALSE;
  MYBOOL ok;
# define SCALINGTHRESHOLD 0.03

  /* read command line arguments */

# if defined FORTIFY
   Fortify_EnterScope();
# endif

  for(i = 1; i < argc; i++) {
    ok = FALSE;
    if(strncmp(argv[i], "-v", 2) == 0) {
      if (argv[i][2])
        verbose = atoi(argv[i] + 2);
      else
        verbose = NORMAL;
    }
    else if(strcmp(argv[i], "-d") == 0)
      debug = TRUE;
    else if(strcmp(argv[i], "-R") == 0)
      report = TRUE;
    else if(strcmp(argv[i], "-i") == 0)
      print_sol = TRUE;
    else if(strcmp(argv[i], "-ia") == 0)
      print_sol = AUTOMATIC;
    else if(strcmp(argv[i], "-stat") == 0)
      print_stats = TRUE;
    else if(strcmp(argv[i], "-nonames") == 0)
      nonames = TRUE;
    else if(strcmp(argv[i], "-norownames") == 0)
      norownames = TRUE;
    else if(strcmp(argv[i], "-nocolnames") == 0)
      nocolnames = TRUE;
    else if((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "-cc") == 0))
      floor_first = BRANCH_CEILING;
    else if(strcmp(argv[i], "-cf") == 0)
      floor_first = BRANCH_FLOOR;
    else if(strcmp(argv[i], "-ca") == 0)
      floor_first = BRANCH_AUTOMATIC;
    else if((strcmp(argv[i], "-depth") == 0) && (i + 1 < argc)) {
      do_set_bb_depthlimit = TRUE;
      bb_depthlimit = atoi(argv[++i]);
    }
    else if(strcmp(argv[i], "-Bw") == 0)
      or_value(&bb_rule2, NODE_WEIGHTREVERSEMODE);
    else if(strcmp(argv[i], "-Bb") == 0)
      or_value(&bb_rule2, NODE_BRANCHREVERSEMODE);
    else if(strcmp(argv[i], "-Bg") == 0)
      or_value(&bb_rule2, NODE_GREEDYMODE);
    else if(strcmp(argv[i], "-Bp") == 0)
      or_value(&bb_rule2, NODE_PSEUDOCOSTMODE);
    else if(strcmp(argv[i], "-BR") == 0)
      or_value(&bb_rule2, NODE_PSEUDORATIOSELECT);
    else if(strcmp(argv[i], "-Bf") == 0)
      or_value(&bb_rule2, NODE_DEPTHFIRSTMODE);
    else if(strcmp(argv[i], "-Br") == 0)
      or_value(&bb_rule2, NODE_RANDOMIZEMODE);
    else if(strcmp(argv[i], "-BG") == 0)
      or_value(&bb_rule2, 0 /* NODE_GUBMODE */); /* doesn't work yet */
    else if(strcmp(argv[i], "-Bd") == 0)
      or_value(&bb_rule2, NODE_DYNAMICMODE);
    else if(strcmp(argv[i], "-Bs") == 0)
      or_value(&bb_rule2, NODE_RESTARTMODE);
    else if(strcmp(argv[i], "-BB") == 0)
      or_value(&bb_rule2, NODE_BREADTHFIRSTMODE);
    else if(strcmp(argv[i], "-Bo") == 0)
      or_value(&bb_rule2, NODE_AUTOORDER);
    else if(strcmp(argv[i], "-Bc") == 0)
      or_value(&bb_rule2, NODE_RCOSTFIXING);
    else if(strcmp(argv[i], "-Bi") == 0)
      or_value(&bb_rule2, NODE_STRONGINIT);
    else if(strncmp(argv[i], "-B", 2) == 0) {
      if (argv[i][2])
        set_value(&bb_rule1, atoi(argv[i] + 2));
      else
        set_value(&bb_rule1, NODE_FIRSTSELECT);
    }
    else if((strcmp(argv[i], "-n") == 0) && (i + 1 < argc)) {
      do_set_solutionlimit = TRUE;
      solutionlimit = atoi(argv[++i]);
    }
    else if((strcmp(argv[i], "-b") == 0) && (i + 1 < argc)) {
      obj_bound = atof(argv[++i]);
      do_set_obj_bound = TRUE;
    }
    else if(((strcmp(argv[i], "-g") == 0) || (strcmp(argv[i], "-ga") == 0)) && (i + 1 < argc))
      mip_absgap = atof(argv[++i]);
    else if((strcmp(argv[i], "-gr") == 0) && (i + 1 < argc))
      mip_relgap = atof(argv[++i]);
    else if((strcmp(argv[i], "-e") == 0) && (i + 1 < argc)) {
      epsint = atof(argv[++i]);
      if((epsint <= 0.0) || (epsint >= 0.5)) {
        fprintf(stderr, "Invalid tolerance %g; 0 < epsilon < 0.5\n",
                (double)epsint);
        EndOfPgr(FORCED_EXIT);
      }
    }
    else if((strcmp(argv[i], "-r") == 0) && (i + 1 < argc))
      max_num_inv = atoi(argv[++i]);
    else if((strcmp(argv[i], "-o") == 0) && (i + 1 < argc)) {
      break_at_value = atof(argv[++i]);
      do_set_break_at_value = TRUE;
    }
    else if(strcmp(argv[i], "-f") == 0)
      break_at_first = TRUE;
    else if(strcmp(argv[i], "-timeoutok") == 0)
      /* timeoutok = TRUE */; /* option no longer needed, but still accepted */
    else if(strcmp(argv[i], "-h") == 0) {
      print_help(argv);
      EndOfPgr(EXIT_SUCCESS);
    }
    else if(strcmp(argv[i], "-prim") == 0)
      preferdual = FALSE;
    else if(strcmp(argv[i], "-dual") == 0)
      preferdual = TRUE;
    else if(strcmp(argv[i], "-simplexpp") == 0)
      simplextype = SIMPLEX_PRIMAL_PRIMAL;
    else if(strcmp(argv[i], "-simplexdp") == 0)
      simplextype = SIMPLEX_DUAL_PRIMAL;
    else if(strcmp(argv[i], "-simplexpd") == 0)
      simplextype = SIMPLEX_PRIMAL_DUAL;
    else if(strcmp(argv[i], "-simplexdd") == 0)
      simplextype = SIMPLEX_DUAL_DUAL;
    else if(strcmp(argv[i], "-sp") == 0)
      or_value(&scalemode2, SCALE_POWER2);
    else if(strcmp(argv[i], "-si") == 0)
      or_value(&scalemode2, SCALE_INTEGERS);
    else if(strcmp(argv[i], "-se") == 0)
      or_value(&scalemode2, SCALE_EQUILIBRATE);
    else if(strcmp(argv[i], "-sq") == 0)
      or_value(&scalemode2, SCALE_QUADRATIC);
    else if(strcmp(argv[i], "-sl") == 0)
      or_value(&scalemode2, SCALE_LOGARITHMIC);
    else if(strcmp(argv[i], "-sd") == 0)
      or_value(&scalemode2, SCALE_DYNUPDATE);
    else if(strcmp(argv[i], "-sr") == 0)
      or_value(&scalemode2, SCALE_ROWSONLY);
    else if(strcmp(argv[i], "-sc") == 0)
      or_value(&scalemode2, SCALE_COLSONLY);
    else if(strncmp(argv[i], "-s", 2) == 0) {
      set_value(&scalemode1, SCALE_NONE);
      scaling = SCALE_MEAN;
      if (argv[i][2]) {
        switch (atoi(argv[i] + 2)) {
        case 0:
          scaling = SCALE_NONE;
          break;
        case 1:
          set_value(&scalemode1, SCALE_GEOMETRIC);
          break;
        case 2:
          set_value(&scalemode1, SCALE_CURTISREID);
          break;
        case 3:
          set_value(&scalemode1, SCALE_EXTREME);
          break;
        case 4:
          set_value(&scalemode1, SCALE_MEAN);
          break;
        case 5:
          set_value(&scalemode1, SCALE_MEAN | SCALE_LOGARITHMIC);
          break;
        case 6:
          set_value(&scalemode1, SCALE_RANGE);
          break;
        case 7:
          set_value(&scalemode1, SCALE_MEAN | SCALE_QUADRATIC);
          break;
        }
      }
      else
        set_value(&scalemode1, SCALE_MEAN);
      if((i + 1 < argc) && (isNum(argv[i + 1])))
        scaleloop = atoi(argv[++i]);
    }
    else if(strncmp(argv[i], "-C", 2) == 0)
      crashmode = atoi(argv[i] + 2);
    else if((strcmp(argv[i],"-gbas") == 0) && (i + 1 < argc))
      guessbasis = argv[++i];
    else if(strcmp(argv[i], "-t") == 0)
      tracing = TRUE;
    else if(strncmp(argv[i], "-S", 2) == 0) {
      if (argv[i][2])
        PRINT_SOLUTION = (short) atoi(argv[i] + 2);
      else
        PRINT_SOLUTION = 2;
    }
    else if(strncmp(argv[i], "-improve", 8) == 0) {
      if (argv[i][8])
        or_value(&improve, atoi(argv[i] + 8));
    }
    else if(strcmp(argv[i], "-pivll") == 0)
      or_value(&pivoting2, PRICE_LOOPLEFT);
    else if(strcmp(argv[i], "-pivla") == 0)
      or_value(&pivoting2, PRICE_LOOPALTERNATE);
#if defined EnablePartialOptimization
    else if(strcmp(argv[i], "-pivpc") == 0)
      or_value(&pivoting2, PRICE_AUTOPARTIALCOLS);
    else if(strcmp(argv[i], "-pivpr") == 0)
      or_value(&pivoting2, PRICE_AUTOPARTIALROWS);
    else if(strcmp(argv[i], "-pivp") == 0)
      or_value(&pivoting2, PRICE_AUTOPARTIAL);
#endif
    else if(strcmp(argv[i], "-pivf") == 0)
      or_value(&pivoting2, PRICE_PRIMALFALLBACK);
    else if(strcmp(argv[i], "-pivm") == 0)
      or_value(&pivoting2, PRICE_MULTIPLE);
    else if(strcmp(argv[i], "-piva") == 0)
      or_value(&pivoting2, PRICE_ADAPTIVE);
    else if(strcmp(argv[i], "-pivr") == 0)
      or_value(&pivoting2, PRICE_RANDOMIZE);
    else if(strcmp(argv[i], "-pivh") == 0)
      or_value(&pivoting2, PRICE_HARRISTWOPASS);
    else if(strcmp(argv[i], "-pivt") == 0)
      or_value(&pivoting2, PRICE_TRUENORMINIT);
    else if(strncmp(argv[i], "-piv", 4) == 0) {
      if (argv[i][4])
        set_value(&pivoting1, atoi(argv[i] + 4));
      else
    set_value(&pivoting1, PRICER_DEVEX | PRICE_ADAPTIVE);
    }
#if defined PARSER_LP
    else if(strcmp(argv[i],"-lp") == 0)
      filetype = filetypeLP;
#endif
    else if((strcmp(argv[i],"-wlp") == 0) && (i + 1 < argc))
      wlp = argv[++i];
    else if(strcmp(argv[i],"-plp") == 0)
      plp = TRUE;
    else if(strcmp(argv[i],"-mps") == 0)
      filetype = filetypeMPS;
    else if(strcmp(argv[i],"-mps_ibm") == 0)
      mps_ibm = TRUE;
    else if(strcmp(argv[i],"-mps_negobjconst") == 0)
      mps_negobjconst = TRUE;
    else if(strcmp(argv[i],"-mps_free") == 0)
      mps_free = TRUE;
    else if(strcmp(argv[i],"-fmps") == 0)
      filetype = filetypeFREEMPS;
    else if((strcmp(argv[i],"-wmps") == 0) && (i + 1 < argc))
      wmps = argv[++i];
    else if((strcmp(argv[i],"-wfmps") == 0) && (i + 1 < argc))
      wfmps = argv[++i];
    else if(strcmp(argv[i],"-wafter") == 0)
      write_model_after = TRUE;
    else if(strcmp(argv[i],"-degen") == 0)
      set_value(&anti_degen1, ANTIDEGEN_DEFAULT);
    else if(strcmp(argv[i],"-degenf") == 0)
      or_value(&anti_degen2, ANTIDEGEN_FIXEDVARS);
    else if(strcmp(argv[i],"-degenc") == 0)
      or_value(&anti_degen2, ANTIDEGEN_COLUMNCHECK);
    else if(strcmp(argv[i],"-degens") == 0)
      or_value(&anti_degen2, ANTIDEGEN_STALLING);
    else if(strcmp(argv[i],"-degenn") == 0)
      or_value(&anti_degen2, ANTIDEGEN_NUMFAILURE);
    else if(strcmp(argv[i],"-degenl") == 0)
      or_value(&anti_degen2, ANTIDEGEN_LOSTFEAS);
    else if(strcmp(argv[i],"-degeni") == 0)
      or_value(&anti_degen2, ANTIDEGEN_INFEASIBLE);
    else if(strcmp(argv[i],"-degend") == 0)
      or_value(&anti_degen2, ANTIDEGEN_DYNAMIC);
    else if(strcmp(argv[i],"-degenb") == 0)
      or_value(&anti_degen2, ANTIDEGEN_DURINGBB);
    else if(strcmp(argv[i],"-degenr") == 0)
      or_value(&anti_degen2, ANTIDEGEN_RHSPERTURB);
    else if(strcmp(argv[i],"-degenp") == 0)
      or_value(&anti_degen2, ANTIDEGEN_BOUNDFLIP);
    else if(strcmp(argv[i],"-time") == 0) {
      if(clock() == -1)
        fprintf(stderr, "CPU times not available on this machine\n");
      else
        print_timing = TRUE;
    }
    else if((strcmp(argv[i],"-bfp") == 0) && (i + 1 < argc))
      bfp = argv[++i];
    else if((strcmp(argv[i],"-rxli") == 0) && (i + 2 < argc)) {
      rxliname = argv[++i];
      rxli = argv[++i];
      fpin = NULL;
      filetype = filetypeXLI;
    }
    else if((strcmp(argv[i],"-rxlidata") == 0) && (i + 1 < argc))
      rxlidata = argv[++i];
    else if((strcmp(argv[i],"-rxliopt") == 0) && (i + 1 < argc))
      rxlioptions = argv[++i];
    else if((strcmp(argv[i],"-wxli") == 0) && (i + 2 < argc)) {
      wxliname = argv[++i];
      wxli = argv[++i];
    }
    else if((strcmp(argv[i],"-wxliopt") == 0) && (i + 1 < argc))
      wxlioptions = argv[++i];
    else if((strcmp(argv[i],"-wxlisol") == 0) && (i + 2 < argc)) {
      wxliname = argv[++i];
      wxlisol = argv[++i];
    }
    else if((strcmp(argv[i],"-wxlisolopt") == 0) && (i + 1 < argc))
      wxlisoloptions = argv[++i];
    else if((strcmp(argv[i],"-rbas") == 0) && (i + 1 < argc))
      rbasname = argv[++i];
    else if((strcmp(argv[i],"-wbas") == 0) && (i + 1 < argc))
      wbasname = argv[++i];
    else if((strcmp(argv[i],"-Db") == 0) && (i + 1 < argc))
      debugdump_before = argv[++i];
    else if((strcmp(argv[i],"-Da") == 0) && (i + 1 < argc))
      debugdump_after = argv[++i];
    else if((strcmp(argv[i],"-timeout") == 0) && (i + 1 < argc))
      sectimeout = atol(argv[++i]);
    else if((strcmp(argv[i],"-trej") == 0) && (i + 1 < argc))
      epspivot = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsp") == 0) && (i + 1 < argc))
      epsperturb = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsd") == 0) && (i + 1 < argc))
      epsd = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsb") == 0) && (i + 1 < argc))
      epsb = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsel") == 0) && (i + 1 < argc))
      epsel = atof(argv[++i]);
    else if(strcmp(argv[i],"-parse_only") == 0)
      parse_only = TRUE;
    else
      ok = TRUE;

    if(!ok)
      ;
    else if(strcmp(argv[i],"-presolverow") == 0)
      or_value(&do_presolve, PRESOLVE_ROWS);
    else if(strcmp(argv[i],"-presolvecol") == 0)
      or_value(&do_presolve, PRESOLVE_COLS);
    else if(strcmp(argv[i],"-presolve") == 0)
      or_value(&do_presolve, PRESOLVE_ROWS | PRESOLVE_COLS);
    else if(strcmp(argv[i],"-presolvel") == 0)
      or_value(&do_presolve, PRESOLVE_LINDEP);
    else if(strcmp(argv[i],"-presolves") == 0)
      or_value(&do_presolve, PRESOLVE_SOS);
    else if(strcmp(argv[i],"-presolver") == 0)
      or_value(&do_presolve, PRESOLVE_REDUCEMIP);
    else if(strcmp(argv[i],"-presolvek") == 0)
      or_value(&do_presolve, PRESOLVE_KNAPSACK);
    else if(strcmp(argv[i],"-presolveq") == 0)
      or_value(&do_presolve, PRESOLVE_ELIMEQ2);
    else if(strcmp(argv[i],"-presolvem") == 0)
      or_value(&do_presolve, PRESOLVE_MERGEROWS);
    else if(strcmp(argv[i],"-presolvefd") == 0)
      or_value(&do_presolve, PRESOLVE_COLFIXDUAL);
    else if(strcmp(argv[i],"-presolvebnd") == 0)
      or_value(&do_presolve, PRESOLVE_BOUNDS);
    else if(strcmp(argv[i],"-presolved") == 0)
      or_value(&do_presolve, PRESOLVE_DUALS);
    else if(strcmp(argv[i],"-presolvef") == 0)
      or_value(&do_presolve, PRESOLVE_IMPLIEDFREE);
    else if(strcmp(argv[i],"-presolveslk") == 0)
      or_value(&do_presolve, PRESOLVE_IMPLIEDSLK);
    else if(strcmp(argv[i],"-presolveg") == 0)
      or_value(&do_presolve, PRESOLVE_REDUCEGCD);
    else if(strcmp(argv[i],"-presolveb") == 0)
      or_value(&do_presolve, PRESOLVE_PROBEFIX);
    else if(strcmp(argv[i],"-presolvec") == 0)
      or_value(&do_presolve, PRESOLVE_PROBEREDUCE);
    else if(strcmp(argv[i],"-presolverowd") == 0)
      or_value(&do_presolve, PRESOLVE_ROWDOMINATE);
    else if(strcmp(argv[i],"-presolvecold") == 0)
      or_value(&do_presolve, PRESOLVE_COLDOMINATE);
    else if(strcmp(argv[i],"-min") == 0)
      objective = -1;
    else if(strcmp(argv[i],"-max") == 0)
      objective =  1;
    else if(strcmp(argv[i],"-noint") == 0)
      noint =  TRUE;
    else if((strcmp(argv[i],"-rpar") == 0) && (i + 1 < argc))
      i++;
    else if((strcmp(argv[i],"-rparopt") == 0) && (i + 1 < argc))
      i++;
    else if((strcmp(argv[i],"-wpar") == 0) && (i + 1 < argc))
      i++;
    else if((strcmp(argv[i],"-wparopt") == 0) && (i + 1 < argc))
      i++;
    else if(strcmp(argv[i],"-o0") == 0)
      obj_in_basis = FALSE;
    else if(strcmp(argv[i],"-o1") == 0)
      obj_in_basis = TRUE;
    else if((strcmp(argv[i], "-ac") == 0) && (i + 1 < argc))
      accuracy_error = atof(argv[++i]);
    else if(fpin == stdin) {
      filen = argv[i];
      if(*filen == '<')
        filen++;
      if((fpin = fopen(filen, "r")) == NULL) {
        print_help(argv);
        fprintf(stderr,"\nError, Unable to open input file '%s'\n",
                argv[i]);
        EndOfPgr(FORCED_EXIT);
      }
    }
    else {
      filen = argv[i];
      if(*filen != '>') {
        print_help(argv);
        fprintf(stderr, "\nError, Unrecognized command line argument '%s'\n",
                argv[i]);
        EndOfPgr(FORCED_EXIT);
      }
    }
  }

  signal(SIGABRT,/* (void (*) OF((int))) */ SIGABRT_func);

  if ((filetype != filetypeXLI) && (fpin == NULL)) {
    lp = NULL;
    fprintf(stderr, "Cannot combine -rxli option with -lp, -mps, -fmps.\n");
  }
  else {
    switch(filetype) {
  #if defined PARSER_LP
    case filetypeLP:
      lp = read_lp(fpin, verbose, NULL);
      break;
  #endif
    case filetypeMPS:
      lp = read_mps(fpin, verbose | (mps_free ? MPS_FREE : 0) | (mps_ibm ? MPS_IBM : 0) | (mps_negobjconst ? MPS_NEGOBJCONST : 0));
      break;
    case filetypeFREEMPS:
      lp = read_freemps(fpin, verbose | (mps_ibm ? MPS_IBM : 0) | (mps_negobjconst ? MPS_NEGOBJCONST : 0));
      break;
    case filetypeXLI:
      lp = read_XLI(rxliname, rxli, rxlidata, rxlioptions, verbose);
      break;
    }
  }

  if((fpin != NULL) && (fpin != stdin))
    fclose(fpin);

  if(print_timing)
    print_cpu_times("Parsing input");

  if(lp == NULL) {
    fprintf(stderr, "Unable to read model.\n");
    EndOfPgr(FORCED_EXIT);
  }

  for(i = 1; i < argc; i++) {
    if((strcmp(argv[i],"-rpar") == 0) && (i + 1 < argc)) {
      if(rparname != NULL) {
        if(!read_params(lp, rparname, rparoptions)) {
          fprintf(stderr, "Unable to read parameter file (%s)\n", rparname);
          delete_lp(lp);
          EndOfPgr(FORCED_EXIT);
        }
      }
      rparname = argv[++i];
    }
    else if((strcmp(argv[i],"-rparopt") == 0) && (i + 1 < argc))
      rparoptions = argv[++i];
    else if((strcmp(argv[i],"-wpar") == 0) && (i + 1 < argc))
      wparname = argv[++i];
    else if((strcmp(argv[i],"-wparopt") == 0) && (i + 1 < argc))
      wparoptions = argv[++i];
  }

  if(rparname != NULL)
    if(!read_params(lp, rparname, rparoptions)) {
      fprintf(stderr, "Unable to read parameter file (%s)\n", rparname);
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }

  if((nonames) || (nocolnames))
    set_use_names(lp, FALSE, FALSE);
  if((nonames) || (norownames))
    set_use_names(lp, TRUE, FALSE);

  if(objective != 0) {
    if(objective == 1)
      set_maxim(lp);
    else
      set_minim(lp);
  }

  if (obj_in_basis != -1)
    set_obj_in_basis(lp, obj_in_basis);

  if(noint) { /* remove integer conditions */
    for(i = get_Ncolumns(lp); i >= 1; i--) {
      if(is_SOS_var(lp, i)) {
        fprintf(stderr, "Unable to remove integer conditions because there is at least one SOS constraint\n");
        delete_lp(lp);
        EndOfPgr(FORCED_EXIT);
      }
      set_semicont(lp, i, FALSE);
      set_int(lp, i, FALSE);
    }
  }

  if(!write_model_after)
    write_model(lp, plp, wlp, wmps, wfmps, wxli, NULL, wxliname, wxlioptions);

  if(print_stats)
    print_statistics(lp);

  if(parse_only) {
    if(!write_model_after) {
      delete_lp(lp);
      EndOfPgr(0);
    }
    /* else if(!sectimeout) */
      sectimeout = 1;
  }

  if(PRINT_SOLUTION >= 5)
    print_lp(lp);

#if 0
  put_abortfunc(lp,(abortfunc *) myabortfunc, NULL);
#endif

  if(sectimeout > 0)
    set_timeout(lp, sectimeout);
  if(print_sol >= 0)
    set_print_sol(lp, print_sol);
  if(epsint >= 0)
    set_epsint(lp, epsint);
  if(epspivot >= 0)
    set_epspivot(lp, epspivot);
  if(epsperturb >= 0)
    set_epsperturb(lp, epsperturb);
  if(epsd >= 0)
    set_epsd(lp, epsd);
  if(epsb >= 0)
    set_epsb(lp, epsb);
  if(epsel >= 0)
    set_epsel(lp, epsel);
  if(debug >= 0)
    set_debug(lp, (MYBOOL) debug);
  if(floor_first != -1)
    set_bb_floorfirst(lp, floor_first);
  if(do_set_bb_depthlimit)
    set_bb_depthlimit(lp, bb_depthlimit);
  if(do_set_solutionlimit)
    set_solutionlimit(lp, solutionlimit);
  if(tracing)
    set_trace(lp, tracing);
  if(do_set_obj_bound)
    set_obj_bound(lp, obj_bound);
  if(do_set_break_at_value)
    set_break_at_value(lp, break_at_value);
  if(break_at_first)
    set_break_at_first(lp, break_at_first);
  if(mip_absgap >= 0)
    set_mip_gap(lp, TRUE, mip_absgap);
  if(mip_relgap >= 0)
    set_mip_gap(lp, FALSE, mip_relgap);
  if((anti_degen1 != -1) || (anti_degen2 != -1)) {
    if((anti_degen1 == -1) || (anti_degen2 != -1))
      anti_degen1 = 0;
    if(anti_degen2 == -1)
      anti_degen2 = 0;
    set_anti_degen(lp, anti_degen1 | anti_degen2);
  }
  set_presolve(lp, ((do_presolve == -1) ? get_presolve(lp): do_presolve) | ((PRINT_SOLUTION >= 4) ? PRESOLVE_SENSDUALS : 0), get_presolveloops(lp));
  if(improve != -1)
    set_improve(lp, improve);
  if(max_num_inv >= 0)
    set_maxpivot(lp, max_num_inv);
  if(preferdual != AUTOMATIC)
    set_preferdual(lp, preferdual);
  if((pivoting1 != -1) || (pivoting2 != -1)) {
    if(pivoting1 == -1)
      pivoting1 = get_pivoting(lp) & PRICER_LASTOPTION;
    if(pivoting2 == -1)
      pivoting2 = 0;
    set_pivoting(lp, pivoting1 | pivoting2);
  }
  if((scalemode1 != -1) || (scalemode2 != -1)) {
    if(scalemode1 == -1)
      scalemode1 = get_scaling(lp) & SCALE_CURTISREID;
    if(scalemode2 == -1)
      scalemode2 = 0;
    set_scaling(lp, scalemode1 | scalemode2);
  }
  if(crashmode != -1)
    set_basiscrash(lp, crashmode);
  if((bb_rule1 != -1) || (bb_rule2 != -1)) {
    if(bb_rule1 == -1)
      bb_rule1 = get_bb_rule(lp) & NODE_USERSELECT;
    if(bb_rule2 == -1)
      bb_rule2 = 0;
    set_bb_rule(lp, bb_rule1 | bb_rule2);
  }
  if(simplextype != -1)
    set_simplextype(lp, simplextype);
  if(bfp != NULL)
    if(!set_BFP(lp, bfp)) {
      fprintf(stderr, "Unable to set BFP package.\n");
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }
  if(debugdump_before != NULL)
    print_debugdump(lp, debugdump_before);
  if(report)
    put_msgfunc(lp, LPMessageCB, NULL, MSG_LPFEASIBLE | MSG_LPOPTIMAL | MSG_MILPFEASIBLE | MSG_MILPBETTER | MSG_PERFORMANCE);

  if(scaling) {
    if(scaleloop <= 0)
      scaleloop = 5;
    if(scaleloop - (int) scaleloop < SCALINGTHRESHOLD)
      scaleloop = (int) scaleloop + SCALINGTHRESHOLD;
    set_scalelimit(lp, scaleloop);
  }

  if (accuracy_error != -1)
    set_break_numeric_accuracy(lp, accuracy_error);

  if(guessbasis != NULL) {
    REAL *guessvector, a;
    int *basisvector;
    int Nrows = get_Nrows(lp);
    int Ncolumns = get_Ncolumns(lp);
    int col;
    char buf[50], *ptr;
    FILE *fp;

    if ((fp = fopen(guessbasis, "r")) != NULL) {
      guessvector = (REAL *) calloc(1+Ncolumns, sizeof(*guessvector));
      basisvector = (int *) malloc((1+Nrows+Ncolumns)*sizeof(*basisvector));
      if ((guessvector != NULL) && (basisvector != NULL)) {
        while ((!feof(fp)) && (fgets(buf, sizeof(buf), fp) != NULL)) {
          ptr = strrchr(buf, ':');
          if (ptr == NULL) {
            printf("Mallformed line: %s\n", buf);
          }
          else {
            a = atof(ptr + 1);
            while ((ptr > buf) && (isspace(ptr[-1])))
              ptr--;
            *ptr = 0;
            col = get_nameindex(lp, buf, FALSE);
            if (col < 1)
              printf("guess_basis: Unknown variable name %s\n", buf);
            else
              guessvector[col] = a;
          }
        }
        if (guess_basis(lp, guessvector, basisvector)) {
          if (!set_basis(lp, basisvector, TRUE))
            printf("Unable to set guessed basis.\n");
        }
        else
          printf("Unable to guess basis from provided variables.\n");
      }
      else
        printf("guess_basis: Out of memory.\n");
      if (basisvector != NULL)
        free(basisvector);
      if (guessvector != NULL)
        free(guessvector);
      fclose(fp);
    }
    else
      printf("Unable to open file %s\n", guessbasis);
  }

  if(rbasname != NULL)
    if(!read_basis(lp, rbasname, NULL)) {
      fprintf(stderr, "Unable to read basis file.\n");
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }

  result = solve(lp);

  if(wbasname != NULL)
    if(!write_basis(lp, wbasname))
      fprintf(stderr, "Unable to write basis file.\n");

  if(write_model_after)
    write_model(lp, plp, wlp, wmps, wfmps, wxli, NULL, wxliname, wxlioptions);

  write_model(lp, FALSE, NULL, NULL, NULL, NULL, wxlisol, wxliname, wxlisoloptions);

  if(PRINT_SOLUTION >= 6)
    print_scales(lp);

  if((print_timing) && (!parse_only))
    print_cpu_times("solving");

  if(debugdump_after != NULL)
    print_debugdump(lp, debugdump_after);

  if(wparname != NULL)
    if(!write_params(lp, wparname, wparoptions)) {
      fprintf(stderr, "Unable to write parameter file (%s)\n", wparname);
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }

  if(parse_only) {
    delete_lp(lp);
    EndOfPgr(0);
  }

/*
  if((timeoutok) && (result == TIMEOUT) && (get_solutioncount(lp) > 0))
    result = OPTIMAL;
*/

  switch(result) {
  case SUBOPTIMAL:
  case PRESOLVED:
  case OPTIMAL:
  case PROCBREAK:
  case FEASFOUND:
    if ((result == SUBOPTIMAL) && (PRINT_SOLUTION >= 1))
      printf("Suboptimal solution\n");

    if (result == PRESOLVED)
      printf("Presolved solution\n");

    if (PRINT_SOLUTION >= 1)
      print_objective(lp);

    if (PRINT_SOLUTION >= 2)
      print_solution(lp, 1);

    if (PRINT_SOLUTION >= 3)
      print_constraints(lp, 1);

    if (PRINT_SOLUTION >= 4)
      print_duals(lp);

    if(tracing)
      fprintf(stderr,
              "Branch & Bound depth: %d\nNodes processed: %.0f\nSimplex pivots: %.0f\nNumber of equal solutions: %d\n",
              get_max_level(lp), (REAL) get_total_nodes(lp), (REAL) get_total_iter(lp), get_solutioncount(lp));
    break;
  case NOMEMORY:
    if (PRINT_SOLUTION >= 1)
      printf("Out of memory\n");
    break;
  case INFEASIBLE:
    if (PRINT_SOLUTION >= 1)
      printf("This problem is infeasible\n");
    break;
  case UNBOUNDED:
    if (PRINT_SOLUTION >= 1)
      printf("This problem is unbounded\n");
    break;
  case PROCFAIL:
   if (PRINT_SOLUTION >= 1)
      printf("The B&B routine failed\n");
    break;
  case TIMEOUT:
    if (PRINT_SOLUTION >= 1)
      printf("Timeout\n");
    break;
  case USERABORT:
    if (PRINT_SOLUTION >= 1)
      printf("User aborted\n");
    break;
  case ACCURACYERROR:
    if (PRINT_SOLUTION >= 1)
      printf("Accuracy error\n");
    break;
  default:
    if (PRINT_SOLUTION >= 1)
      printf("lp_solve failed\n");
    break;
  }

  if (PRINT_SOLUTION >= 7)
    print_tableau(lp);

  delete_lp(lp);

  EndOfPgr(result);
  return(result);
}
Exemple #24
0
bool EngineBase::Initialize(HWND hwnd)
{
    hwnd_ = hwnd;

    RECT dimensions;
    GetClientRect( hwnd, &dimensions );

    int width = dimensions.right - dimensions.left;
    int height = dimensions.bottom - dimensions.top;

    D3D_DRIVER_TYPE driverTypes[] =
    {
        D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP,
        D3D_DRIVER_TYPE_REFERENCE, D3D_DRIVER_TYPE_SOFTWARE
    };

    int totalDriverTypes = ARRAYSIZE( driverTypes );

    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0
    };

    int totalFeatureLevels = ARRAYSIZE( featureLevels );

    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    ZeroMemory( &swapChainDesc, sizeof( swapChainDesc ) );
    swapChainDesc.BufferCount = 1;
    swapChainDesc.BufferDesc.Width = width;
    swapChainDesc.BufferDesc.Height = height;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.OutputWindow = hwnd;
    swapChainDesc.Windowed = true;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;

    int creationFlags = 0;

#ifdef _DEBUG
    creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    HRESULT result;
    int driver = 0;

    for( driver = 0; driver < totalDriverTypes; ++driver )
    {
        result = D3D11CreateDeviceAndSwapChain( 0, driverTypes[driver], 0, creationFlags,
                                                featureLevels, totalFeatureLevels,
                                                D3D11_SDK_VERSION, &swapChainDesc, &swapChain_,
                                                &d3dDevice_, &featureLevel_, &d3dContext_ );

        if( SUCCEEDED( result ) )
        {
            driverType_ = driverTypes[driver];
            break;
        }
    }

    if( FAILED( result ) )
    {
        MessageBox(0,  "Failed to create the Direct3D device!", 0, 0 );
        return false;
    }

    ID3D11Texture2D* backBufferTexture;

    result = swapChain_->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTexture );

    if( FAILED( result ) )
    {
        MessageBox(0,  "Failed to get the swap chain back buffer!", 0, 0);
        return false;
    }

    result = d3dDevice_->CreateRenderTargetView( backBufferTexture, 0, &backBufferTarget_ );

    if( backBufferTexture )
        backBufferTexture->Release( );

    if( FAILED( result ) )
    {
        MessageBox(0,  "Failed to create the render target view!", 0, 0);
        return false;
    }

	// Create depth stencil texture
	D3D11_TEXTURE2D_DESC descDepth;
	ZeroMemory(&descDepth, sizeof(descDepth));
	descDepth.Width = width;
	descDepth.Height = height;
	descDepth.MipLevels = 1;
	descDepth.ArraySize = 1;
	descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	descDepth.SampleDesc.Count = 1;
	descDepth.SampleDesc.Quality = 0;
	descDepth.Usage = D3D11_USAGE_DEFAULT;
	descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	descDepth.CPUAccessFlags = 0;
	descDepth.MiscFlags = 0;
	result = d3dDevice_->CreateTexture2D(&descDepth, nullptr, &depthStencil_);
	if (FAILED(result))
	{
		MessageBox(0, "error creating depthstencilbuffer!", 0, 0);
		return false;
	}

	// Create the depth stencil view
	D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
	ZeroMemory(&descDSV, sizeof(descDSV));
	descDSV.Format = descDepth.Format;
	descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	descDSV.Texture2D.MipSlice = 0;
	result = d3dDevice_->CreateDepthStencilView(depthStencil_, &descDSV, &depthStencilView_);
	if (FAILED(result))
	{
		MessageBox(0, "error creating depthstencilview!", 0, 0);
		return false;
	}
	
	d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, depthStencilView_);

    D3D11_VIEWPORT viewport;
    viewport.Width = static_cast<float>(width);
    viewport.Height = static_cast<float>(height);
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;

    d3dContext_->RSSetViewports( 1, &viewport );

	//read some parameters
	if (!read_params("rescs/params.in"))
	{
		return false;
	}

	//init directinput
	if (!EngineInput::Instance()->DirectInput_Init(hwnd))
	{
		return false;
	}

	return true;
}
Exemple #25
0
int main() { 
    int rc;
    char s[1024];
    char last_message_i_wrote[256];
    char md5ified_message[256];
    int i = 0;
    int done = 0;
    struct param_struct params;
    int shm_id;
    void *address = NULL;
    int sem_id;
    struct shmid_ds shm_info;

    say(MY_NAME, "Oooo 'ello, I'm Mrs. Premise!");
    
    read_params(&params);
    
    // Create the shared memory
    shm_id = shmget(params.key, params.size, IPC_CREAT | IPC_EXCL | params.permissions);
    
    if (shm_id == -1) {
        shm_id = 0;
        sprintf(s, "Creating the shared memory failed; errno is %d", errno);
        say(MY_NAME, s);
    }
    else {
        sprintf(s, "Shared memory's id is %d", shm_id);
        say(MY_NAME, s);

        // Attach the memory.
        address = shmat(shm_id, NULL, 0);

        if ((void *)-1 == address) {
            address = NULL;
            sprintf(s, "Attaching the shared memory failed; errno is %d", errno);
            say(MY_NAME, s);
        }
        else {
            sprintf(s, "shared memory address = %p", address);
            say(MY_NAME, s);
        }
    }
    
    if (address) {
        // Create the semaphore
        sem_id = semget(params.key, 1, IPC_CREAT | IPC_EXCL | params.permissions);
    
        if (-1 == sem_id) {
            sem_id = 0;
            sprintf(s, "Creating the semaphore failed; errno is %d", errno);
            say(MY_NAME, s);
        }
        else {
            sprintf(s, "the semaphore id is %d", sem_id);
            say(MY_NAME, s);
        
            // I seed the shared memory with a random string (the current time).
            get_current_time(s);
    
            strcpy((char *)address, s);
            strcpy(last_message_i_wrote, s);

            sprintf(s, "Wrote %zu characters: %s", strlen(last_message_i_wrote), last_message_i_wrote);
            say(MY_NAME, s);
            
            i = 0;
            while (!done) {
                sprintf(s, "iteration %d", i);
                say(MY_NAME, s);

                // Release the semaphore...
                rc = release_semaphore(MY_NAME, sem_id, params.live_dangerously);
                // ...and wait for it to become available again. In real code 
                // I might want to sleep briefly before calling .acquire() in
                // order to politely give other processes an opportunity to grab
                // the semaphore while it is free so as to avoid starvation. But 
                // this code is meant to be a stress test that maximizes the 
                // opportunity for shared memory corruption and politeness is 
                // not helpful in stress tests.
                if (!rc)
                    rc = acquire_semaphore(MY_NAME, sem_id, params.live_dangerously);

                if (rc)
                    done = 1;
                else {
                    // I keep checking the shared memory until something new has 
                    // been written.
                    while ( (!rc) && \
                            (!strcmp((char *)address, last_message_i_wrote)) 
                          ) {
                        // Nothing new; give Mrs. Conclusion another change to respond.
                        sprintf(s, "Read %zu characters '%s'", strlen((char *)address), (char *)address);
                        say(MY_NAME, s);
                        rc = release_semaphore(MY_NAME, sem_id, params.live_dangerously);
                        if (!rc) {
                            rc = acquire_semaphore(MY_NAME, sem_id, params.live_dangerously);
                        }
                    }


                    if (rc) 
                        done = 1;
                    else {
                        sprintf(s, "Read %zu characters '%s'", strlen((char *)address), (char *)address);
                        say(MY_NAME, s);

                        // What I read must be the md5 of what I wrote or something's 
                        // gone wrong.
                        md5ify(last_message_i_wrote, md5ified_message);
                    
                        if (strcmp(md5ified_message, (char *)address) == 0) {
                            // Yes, the message is OK
                            i++;
                            if (i == params.iterations)
                                done = 1;

                            // MD5 the reply and write back to Mrs. Conclusion.
                            md5ify(md5ified_message, md5ified_message);
                            
                            sprintf(s, "Writing %zu characters '%s'", strlen(md5ified_message), md5ified_message);
                            say(MY_NAME, s);

                            strcpy((char *)address, md5ified_message);
                            strcpy((char *)last_message_i_wrote, md5ified_message);
                        }
                        else {
                            sprintf(s, "Shared memory corruption after %d iterations.", i);
                            say(MY_NAME, s);                            
                            sprintf(s, "Mismatch; new message is '%s', expected '%s'.", (char *)address, md5ified_message);
                            say(MY_NAME, s);
                            done = 1;
                        }
                    }
                }
            }

            // Announce for one last time that the semaphore is free again so that 
            // Mrs. Conclusion can exit.
            say(MY_NAME, "Final release of the semaphore followed by a 5 second pause");            
            rc = release_semaphore(MY_NAME, sem_id, params.live_dangerously);
            sleep(5);
            // ...before beginning to wait until it is free again. 
            // Technically, this is bad practice. It's possible that on a 
            // heavily loaded machine, Mrs. Conclusion wouldn't get a chance
            // to acquire the semaphore. There really ought to be a loop here
            // that waits for some sort of goodbye message but for purposes of
            // simplicity I'm skipping that.

            say(MY_NAME, "Final wait to acquire the semaphore");
            rc = acquire_semaphore(MY_NAME, sem_id, params.live_dangerously);
            if (!rc) {
                say(MY_NAME, "Destroying the shared memory.");
                
                if (-1 == shmdt(address)) {
                    sprintf(s, "Detaching the memory failed; errno is %d", errno);
                    say(MY_NAME, s);
                }
                address = NULL;
                
            
                if (-1 == shmctl(shm_id, IPC_RMID, &shm_info)) {
                    sprintf(s, "Removing the memory failed; errno is %d", errno);
                    say(MY_NAME, s);
                }
            }
        }

        say(MY_NAME, "Destroying the semaphore.");
        // Clean up the semaphore
        if (-1 == semctl(sem_id, 0, IPC_RMID)) {
            sprintf(s, "Removing the semaphore failed; errno is %d", errno);
            say(MY_NAME, s);
        }
    }
    return 0; 
}
Exemple #26
0
scanner::token scanner::read_id(char first_char) {
    char ch;
    m_string.reset();
    m_params.reset();
    m_string.push_back(first_char);

    bool is_arith = (m_normalized[(unsigned char) first_char] == '+');
    bool is_alpha = (m_normalized[(unsigned char) first_char] == 'a');
    
    ch = read_char();        
    // In SMT2 "-20" is an identifier.
    if (!m_smt2 && state_ok() && first_char == '-' && m_normalized[(unsigned char) ch] == '0') {
        return read_number(ch, false);
    }

    if (state_ok() && first_char == '|') {
        return read_symbol(ch);
    }
    
    while (state_ok()) {                        
        switch(m_normalized[(unsigned char) ch]) {
        case '+':
            if (is_arith) {
                m_string.push_back(ch);
                break;
            }
            // strings can have hyphens.
            if (!is_alpha || ch != '-') {
                goto bail_out;  
            }
        case 'a':
        case ':':
        case '.':
        case '0':
            if (is_arith) {
                goto bail_out;
            }
            m_string.push_back(ch);
            break;
        case '[':                
            m_string.push_back(0);
            m_id = m_string.begin();
            if (read_params()) {
                return ID_TOKEN;
            }
            else {
                return m_state;
            }
        default:
            goto bail_out;
        }
        ch = read_char();
    }
    return m_state;

 bail_out:
    m_string.push_back(0);
    m_id = m_string.begin();
    unread_char();
    return ID_TOKEN;
}
Exemple #27
0
int main(int argc, char **argv)
{
    struct time_type time;
    ZOOM_connection *z;
    ZOOM_resultset *r;
    int *elc;
    struct event_line_t *els;
    ZOOM_options o;
    int i;
    int k;

    init_statics();

    read_params(argc, argv, &parameters);

    z = (ZOOM_connection *) xmalloc(sizeof(*z) * parameters.concurrent);
    r = (ZOOM_resultset *) xmalloc(sizeof(*r) * parameters.concurrent);
    elc = (int *) xmalloc(sizeof(*elc) * parameters.concurrent * parameters.repeat);
    els = (struct event_line_t *) xmalloc(
        sizeof(*els) * parameters.concurrent * parameters.repeat * 10);
    o = ZOOM_options_create();

    /* async mode */
    ZOOM_options_set (o, "async", "1");

    /* get first record of result set (using piggypack) */
    if (parameters.piggypack)
        ZOOM_options_set (o, "count", "1");

    /* set proxy */
    if (strlen(parameters.proxy))
        ZOOM_options_set (o, "proxy", parameters.proxy);


    /* preferred record syntax */
    if (0){
        ZOOM_options_set (o, "preferredRecordSyntax", "usmarc");
        ZOOM_options_set (o, "elementSetName", "F");
    }

    time_init(&time);
    /* repeat loop */
    for (k = 0; k < parameters.repeat; k++){

        /* progress zeroing */
        for (i = 0; i < 4096; i++){
            parameters.progress[i] = k * 5 -1;
        }

        /* connect to all concurrent connections*/
        for ( i = 0; i < parameters.concurrent; i++){
            /* set event count to zero */
            elc[k * parameters.concurrent + i] = 0;

            /* create connection - pass options (they are the same for all) */
            z[i] = ZOOM_connection_create(o);

            /* connect and init */
            ZOOM_connection_connect(z[i], parameters.host, 0);
        }
        /* search all */
        for (i = 0; i < parameters.concurrent; i++)
            r[i] = ZOOM_connection_search_pqf (z[i], parameters.query);

        /* network I/O. pass number of connections and array of connections */
        while ((i = ZOOM_event (parameters.concurrent, z))){
            int event = ZOOM_connection_last_event(z[i-1]);
            const char *errmsg;
            const char *addinfo;
            int error = 0;
            //int progress = zoom_progress[event];

            if (event == ZOOM_EVENT_SEND_DATA || event == ZOOM_EVENT_RECV_DATA)
                continue;

            time_stamp(&time);

            /* updating events and event list */
            error = ZOOM_connection_error(z[i-1] , &errmsg, &addinfo);
            if (error)
                parameters.progress[i] = zoom_progress[ZOOM_EVENT_UNKNOWN];
            //parameters.progress[i] = zoom_progress[ZOOM_EVENT_NONE];
            else if (event == ZOOM_EVENT_CONNECT)
                parameters.progress[i] = zoom_progress[event];
            else
                //parameters.progress[i] = zoom_progress[event];
                parameters.progress[i] += 1;

            update_events(elc, els,
                          k, i-1,
                          time_sec(&time), time_usec(&time),
                          parameters.progress[i],
                          event, zoom_events[event],
                          error, errmsg);
        }

        /* destroy connections */
        for (i = 0; i<parameters.concurrent; i++)
            {
                ZOOM_resultset_destroy (r[i]);
                ZOOM_connection_destroy (z[i]);
            }



    } /* for (k = 0; k < parameters.repeat; k++) repeat loop */

    /* output */

    if (parameters.gnuplot){
        printf("# gnuplot data and instruction file \n");
        printf("# gnuplot thisfile \n");
        printf("\n");
        printf("set title \"Z39.50 connection plot\"\n");
        printf("set xlabel \"Connection\"\n");
        printf("set ylabel \"Time Seconds\"\n");
        printf("set zlabel \"Progress\"\n");
        printf("set ticslevel 0\n");
        printf("set grid\n");
        printf("set pm3d\n");
        printf("splot '-' using ($1):($2):($3) t '' with points\n");
        printf("\n");
        printf("\n");
    }

    print_table_header();
    print_events(elc,  els, parameters.concurrent);

    if (parameters.gnuplot){
        printf("end\n");
        printf("pause -1 \"Hit ENTER to return\"\n");
    }

    /* destroy data structures and exit */
    xfree(z);
    xfree(r);
    xfree(elc);
    xfree(els);
    ZOOM_options_destroy(o);
    exit (0);
}
Exemple #28
0
int parse_cla(int argc,char *argv[],struct ARDOP_PARAMS *g,meta_parameters **meta_out)
{
  int read_offset = 0,   /* Flag - Read resampling offsets from file?   */
    read_dopplr = 0;   /* Flag - Read doppler constant from file?     */
  int cal_check=0;       /* checks if output file needs input cal file  */
  int debug_help=-1;     /* If -debug 0 used, give debug usage          */
  char fName_slope[256], /* Input slope,intercept (offsets) file        */
    fName_doppler[256]; /* Input doppler constant file                 */
  FILE  *fp;
  meta_parameters *meta;
  
  /* Preset Optional Command Line Parameters
     ---------------------------------------------------------*/
  g->hamFlag=0;
  g->kaiFlag=0;
  g->pwrFlag=0;
  g->sigmaFlag=0;
  g->gammaFlag=0;
  g->betaFlag=0;
  g->nextend=0.0;
  g->pctbw=g->pctbwaz=0.0;
  g->fd=0;
  g->fdd=-99;   /*Doppler slope of -99 means to figure it out ourselves.*/
  g->fddd=-99;  /*Doppler slope of -99 means to figure it out ourselves.*/
  g->ifirstline = 0;  /* First line to process                          */
  g->npatches = 100;  /* (Absurdly Large) Number of patches             */
  g->ifirst = 0;      /* i,q byte samples to skip                       */
  g->isave = 0;       /* start range bin                                */
  g->na_valid = -99;  /* Valid output samples per patch (-99->determine)*/
  g->iflag = 1;       /* Debug Flag                                     */
  g->deskew=0;
  g->sloper = g->interr = g->slopea = g->intera = 0.0;
  g->dsloper = g->dinterr = g->dslopea = g->dintera = 0.0;  
  strcpy(g->CALPRMS,"NO");
  
  /* Process the Command Line Arguments
     ------------------------------------*/
  if (argc<3)
    {printf("Must give input and output filenames.\n");return 0;}
  strcpy(g->in1,argv[argc-2]);
  strcpy(g->out,argv[argc-1]);
  
  
  /*Create ARDOP_PARAMS struct as well as meta_parameters.*/
  if (extExists(g->in1,".in"))
    {/*Read parameters from parameter file*/
      read_params(g->in1,g);
      if (extExists(g->in1,".meta"))/*Input file has .meta attached: read it*/
	meta=meta_read(g->in1);
      else /*No .meta exists--fabricate one*/
	meta=raw_init();
    }
  else    /*Read parameters & .meta from CEOS.*/
    get_params(g->in1,g,&meta);
  
  while (currArg < (argc-2)) {
    char *key=argv[currArg++];
    if      (strmatch(key,"-log"))   {CHK_ARG_ASP(1); strcpy(logFile, GET_ARG(1));
      logflag = 1; fLog = FOPEN(logFile, "a");}
    else if (strmatch(key,"-debug")) {
      CHK_ARG_ASP(1);
      g->iflag    = atoi(GET_ARG(1)); 
      if (g->iflag==0) return debug_help; }
    else if (strmatch(key,"-quiet")) {quietflag = 1;}
    else if (strmatch(key,"-power")) {g->pwrFlag=1;}
    else if (strmatch(key,"-sigma")) {g->sigmaFlag=1; cal_check=1;}
    else if (strmatch(key,"-gamma")) {g->gammaFlag=1; cal_check=1;}
    else if (strmatch(key,"-beta" )) {g->betaFlag=1; cal_check=1;}
    else if (strmatch(key,"-hamming")) {g->hamFlag = 1;}
    else if (strmatch(key,"-kaiser"))  {g->kaiFlag = 1;}
    else if (strmatch(key,"-l")) {CHK_ARG_ASP(1); g->ifirstline = atoi(GET_ARG(1));}
    else if (strmatch(key,"-p")) {CHK_ARG_ASP(1); g->npatches = atoi(GET_ARG(1));}
    else if (strmatch(key,"-f")) {CHK_ARG_ASP(1); g->isave   += atoi(GET_ARG(1));}
    else if (strmatch(key,"-s")) {CHK_ARG_ASP(1); g->ifirst  += atoi(GET_ARG(1));}
    else if (strmatch(key,"-n")) {CHK_ARG_ASP(1); g->nla      = atoi(GET_ARG(1));}
    else if (strmatch(key,"-r")) {CHK_ARG_ASP(1); g->azres    = atof(GET_ARG(1));}
    else if (strmatch(key,"-e")) {CHK_ARG_ASP(1); g->deskew   = atoi(GET_ARG(1));
      g->na_valid =-99;}
    /* If you use the -e flag, then a deskew wedge in the data will need to be removed. 
       Override internal measurement of the number of valid azimuth lines with the 
       -v option flag */
    else if (strmatch(key,"-v")) {CHK_ARG_ASP(1); g->na_valid = atoi(GET_ARG(1));}
    else if (strmatch(key,"-o")) {CHK_ARG_ASP(1); strcpy(fName_slope,GET_ARG(1));
      read_offset = 1;}
    else if (strmatch(key,"-c")) {CHK_ARG_ASP(1); strcpy(fName_doppler,GET_ARG(1));
      read_dopplr = 1;}
    else if (strmatch(key,"-m")) {CHK_ARG_ASP(1);strcpy(g->CALPRMS,GET_ARG(1));}
    else {printf("**Invalid option: %s\n\n",argv[currArg-1]); return 0;}
  }
  if ((strcmp(g->CALPRMS,"NO")==0)&&(cal_check==1))
    {
      printf("   You can only use -sigma, -beta, or -gamma in conjunction with -m\n");
      printf("   I will proceed, ignoring the option.\n");
      g->sigmaFlag=0;
      g->gammaFlag=0;
      g->betaFlag=0;
    }
  
  if (read_offset) {
    fp=FOPEN(fName_slope,"r");
    fscanf(fp,"%f %f %f %f",&g->sloper,&g->interr,&g->slopea,&g->intera);
    fscanf(fp,"%g %g %g %g",&g->dsloper,&g->dinterr,&g->dslopea,&g->dintera);
    FCLOSE(fp);
  }
  if (read_dopplr) {
    fp=FOPEN(fName_doppler,"r");
    g->fd=g->fdd=g->fddd=0.0;
    fscanf(fp,"%f %f %f", &g->fd,&g->fdd,&g->fddd);
    FCLOSE(fp);
  }
    
  /*Copy fields from ARDOP_PARAMS struct to meta_parameters struct.*/
  meta->sar->image_type              = 'S';          /*Slant range image*/
  meta->sar->azimuth_look_count      = g->nlooks;
  meta->sar->range_look_count        = 1;
  meta->sar->deskewed                = g->deskew;
  meta->sar->range_time_per_pixel    = 1.0/g->fs;
  meta->sar->azimuth_time_per_pixel  = 1.0/g->prf;
  meta->sar->slant_shift             = g->slantOff;
  meta->sar->time_shift              = g->timeOff;
  meta->sar->slant_range_first_pixel = g->r00;
  meta->sar->wavelength              = g->wavl;
  meta->sar->prf                     = g->prf;
  meta->sar->earth_radius            = g->re;
  meta->sar->satellite_height        = g->re+g->ht;
  meta->sar->range_doppler_coefficients[0] = g->fd*g->prf;
  meta->sar->range_doppler_coefficients[1] = g->fdd*g->prf;
  meta->sar->range_doppler_coefficients[2] = g->fddd*g->prf;
  meta->sar->azimuth_doppler_coefficients[0] = g->fd*g->prf;
  meta->sar->azimuth_doppler_coefficients[1] = 0.0;
  meta->sar->azimuth_doppler_coefficients[2] = 0.0;
  
  meta->general->data_type = REAL32;
  meta->general->band_count = 1;
  meta->general->x_pixel_size = meta->sar->range_time_per_pixel
    * (speedOfLight/2.0);
  meta->general->y_pixel_size = meta->sar->azimuth_time_per_pixel
    * g->vel * (g->re/g->ht);
  
  *meta_out = meta;
  
  return 1;
}
Exemple #29
0
int main (int argc, const char * argv[]) {
	
	EC_KEY *eckey;

	unsigned int curve;
	size_t digest_len;
	
	char name[1024], curve_name[200], pubkey[1024], privkey[1024];

	if (!read_params(name, 1024, curve_name, 200, pubkey, 1024, privkey, 1024))
		return ERR_STDIN_READ;
	
	///*debug*/printf("%s\n%s\n%s\n%s\n", name, curve_name, pubkey, privkey);
	
	// Get curve type and digest_len
	if (strcmp(curve_name, "secp112r1") == 0) {
		curve = NID_secp112r1;
		digest_len = 14;
	} else if (strcmp(curve_name, "secp128r1") == 0) {
		curve = NID_secp128r1;
		digest_len = 16;		
	} else if (strcmp(curve_name, "secp160r1") == 0) {
		curve = NID_secp160r1;
		digest_len = 20;		
	} else {
		return ERR_CURVE_UNKNOWN;
	}
	
	eckey = EC_KEY_new_by_curve_name(curve);
	if (eckey == NULL)
		return ERR_INIT_KEY;
	
	// set public key
	unsigned char *bin = NULL;
	size_t len = hex2bin(&bin, pubkey);
	if (len == 0)
		return ERR_PUBLIC_KEY_DECODING;
	const unsigned char *bin_copy = bin;
	eckey = o2i_ECPublicKey(&eckey, &bin_copy, len);
	OPENSSL_free(bin);
	
	// set private key
	len = hex2bin(&bin, privkey);
	if (len == 0)
		return ERR_PUBLIC_KEY_DECODING;
	bin_copy = bin;
	eckey = d2i_ECPrivateKey(&eckey, &bin_copy, len);
	OPENSSL_free(bin);
	
	// check keys
	if (!EC_KEY_check_key(eckey))
		return ERR_WRONG_KEYS;
	
	// calculate sha-1
	unsigned char digest[digest_len];
    el_compute_digest(name, digest, digest_len);

	// sign
	ECDSA_SIG *sig = ECDSA_do_sign(digest, digest_len, eckey);
	if (sig == NULL)
		return ERR_SIGNING;
	
	size_t rlen = BN_num_bytes(sig->r);
	size_t slen = BN_num_bytes(sig->s);
	size_t binlen = rlen + slen;
	bin = OPENSSL_malloc(binlen);
	bzero(bin, binlen);
	BN_bn2bin(sig->r, bin);
	BN_bn2bin(sig->s, bin + rlen); // join two values into bin
	ECDSA_SIG_free(sig);
	
	size_t b32len = el_base32_encode_buffer_size(binlen);
	char *base32 = OPENSSL_malloc(b32len);
	bzero(base32, b32len);

    el_base32_encode(bin, binlen, base32, b32len);
	printf("%s", base32);
	
	OPENSSL_free(bin);
	OPENSSL_free(base32);
	return 0;
}
static int read_nist_nls_data (const char *fname)
{
    FILE *fp;
    char line[128];
    int err = 0;
    int got_name = 0;
    int got_model = 0;
    int got_data = -1;

    fp = fopen(fname, "r");
    if (fp == NULL) {
	fprintf(stderr, "Couldn't open %s\n", fname);
	return 1;
    }

    tester_init();

    while (fgets(line, sizeof line, fp) && !err) {
	tail_strip(line);
	if (strstr(line, "Dataset Name:")) {
	    err = get_id(line + 13);
	    if (!err) got_name = 1;
	} else if (strstr(line, "Number of Observations:")) {
	    if (sscanf(line + 24, "%d", &tester.nobs) != 1) {
		err = 1;
	    } else {
		if (tester.nobs > 0) {
		    datainfo = create_new_dataset(&Z, tester.nvars + 1, 
						  tester.nobs, 0);
		    if (datainfo == NULL) err = 1;
		} else {
		    err = 1;
		}
	    }
	} else if (strncmp(line, "Model:", 6) == 0) {
	    err = read_model_lines(line, fp);
	    if (!err) got_model = 1;
	} else if (strstr(line, "Starting") && strstr(line, "Certified")) {
	    err = read_params(fp);
	} else if (strncmp(line, "Data:", 5) == 0) {
	    if (got_data < 0) {
		got_data = 0;
	    } else {
		err = read_data(fp);
		if (!err) got_data = 1;
	    }
	} else if (strstr(line, "Predictor")) {
	    err = get_nvars(line);
	} else if (strstr(line, "evel of Diffic")) {
	    print_grade(line);
	}
    }

    if (!got_name) {
	missing("dataset identifier");
    }
    if (!got_model) {
	missing("model specification");
    }
    if (tester.nparam == 0) {
	missing("parameter values");
    }

    if (got_data <= 0) {
	missing("input data");
    } else if (tester.nobs == 0) {
	missing("number of observations");
    }

    fclose(fp);

    return err;
}