Пример #1
0
/**
 * Creates a matrix from an input stream. Returns data as an array of rows.
 * Caller responsible for freeing returned structure.
 */
Matrix* create_matrix(FILE *in) {
    Matrix *m = NULL;
    int rows = 0;
    int columns = 0;

    if (!at_valid_matrix(in)) goto MatrixMalformedError;
    if (!read_dims(in, &rows, &columns)) {
        goto MatrixDimError;
    }
    m = new_matrix(rows, columns);
    int i = 0;
    for (i = 0; i < m->rows; ++i) {
        if (!read_row(in, m->data[i], m->columns)) {
            goto MatrixEntryError;
        }
    }
    return m;
    // evil gotos for exception handling
MatrixMalformedError:
    printf("The input.dat file appears corrupt, are you sure it's the proper format?\n");
    goto FreeAndReturn;
MatrixDimError:
    printf("Matrix dimension data corrupt\n");
    goto FreeAndReturn;
MatrixEntryError:
    printf("Matrix data corrupt\n");
    goto FreeAndReturn;
FreeAndReturn:
    free_matrix(&m);
    return NULL;
}
Пример #2
0
void ossimVpfLibrary::setTileNames()const
{
   ossimVpfTable table;
   theTileNameMap.clear();
   row_type row;
   if(table.openTable(theLibraryNameFullPath.dirCat("tileref").dirCat("tileref.aft")))
   {
      table.reset();
      const int ROWS = table.getNumberOfRows();
      for (int rowIdx = 1; rowIdx <= ROWS; ++rowIdx)
      {
         // Note:  read_row takes a "one based" index.
         row = read_row( rowIdx, *(table.getVpfTableData()) );
         ossim_int32 namePosition   = table.getColumnPosition("TILE_NAME");
         ossim_int32 tileIdPosition = table.getColumnPosition("ID");
         
         ossimString tileName = table.getColumnValueAsString(row,
                                                             namePosition);;
         ossimString tileId   = table.getColumnValueAsString(row,
                                                             tileIdPosition);
         theTileNameMap.insert(make_pair(tileId.toInt32(), tileName.trim()));
         free_row( row, *(table.getVpfTableData()) );
      }
   }
}
Пример #3
0
static int read_next(void)
{
    int n;

    top = bottom++;		/* switch top and bottom, */
    bottom = 1 & bottom;	/*   which are always 0 or 1 */
    n = read_row(buffer[bottom]);

    return (n);
}
Пример #4
0
ossimString ossimVpfTable::getColumnValueAsString(ossim_int32 rowNumber,
                                                  long columnNumber)const
{
   row_type row = read_row( rowNumber, *theTableInformation);
   ossimString result = getColumnValueAsString(row,
                                               columnNumber);
   free_row(row, *theTableInformation);

   return result;
}
Пример #5
0
    /// Read part of image defined by View and return the data.
    void read( byte_t* dst, int pos )
    {
        // jump to scanline
        long offset = this->_info._offset
                    + ( this->_info._height - 1 - pos ) * static_cast< long >( this->_scanline_length );
        
        this->_io_dev.seek( offset );
        

        read_row( dst );
    }
Пример #6
0
static int read_next(void)
{
    void *p;

    row++;
    p = top;
    top = middle;
    middle = bottom;
    bottom = p;

    return (read_row(bottom));
}
Пример #7
0
static int check_row(FILE* spreadsheet)
{
	int row[20];
	size_t count = 0;

	count = read_row(spreadsheet, row);

	if (count == 0)
		return 0; // empty line

	return do_check_row(row, count);
}
void rspfVpfFeatureClassSchema::setFeatureClassMapping()
{
   if(!isClosed())
   {
      rspf_int32 featureIdx = getColumnPosition("feature_class");
      rspf_int32 table1Idx = getColumnPosition("table1");
      rspf_int32 table1KeyIdx = getColumnPosition("table1_key");
      rspf_int32 table2Idx = getColumnPosition("table2");
      rspf_int32 table2KeyIdx = getColumnPosition("table2_key");
      reset();
      if(getNumberOfRows() > 0)
      {
         row_type row;
         const int ROWS = getNumberOfRows();
         for(int rowIdx = 1; rowIdx <= ROWS; ++rowIdx)
         {
            if(rowIdx == 1)
            {
               row = read_row(rowIdx,
                              *theTableInformation);
            }
            else
            {
               row = read_next_row(*theTableInformation);
            }
            rspfFilename primitiveTable =  getColumnValueAsString(row,
                                                                   table2Idx);
            if(rspfVpfFeatureClass::isPrimitive(primitiveTable))
            {
               rspfString primitiveTableKey = getColumnValueAsString(row,
                                                                      table2KeyIdx);
               rspfFilename table = getColumnValueAsString(row,
                                                            table1Idx);
               rspfString tableKey = getColumnValueAsString(row,
                                                             table1KeyIdx);
               rspfString featureClass = getColumnValueAsString(row,
                                                                 featureIdx);
               rspfVpfFeatureClassSchemaNode node(table,
                                                   tableKey,
                                                   primitiveTable,
                                                   primitiveTableKey);
               
               theFeatureClassMap.insert(make_pair(featureClass,
                                                   node));
            }
            
            free_row(row, *theTableInformation);
         }
      }
   }
}
Пример #9
0
/*************************************************************************
 *
 *N  get_row
 *
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Purpose:
 *P
 *     This function returns the specified row of the table.  If the table
 *     is stored in memory, the row is copied from there.  If it is on disk,
 *     it is read and returned.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Parameters:
 *A
 *    row_number <input> == (ossim_int32) row number in range [1 .. table.nrows].
 *    table      <input> == (vpf_table_type) vpf table structure.
 *    return    <output> == (row_type) returned row.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   History:
 *H
 *    Barry Michaels   May 1991      DOS Turbo C
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   External Variables:
 *X
 *    None
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Functions Called:
 *F
 *    row_type rowcpy                VPFREAD.C
 *    row_type read_row              VPFREAD.C
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Portability:
 *O
 *    This module should be ANSI C compatible.
 *E
 *************************************************************************/
row_type get_row( ossim_int32 row_number,
		  vpf_table_type table )
{
   row_type row;

   row_number = max(min(row_number, table.nrows), 1);

   if (table.storage == RAM) {
      row = rowcpy(table.row[row_number-1],table);
      return row;
   } else {
      return read_row( row_number, table );
   }
}
Пример #10
0
/*************************************************************************
 *
 *N  display_attributes
 *
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Purpose:
 *P
 *     This function displays all of the attributes of a particular
 *     feature, including the descriptions of the fields and their
 *     values.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Parameters:
 *A
 *    fc      <input> == (int) feature class number.
 *    row     <input> == (ossim_int32) row of the attribute table.
 *    library <input> == (library_type *) VPF library structure.
 *    fp      <input> == (FILE *) pointer to the output file.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   History:
 *H
 *    Barry Michaels    May 1991                      DOS Turbo C
 *E
 *************************************************************************/
void display_attributes( int fc,
			 ossim_int32 row,
			 library_type *library,
			 FILE *fp )
{
   vpf_table_type feature_table;
   row_type vpfrow;

   feature_table = vpf_open_table(library->fc[fc].table,disk,"rb",NULL);

   vpfrow = read_row( row, feature_table );

   vpf_display_record( vpfrow, feature_table, fp );

   free_row(vpfrow,feature_table);

   vpf_close_table(&feature_table);
}
Пример #11
0
/*
 * wts_read_scan --
 *	Read and verify all elements in a file.
 */
void
wts_read_scan(void)
{
	WT_CONNECTION *conn;
	WT_CURSOR *cursor;
	WT_ITEM key;
	WT_SESSION *session;
	uint64_t cnt, last_cnt;
	uint8_t *keybuf;
	int ret;

	conn = g.wts_conn;

	/* Set up the default key buffer. */
	key_gen_setup(&keybuf);

	/* Open a session and cursor pair. */
	if ((ret = conn->open_session(
	    conn, NULL, ops_session_config(NULL), &session)) != 0)
		die(ret, "connection.open_session");
	if ((ret = session->open_cursor(
	    session, g.uri, NULL, NULL, &cursor)) != 0)
		die(ret, "session.open_cursor");

	/* Check a random subset of the records using the key. */
	for (last_cnt = cnt = 0; cnt < g.key_cnt;) {
		cnt += mmrand(NULL, 1, 17);
		if (cnt > g.rows)
			cnt = g.rows;
		if (cnt - last_cnt > 1000) {
			track("read row scan", cnt, NULL);
			last_cnt = cnt;
		}

		key.data = keybuf;
		if ((ret = read_row(cursor, &key, cnt)) != 0)
			die(ret, "read_scan");
	}

	if ((ret = session->close(session, NULL)) != 0)
		die(ret, "session.close");

	free(keybuf);
}
Пример #12
0
/* 
 * is_end_token processes one token and returns 0 for an incomplete token
 * or -1 if this is the END token, and 1 for successful processing of token.  
 * The number of bytes read from the stream is returned in 'bytes_read'.
 */
static int
pool_is_end_token(TDS_POOL_MEMBER * pmbr, const unsigned char *buf, int maxlen, int *bytes_read)
{
	TDS_SMALLINT sz;
	int marker;
	int ret;

	if (maxlen == 0)
		return 0;

	marker = buf[0];
	sz = tds_get_token_size(marker);

	if (sz) {
		ret = read_fixed_token(pmbr, buf, maxlen, bytes_read);
	} else if (marker == TDS_ROW_TOKEN) {
		ret = read_row(pmbr, buf, maxlen, bytes_read);
	} else if (marker == TDS_COLNAME_TOKEN) {
		ret = read_col_name(pmbr, buf, maxlen, bytes_read);
	} else if (marker == TDS_COLFMT_TOKEN) {
		ret = read_col_info(pmbr, buf, maxlen, bytes_read);
	} else if (marker == TDS_RESULT_TOKEN) {
		ret = read_result(pmbr, buf, maxlen, bytes_read);
	} else {
		ret = read_variable_token(pmbr, buf, maxlen, bytes_read);
	}

	/* fprintf(stderr,"bytes_read = %d\n",*bytes_read); */
	if (!ret) {
		return 0;
	}

	if (is_end_token(marker)) {
		if (is_final_token(buf)) {
			/* clean up */
			return -1;
		}
	}

	return 1;
}
Пример #13
0
int main(void){
	int n,c,set;
	int row[MAX_INPUT], num_per_row;
	int lead[MAX_INPUT],power[MAX_INPUT];
	//init
	for (n=0;n<MAX_INPUT;n++){
		lead[n] = 0;
		power[n] = -1;
	}

	scanf("%d",&n);
	scanf("%c",&c);
	while(n--){
		set = -1;
		while(++set < 2){
			num_per_row = read_row(row);
			process(row,num_per_row,lead,power);
		}
		printResult(lead,power);
	}
}
Пример #14
0
int load_text_table(char *filename, struct ci_lookup_table *table) {
     FILE *f;
     struct text_table_entry *e, *l = NULL;
     int rows, ret;
     struct text_table *text_table = (struct text_table *)table->data;
     if ((f = fopen(filename, "r")) == NULL) {
	 ci_debug_printf(1, "Error opening file: %s\n", filename);
	 return 0;
     }

     rows = 0;
     if (text_table->entries != NULL) /*if table is not empty try to find the last element*/
         for (l = text_table->entries; l->next != NULL; l = l->next); 

     while(0 < (ret=read_row(f, table->cols, &e, table))) {
         if (e) {
             e->next = NULL;
             if(text_table->entries==NULL) {
                 text_table->entries = e;
                 l = e;
             }
             else {
                 l->next = e;
                 l = e;
             }
         }
         rows++;
     }
     fclose(f);

     if(ret==-1) {
         ci_debug_printf(1, "Error loading file table %s: parse error on line %d\n", 
                         filename, rows+1);
	 file_table_close(table);
	 return 0;
     }

     text_table->rows = rows;
     return 1;
}
Пример #15
0
void execute_histogram(char * histogram_query, char * data_filename, FILE * output) {
    
    char * command;
    command = (char *)calloc(11, sizeof(char));
    char * header;
    header = (char *)calloc(17, sizeof(char));
    char * header_word_2;
    header_word_2 = (char *)calloc(4, sizeof(char));
    char * header_word_3;
    header_word_3 = (char *)calloc(2, sizeof(char));
    int bins;
    char * start_date;
    start_date = (char *)calloc(17, sizeof(char));
    char * end_date;
    end_date = (char *)calloc(19, sizeof(char));
    
    // count whitespace in query to determine if header is multiple words
    int query_length = (int)strlen(histogram_query);
    int num_spaces = 0;
    for (int i=0; i<query_length; i++) {
        if (histogram_query[i] == ' ') {
            num_spaces++;
        }
    }
    if (num_spaces == 6) {
        sscanf(histogram_query, "%s %s %s %s %d %s %s", command, header, header_word_2, header_word_3, &bins, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        header[i+k+1] = ' ';
                        header[i+k+2] = header_word_3 [0];
                        header[i+k+3] = '\0';
                        break;
                    }
                }
                break;
            }
        }
    } else if (num_spaces == 5) {
        sscanf(histogram_query, "%s %s %s %d %s %s", command, header, header_word_2, &bins, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        break;
                    }
                }
                break;
            }
        }
    } else {
        sscanf(histogram_query, "%s %s %d %s %s", command, header, &bins, start_date, end_date);
    }
    
    Type_t data_type;
    data_type = column_type(header);
    
    int num_data_columns = header_columns(data_filename);
    char * column_headers[num_data_columns];
    read_header(data_filename, column_headers);
    
    int data_column_index = -1;
    int date_index = -1;
    int time_index = -1;
    
    char  date[] = "Date";
    char time[] = "HrMn";
    
    //date is LONG time is INT
    
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], header) == 0) {
            data_column_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], date) == 0) {
            date_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], time) == 0) {
            time_index = i;
        }
    }
    
    FILE * data_file = NULL;
    data_file = fopen(data_filename, "r");
    if (data_file == NULL) {
        printf("ERROR invalid data file: %s/n", data_filename);
    }
    
    void * row_data[num_data_columns];
    
    int ivalue; int imax; int imin;
    long lvalue ; long lmax; long lmin;
    float fvalue; float fmax;  float fmin; float maximum; float minimum;
    int row_count = 0;
    
    long * data_date;
    //    data_date = calloc(9, sizeof(char));
    
    int * data_time;
    //    data_time = calloc(5, sizeof(char));
    
    
    char * row;
    row = (char *)calloc(200,sizeof(char));
    int status = 0;
    // read file for maximum
    fgets(row, 200, data_file);
    while(fscanf(data_file, "*") != EOF) {
        status = read_row(data_file, column_headers, row_data);
        data_date = ((long*)row_data[date_index]);
        data_time = ((int*)row_data[time_index]);
        
        
        int in_time_range = is_in_range(start_date, end_date, data_date, data_time);
        if (in_time_range == 1) {
            if (data_type==FLOAT) {
                fvalue = *((float*)row_data[data_column_index]);
                if(row_count == 0) {
                    fmax = fvalue;
                } else if (fvalue > fmax) {
                    fmax = fvalue;
                }
            }
            if (data_type==INT) {
                ivalue = *((int*)row_data[data_column_index]);
                if(row_count == 0) {
                    imax = ivalue;
                } else if (ivalue > imax) {
                    imax = ivalue;
                }
            }
            if (data_type==LONG) {
                lvalue = *((long*)row_data[data_column_index]);
                if(row_count == 0) {
                    lmax = lvalue;
                } else if (lvalue > lmax) {
                    lmax = lvalue;
                }
            }
        }
        row_count++;
    }
    if (data_type==FLOAT) {
        printf("Maximum = %f\n",fmax);
        maximum = fmax;
    }else if (data_type==INT) {
        printf("Maximum = %d\n",imax);
        maximum = (float)imax;
    } else if (data_type==LONG) {
        printf("Maximum = %ld\n",lmax);
        maximum = (float)lmax;
    }
    
    rewind(data_file);
    
    fgets(row, 200, data_file);
    while(fscanf(data_file, "*") != EOF) {
        status = read_row(data_file, column_headers, row_data);
        data_date = ((long*)row_data[date_index]);
        data_time = ((int*)row_data[time_index]);
        
        
        int in_time_range = is_in_range(start_date, end_date, data_date, data_time);
        if (in_time_range == 1) {
            if (data_type==FLOAT) {
                fvalue = *((float*)row_data[data_column_index]);
                if(row_count == 0) {
                    fmin = fvalue;
                } else if (fvalue < fmin) {
                    fmin = fvalue;
                }
            }
            if (data_type==INT) {
                ivalue = *((int*)row_data[data_column_index]);
                if(row_count == 0) {
                    imin = ivalue;
                } else if (ivalue < imin) {
                    imin = ivalue;
                }
            }
            if (data_type==LONG) {
                lvalue = *((long*)row_data[data_column_index]);
                if(row_count == 0) {
                    lmin = lvalue;
                } else if (lvalue < lmin) {
                    lmin = lvalue;
                }
            }
        }
        row_count++;
    }
    if (data_type==FLOAT) {
        printf("Minimum = %f\n",fmin);
        minimum = fmin;
    }else if (data_type==INT) {
        printf("Minimum = %d\n",imin);
        minimum = (float)imin;
    } else if (data_type==LONG) {
        printf("Minimum = %ld\n",lmin);
        minimum = (float)lmin;
    }

}
Пример #16
0
static void *
ops(void *arg)
{
	TINFO *tinfo;
	WT_CONNECTION *conn;
	WT_CURSOR *cursor, *cursor_insert;
	WT_SESSION *session;
	WT_ITEM key, value;
	uint64_t keyno, ckpt_op, session_op;
	uint32_t op;
	uint8_t *keybuf, *valbuf;
	u_int np;
	int ckpt_available, dir, insert, intxn, notfound, readonly, ret;
	char *ckpt_config, ckpt_name[64];

	tinfo = arg;

	/* Initialize the per-thread random number generator. */
	__wt_random_init(&tinfo->rnd);

	conn = g.wts_conn;
	keybuf = valbuf = NULL;
	readonly = 0;			/* -Wconditional-uninitialized */

	/* Set up the default key and value buffers. */
	key_gen_setup(&keybuf);
	val_gen_setup(&tinfo->rnd, &valbuf);

	/* Set the first operation where we'll create sessions and cursors. */
	session_op = 0;
	session = NULL;
	cursor = cursor_insert = NULL;

	/* Set the first operation where we'll perform checkpoint operations. */
	ckpt_op = g.c_checkpoints ? mmrand(&tinfo->rnd, 100, 10000) : 0;
	ckpt_available = 0;

	for (intxn = 0; !tinfo->quit; ++tinfo->ops) {
		/*
		 * We can't checkpoint or swap sessions/cursors while in a
		 * transaction, resolve any running transaction.
		 */
		if (intxn &&
		    (tinfo->ops == ckpt_op || tinfo->ops == session_op)) {
			if ((ret = session->commit_transaction(
			    session, NULL)) != 0)
				die(ret, "session.commit_transaction");
			++tinfo->commit;
			intxn = 0;
		}

		/* Open up a new session and cursors. */
		if (tinfo->ops == session_op ||
		    session == NULL || cursor == NULL) {
			if (session != NULL &&
			    (ret = session->close(session, NULL)) != 0)
				die(ret, "session.close");

			if ((ret = conn->open_session(conn, NULL,
			    ops_session_config(&tinfo->rnd), &session)) != 0)
				die(ret, "connection.open_session");

			/*
			 * 10% of the time, perform some read-only operations
			 * from a checkpoint.
			 *
			 * Skip that if we single-threaded and doing checks
			 * against a Berkeley DB database, because that won't
			 * work because the Berkeley DB database records won't
			 * match the checkpoint.  Also skip if we are using
			 * LSM, because it doesn't support reads from
			 * checkpoints.
			 */
			if (!SINGLETHREADED && !DATASOURCE("lsm") &&
			    ckpt_available && mmrand(&tinfo->rnd, 1, 10) == 1) {
				if ((ret = session->open_cursor(session,
				    g.uri, NULL, ckpt_name, &cursor)) != 0)
					die(ret, "session.open_cursor");

				/* Pick the next session/cursor close/open. */
				session_op += 250;

				/* Checkpoints are read-only. */
				readonly = 1;
			} else {
				/*
				 * Open two cursors: one for overwriting and one
				 * for append (if it's a column-store).
				 *
				 * The reason is when testing with existing
				 * records, we don't track if a record was
				 * deleted or not, which means we must use
				 * cursor->insert with overwriting configured.
				 * But, in column-store files where we're
				 * testing with new, appended records, we don't
				 * want to have to specify the record number,
				 * which requires an append configuration.
				 */
				if ((ret = session->open_cursor(session, g.uri,
				    NULL, "overwrite", &cursor)) != 0)
					die(ret, "session.open_cursor");
				if ((g.type == FIX || g.type == VAR) &&
				    (ret = session->open_cursor(session, g.uri,
				    NULL, "append", &cursor_insert)) != 0)
					die(ret, "session.open_cursor");

				/* Pick the next session/cursor close/open. */
				session_op += mmrand(&tinfo->rnd, 100, 5000);

				/* Updates supported. */
				readonly = 0;
			}
		}

		/* Checkpoint the database. */
		if (tinfo->ops == ckpt_op && g.c_checkpoints) {
			/*
			 * LSM and data-sources don't support named checkpoints,
			 * and we can't drop a named checkpoint while there's a
			 * cursor open on it, otherwise 20% of the time name the
			 * checkpoint.
			 */
			if (DATASOURCE("helium") || DATASOURCE("kvsbdb") ||
			    DATASOURCE("lsm") ||
			    readonly || mmrand(&tinfo->rnd, 1, 5) == 1)
				ckpt_config = NULL;
			else {
				(void)snprintf(ckpt_name, sizeof(ckpt_name),
				    "name=thread-%d", tinfo->id);
				ckpt_config = ckpt_name;
			}

			/* Named checkpoints lock out backups */
			if (ckpt_config != NULL &&
			    (ret = pthread_rwlock_wrlock(&g.backup_lock)) != 0)
				die(ret,
				    "pthread_rwlock_wrlock: backup lock");

			if ((ret =
			    session->checkpoint(session, ckpt_config)) != 0)
				die(ret, "session.checkpoint%s%s",
				    ckpt_config == NULL ? "" : ": ",
				    ckpt_config == NULL ? "" : ckpt_config);

			if (ckpt_config != NULL &&
			    (ret = pthread_rwlock_unlock(&g.backup_lock)) != 0)
				die(ret,
				    "pthread_rwlock_wrlock: backup lock");

			/* Rephrase the checkpoint name for cursor open. */
			if (ckpt_config == NULL)
				strcpy(ckpt_name,
				    "checkpoint=WiredTigerCheckpoint");
			else
				(void)snprintf(ckpt_name, sizeof(ckpt_name),
				    "checkpoint=thread-%d", tinfo->id);
			ckpt_available = 1;

			/* Pick the next checkpoint operation. */
			ckpt_op += mmrand(&tinfo->rnd, 5000, 20000);
		}

		/*
		 * If we're not single-threaded and we're not in a transaction,
		 * start a transaction 20% of the time.
		 */
		if (!SINGLETHREADED &&
		    !intxn && mmrand(&tinfo->rnd, 1, 10) >= 8) {
			if ((ret =
			    session->begin_transaction(session, NULL)) != 0)
				die(ret, "session.begin_transaction");
			intxn = 1;
		}

		insert = notfound = 0;

		keyno = mmrand(&tinfo->rnd, 1, (u_int)g.rows);
		key.data = keybuf;
		value.data = valbuf;

		/*
		 * Perform some number of operations: the percentage of deletes,
		 * inserts and writes are specified, reads are the rest.  The
		 * percentages don't have to add up to 100, a high percentage
		 * of deletes will mean fewer inserts and writes.  Modifications
		 * are always followed by a read to confirm it worked.
		 */
		op = readonly ? UINT32_MAX : mmrand(&tinfo->rnd, 1, 100);
		if (op < g.c_delete_pct) {
			++tinfo->remove;
			switch (g.type) {
			case ROW:
				/*
				 * If deleting a non-existent record, the cursor
				 * won't be positioned, and so can't do a next.
				 */
				if (row_remove(cursor, &key, keyno, &notfound))
					goto deadlock;
				break;
			case FIX:
			case VAR:
				if (col_remove(cursor, &key, keyno, &notfound))
					goto deadlock;
				break;
			}
		} else if (op < g.c_delete_pct + g.c_insert_pct) {
			++tinfo->insert;
			switch (g.type) {
			case ROW:
				if (row_insert(
				    tinfo, cursor, &key, &value, keyno))
					goto deadlock;
				insert = 1;
				break;
			case FIX:
			case VAR:
				/*
				 * We can only append so many new records, if
				 * we've reached that limit, update a record
				 * instead of doing an insert.
				 */
				if (g.append_cnt >= g.append_max)
					goto skip_insert;

				/* Insert, then reset the insert cursor. */
				if (col_insert(tinfo,
				    cursor_insert, &key, &value, &keyno))
					goto deadlock;
				if ((ret =
				    cursor_insert->reset(cursor_insert)) != 0)
					die(ret, "cursor.reset");

				insert = 1;
				break;
			}
		} else if (
		    op < g.c_delete_pct + g.c_insert_pct + g.c_write_pct) {
			++tinfo->update;
			switch (g.type) {
			case ROW:
				if (row_update(
				    tinfo, cursor, &key, &value, keyno))
					goto deadlock;
				break;
			case FIX:
			case VAR:
skip_insert:			if (col_update(tinfo,
				    cursor, &key, &value, keyno))
					goto deadlock;
				break;
			}
		} else {
			++tinfo->search;
			if (read_row(cursor, &key, keyno))
				if (intxn)
					goto deadlock;
			continue;
		}

		/*
		 * The cursor is positioned if we did any operation other than
		 * insert, do a small number of next/prev cursor operations in
		 * a random direction.
		 */
		if (!insert) {
			dir = (int)mmrand(&tinfo->rnd, 0, 1);
			for (np = 0; np < mmrand(&tinfo->rnd, 1, 8); ++np) {
				if (notfound)
					break;
				if (nextprev(cursor, dir, &notfound))
					goto deadlock;
			}
		}

		/* Read to confirm the operation. */
		++tinfo->search;
		if (read_row(cursor, &key, keyno))
			goto deadlock;

		/* Reset the cursor: there is no reason to keep pages pinned. */
		if ((ret = cursor->reset(cursor)) != 0)
			die(ret, "cursor.reset");

		/*
		 * If we're in the transaction, commit 40% of the time and
		 * rollback 10% of the time.
		 */
		if (intxn)
			switch (mmrand(&tinfo->rnd, 1, 10)) {
			case 1: case 2: case 3: case 4:		/* 40% */
				if ((ret = session->commit_transaction(
				    session, NULL)) != 0)
					die(ret, "session.commit_transaction");
				++tinfo->commit;
				intxn = 0;
				break;
			case 5:					/* 10% */
				if (0) {
deadlock:				++tinfo->deadlock;
				}
				if ((ret = session->rollback_transaction(
				    session, NULL)) != 0)
					die(ret,
					    "session.rollback_transaction");
				++tinfo->rollback;
				intxn = 0;
				break;
			default:
				break;
			}
	}

	if (session != NULL && (ret = session->close(session, NULL)) != 0)
		die(ret, "session.close");

	free(keybuf);
	free(valbuf);

	tinfo->state = TINFO_COMPLETE;
	return (NULL);
}
bool ossimVpfBoundingRecordTable::openTable(const ossimFilename& tableName)
{
   bool result = false;
   theExtent = ossimVpfExtent(0,0,0,0);
   bool firstOneSetFlag = false;
   
   if(ossimVpfTable::openTable(tableName))
   {
      ossim_int32 xminIdx = getColumnPosition("XMIN");
      ossim_int32 yminIdx = getColumnPosition("YMIN");
      ossim_int32 xmaxIdx = getColumnPosition("XMAX");
      ossim_int32 ymaxIdx = getColumnPosition("YMAX");
      
      if((xminIdx < 0)||
         (yminIdx < 0)||
         (xmaxIdx < 0)||
         (ymaxIdx < 0))
      {
         closeTable();
      }
      else
      {
         if(getNumberOfRows() > 0)
         {
            result = true;
            reset();
            ossim_int32 n = 1;
            
            ossim_float32 xmin;
            ossim_float32 ymin;
            ossim_float32 xmax;
            ossim_float32 ymax;
            
            row_type row;
            for(int rowIdx = 1; rowIdx < getNumberOfRows(); ++rowIdx)
            {
               if(rowIdx == 1)
               {
                  row = read_row(rowIdx,
                                 *theTableInformation);
               }
               else
               {
                  row = read_next_row(*theTableInformation);
               }
               get_table_element(xminIdx,
                                 row,
                                 *theTableInformation,
                                 &xmin,
                                 &n);
               get_table_element(yminIdx,
                                 row,
                                 *theTableInformation,
                                 &ymin,
                                 &n);
               get_table_element(xmaxIdx,
                                 row,
                                 *theTableInformation,
                                 &xmax,
                                 &n);
               get_table_element(ymaxIdx,
                                 row,
                                 *theTableInformation,
                                 &ymax,
                                 &n);
               if(!is_vpf_null_float(xmin)&&
                  !is_vpf_null_float(ymin)&&
                  !is_vpf_null_float(xmax)&&
                  !is_vpf_null_float(ymax))
               {
                  if(!firstOneSetFlag)
                  {
                     theExtent = ossimVpfExtent(xmin,
                                                ymin,
                                                xmax,
                                                ymax);
                     firstOneSetFlag = true;
                  }
                  else
                  {
                     theExtent = theExtent + ossimVpfExtent(xmin,
                                                            ymin,
                                                            xmax,
                                                            ymax);
                  }                  
               }
               free_row(row, *theTableInformation);
            }
         }
      }
   }
   return result;
}
Пример #18
0
static void *
ops(void *arg)
{
	TINFO *tinfo;
	WT_CONNECTION *conn;
	WT_CURSOR *cursor, *cursor_insert;
	WT_SESSION *session;
	WT_ITEM key, value;
	uint64_t cnt, keyno, sync_op, thread_ops;
	uint32_t op;
	uint8_t *keybuf, *valbuf;
	u_int np;
	int dir, insert, notfound, ret, sync_drop;
	char sync_name[64];

	conn = g.wts_conn;

	tinfo = arg;

	/* Set up the default key and value buffers. */
	memset(&key, 0, sizeof(key));
	key_gen_setup(&keybuf);
	memset(&value, 0, sizeof(value));
	val_gen_setup(&valbuf);

	/* Open a session. */
	if ((ret = conn->open_session(conn, NULL, NULL, &session)) != 0)
		die(ret, "connection.open_session");

	/*
	 * Open two cursors: one configured for overwriting and one configured
	 * for append if we're dealing with a column-store.
	 *
	 * The reason is when testing with existing records, we don't track if
	 * a record was deleted or not, which means we must use cursor->insert
	 * with overwriting configured.  But, in column-store files where we're
	 * testing with new, appended records, we don't want to have to specify
	 * the record number, which requires an append configuration.
	 */
	cursor = cursor_insert = NULL;
	if ((ret = session->open_cursor(session,
	    WT_TABLENAME, NULL, "overwrite", &cursor)) != 0)
		die(ret, "session.open_cursor");
	if ((g.c_file_type == FIX || g.c_file_type == VAR) &&
	    (ret = session->open_cursor(session,
	    WT_TABLENAME, NULL, "append", &cursor_insert)) != 0)
		die(ret, "session.open_cursor");

	/* Each thread does its share of the total operations. */
	thread_ops = g.c_ops / g.c_threads;

	/* Pick an operation where we'll do a sync and create the name. */
	sync_drop = 0;
	sync_op = MMRAND(1, thread_ops);
	snprintf(sync_name, sizeof(sync_name), "snapshot=thread-%d", tinfo->id);

	for (cnt = 0; cnt < thread_ops; ++cnt) {
		if (SINGLETHREADED && cnt % 100 == 0)
			track("read/write ops", 0ULL, tinfo);

		if (cnt == sync_op) {
			if (sync_drop && (int)MMRAND(1, 4) == 1) {
				if ((ret = session->drop(
				    session, WT_TABLENAME, sync_name)) != 0)
					die(ret, "session.drop: %s: %s",
					    WT_TABLENAME, sync_name);
				sync_drop = 0;
			} else {
				if ((ret = session->checkpoint(
				    session, sync_name)) != 0)
					die(ret, "session.checkpoint: %s",
					    sync_name);
				sync_drop = 1;
			}

			/*
			 * Pick the next sync operation, try for roughly five
			 * snapshot operations per thread run.
			 */
			sync_op += MMRAND(1, thread_ops) / 5;
		}

		insert = notfound = 0;

		keyno = MMRAND(1, g.rows);
		key.data = keybuf;
		value.data = valbuf;

		/*
		 * Perform some number of operations: the percentage of deletes,
		 * inserts and writes are specified, reads are the rest.  The
		 * percentages don't have to add up to 100, a high percentage
		 * of deletes will mean fewer inserts and writes.  A read
		 * operation always follows a modification to confirm it worked.
		 */
		op = (uint32_t)(wts_rand() % 100);
		if (op < g.c_delete_pct) {
			++tinfo->remove;
			switch (g.c_file_type) {
			case ROW:
				/*
				 * If deleting a non-existent record, the cursor
				 * won't be positioned, and so can't do a next.
				 */
				row_remove(cursor, &key, keyno, &notfound);
				break;
			case FIX:
			case VAR:
				col_remove(cursor, &key, keyno, &notfound);
				break;
			}
		} else if (op < g.c_delete_pct + g.c_insert_pct) {
			++tinfo->insert;
			switch (g.c_file_type) {
			case ROW:
				row_update(cursor, &key, &value, keyno, 1);
				break;
			case FIX:
			case VAR:
				/*
				 * Reset the standard cursor so it doesn't keep
				 * pages pinned.
				 */
				if ((ret = cursor->reset(cursor)) != 0)
					die(ret, "cursor.reset");
				col_insert(cursor_insert, &key, &value, &keyno);
				insert = 1;
				break;
			}
		} else if (
		    op < g.c_delete_pct + g.c_insert_pct + g.c_write_pct) {
			++tinfo->update;
			switch (g.c_file_type) {
			case ROW:
				row_update(cursor, &key, &value, keyno, 0);
				break;
			case FIX:
			case VAR:
				col_update(cursor, &key, &value, keyno);
				break;
			}
		} else {
			++tinfo->search;
			read_row(cursor, &key, keyno);
			continue;
		}

		/*
		 * If we did any operation, we've set the cursor, do a small
		 * number of next/prev cursor operations in a random direction.
		 */
		dir = (int)MMRAND(0, 1);
		for (np = 0; np < MMRAND(1, 8); ++np) {
			if (notfound)
				break;
			nextprev(
			    insert ? cursor_insert : cursor, dir, &notfound);
		}

		if (insert && (ret = cursor_insert->reset(cursor_insert)) != 0)
			die(ret, "cursor.reset");

		/* Read the value we modified to confirm the operation. */
		read_row(cursor, &key, keyno);
	}

	if ((ret = session->close(session, NULL)) != 0)
		die(ret, "session.close");

	free(keybuf);
	free(valbuf);

	tinfo->state = TINFO_COMPLETE;
	return (NULL);
}
Пример #19
0
/*************************************************************************
 *
 *N  draw_face_row
 *
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Purpose:
 *P
 *     This function draws the specified face from the given row of
 *     the given face table.
 *     It is complicated by the fact that it checks to see whether a
 *     face has wrapped around the screen due to projection effects.
 *     If so, it first adjusts the coordinates off the right edge of the
 *     screen to fill that portion of the face.  Then, if the face
 *     wraps around to the other edge of the screen, it adjusts the
 *     coordinates to the left edge of the screen and refills to
 *     display that portion of the face.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Parameters:
 *A
 *     row       <input>==(row_type) row of the specified face table.
 *     facetable <input>==(vpf_table_type) VPF face primitive table.
 *     ringtable <input>==(vpf_table_type) VPF ring primitive table.
 *     edgetable <input>==(vpf_table_type) VPF edge primitive table.
 *     fbr       <input>==(vpf_table_type) VPF face bounding rectangle table.
 *     outline   <input>==(color_type) outline color.
 *     c1        <input>==(color_type) 1st color in the fill pattern.
 *     c2        <input>==(color_type) 2nd color in the fill pattern.
 *     c3        <input>==(color_type) 3rd color in the fill pattern.
 *     c4        <input>==(color_type) 4th color in the fill pattern.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   History:
 *H
 *    Barry Michaels   May 1991                           DOS Turbo C
 *E
 *************************************************************************/
void draw_face_row( row_type row,
		vpf_table_type facetable,
		vpf_table_type ringtable,
		vpf_table_type edgetable,
		vpf_table_type fbr,
		color_type outline,
		color_type c1,
		color_type c2,
		color_type c3,
		color_type c4 )
{
   ossim_int32 count;
   int  spx1,spy1,spx2,spy2,  rowid,ring;
   extent_type shade_box;
   Pattern  pattern;
   face_rec_type face_rec;
   int wrap, mbrx2;
   row_type fbrrow;
   int XMIN_,YMIN_,XMAX_,YMAX_;

   rowid = table_pos( "ID", facetable );
   ring = table_pos( "RING_PTR", facetable );
   get_table_element( rowid, row, facetable, &(face_rec.id), &count );
   get_table_element( ring, row, facetable, &(face_rec.ring), &count );

   gpsetlinecolor(outline);
   gpsetlinestyle(SOLID_LINE);
   gpsetlinewidth(NORM_WIDTH);

   wrap = 0;

   if (gpgetdevice()==SCREEN) {
      pattern = MakePattern(c1,c2,c3,c4);

      /* Read bounding box */
      fbrrow = read_row( face_rec.id, fbr );
      XMIN_ = table_pos( "XMIN", fbr );
      YMIN_ = table_pos( "YMIN", fbr );
      XMAX_ = table_pos( "XMAX", fbr );
      YMAX_ = table_pos( "YMAX", fbr );
      get_table_element(XMIN_,fbrrow,fbr,&shade_box.x1,&count);
      get_table_element(YMIN_,fbrrow,fbr,&shade_box.y1,&count);
      get_table_element(XMAX_,fbrrow,fbr,&shade_box.x2,&count);
      get_table_element(YMAX_,fbrrow,fbr,&shade_box.y2,&count);
      free_row(fbrrow,fbr);

      screen_bounds(shade_box.x1,shade_box.y1,
		 shade_box.x2,shade_box.y2,
		 &spx1,&spy1,&spx2,&spy2);
      mbrx2 = spx2;
      if (spx2<spx1) {
	 /* The face wraps around the screen */
	 /* (or at least wraps off the edge of the screen) */
	 wrap = gpgetmaxx();
	 if (spx2 < 0) wrap -= spx2;
	 /* Adjust the maximum screen value */
	 spx2 += wrap;
      }

   } else {
      gpstartpoly();
   }

   draw_polygon( spx1,spy1,spx2,spy2, face_rec, ringtable,
		 edgetable, outline, pattern, wrap );

   if (wrap && mbrx2 > 0) {
      /* The polygon has wrapped around to the other side of the */
      /* screen.  Must redraw the part left off on the first pass. */

      if (gpgetdevice()==SCREEN) {

	 spx1 -= wrap;
	 spx2 -= wrap;

      } else {
	 gpstartpoly();
      }

      wrap *= -1;
      draw_polygon( spx1,spy1,spx2,spy2, face_rec, ringtable,
		    edgetable, outline, pattern, wrap );

   }

}
Пример #20
0
/*
 *			M A I N ( )
 */
int
main (int argc, char **argv)
{
    char		*inbuf;		/* The input scanline */
    char		*outbuf;	/*  "  output    "    */
    char		*in, *out;	/* Pointers into inbuf and outbuf */
    fastf_t		twice_r1r2;
    fastf_t		squares;
    fastf_t		scale_fac;
    fastf_t		theta;
    fastf_t		x;		/* Scale factor for pixel blending */
    int			i;		/* Pixel index in inbuf */
    int			j;		/*   "     "    " outbuf */
    long int		row;
    long int		row_width;

    if (!get_args( argc, argv ))
    {
	(void) fputs(usage, stderr);
	bu_exit (1, NULL);
    }

    if (solid_type == SPHERE)
    {
	(void) fprintf(stderr, "Sphere scaling not yet implemented\n");
	bu_exit (1, NULL);
    }
    else if (solid_type != TORUS)
    {
	(void) fprintf(stderr, "Illegal solid type %d\n", solid_type);
	bu_exit (0, NULL);
    }

    /*
     *	Autosize the input if appropriate
     */
    if (fileinput && autosize)
    {
	unsigned long int	w, h;

	if (fb_common_file_size(&w, &h, file_name, 3))
	{
	    file_width = (long)w;
	    file_height = (long)h;
	}
	else
	    (void) fprintf(stderr, "texturescale: unable to autosize\n");
    }

    /*
     *	Initialize some runtime constants
     */
    twice_r1r2 = 2 * r1 * r2;
    squares = r1 * r1 + r2 * r2;
    scale_fac = file_width / (r1 + r2);

    /*
     *	Allocate 1-scanline buffers for input and output
     */
    outbuf = bu_malloc(3*file_width, "outbuf");
    inbuf  = bu_malloc(3*file_width, "inbuf");

    /*
     *	Do the filtering
     */
    for (row = 0; row < file_height; ++row)
    {
	/*
	 *	Read an input scanline
	 */
	if (! read_row(inbuf, file_width, infp))
	{
	    perror(file_name);
	    (void) fprintf(stderr, "texturescale:  fread() error\n");
	    bu_exit (1, NULL);
	}

	/*
	 *	Determine how much of the input scanline we want
	 */
	theta = 2 * bn_pi * row / file_height;
	row_width = scale_fac * sqrt(squares - twice_r1r2 * cos(theta));
	in = inbuf + ((file_width - row_width) / 2) * 3;
	out = outbuf;

	/*
	 *	Scale the input scanline into the output scanline
	 */
	for (i = j = 1; j <= file_width; ++j)
	{
	    if (i * file_width < j * row_width)
	    {
		x = j - (i * file_width) / row_width;
		VBLEND2(out, (1.0 - x), in, x, in + 3);
		++i;
		in += 3;
	    }
	    else
		VMOVE(out, in);
	    out += 3;
	}

	/*
	 *	Write the output scanline
	 */
	if (fwrite(outbuf, 3, file_width, stdout) != file_width)
	{
	    perror("stdout");
	    bu_exit (2, NULL);
	}
    }

    bu_exit (1, NULL);
}
Пример #21
0
board_60GHz_RX::board_60GHz_RX(uhd::usrp::dboard_iface::sptr db_iface) :
board_60GHz_base(db_iface,uhd::usrp::dboard_iface::UNIT_TX,
				   ENABLE_HMC, DATA_IN_HMC, CLK_HMC,
		 DATA_OUT_HMC, RESET_HMC,1+2+4) {


    write_row(0,128); // Everthing on except ASK mod.
    int bb_gain1=0; // 0-3
    int bb_gain2=0; // 0-3
    int bb_att1=3-bb_gain1;
    int bb_att2=3-bb_gain2;
    write_row(1,bb_att2+4*bb_att1); // Power on + gain control

    int bb_gain_fineI=0; // 0-5
    int bb_gain_fineQ=0; // 0-5

    int bb_att_fineI=5-bb_gain_fineI;
    int bb_att_fineQ=5-bb_gain_fineQ;


    write_row(2,4*bb_att_fineQ+32*bb_att_fineI); 
                                               // Normal operation

    int bb_low_pass_corner=3; // 0=>1.4GHz, 1=>500MHz, 2=> 300MHz, 3=>200MHz.
    int bb_high_pass_corner=2; // 0=>30kHz, 1=>300kHz, 2=>1.5MHz.

    write_row(3,3+16*bb_high_pass_corner+64*bb_low_pass_corner);
                                            // Normal operation
    
    write_row(4,158); // Normal operation

    int if_gain=15; // 0-15
    int if_att=15-if_gain;

    write_row(5,15+16*if_att); // Normal operation
    write_row(6,191); // Normal operation
    write_row(7,109); // Normal operation
    write_row(8,128); // Normal operation
    write_row(9,0); // Normal operation
    write_row(10,240); // 240+DIVRATIO<4>
    write_row(11,16*(1+2+4)+2*3+1); // 16*DIVRATIO<3:0>+2*BAND+1
    write_row(12,95); // Normal operation
    write_row(13,128); // Normal operation
    write_row(14,118); // Normal operation

    
    #if 0
    for (int i1=0;i1<15;i1++) {
      std::cout << "reg=" << i1 << " value=" << read_row(i1) 
          << "\n";
    };
    #endif

    std::cout << "Waiting for PLL lock \n";
    int lock=read_row(15)>> 6;
    while (lock!=1) {
      std::cout << ".";
      usleep(1e6);
      lock=read_row(15)>> 6;
    };
    std::cout << "PLL has locked! \n";


  


}
Пример #22
0
board_60GHz_TX::board_60GHz_TX(uhd::usrp::dboard_iface::sptr db_iface) :
board_60GHz_base(db_iface,uhd::usrp::dboard_iface::UNIT_TX,
				   ENABLE_HMC, DATA_IN_HMC, CLK_HMC,
		 DATA_OUT_HMC, RESET_HMC,2+4) {


    write_row(0,0); // Power on everything
    write_row(1,0); // Power on and highest Q of filter.
    write_row(2,240); // Taken from PC app.
    write_row(3,31); // Taken from PC app.
    write_row(4,63); // Normal operation
    write_row(5,244); // Normal operation
    write_row(6,143); // 

    int l_tx_gain=13; // 0:13. Increasing gain.
    write_row(7,15+16*(13-l_tx_gain)); 
                                   // Highest gain + normal operation
    
    write_row(8,191); // normal operation
    write_row(9,111); // normal operation


    // Table 10. 285.7143MHz Reference
    // Frequency(GHz)    DIVRATIO            BAND

    /*      57             00001             000
            57.5           00010             000
            58             00011             001
            58.5           00100             001
            59             00101             010
            59.5           00110             010
            60             00111             011
            60.5           01000             011
            61             01001             100
            61.5           01010             100
            62             01011             101
            62.5           01100             101
            63             01101             110
            63.5           01110             110
            64             01111             111  */


    write_row(10,240); // 240+DIVRATIO<4>
    write_row(11,16*(1+2+4)+2*3+1); // 16*DIVRATIO<3:0>+2*BAND+1


    write_row(12,95); // Syntesizer parameters (lock window)
    write_row(13,128); // normal operation (synths on)
    write_row(14,118); // normal operation

    #if 0
    for (int i1=0;i1<15;i1++) {
      std::cout << "reg=" << i1 << " value=" << read_row(i1) 
          << "\n";
    };
    #endif

    std::cout << "Waiting for PLL lock \n";
    int lock=read_row(15)>> 6;
    while (lock!=1) {
      std::cout << ".";
      usleep(1e6);
      lock=read_row(15)>> 6;
    };
    std::cout << "PLL has locked! \n";
   
}
Пример #23
0
bool ossimVpfLibrary::getExtent(ossimVpfExtent& extent)const
{
   bool result = false;
   ossimVpfTable tempTable;


   // this code was basically cut paste from vhcl with just
   // a couple modifications.
   
    /* Get library extent from Library Attribute Table (LAT) */
/*    char* buf;*/
/*    long int n;*/
/*    double xmin,ymin,xmax,ymax;*/
    int libraryNamePosition, xminPosition, yminPosition;
    int xmaxPosition, ymaxPosition;
    int i;
    bool found;
    row_type row;
    extent_type libextent;

    if(!theDatabase)
    {
       return false;
    }
    ossimFilename file(theDatabase->getLibraryAttributeTable());
    if(!tempTable.openTable(file))
    {
       return result;
    }
    vpf_table_type *table = tempTable.getVpfTableData();
       
    libraryNamePosition = table_pos( "LIBRARY_NAME", *table );
    found = false;
    for (i=1;(i<=tempTable.getNumberOfRows())&&(!found);i++)
    {
       row = read_row( i, *table );
       ossimString libraryName = tempTable.getColumnValueAsString(row, libraryNamePosition);
       libraryName = libraryName.trim();
       if (libraryName == theLibraryName)
       {
          xminPosition = table_pos( "XMIN", *table );
          yminPosition = table_pos( "YMIN", *table );
          xmaxPosition = table_pos( "XMAX", *table );
          ymaxPosition = table_pos( "YMAX", *table );

          libextent.x1 = tempTable.getColumnValueAsString(row, xminPosition).toDouble();
          libextent.y1 = tempTable.getColumnValueAsString(row, yminPosition).toDouble();
          libextent.x2 = tempTable.getColumnValueAsString(row, xmaxPosition).toDouble();
          libextent.y2 = tempTable.getColumnValueAsString(row, ymaxPosition).toDouble();
          found = true;
       }
       else
       {
          result = false;
       }
       free_row( row, *table );
    }
    
    extent =  ossimVpfExtent(libextent);
    return result;
}
Пример #24
0
int main( int argc, char *argv[] )
{

	xmlrpc_env env;
	xmlrpc_value * resultP;
	xmlrpc_value * keyP;
	xmlrpc_value * valueP;
	int struct_size;
	int i, j;
	size_t length;
	const char * str_key_value;
	xmlrpc_int   int_key_value;
	unsigned int max_hits = 0;
	unsigned int rows = 0;
	int rv;
	char *uri;
	int options;		/* what kind of nodes should be processed */
	int uri_pos;		/* position of first non option argument */
	char stropts[16];
	int  pos = 0;
	int  mask_length = 32;	/* 32 means NO aggregate */

	if (argc-1 < 1) {
		print_help();
		exit(0);
	}
	uri_pos = process_options(argc, argv, &options, &mask_length);
	switch (options) {
		case OPT_HOT:
				sprintf(stropts, "HOT");
				break;
		case OPT_ALL:
				sprintf(stropts, "ALL");
				break;
		case OPT_WARM:
				sprintf(stropts, "WARM");
				break;
	}
	printf("Nodes = %s\n", stropts);
	printf("Mask  = /%d\n", mask_length);

	/* Start up our XML-RPC client library. */
	xmlrpc_client_init(XMLRPC_CLIENT_NO_FLAGS, NAME, VERSION);
	
	/* Initialize our error-handling environment. */
	xmlrpc_env_init(&env);

	/* prototype:
	   xmlrpc_value * xmlrpc_client_call(xmlrpc_env * const envP,
	                                     const char * const server_url, const char * const method_name,
	                                     const char * const format, ...);
	 */
	asprintf(&uri, "http://%s/RPC2", argv[uri_pos]);
	resultP = xmlrpc_client_call(&env, uri,
	                             "pike.top",
	                             "(s)", stropts);
	free(uri);
	die_if_fault_occurred_line(&env, __LINE__);
	
	/* parse returned structure */
	if ( xmlrpc_value_type(resultP) != XMLRPC_TYPE_STRUCT ) {
		printf("unexpected result - should be structure\n");
		xmlrpc_env_clean(&env);
		xmlrpc_client_cleanup();
		exit(1);
	}

	struct_size = xmlrpc_struct_size(&env, resultP);
	die_if_fault_occurred_line(&env, __LINE__);
//	printf("Struct size: %d\n", struct_size);

	if ( ! get_int_from_struct_by_name(resultP, MAX_HITS, &max_hits) ) {
		fprintf(stderr, "ERROR: %s not foung in result\n", MAX_HITS);
		exit (1);
	}
	printf("max_hits = %d\n", max_hits);
	if ( ! get_int_from_struct_by_name(resultP, NUMBER_OF_ROWS, &rows) ) {
		fprintf(stderr, "ERROR: %s not foung in result\n", NUMBER_OF_ROWS);
		exit (1);
	}
	printf("rows = %d\n", rows);
	TopItem top_items[rows];
	TopItem *item;			/* tmp item ptr */
	TopItem *result_items = top_items;	/* if no aggregation use this */
	memset(top_items, 0, sizeof(top_items));

	/* aggregated values */
	
	if ( rows == 0 )
		return 0;
	
	for ( i = 0, item = top_items; i < rows; ++i, ++item ) {
		if ( ! read_row(resultP, i, item) ) {
			fprintf(stderr, "ERROR: while reading row number %d\n", i);
		}
		/* fill in ipv4 addr */
//		printf("item[%d].ip_addr = %s, len = %d\n", i, item->ip_addr, strlen(item->ip_addr));
		rv = inet_pton(AF_INET, item->ip_addr, &item->ipv4_addr);
		if ( rv > 0 ) {
//			printf("IPv4 addr: %x\n", item->ipv4_addr);
		} else {
			fprintf(stderr, "IP conversion failed - not an IPv4 address: '%s'\n", item->ip_addr);	/* conversion failed from any reason */
			printf("item[%d].ipv4_addr = %x\n", i, item->ipv4_addr);
		}
			
	}

	assert( rows > 0 );
	/* if IP mask length is shorter than 32 then aggregate list according to the mask */
	if ( mask_length < 32 ) {
		uint32_t ip_mask = htonl(mask(mask_length));
		
		qsort(top_items, rows, sizeof(TopItem), compare_TopItem_ipv4_addr);		/* sort by IPv4 */

		/* skip items without ipv4 address */
		i = 0;	/* index of non aggregated items */
		while (!top_items[i].ipv4_addr && i < rows ) {
			printf("Skip item[%d] - do not has IPv4 address: %s\n", i, top_items[i].ip_addr);
			memset(&top_items[i], 0, sizeof(TopItem));
			++i;
		}

		j = 0;	/* index of aggregated items */
		if ( i == 0 )
			++i;
		
		top_items[0].ipv4_addr &= ip_mask;
		top_items[0].num_of_ips = 1;
		inet_ntop(AF_INET, &top_items[0].ipv4_addr, top_items[0].ip_addr, sizeof(top_items[0].ip_addr));
		while ( i < rows ) {
			top_items[i].ipv4_addr &= ip_mask;
			
			if ( top_items[j].ipv4_addr == top_items[i].ipv4_addr ) {
				top_items[j].leaf_hits[0] += top_items[i].leaf_hits[0];
				top_items[j].leaf_hits[1] += top_items[i].leaf_hits[1];
				++(top_items[j].num_of_ips);
				++i;
			}
			else {
				++j;
				top_items[j] = top_items[i];
				top_items[j].num_of_ips = 1;
				inet_ntop(AF_INET, &top_items[j].ipv4_addr, top_items[j].ip_addr, sizeof(top_items[j].ip_addr));
				++i;
			}
		}
		rows = j + 1;
	}

	qsort(top_items, rows, sizeof(TopItem), compare_TopItem_hits_reverse);

	print_rows( top_items, rows, mask_length );

	/* Dispose of our result value. */
	xmlrpc_DECREF(resultP);

	/* Clean up our error-handling environment. */
	xmlrpc_env_clean(&env);
	/* Shutdown our XML-RPC client library. */
	xmlrpc_client_cleanup();

	return 0;
}
Пример #25
0
NCURSES_SP_NAME(getwin) (NCURSES_SP_DCLx FILE *filep)
{
    WINDOW tmp, *nwin;
    int n;
    bool old_format = FALSE;

    T((T_CALLED("getwin(%p)"), (void *) filep));

    if (filep == 0) {
	returnWin(0);
    }

    /*
     * Read the first 4 bytes to determine first if this is an old-format
     * screen-dump, or new-format.
     */
    if (read_block(&tmp, 4, filep) < 0) {
	returnWin(0);
    }
    /*
     * If this is a new-format file, and we do not support it, give up.
     */
    if (!memcmp(&tmp, my_magic, 4)) {
#if NCURSES_EXT_PUTWIN
	if (read_win(&tmp, filep) < 0)
#endif
	    returnWin(0);
    } else if (read_block(((char *) &tmp) + 4, sizeof(WINDOW) - 4, filep) < 0) {
	returnWin(0);
    } else {
	old_format = TRUE;
    }

    /*
     * Check the window-size:
     */
    if (tmp._maxy == 0 ||
	tmp._maxy > MAX_SIZE ||
	tmp._maxx == 0 ||
	tmp._maxx > MAX_SIZE) {
	returnWin(0);
    }

    if (tmp._flags & _ISPAD) {
	nwin = NCURSES_SP_NAME(newpad) (NCURSES_SP_ARGx
					tmp._maxy + 1,
					tmp._maxx + 1);
    } else {
	nwin = NCURSES_SP_NAME(newwin) (NCURSES_SP_ARGx
					tmp._maxy + 1,
					tmp._maxx + 1, 0, 0);
    }

    /*
     * We deliberately do not restore the _parx, _pary, or _parent
     * fields, because the window hierarchy within which they
     * made sense is probably gone.
     */
    if (nwin != 0) {
	size_t linesize = sizeof(NCURSES_CH_T) * (size_t) (tmp._maxx + 1);

	nwin->_curx = tmp._curx;
	nwin->_cury = tmp._cury;
	nwin->_maxy = tmp._maxy;
	nwin->_maxx = tmp._maxx;
	nwin->_begy = tmp._begy;
	nwin->_begx = tmp._begx;
	nwin->_yoffset = tmp._yoffset;
	nwin->_flags = tmp._flags & ~(_SUBWIN);

	WINDOW_ATTRS(nwin) = WINDOW_ATTRS(&tmp);
	nwin->_nc_bkgd = tmp._nc_bkgd;

	nwin->_notimeout = tmp._notimeout;
	nwin->_clear = tmp._clear;
	nwin->_leaveok = tmp._leaveok;
	nwin->_idlok = tmp._idlok;
	nwin->_idcok = tmp._idcok;
	nwin->_immed = tmp._immed;
	nwin->_scroll = tmp._scroll;
	nwin->_sync = tmp._sync;
	nwin->_use_keypad = tmp._use_keypad;
	nwin->_delay = tmp._delay;

	nwin->_regtop = tmp._regtop;
	nwin->_regbottom = tmp._regbottom;

	if (tmp._flags & _ISPAD)
	    nwin->_pad = tmp._pad;

	if (old_format) {
	    T(("reading old-format screen dump"));
	    for (n = 0; n <= nwin->_maxy; n++) {
		if (read_block(nwin->_line[n].text, linesize, filep) < 0) {
		    delwin(nwin);
		    returnWin(0);
		}
	    }
	}
#if NCURSES_EXT_PUTWIN
	else {
	    char *txt = 0;
	    bool success = TRUE;
	    NCURSES_CH_T prior = blank;

	    T(("reading new-format screen dump"));
	    for (n = 0; n <= nwin->_maxy; n++) {
		long row;
		char *next;

		if ((txt = read_txt(filep)) == 0) {
		    T(("...failed to read string for row %d", n + 1));
		    success = FALSE;
		    break;
		}
		row = strtol(txt, &next, 10);
		if (row != (n + 1) || *next != ':') {
		    T(("...failed to read row-number %d", n + 1));
		    success = FALSE;
		    break;
		}

		if (read_row(++next, &prior, nwin->_line[n].text, tmp._maxx
			     + 1) < 0) {
		    T(("...failed to read cells for row %d", n + 1));
		    success = FALSE;
		    break;
		}
		free(txt);
		txt = 0;
	    }

	    if (!success) {
		free(txt);
		delwin(nwin);
		returnWin(0);
	    }
	}
#endif
	touchwin(nwin);
    }
    returnWin(nwin);
}
Пример #26
0
char get_char(void)
{
    unsigned int col = read_column();
    unsigned int row = read_row();
    unsigned int coords = row | col;

    switch (coords)
    {
    case 0x77:
        PORTH = 0;
        return "11111100";
        break;
    case 0x7B:
        PORTH = 1;
        return "01100000";
        break;
    case 0x7D:
        PORTH = 2;
        return "11011010";
        break;
    case 0x7E:
        PORTH = 3;
        return "11110010";
        break;
    case 0xB7:
        PORTH = 4;
        return "01100110";
        break;
    case 0xBB:
        PORTH = 5;
        return "10110110";
        break;
    case 0xBD:
        PORTH = 6;
        return "10111110";
        break;
    case 0xBE:
        PORTH = 7;
        return "11100000";
        break;
    case 0xD7:
        PORTH = 8;
        return "11111110";
        break;
    case 0xDB:
        PORTH = 9;
        return "11110110";
        break;
        /* case 0xDD:
             PORTH = 10;
             return 'A';
             break;
         case 0xDE:
             PORTH = 11;
             return 'B';
             break;
         case 0xE7:
             PORTH = 12;
             return 'C';
             break;
         case 0xEB:
             PORTH = 13;
             return 'D';
             break;
         case 0xED:
             PORTH = 14;
             return 'E';
             break;
         case 0xEE:
             PORTH = 15;
             return 'F';
             break;
         default:
             PORTH = 0;
             return ' ';
        */
    }
}
Пример #27
0
/*************************************************************************
 *
 *N  vpf_display_record
 *
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Purpose:
 *P
 *     This function displays all of the fields of a particular VPF
 *     record, including the descriptions of the fields and their
 *     values.  It accesses the online data dictionary metadata
 *     contained in the specified Value Description Tables.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Parameters:
 *A
 *    row     <input> == (row_type) vpf table row structure.
 *    table   <input> == (vpf_table_type) vpf table.
 *    fp      <input> == (FILE *) pointer to the output file.
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   History:
 *H
 *    Barry Michaels    Sept 1991                     DOS Turbo C
 *E
 *************************************************************************/
void vpf_display_record( row_type row,
			 vpf_table_type table,
			 FILE *fp )
{
   register int i,j;
   char *buf,*num, path[128], *tablename;
   char *attr,*val,*descr, vdtpath[128], fmtdate[40];
   vpf_table_type vdt;
   row_type vdtrow;
   int found;
   ossim_int32 l, lval, count, *lptr;
   short int s,sval,*sptr;
   float f,*fptr;
   date_type date;
   int TABLE_ = 1, ATTR_ = 2, VAL_ = 3, DESCR_ = 4;

   num = (char *)vpfmalloc(20*sizeof(char));

   strcpy( vdtpath, "" );

   /* Display all secondary attributes */
   for (i=0;i<table.nfields;i++) {
      switch (table.header[i].type) {
	 case 'T':
	    buf = (char *)get_table_element(i,row,table,
					    NULL,&count);
	    rightjust(buf);
	    if (strcmp( buf, "" ) != 0) {
	       fputs(table.header[i].name,fp);
	       fputs(" - ",fp);
	       fputs(table.header[i].description,fp);
	       fputs(": ",fp);
	       fputs(buf,fp);


	       strcpy( path, table.path );
	       strcat( path, table.header[i].vdt );
	       if ( (access(path,4)==0) &&
		    (strcmp(table.header[i].vdt,"") != 0) ) {

		  if (strcmp(vdtpath,path) != 0) {
		     if (strcmp(vdtpath,"") != 0) {
			vpf_close_table(&vdt);
		     }
		     vdt = vpf_open_table( path, disk, "rb", NULL );
		  }

		  strcpy( vdtpath, path );
		  for (j=1;j<=vdt.nrows;j++) {
		     vdtrow = read_row( j, vdt );
		     tablename = (char *)get_table_element( TABLE_, vdtrow,
							 vdt, NULL, &count );
		     rightjust(tablename);
		     strupr2(tablename);
		     attr = (char *)get_table_element( ATTR_, vdtrow, vdt,
						       NULL, &count );
		     rightjust(attr);
		     val = (char *)get_table_element( VAL_, vdtrow, vdt,
						      NULL, &count );
		     rightjust(val);

		     found = FALSE;
		     if ( (strstr(table.name,tablename)) &&
			  (ossim_strcasecmp(attr,table.header[i].name)==0) &&
			  (ossim_strcasecmp(val,buf)==0) ) {
			descr = (char *)get_table_element(DESCR_,vdtrow,vdt,
							  NULL, &count);
			rightjust(descr);
			fputs(" (",fp);
			fputs(descr,fp);
			fputs(")",fp);

			free(descr);
			found = TRUE;
		     }
		     free(tablename);
		     free(attr);
		     free(val);
		     free_row( vdtrow, vdt );
		     if (found) break;
		  }
	       }


	       fputc('\n',fp);
	    }
	    free(buf);
	    break;
	 case 'I':
	    if (table.header[i].count==1) {
	       get_table_element(i,row,table,&l,&count);
	       if (l != NULLINT) {
		  fputs(table.header[i].name,fp);
		  fputs(" - ",fp);
		  fputs(table.header[i].description,fp);
		  fputs(": ",fp);
		  ltoa((int)l,num,10);
		  fputs(num,fp);

		  strcpy( path, table.path );
		  strcat( path, table.header[i].vdt );
		  if ( (access(path,4)==0) &&
		     (strcmp(table.header[i].vdt,"") != 0) ) {

		     if (strcmp(vdtpath,path) != 0) {
			if (strcmp(vdtpath,"") != 0) {
			   vpf_close_table(&vdt);
			}
			vdt = vpf_open_table( path, disk, "rb", NULL );
		     }
		     strcpy( vdtpath, path );

		     for (j=1;j<=vdt.nrows;j++) {
			vdtrow = read_row( j, vdt );
			tablename = (char *)get_table_element( TABLE_,
					      vdtrow, vdt, NULL, &count );
			rightjust(tablename);
			strupr2(tablename);
			attr = (char *)get_table_element( ATTR_, vdtrow, vdt,
							  NULL, &count );
			rightjust(attr);
			get_table_element( VAL_, vdtrow, vdt,
					   &lval, &count );

			found = FALSE;
			if ( (strstr(table.name,tablename)) &&
			   (ossim_strcasecmp(attr,table.header[i].name)==0) &&
			   (lval==l) ) {
			   descr = (char *)get_table_element(DESCR_,vdtrow,
							 vdt, NULL, &count);
			   rightjust(descr);
			   fputs(" (",fp);
			   fputs(descr,fp);
			   fputs(")",fp);

			   free(descr);
			   found = TRUE;
			}
			free(tablename);
			free(attr);
			free_row( vdtrow, vdt );
			if (found) break;
		     }
		  }

		  fputc('\n',fp);
	       }
	    } else {
	       get_table_element(i,row,table,&lptr,&count);
	       fputs(table.header[i].name,fp);
	       fputs(" - ",fp);
	       fputs(table.header[i].description,fp);
	       fputs(": (",fp);
	       for (j=0;j<count;j++) {
		  ltoa((int)lptr[j],num,10);
		  fputs(num,fp);
		  if (j<count-1) fputs(", ",fp);
	       }
	       fputs(")\n",fp);
	    }
	    break;
	 case 'S':
	    if (table.header[i].count==1) {
	       get_table_element(i,row,table,&s,&count);
	       if (s != NULLSHORT) {
		  fputs(table.header[i].name,fp);
		  fputs(" - ",fp);
		  fputs(table.header[i].description,fp);
		  fputs(": ",fp);
		  itoa(s,num,10);
		  fputs(num,fp);

		  strcpy( path, table.path );
		  strcat( path, table.header[i].vdt );
		  if ( (access(path,4)==0) &&
		     (strcmp(table.header[i].vdt,"") != 0) ) {

		     if (strcmp(vdtpath,path) != 0) {
			if (strcmp(vdtpath,"") != 0) {
			   vpf_close_table(&vdt);
			}
			vdt = vpf_open_table( path, disk, "rb", NULL );
		     }
		     strcpy( vdtpath, path );

		     for (j=1;j<=vdt.nrows;j++) {
			vdtrow = read_row( j, vdt );
			tablename = (char *)get_table_element( TABLE_,
					      vdtrow, vdt, NULL, &count );
			rightjust(tablename);
			strupr2(tablename);
			attr = (char *)get_table_element( ATTR_, vdtrow, vdt,
							  NULL, &count );
			rightjust(attr);
			get_table_element( VAL_, vdtrow, vdt,
					   &sval, &count );

			found = FALSE;
			if ( (strstr(table.name,tablename)) &&
			   (ossim_strcasecmp(attr,table.header[i].name)==0) &&
			   (sval==s) ) {
			   descr = (char *)get_table_element(DESCR_,vdtrow,
							 vdt, NULL, &count);
			   rightjust(descr);
			   fputs(" (",fp);
			   fputs(descr,fp);
			   fputs(")",fp);

			   free(descr);
			   found = TRUE;
			}
			free(tablename);
			free(attr);
			free_row( vdtrow, vdt );
			if (found) break;
		     }
		  }

		  fputc('\n',fp);
	       }
	    } else {
	       get_table_element(i,row,table,&sptr,&count);
	       fputs(table.header[i].name,fp);
	       fputs(" - ",fp);
	       fputs(table.header[i].description,fp);
	       fputs(": (",fp);
	       for (j=0;j<count;j++) {
		  itoa(sptr[j],num,10);
		  fputs(num,fp);
		  if (j<count-1) fputs(", ",fp);
	       }
	       fputs(")\n",fp);
	    }
	    break;
	 case 'F':
	    if (table.header[i].count==1) {
	       get_table_element(i,row,table,&f,&count);
	       if (!is_vpf_null_float(f)) {
		  fputs(table.header[i].name,fp);
		  fputs(" - ",fp);
		  fputs(table.header[i].description,fp);
		  fputs(": ",fp);
#if !defined(__APPLE__) && !defined(__FreeBSD__)
		  gcvt(f,6,num);
#endif
		  fputs(num,fp);
		  fputc('\n',fp);
	       }
	    } else {
	       get_table_element(i,row,table,&fptr,&count);
	       fputs(table.header[i].name,fp);
	       fputs(" - ",fp);
	       fputs(table.header[i].description,fp);
	       fputs(": (",fp);
	       for (j=0;j<count;j++) {
		  if (is_vpf_null_float(fptr[j])) {
		     fputs("(null)",fp);
		  } else {
#if !defined(__APPLE__) && !defined(__FreeBSD__)
		     gcvt(fptr[j],6,num);
#endif
		     fputs(num,fp);
		  }
		  if (j<count-1) fputs(", ",fp);
	       }
	       fputs(")\n",fp);
	    }
	    break;
	 case 'D':
	    if (table.header[i].count==1) {
	       get_table_element(i,row,table,date,&count);
	       fputs(table.header[i].name,fp);
	       fputs(" - ",fp);
	       fputs(table.header[i].description,fp);
	       fputs(": ",fp);
	       format_date(date,fmtdate);
	       fputs(fmtdate,fp);
	       fputc('\n',fp);
	    }
	    break;
      }
   }

   if (strcmp(vdtpath,"") != 0)
      vpf_close_table( &vdt );

   free(num);
}
Пример #28
0
float execute_avg(char * avg_query, char * data_filename, FILE * output) {
    
    char * command;
    command = (char *)calloc(11, sizeof(char));
    char * header;
    header = (char *)calloc(17, sizeof(char));
    char * header_word_2;
    header_word_2 = (char *)calloc(4, sizeof(char));
    char * header_word_3;
    header_word_3 = (char *)calloc(2, sizeof(char));
    char * start_date;
    start_date = (char *)calloc(17, sizeof(char));
    char * end_date;
    end_date = (char *)calloc(19, sizeof(char));
    
    // count whitespace in query to determine if header is multiple words
    int query_length = (int)strlen(avg_query);
    int num_spaces = 0;
    for (int i=0; i<query_length; i++) {
        if (avg_query[i] == ' ') {
            num_spaces++;
        }
    }
    if (num_spaces == 5) {
        sscanf(avg_query, "%s %s %s %s %s %s", command, header, header_word_2, header_word_3, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        header[i+k+1] = ' ';
                        header[i+k+2] = header_word_3 [0];
                        header[i+k+3] = '\0';
                        break;
                    }
                }
                break;
            }
        }
    } else if (num_spaces == 4) {
        sscanf(avg_query, "%s %s %s %s %s", command, header, header_word_2, start_date, end_date);
        for (int i=0; i<40; i++) {
            if (header[i] == '\0') {
                header[i] = ' ';
                for (int k=0; k<40; k++) {
                    if (header_word_2[k] != '\0') {
                        header[i+k+1] = header_word_2[k];
                    } else {
                        break;
                    }
                }
                break;
            }
        }
    } else {
        sscanf(avg_query, "%s %s %s %s", command, header, start_date, end_date);
    }
    
    Type_t data_type;
    data_type = column_type(header);
    
    int num_data_columns = header_columns(data_filename);
    char * column_headers[num_data_columns];
    read_header(data_filename, column_headers);
    
    int data_column_index = -1;
    int date_index = -1;
    int time_index = -1;
    
    char  date[] = "Date";
    char time[] = "HrMn";
    
    //date is LONG time is INT
    
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], header) == 0) {
            data_column_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], date) == 0) {
            date_index = i;
        }
    }
    for (int i = 0; i<num_data_columns; i++) {
        if (strcmp(column_headers[i], time) == 0) {
            time_index = i;
        }
    }
    
    if (data_column_index == -1) {
        printf("ERROR header %s not found in data file\n Query: %s\n", header, avg_query);
        return 0;
    }
    if (time_index == -1) {
        printf("ERROR header HrMn not found in data file\n Query: %s\n", avg_query);
        return 0;
    }
    if (date_index == -1) {
        printf("ERROR header Date not found in data file\n Query: %s\n", avg_query);
        return 0;
    }
    
    FILE * data_file = NULL;
    data_file = fopen(data_filename, "r");
    if (data_file == NULL) {
        printf("ERROR invalid data file: %s/n", data_filename);
    }
    
    void * row_data[num_data_columns];
    
    int ivalue = 0;
    long lvalue = 0;
    float fvalue = 0; float avg = 0;
    int data_count = 0;
    int row_count = 0;
    
    long * data_date;
    //    data_date = calloc(9, sizeof(char));
    
    int * data_time;
    //    data_time = calloc(5, sizeof(char));
    
    char * row;
    row = (char *)calloc(200,sizeof(char));
    int status = 0;
    // read file
    fgets(row, 200, data_file);
    while(fscanf(data_file, "*") != EOF) {
        status = read_row(data_file, column_headers, row_data);
        data_date = ((long*)row_data[date_index]);
        data_time = ((int*)row_data[time_index]);
        
        
        int in_time_range = is_in_range(start_date, end_date, data_date, data_time);
        if (in_time_range == 1) {
            data_count++;
            if (data_type==FLOAT) {
                fvalue = fvalue + *((float*)row_data[data_column_index]);
            }
            if (data_type==INT) {
                ivalue = ivalue + *((int*)row_data[data_column_index]);
            }
            if (data_type==LONG) {
                lvalue = lvalue + *((long*)row_data[data_column_index]);
            }
        }
        row_count++;
    }
    if (data_type==FLOAT) {
        if (output == NULL) {
            avg = fvalue/data_count;
            printf("Average = %f\n",avg);
        } else {
            fprintf(output, "Average = %f\n",avg);
        }
        
    }else if (data_type==INT) {
        if(output == NULL) {
            avg = (float) ivalue/data_count;
            printf("Average = %d\n",(int)avg);
        }else {
            fprintf(output, "Average = %d\n",(int)avg);
        }
    } else if (data_type==LONG) {
        if(output == NULL) {
            avg = (float) lvalue/data_count;
            printf("Average = %ld\n",(long)avg);
        }else {
            fprintf(output, "Average = %ld\n",(long)avg);
        }
    }
    return avg;
}
Пример #29
0
static void *
ops(void *arg)
{
	TINFO *tinfo;
	WT_CONNECTION *conn;
	WT_CURSOR *cursor, *cursor_insert;
	WT_SESSION *session;
	WT_ITEM key, value;
	uint64_t cnt, keyno, ckpt_op, session_op, thread_ops;
	uint32_t op;
	uint8_t *keybuf, *valbuf;
	u_int np;
	int dir, insert, intxn, notfound, ret;
	char *ckpt_config, config[64];

	tinfo = arg;

	conn = g.wts_conn;
	keybuf = valbuf = NULL;

	/* Set up the default key and value buffers. */
	key_gen_setup(&keybuf);
	val_gen_setup(&valbuf);

	/*
	 * Each thread does its share of the total operations, and make sure
	 * that it's not 0 (testing runs: threads might be larger than ops).
	 */
	thread_ops = 100 + g.c_ops / g.c_threads;

	/*
	 * Select the first operation where we'll create sessions and cursors,
	 * perform checkpoint operations.
	 */
	ckpt_op = MMRAND(1, thread_ops);
	session_op = 0;

	session = NULL;
	cursor = cursor_insert = NULL;
	for (intxn = 0, cnt = 0; cnt < thread_ops; ++cnt) {
		if (SINGLETHREADED && cnt % 100 == 0)
			track("ops", 0ULL, tinfo);

		/*
		 * We can't checkpoint or swap sessions/cursors while in a
		 * transaction, resolve any running transaction.  Otherwise,
		 * reset the cursor: we may block waiting for a lock and there
		 * is no reason to keep pages pinned.
		 */
		if (cnt == ckpt_op || cnt == session_op) {
			if (intxn) {
				if ((ret = session->commit_transaction(
				    session, NULL)) != 0)
					die(ret, "session.commit_transaction");
				++tinfo->commit;
				intxn = 0;
			}
			else if (cursor != NULL &&
			    (ret = cursor->reset(cursor)) != 0)
				die(ret, "cursor.reset");
		}

		/* Open up a new session and cursors. */
		if (cnt == session_op || session == NULL || cursor == NULL) {
			if (session != NULL &&
			    (ret = session->close(session, NULL)) != 0)
				die(ret, "session.close");

			if ((ret = conn->open_session(
			    conn, NULL, NULL, &session)) != 0)
				die(ret, "connection.open_session");

			/*
			 * Open two cursors: one configured for overwriting and
			 * one configured for append if we're dealing with a
			 * column-store.
			 *
			 * The reason is when testing with existing records, we
			 * don't track if a record was deleted or not, which
			 * means we must use cursor->insert with overwriting
			 * configured.  But, in column-store files where we're
			 * testing with new, appended records, we don't want to
			 * have to specify the record number, which requires an
			 * append configuration.
			 */
			if ((ret = session->open_cursor(session,
			    g.uri, NULL, "overwrite", &cursor)) != 0)
				die(ret, "session.open_cursor");
			if ((g.type == FIX || g.type == VAR) &&
			    (ret = session->open_cursor(session,
			    g.uri, NULL, "append", &cursor_insert)) != 0)
				die(ret, "session.open_cursor");

			/* Pick the next session/cursor close/open. */
			session_op += SINGLETHREADED ?
			    MMRAND(1, thread_ops) : 100 * MMRAND(1, 50);
		}

		/* Checkpoint the database. */
		if (cnt == ckpt_op) {
			/*
			 * LSM and data-sources don't support named checkpoints,
			 * else 25% of the time we name the checkpoint.
			 */
			if (DATASOURCE("lsm") || DATASOURCE("kvsbdb") ||
			    DATASOURCE("memrata") || MMRAND(1, 4) == 1)
				ckpt_config = NULL;
			else {
				(void)snprintf(config, sizeof(config),
				    "name=thread-%d", tinfo->id);
				ckpt_config = config;
			}

			/* Named checkpoints lock out hot backups */
			if (ckpt_config != NULL &&
			    (ret = pthread_rwlock_wrlock(&g.backup_lock)) != 0)
				die(ret,
				    "pthread_rwlock_wrlock: hot-backup lock");

			if ((ret =
			    session->checkpoint(session, ckpt_config)) != 0)
				die(ret, "session.checkpoint%s%s",
				    ckpt_config == NULL ? "" : ": ",
				    ckpt_config == NULL ? "" : ckpt_config);

			if (ckpt_config != NULL &&
			    (ret = pthread_rwlock_unlock(&g.backup_lock)) != 0)
				die(ret,
				    "pthread_rwlock_wrlock: hot-backup lock");

			/*
			 * Pick the next checkpoint operation, try for roughly
			 * five checkpoint operations per thread run.
			 */
			ckpt_op += MMRAND(1, thread_ops) / 5;
		}

		/*
		 * If we're not single-threaded and we're not in a transaction,
		 * start a transaction 80% of the time.
		 */
		if (!SINGLETHREADED && !intxn && MMRAND(1, 10) >= 8) {
			if ((ret =
			    session->begin_transaction(session, NULL)) != 0)
				die(ret, "session.begin_transaction");
			intxn = 1;
		}

		insert = notfound = 0;

		keyno = MMRAND(1, g.rows);
		key.data = keybuf;
		value.data = valbuf;

		/*
		 * Perform some number of operations: the percentage of deletes,
		 * inserts and writes are specified, reads are the rest.  The
		 * percentages don't have to add up to 100, a high percentage
		 * of deletes will mean fewer inserts and writes.  Modifications
		 * are always followed by a read to confirm it worked.
		 */
		op = (uint32_t)(rng() % 100);
		if (op < g.c_delete_pct) {
			++tinfo->remove;
			switch (g.type) {
			case ROW:
				/*
				 * If deleting a non-existent record, the cursor
				 * won't be positioned, and so can't do a next.
				 */
				if (row_remove(cursor, &key, keyno, &notfound))
					goto deadlock;
				break;
			case FIX:
			case VAR:
				if (col_remove(cursor, &key, keyno, &notfound))
					goto deadlock;
				break;
			}
		} else if (op < g.c_delete_pct + g.c_insert_pct) {
			++tinfo->insert;
			switch (g.type) {
			case ROW:
				if (row_insert(cursor, &key, &value, keyno))
					goto deadlock;
				insert = 1;
				break;
			case FIX:
			case VAR:
				/*
				 * We can only append so many new records, if
				 * we've reached that limit, update a record
				 * instead of doing an insert.
				 */
				if (g.append_cnt >= g.append_max)
					goto skip_insert;

				/*
				 * Reset the standard cursor so it doesn't keep
				 * pages pinned.
				 */
				if ((ret = cursor->reset(cursor)) != 0)
					die(ret, "cursor.reset");

				/* Insert, then reset the insert cursor. */
				if (col_insert(
				    cursor_insert, &key, &value, &keyno))
					goto deadlock;
				if ((ret =
				    cursor_insert->reset(cursor_insert)) != 0)
					die(ret, "cursor.reset");

				insert = 1;
				break;
			}
		} else if (
		    op < g.c_delete_pct + g.c_insert_pct + g.c_write_pct) {
			++tinfo->update;
			switch (g.type) {
			case ROW:
				if (row_update(cursor, &key, &value, keyno))
					goto deadlock;
				break;
			case FIX:
			case VAR:
skip_insert:			if (col_update(cursor, &key, &value, keyno))
					goto deadlock;
				break;
			}
		} else {
			++tinfo->search;
			if (read_row(cursor, &key, keyno))
				goto deadlock;
			continue;
		}

		/*
		 * The cursor is positioned if we did any operation other than
		 * insert, do a small number of next/prev cursor operations in
		 * a random direction.
		 */
		if (!insert) {
			dir = (int)MMRAND(0, 1);
			for (np = 0; np < MMRAND(1, 8); ++np) {
				if (notfound)
					break;
				if (nextprev(cursor, dir, &notfound))
					goto deadlock;
			}
		}

		/* Read the value we modified to confirm the operation. */
		++tinfo->search;
		if (read_row(cursor, &key, keyno))
			goto deadlock;

		/*
		 * If we're in the transaction, commit 40% of the time and
		 * rollback 10% of the time.
		 */
		if (intxn)
			switch (MMRAND(1, 10)) {
			case 1: case 2: case 3: case 4:		/* 40% */
				if ((ret = session->commit_transaction(
				    session, NULL)) != 0)
					die(ret, "session.commit_transaction");
				++tinfo->commit;
				intxn = 0;
				break;
			case 5:					/* 10% */
				if (0) {
deadlock:				++tinfo->deadlock;
				}
				if ((ret = session->rollback_transaction(
				    session, NULL)) != 0)
					die(ret, "session.commit_transaction");
				++tinfo->rollback;
				intxn = 0;
				break;
			default:
				break;
			}
	}

	if (session != NULL && (ret = session->close(session, NULL)) != 0)
		die(ret, "session.close");

	free(keybuf);
	free(valbuf);

	tinfo->state = TINFO_COMPLETE;
	return (NULL);
}