Пример #1
0
void 
Squeezer_file_header_t::write_to_file(FILE * out) const
{
    write_uint8(out, file_type_mark[0]);
    write_uint8(out, file_type_mark[1]);
    write_uint8(out, file_type_mark[2]);
    write_uint8(out, file_type_mark[3]);

    write_double(out, floating_point_check);

    write_uint16(out, date_year);
    write_uint8(out, date_month);
    write_uint8(out, date_day);

    write_uint8(out, time_hour);
    write_uint8(out, time_minute);
    write_uint8(out, time_second);

    write_uint8(out, radiometer.horn);
    write_uint8(out, radiometer.arm);
    write_uint16(out, od);
    write_double(out, first_obt);
    write_double(out, last_obt);
    write_double(out, first_scet_in_ms);
    write_double(out, last_scet_in_ms);
    write_uint32(out, number_of_chunks);
}
Пример #2
0
static void write_gmt_header(const struct GRD_HEADER *header, int swap_flag, FILE *fp)
{
    /* Write Values 1 at a time if byteswapping */
    write_int(fp, swap_flag, header->nx);
    write_int(fp, swap_flag, header->ny);
    write_int(fp, swap_flag, header->node_offset);

    write_double(fp, swap_flag, header->x_min);
    write_double(fp, swap_flag, header->x_max);
    write_double(fp, swap_flag, header->y_min);
    write_double(fp, swap_flag, header->y_max);
    write_double(fp, swap_flag, header->z_min);
    write_double(fp, swap_flag, header->z_max);
    write_double(fp, swap_flag, header->x_inc);
    write_double(fp, swap_flag, header->y_inc);
    write_double(fp, swap_flag, header->z_scale_factor);
    write_double(fp, swap_flag, header->z_add_offset);

    fwrite(header->x_units, sizeof(char[GRD_UNIT_LEN]),    1, fp);
    fwrite(header->y_units, sizeof(char[GRD_UNIT_LEN]),    1, fp);
    fwrite(header->z_units, sizeof(char[GRD_UNIT_LEN]),    1, fp);
    fwrite(header->title,   sizeof(char[GRD_TITLE_LEN]),   1, fp);
    fwrite(header->command, sizeof(char[GRD_COMMAND_LEN]), 1, fp);
    fwrite(header->remark,  sizeof(char[GRD_REMARK_LEN]),  1, fp);
}
Пример #3
0
ofstream* CovOptimData::write(const char* filename, const CovOptimData& cov, std::stack<unsigned int>& format_id, std::stack<unsigned int>& format_version) {

	format_id.push(subformat_number);
	format_version.push(FORMAT_VERSION);

	ofstream* f = CovList::write(filename, cov, format_id, format_version);

	write_vars   (*f, cov.var_names());
	write_pos_int(*f, cov.optimizer_status());
	write_pos_int(*f, (uint32_t) cov.is_extended_space());
	write_double (*f, cov.uplo());
	write_double (*f, cov.uplo_of_epsboxes());
	write_double (*f, cov.loup());

	if (!cov.loup_point().is_empty()) {
		unsigned int nb_var   = cov.is_extended_space() ? cov.n-1 : cov.n;
		// TODO: we assume here that the goal var is n-1
		if (cov[0].subvector(0,nb_var-1)!=cov.loup_point()) {
			ibex_error("[CovOptimData] the first box in the list must be the 'loup-point'.");
		}
		write_pos_int(*f, (uint32_t) 1);
	} else {
		write_pos_int(*f, (uint32_t) 0);
	}

	write_double(*f, cov.time());
	write_pos_int   (*f, cov.nb_cells());

	return f;
}
Пример #4
0
void img_dmap_write(FILE *f, img_dmap_t *dmap) {
    int count;
    short int has_uppers;

    /* Write the identifier */
    write_word((u_int32_t *)"DMAP", f);

    /* Write the width and height */
    write_short(&dmap->w, f);
    write_short(&dmap->h, f);

    if (dmap->uppers == NULL)
	has_uppers = 0;
    else
	has_uppers = 1;
    
    write_short(&has_uppers, f);

    /* Write the distances */
    for (count = 0; count < dmap->w * dmap->h; count++)
	write_double(&(dmap->dists[count]), f);

    /* Write each vector */
    for (count = 0; count < dmap->w * dmap->h; count++) {
	write_double(&(Vx(dmap->nns[count])), f);
	write_double(&(Vy(dmap->nns[count])), f);
    }

    if (dmap->uppers != NULL) {
	for (count = 0; count < dmap->w * dmap->h; count++) {
	    write_short(&Vx(dmap->uppers[count]), f);
	    write_short(&Vy(dmap->uppers[count]), f);
	}
    }
}
Пример #5
0
void
Error_t::write_to_file(FILE * out) const
{
    write_double(out, min_abs_error);
    write_double(out, max_abs_error);
    write_double(out, mean_abs_error);
    write_double(out, mean_error);
}
Пример #6
0
static int erl_json_ei_number(void* ctx, const char * val, unsigned int len) {
  State* pState = (State*) ctx;

  flog(stderr, "number", 0, val, len);

  list_header_for_value(pState);

  switch(numbers_as(pState)) {
    case EEP0018_PARSE_NUMBERS_AS_NUMBER:
    {
      if(memchr(val, '.', len) || memchr(val, 'e', len) || memchr(val, 'E', len))
        write_double(pState, strtod(val, 0));
      else
        write_long(pState, strtol(val, 0, 10));
      break;
    }
    case EEP0018_PARSE_NUMBERS_AS_FLOAT:
    {
      write_double(pState, strtod(val, 0));
      break;
    }
    case EEP0018_PARSE_NUMBERS_AS_TUPLE:
    {
      /* 
        While "1e1" is a valid JSON number, it is not a valid parameter to list_to_float/1 
        We fix that by inserting ".0" before the exponent e. 
      */
      const char* exp = memchr(val, 'e', len);
      if(exp && exp > val) {
        const char* dot = memchr(val, '.', exp - val);
        if(!dot) {
          char* tmp = alloca(len + 5);
          memcpy(tmp, val, exp - val);
          memcpy(tmp + (exp - val), ".0", 2);
          memcpy(tmp + (exp - val) + 2, exp, len - (exp - val));
          len += 2;
          val = tmp;
          tmp[len] = 0;
        }
      }

      write_tuple_header(pState, 3);
      write_atom(pState, "number", 6);
      write_string(pState, val, len);
      write_atom(pState, "a", 1);       // a dummy
      break;
    }
  }

  
  return 1;
}
Пример #7
0
void Manifold::write_output_box(ofstream& f, const SolverOutputBox& sol) const {
	const IntervalVector& box=(sol);
	for (int i=0; i<sol.existence().size(); i++) {
		write_double(f,box[i].lb());
		write_double(f,box[i].ub());
	}
	write_int(f,sol.status);
	if (sol.varset!=NULL) {
		for (int i=0; i<sol.varset->nb_param; i++) {
			write_int(f,(sol.varset->param(i)) + 1);
		}
	}
}
Пример #8
0
void Manifold::write(const char* filename) const {
	ofstream f;

	f.open(filename, ios::out | ios::binary);

	if (f.fail())
		ibex_error("[manifold]: cannot create output file.\n");

	write_signature(f);
	write_int(f,n);
	write_int(f,m);
	write_int(f,nb_ineq);
	write_int(f,status);
	write_int(f,inner.size());
	write_int(f,boundary.size());
	write_int(f,unknown.size());
	write_int(f,pending.size());
	write_double(f,time);
	write_int(f,nb_cells);

	for (vector<SolverOutputBox>::const_iterator it=inner.begin(); it!=inner.end(); it++)
		write_output_box(f,*it);

	for (vector<SolverOutputBox>::const_iterator it=boundary.begin(); it!=boundary.end(); it++)
		write_output_box(f,*it);

	for (vector<SolverOutputBox>::const_iterator it=unknown.begin(); it!=unknown.end(); it++)
		write_output_box(f,*it);

	for (vector<SolverOutputBox>::const_iterator it=pending.begin(); it!=pending.end(); it++)
		write_output_box(f,*it);

	f.close();
}
Пример #9
0
int main (void)
{
	printf ("Hello World\n");
	OpenIniFile ("Test.Ini");
#ifdef INIFILE_TEST_READ_AND_WRITE
	write_string  ("Test", "Name", "Value");
	write_string  ("Test", "Name", "OverWrittenValue");
	write_string  ("Test", "Port", "COM1");
	write_string  ("Test", "User", "James Brown jr.");
	write_string  ("Configuration", "eDriver", "MBM2.VXD");
	write_string  ("Configuration", "Wrap", "LPT.VXD");
	write_int 	 ("IO-Port", "Com", 2);
	write_bool 	 ("IO-Port", "IsValid", 0);
	write_double  ("TheMoney", "TheMoney", 67892.00241);
	write_int     ("Test"    , "ToDelete", 1234);
	WriteIniFile ("Test.Ini");
	printf ("Key ToDelete created. Check ini file. Any key to continue");
	while (!kbhit());
	OpenIniFile  ("Test.ini");
	delete_key    ("Test"	  , "ToDelete");
	WriteIniFile ("Test.ini");
#endif
	printf ("[Test] Name = %s\n", read_string ("Test", "Name", "NotFound"));
	printf ("[Test] Port = %s\n", read_string ("Test", "Port", "NotFound"));
	printf ("[Test] User = %s\n", read_string ("Test", "User", "NotFound"));
	printf ("[Configuration] eDriver = %s\n", read_string ("Configuration", "eDriver", "NotFound"));
	printf ("[Configuration] Wrap = %s\n", read_string ("Configuration", "Wrap", "NotFound"));
	printf ("[IO-Port] Com = %d\n", read_int ("IO-Port", "Com", 0));
	printf ("[IO-Port] IsValid = %d\n", read_bool ("IO-Port", "IsValid", 0));
	printf ("[TheMoney] TheMoney = %1.10lf\n", read_double ("TheMoney", "TheMoney", 111));
	CloseIniFile ();
	return 0;
}
Пример #10
0
int iio_device_debug_attr_write_double(const struct iio_device *dev,
		const char *attr, double val)
{
	ssize_t ret;
	char buf[1024];

	ret = (ssize_t) write_double(buf, sizeof(buf), val);
	if (!ret)
		ret = iio_device_debug_attr_write(dev, attr, buf);
	return ret < 0 ? ret : 0;
}
int key_value_write_lines(FILE *f, struct key_value_specification *kvs, void *base_address[])
{
	struct key_value_specification *k;
	int rc;
	int errs = 0;

	for (k = kvs; k->key; k++) {
		switch (k->type) {
		case KVS_STRING:
			rc = write_string(f, k, base_address);
			break;
		case KVS_INT64:
			rc = write_int64(f, k, base_address);
			break;
		case KVS_INT32:
			rc = write_int32(f, k, base_address);
			break;
		case KVS_INT16:
			rc = write_int16(f, k, base_address);
			break;
		case KVS_INT8:
			rc = write_int8(f, k, base_address);
			break;
		case KVS_UINT64:
			rc = write_uint64(f, k, base_address);
			break;
		case KVS_UINT32:
			rc = write_uint32(f, k, base_address);
			break;
		case KVS_UINT16:
			rc = write_uint16(f, k, base_address);
			break;
		case KVS_UINT8:
			rc = write_uint8(f, k, base_address);
			break;
		case KVS_DOUBLE:
			rc = write_double(f, k, base_address);
			break;
		case KVS_FLOAT:
			rc = write_float(f, k, base_address);
			break;
		default:
			fprintf(stderr, "%s:%d: unknown key type '%c' for key '%s'\n",
				__func__, __LINE__, k->type, k->key);
			rc = -1;
			break;
		}
		if (rc)
			errs++;
	}
	return errs;
}
Пример #12
0
int
bson_encoder_append_double(bson_encoder_t encoder, const char *name, double value)
{
	CODER_CHECK(encoder);

	if (write_int8(encoder, BSON_DOUBLE) ||
	    write_name(encoder, name) ||
	    write_double(encoder, value)) {
		CODER_KILL(encoder, "write error on BSON_DOUBLE");
	}


	return 0;
}
Пример #13
0
/**
 * im_write_dmask_name:
 * @in: mask to write
 * @filename: filename to write to
 *
 * Write a dmask to a file. See im_read_dmask() for a description of the mask
 * file format.
 *
 * See also: im_write_dmask().
 *
 * Returns: 0 on success, or -1 on error.
 */
int 
im_write_dmask_name( DOUBLEMASK *in, const char *filename )
{
	FILE *fp;
	int x, y, i;

	if( im_check_dmask( "im_write_dmask_name", in ) ||
		!(fp = im__file_open_write( filename, TRUE )) )
		return( -1 );

	if( write_line( fp, "%d %d", in->xsize, in->ysize ) ) {
		fclose( fp ); 
		return( -1 );
	}
	if( in->scale != 1.0 || in->offset != 0.0 ) {
		write_line( fp, " " );
		write_double( fp, in->scale );
		write_line( fp, " " );
		write_double( fp, in->offset );
	}
	write_line( fp, "\n" );

	for( i = 0, y = 0; y < in->ysize; y++ ) {
		for( x = 0; x < in->xsize; x++, i++ ) {
			write_double( fp, in->coeff[i] );
			write_line( fp, " " );
		}

		if( write_line( fp, "\n" ) ) {
			fclose( fp ); 
			return( -1 );
		}
	}
	fclose( fp );

	return( 0 );
}
Пример #14
0
/*******************************************************************************
* Function Name  : SdTest
* Description    : 测试函数
* Input          : 
* Return         :
*******************************************************************************/
void SdTest(void)
{		int i=0;
		double temp=3.14159;
//		Pointfp64 point;
//		point.x=-0.567;
//		point.y=-1000.3432;
		f_mount_on();
		file_open("hello6.txt");
    	for (i=0;i<20;i++)
        {
            write_double(temp);
        }
		file_close();
		f_mount_off();
    
     while(1)
	{
		
		LCD_Clear();
		LCD_SetXY(0,0);
		LCD_WriteString("========SD========");
        
		
        switch(filStatus)
        {
            case FR_OK:
                LCD_SetXY(0,1);
                LCD_WriteString("FR_OK");
                break;
            default :
                LCD_SetXY(0,1);
                LCD_WriteString("ERROR");
                break;
                
        }
		refresh();	
        
		if(KeyReady==1)
		  {
			KeyReady=0;
			switch(KeyValue)
			{
				case keyback:
					return;
			}
		  }
		delay(LCD_DELAY);
	}
}
Пример #15
0
int double_correlation_write_data_to_file(const double_correlation* self, const char * filename, bool binary){
  FILE* fp=0;
  fp=fopen(filename, "w");
  if (!fp) {
    return 1;
  }
  for (unsigned int i=0; i<self->hierarchy_depth; i++) {
    for (unsigned int j=0; j<self->tau_lin+1; j++) {
      write_double(fp,self->A[i][j],self->dim_A,binary);
    }
  }
  if (!self->autocorrelation){
    for (unsigned int i=0; i<self->hierarchy_depth; i++) {
      for (unsigned int j=0; j<self->tau_lin+1; j++) {
	write_double(fp,self->B[i][j],self->dim_B,binary);
      }
    } 
  }
  for (unsigned int i=0; i<self->n_result; i++) {
    write_double(fp,self->result[i],self->dim_corr,binary);
  }
  write_uint(fp,self->n_sweeps,self->n_result       ,binary);
  write_uint(fp,self->n_vals  ,self->hierarchy_depth,binary);
  write_uint(fp,self->newest  ,self->hierarchy_depth,binary);
  
  write_double(fp,self->A_accumulated_average ,self->dim_A,binary);
  write_double(fp,self->A_accumulated_variance,self->dim_A,binary);
  if (!self->autocorrelation){
    write_double(fp,self->B_accumulated_average ,self->dim_B,binary);
    write_double(fp,self->B_accumulated_variance,self->dim_B,binary);
  }
  write_uint(fp,&(self->n_data),1,binary);
  write_uint(fp,&(self->t     ),1,binary);
  write_double(fp,&(self->last_update),1,binary);
  fclose(fp);
  return 0;
}
Пример #16
0
int db_clean()
{
  int user_fd;
  struct flock user_lock;
  int user_fd_bak;
  int poi_fd;
  int poi_fd_bak;
  struct flock poi_lock;
  char buff[sizeof(char)*10240]; // 10Kb buffer
  USER tmp_user;
  POI tmp_poi;
  int saved_users[MAX_USER_LIMIT];
  int good_user_count=0;
  int poiCount=0;
  unsigned int now;
  int i=0;
  int good=0;
  long poi_file_len=0;
  long user_file_len=0;
  size_t byte_read=0;
  size_t byte_written=0;


  now=time(NULL);
  fprintf(stderr,"\n ***** Cleaning routines started at %u. ***** \n",now);

  // Open both user and poi files
  // Acquire locks on both of them
  user_fd = open(USER_DB_PATH,O_RDWR|O_CREAT,S_IRWXU);
  if (user_fd<0)
    {
      // Error occurred
      perror("Error opening USER DB file.");
      return DB_OPEN_ERROR;
    }

  poi_fd = open(POI_DB_PATH,O_RDWR|O_CREAT,S_IRWXU);
  if (poi_fd<0)
    {
      // Error occurred
      perror("Error opening POI DB file.");
      return DB_OPEN_ERROR;
    }

  // Copy both the file
  poi_fd_bak = open(POI_DB_PATH_BAK,O_RDWR|O_CREAT,S_IRWXU);
  if (poi_fd_bak<0)
    {
      // Error occurred
      perror("Error opening POI BAK DB file.");
      return DB_OPEN_ERROR;
    }

  user_fd_bak = open(USER_DB_PATH_BAK,O_RDWR|O_CREAT,S_IRWXU);
  if (user_fd_bak<0)
    {
      // Error occurred
      perror("Error opening USER BAK DB file.");
      return DB_OPEN_ERROR;
    }

  memset (&user_lock, 0, sizeof(user_lock));
  user_lock.l_type = F_WRLCK;
  memset (&poi_lock, 0, sizeof(poi_lock));
  poi_lock.l_type = F_WRLCK;

  // Get the lock on both of them
  fcntl (user_fd, F_SETLKW, &user_lock);
  fcntl (poi_fd, F_SETLKW, &poi_lock);

  /*----- COPING USER DB FILE-----*/
  //fprintf(stderr,"Copying %s -> %s\n", USER_DB_PATH,USER_DB_PATH_BAK);
  while ((byte_read=read(user_fd,buff,sizeof(buff)))>0)
    {
      byte_written=0;
      //fprintf(stderr,"->Read buffer of %u bytes\n", byte_read);
      while(byte_written<byte_read)
        {
          i=write(user_fd_bak,buff+byte_written,byte_read-byte_written);
          if (i<1)
            {
              perror("I was unable to copty USER.DAT file");
              user_lock.l_type = F_UNLCK;
              poi_lock.l_type = F_UNLCK;
              fcntl (user_fd, F_SETLKW, &user_lock);
              fcntl (poi_fd, F_SETLKW, &poi_lock);
              close(user_fd_bak);
              close(poi_fd_bak);
              close(user_fd);
              close(poi_fd);
              unlink(USER_DB_PATH_BAK);
              unlink(POI_DB_PATH_BAK);
              return DB_ERROR;

            }
          byte_written+=i;
        }
    }

  /*----- COPING POI DB FILE-----*/
  //fprintf(stderr,"Copying %s -> %s\n", POI_DB_PATH,POI_DB_PATH_BAK);
  while ((byte_read=read(poi_fd,buff,sizeof(buff)))>0)
    {
      byte_written=0;
      //fprintf(stderr,"->Read buffer of %u bytes\n", byte_read);
      while(byte_written<byte_read)
        {
          i+=write(poi_fd_bak,buff+byte_written,byte_read-byte_written);
          if (i<1)
            {
              perror("I was unable to copty POI.DAT file");
              user_lock.l_type = F_UNLCK;
              poi_lock.l_type = F_UNLCK;
              fcntl (user_fd, F_SETLKW, &user_lock);
              fcntl (poi_fd, F_SETLKW, &poi_lock);
              close(user_fd_bak);
              close(poi_fd_bak);
              close(user_fd);
              close(poi_fd);
              unlink(USER_DB_PATH_BAK);
              unlink(POI_DB_PATH_BAK);
              return DB_ERROR;
            }
          byte_written+=i;
          //fprintf(stderr,"\n-- Written %u bytes\n", byte_written);
        }
    }
  //fprintf(stderr,"Copied %u bytes\n", byte_written);

  // Reset FD pointer
  lseek(user_fd,0,SEEK_SET);
  lseek(user_fd_bak,0,SEEK_SET);
  lseek(poi_fd,0,SEEK_SET);
  lseek(poi_fd_bak,0,SEEK_SET);

  // >>>>>>>>>>>>>>>>>>>> Users cleaning <<<<<<<<<<<<<<<<<<<<
  good_user_count=0;
  // For each line you read in users bak file, if the timestamp is older than the limit, do not copy the record in the new file. Remember the good users.
  do {
    // Read timestamp
    if (!read_uinteger(&tmp_user.ts,user_fd_bak))
      {
        // This has failed, because there are no more lines. So break
        break;
      }

    // Read the User Id
    if (!read_integer(&tmp_user.user_id,user_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The user.dat file contains an invalid row: I was unable to read user id");
        return DB_ERROR;
      }

    // Read the username length
    if (!read_integer(&tmp_user.uname_len,user_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The user.dat file contains an invalid row: I was unable to read username len");
        return DB_ERROR;
      }

    // Read the password length
    if (!read_integer(&tmp_user.pass_len,user_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The user.dat file contains an invalid row: I was unable to read password len");
        return DB_ERROR;
      }

    // Read the username
    if (!read_string(tmp_user.username,tmp_user.uname_len,user_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The user.dat file contains an invalid row: I was unable to read the first string (username).");
        return DB_ERROR;
      }

    // Read the password
    if (!read_string(tmp_user.pass,tmp_user.pass_len,user_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The user.dat file contains an invalid row: I was unable to read the first string (password).");
        return DB_ERROR;
      }

    // Check if timestamp is older than the limit
    // If yes, write it to the user_fd file directly
    if((now-tmp_user.ts)<DATA_VALIDITY_INTERVAL)
      {
        //fprintf(stderr,"\n--- Found 1 good record to preserve:\nTIMESTAMP:%u\nUSERID: %d\nLEN USER: %d\nLEN PASS: %d\nUsername: %s \n Password: %s",tmp_user.ts,tmp_user.user_id,tmp_user.uname_len,tmp_user.pass_len,tmp_user.username, tmp_user.pass);

        // Write the timestamp
        if(!write_integer(tmp_user.ts,user_fd))
          {perror("0");}
        // Write the user id
        if(!write_integer(tmp_user.user_id,user_fd))
          {perror("1");}
        // Write the length of username
        if(!write_integer(tmp_user.uname_len,user_fd))
          {perror("2");}
        // Write the length of password
        if(!write_integer(tmp_user.pass_len,user_fd))
          {perror("3");}
        // Write the username
        if(!write_string(tmp_user.username,tmp_user.uname_len,user_fd))
          {perror("4");}
        // Write the password
        if(!write_string(tmp_user.pass, tmp_user.pass_len,user_fd))
          {perror("5");}
        user_file_len+=sizeof(int)*4+tmp_user.uname_len*sizeof(char)+tmp_user.pass_len*sizeof(char);

        saved_users[good_user_count]=tmp_user.user_id;
        ++good_user_count;
      }
  }
  while(1);

  //fprintf(stderr,"\nSaved %d records to USER.DAT.",good_user_count);

  // >>>>>>>>>>>>>>>>>>>> Poi cleaning <<<<<<<<<<<<<<<<<<<<
  // Same policy for poi: delete all the POI matching a trashed user
  // Scan the poi file, save only pois matching good user ids, skip the others
  poiCount=0;
  do {
    // Read the Timsetamp
    if (!read_integer(&tmp_poi.timestamp,poi_fd_bak))
      {
        // This has failed, because there are no more lines. So break
        break;
      }

    // Read the SpotId
    if (!read_integer(&tmp_poi.spotId,poi_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read spotId integer");
        return DB_ERROR;
      }

    // Read the description length
    if (!read_integer(&tmp_poi.descriptionLen,poi_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read desc len");
        return DB_ERROR;
      }

    // Read the userId
    if (!read_integer(&tmp_poi.userId,poi_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read userid");
        return DB_ERROR;
      }

    // If the user ID is the same of the userid is marked as valid, then procced with reading other stuff. Otherwise,
    // simply seek ahead without incrementing the counter
    good=0;
    for (i=0;i<good_user_count;i++)
      {
        if (saved_users[i]==tmp_poi.userId)
          {
            // Found! it is good and must be kept
            good=1;
          }
      }
    if (good==0)
      {
        // I have to seek of sizeof(double)*2 + sizeof(char)*descrLen
        lseek(poi_fd_bak,sizeof(double)*2 + sizeof(char)*tmp_poi.descriptionLen,SEEK_CUR);
        continue;
      }

    // Read the latitude
    if (!read_double(&tmp_poi.lat,poi_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read the first double (latitude).");
        return DB_ERROR;
      }

    // Read the longitude
    if (!read_double(&tmp_poi.lon,poi_fd_bak))
      {
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd); // DB file corrupted
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        perror("The poi.dat file contains an invalid row: I was unable to read the second double (longitude).");
        return DB_ERROR;
      }

    // Read the description
    tmp_poi.descr[0]='\0';
    if (!read_string(tmp_poi.descr,tmp_poi.descriptionLen,poi_fd_bak))
      {
        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read the poi description.");
        // Unlock and close the file
        user_lock.l_type = F_UNLCK;
        poi_lock.l_type = F_UNLCK;
        fcntl (user_fd, F_SETLKW, &user_lock);
        fcntl (poi_fd, F_SETLKW, &poi_lock);
        close(user_fd_bak);
        close(poi_fd_bak);
        close(user_fd);
        close(poi_fd);
        unlink(USER_DB_PATH_BAK);
        unlink(POI_DB_PATH_BAK);

        return DB_ERROR;
      }

    // Write to the poi db
    // Write the timestamp
    if(!write_integer(tmp_poi.timestamp,poi_fd))
      {perror("0");}
    // Write the spotId
    if(!write_integer(tmp_poi.spotId,poi_fd))
      {perror("1");}
    // Write the length of description
    if(!write_integer(tmp_poi.descriptionLen,poi_fd))
      {perror("2");}
    // Write the user_id
    if(!write_integer(tmp_poi.userId,poi_fd))
      {perror("3");}
    // Write the latitude
    if(!write_double(tmp_poi.lat,poi_fd))
      {perror("4");}
    // Write the longitude
    if(!write_double(tmp_poi.lon, poi_fd))
      {perror("5");}
    // Write the description
    if(!write_string(tmp_poi.descr,tmp_poi.descriptionLen, poi_fd))
      {perror("5");}
    poi_file_len+=sizeof(int)*4+sizeof(double)*2+sizeof(char)*tmp_poi.descriptionLen;

    ++poiCount;
  }
  while(1);

  //fprintf(stderr,"\nSaved %d records to POI.DAT.",poiCount);

  ftruncate(poi_fd,poi_file_len);
  ftruncate(user_fd,user_file_len);

  // Release both the locks
  // close both the files
  user_lock.l_type = F_UNLCK;
  poi_lock.l_type = F_UNLCK;
  fcntl (user_fd, F_SETLKW, &user_lock);
  fcntl (poi_fd, F_SETLKW, &poi_lock);
  close(user_fd_bak);
  close(poi_fd_bak);
  close(user_fd);
  close(poi_fd);

  i = unlink(USER_DB_PATH_BAK);
  if (i!=0)
    perror("It was impossible to delete the USER.DAT.BAK file");


  i = unlink(POI_DB_PATH_BAK);
  if (i!=0)
    perror("It was impossible to delete the USER.DAT.BAK file");

  now = time(NULL);
  fprintf(stderr,"\n ***** Cleaning routines ended at %u. ***** \n",now);

  return RESULT_OK;

}
Пример #17
0
int buf::createOutput()
{
	if (fileErr)
	{
		return -1;
	}
	int n = 0; //total number of objects
	UINT32 time, len, type;
	UINT32 curTime = 0;
	char* str = NULL;
	bool toWrite = false;
	messages.assign(TotalTypes + 1, 0);
	while (in)
	{
		if( in.peek() == EOF )
		{
			break;
		}
		type = read_uint32(in);
		time = read_uint32(in);
		if(time>curTime)
		{
			curTime = time;
			numBytes.assign(TotalTypes + 1, 0);
		}		
		len = read_uint32(in);
		if ((type<TotalTypes)&&((numBytes[type] + len + 3 * sizeof(UINT32)) <= 2048))
		{
			numBytes[type] += len + 3 * sizeof(UINT32);
			messages[type] ++;
		}
		str = new char[len+1];
		for (size_t i = 0; i < len; i++)
		{
			in.read(&(str[i]), 1);
		}
		str[len] = '\0';
		n++;
		if(str)
		{
			delete[] str;
		}
		if((len == 0) || (type > TotalTypes) )
		{
			continue;
		}
	}
	type = 0;

	for(vector<size_t>::iterator msgs = messages.begin(); msgs != messages.end(); ++msgs)
	{
		if (*msgs == 0)
		{
			type++;
			continue;
		}
		write_uint32(out, type);
		double val = (double)*msgs/curTime;
		write_double(out, val);
		type++;
	}
	return n;
}
Пример #18
0
int insert_poi(int user_id,double latitude, double longitude, char* description)
{
  int fd;
  struct flock lock;
  int maxId=0;
  int scanningSpotId=0;
  int scanningDescrLength=0;
  int scanningUserId=0;
  double scanningLat,scanningLon;
  char scanningDescr[MAX_USER_LEN];
  int userPoiCount=0;
  unsigned int t;

  // Check validity of description
  if (!is_str_valid(description))
    return STRING_WRONG_FORMAT;

  // If it is correct
  // Open the USER file in READ and WRITE,
  fd = open(POI_DB_PATH,O_RDWR|O_CREAT,S_IRWXU);
  if (fd<0)
    {
      // Error occurred
      perror("Error opening POI DB file.");
      return DB_OPEN_ERROR;
    }

  // Lock for writing
  memset (&lock, 0, sizeof(lock));
  lock.l_type = F_WRLCK;
  fcntl (fd, F_SETLKW, &lock);

  // Scan each row, it is needed to increment the ID
  do {
    // Read the Timestamp (integer)
    if (!read_uinteger(&t,fd))
      {
        // This has failed, because there are no more lines. So break
        break;
      }
    // Read the SpotId (integer)
    if (!read_integer(&scanningSpotId,fd))
      {
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read spotId");
        return DB_ERROR;
      }
    // Read the dimension of the description
    if (!read_integer(&scanningDescrLength,fd))
      {
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read descr len");
        return DB_ERROR;
      }

    // Read the user id
    if (!read_integer(&scanningUserId,fd))
      {
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read userid");
        return DB_ERROR;
      }

    // Read the lat
    if (!read_double(&scanningLat,fd))
      {
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read the latitude");
        return DB_ERROR;
      }

    // Read the lon
    if (!read_double(&scanningLon,fd))
      {
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read the longitude");
        return DB_ERROR;
      }

    // Read the description
    if (!read_string(scanningDescr,scanningDescrLength,fd))
      {
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        // DB file corrupted
        perror("The poi.dat file contains an invalid row: I was unable to read the description");
        return DB_ERROR;
      }

    // Find the maximum user id
    if (scanningSpotId>maxId)
      maxId=scanningSpotId;

    // Check if the user already has reached maximum amount of allowed POI
    if (user_id==scanningUserId)
      ++userPoiCount;

    // Check there areno equals rows
    if ((user_id==scanningUserId) && (scanningLat==latitude) && (scanningLon==longitude) && (strncmp(scanningDescr,description,MAX_USER_LEN)==0))
      {
        // This is a duplicate!
        // Unlock and close the file
        lock.l_type = F_UNLCK;
        fcntl (fd, F_SETLKW, &lock);
        close(fd);

        perror("The POI you specified is already n use.");
        return DB_ERROR_POI_EXISTS;
      }
  }
  while(userPoiCount<MAX_POI_PER_USER);

  // Write only if you are not at the maximum capacity
  if (userPoiCount>=MAX_POI_PER_USER)
    {
      lock.l_type = F_UNLCK;
      fcntl (fd, F_SETLKW, &lock);
      close(fd);

      perror("User reached the maximum amount of allowed POIs.");
      return DB_ERROR_TOO_MANY_POIS;
    }
  // Get the timestamp
  t = time(NULL);
  // Write the timestamp
  if(!write_integer(t,fd))
    {perror("0");}
  // Write the spotId
  if(!write_integer(maxId+1,fd))
    {perror("1");}
  // Write the length of description
  if(!write_integer(strnlen(description,MAX_USER_LEN),fd))
    {perror("2");}
  // Write the user_id
  if(!write_integer(user_id,fd))
    {perror("3");}
  // Write the latitude
  if(!write_double(latitude,fd))
    {perror("4");}
  // Write the longitude
  if(!write_double(longitude, fd))
    {perror("5");}
  // Write the description
  if(!write_string(description,strnlen(description,MAX_USER_LEN), fd))
    {perror("5");}

  // Then unlock the file, close the file.
  lock.l_type = F_UNLCK;
  fcntl (fd, F_SETLKW, &lock);
  close(fd);

  //fprintf(stderr,"\nInserted POI from userId %d.",user_id);

  return RESULT_OK;
}
Пример #19
0
void solve(void * args) {
	unsigned int it, iterations;
	char checkpoint_file_name[512];

	// Structs for the parameters
	InputParameters * params = (InputParameters *) args;
	FlowParams flow_params;
	FsiParams fsi_params;
	OutputParams output_params;

	// Parse input parameters
	input_parse_input_params(params, &flow_params, &fsi_params, &output_params);

	// Allocate state structs for the flow and particle
	FlowState * flow_state = flow_alloc_state(flow_params.lx, flow_params.ly);
	ParticleState * particle_state = fsi_alloc_state(fsi_params.nodes);
	LbmState * lbm_state = lbm_alloc_state(flow_params.lx, flow_params.ly);

	// State structs for Lyapunov calculation
	LyapunovState * lya_state = NULL;
	FlowState * lya_flow_state = NULL;
	ParticleState * lya_particle_state = NULL;
	LbmState * lya_lbm_state = NULL;

	// Setup output
	output_init(&output_params);

	// Try to initialize the solution from a checkpoint file
	sprintf(checkpoint_file_name, "%s/checkpoint.dat", output_params.output_folder);
	FILE * cp_handle = fopen(checkpoint_file_name, "r");

	if(cp_handle) {
		// Checkpoint file existed, read the file and initialize the states
		int lya_exists;

		read_uint(cp_handle, &it);
		fsi_read_state_binary(cp_handle, particle_state);
		flow_read_state_unformatted(cp_handle, flow_state);
		lbm_read_state_binary(cp_handle, lbm_state);

		read_uint(cp_handle, &lya_exists);
		if(lya_exists) {
			lya_particle_state = fsi_alloc_state(fsi_params.nodes);
			fsi_read_state_binary(cp_handle, lya_particle_state);
			lya_flow_state = flow_alloc_state(flow_params.lx, flow_params.ly);
			flow_read_state_unformatted(cp_handle, lya_flow_state);
			lya_lbm_state = lbm_alloc_state(flow_params.lx, flow_params.ly);
			lbm_read_state_binary(cp_handle, lya_lbm_state);

			lya_state = malloc(sizeof(LyapunovState));
			read_double(cp_handle, &lya_state->d0);
			read_double(cp_handle, &lya_state->cum_sum);
			read_double(cp_handle, &lya_state->lambda);
			read_uint(cp_handle, &lya_state->t0);
		}

		fclose(cp_handle);
	} else {
		// No checkpoint file, initialize normally

		// Print parameter file
		output_write_parameters_to_file(&output_params, params);

		// Initialize from base state
		it = 0;
		fsi_init_state(&fsi_params, particle_state);
		flow_init_state(&flow_params, flow_state);
		lbm_init_state(flow_state, lbm_state);

		// Print initial state
		output_write_state_to_file(0, &output_params, flow_state, particle_state, lya_state);
	}

	// Number of iterations
	iterations = it + output_params.timesteps;

	// Main loop
	while(it < iterations) {
		// Advance the solution
		it += 1;
		if( ! lbm_ebf_step(it, &flow_params, flow_state, particle_state, lbm_state))
			break;

		// Check if the Lyapunov exponent should be calculated
		if(output_params.print_lyapunov) {
			double d, alpha;

			// Initialize Lyapunov calculation stuff, if not already done
			if( ! lya_state) {
				lya_state = malloc(sizeof(LyapunovState));
				lya_state->d0 = 1.0e-4;
				lya_state->cum_sum = 0;
				lya_state->t0 = it;
				lya_state->lambda = 0;

				// Copy states
				lya_lbm_state = lbm_clone_state(lbm_state);
				lya_flow_state = flow_clone_state(flow_state);
				lya_particle_state = fsi_clone_state(particle_state);

				// Perturb the particle state
				lya_particle_state->angle += lya_state->d0;
				fsi_update_particle_nodes(lya_particle_state);

			} else {
				// Advance the perturbed state
				if( ! lbm_ebf_step(it, &flow_params, lya_flow_state, lya_particle_state, lya_lbm_state))
					break;

				// Calculate the distance between the original and perturbed orbit
				double ang_vel = particle_state->ang_vel / flow_params.G;
				double lya_ang_vel = lya_particle_state->ang_vel / flow_params.G;

				d = pow(lya_particle_state->angle - particle_state->angle, 2) + pow((lya_ang_vel - ang_vel), 2);
				alpha = sqrt(d / pow(lya_state->d0, 2));

				//printf("%.18g %.18g\n", (it - lya_state->t0)*flow_params.f / (2*PI), alpha);

				if(((it - lya_state->t0) % output_params.lyapunov_calc_step) == 0 && it != lya_state->t0) {
					// Push the perturbed orbit towards the base orbit
					lya_particle_state->angle = particle_state->angle + (lya_particle_state->angle - particle_state->angle) / alpha;
					lya_particle_state->ang_vel = flow_params.G * (ang_vel + (lya_ang_vel - ang_vel) / alpha);

					// Update particle node positions and reset the flow and lbm state to that of the base state
					unsigned int i;
					#pragma omp parallel
					{
						fsi_update_particle_nodes(lya_particle_state);
						#pragma omp for
						for(i = 0; i < lya_flow_state->lx*lya_flow_state->ly; ++i) {
							lya_flow_state->u[0][i] = flow_params.u_max * ((flow_state->u[0][i]/flow_params.u_max) +
														((lya_flow_state->u[0][i]/flow_params.u_max) - (flow_state->u[0][i]/flow_params.u_max)) / alpha);
							lya_flow_state->u[1][i] = flow_params.u_max * ((flow_state->u[1][i]/flow_params.u_max) +
														((lya_flow_state->u[1][i]/flow_params.u_max) - (flow_state->u[1][i]/flow_params.u_max)) / alpha);
							lya_flow_state->rho[i] = flow_state->rho[i] + (lya_flow_state->rho[i] - flow_state->rho[i]) / alpha;
						}
						lbm_init_state(lya_flow_state, lya_lbm_state);
					}

					// Update the lyapunov exponent
					lya_state->cum_sum += log(alpha);
					lya_state->lambda = lya_state->cum_sum / (lya_flow_state->G*(it - lya_state->t0));
					printf("%d %.12g\n", it-lya_state->t0, lya_state->lambda);
				}
			}
		}

		// Post process the result
		if((it % output_params.output_step) == 0)
			output_write_state_to_file(it, &output_params, flow_state, particle_state, lya_state);
	}

	// Write a checkpoint file so the simulation can be resumed at later times
	cp_handle = fopen(checkpoint_file_name, "w");
	write_uint(cp_handle, it);
	fsi_write_state_binary(cp_handle, particle_state);
	flow_write_state_unformatted(cp_handle, flow_state);
	lbm_write_state_binary(cp_handle, lbm_state);
	if( ! lya_state) {
		write_uint(cp_handle, 0);
	} else {
		write_uint(cp_handle, 1);
		fsi_write_state_binary(cp_handle, lya_particle_state);
		flow_write_state_unformatted(cp_handle, lya_flow_state);
		lbm_write_state_binary(cp_handle, lya_lbm_state);

		write_double(cp_handle, lya_state->d0);
		write_double(cp_handle, lya_state->cum_sum);
		write_double(cp_handle, lya_state->lambda);
		write_uint(cp_handle, lya_state->t0);
	}
	fclose(cp_handle);

	// Clean up
	output_destroy(&output_params);
	fsi_free_state(particle_state);
	lbm_free_state(lbm_state);
	flow_free_state(flow_state);

	if(lya_state) {
		fsi_free_state(lya_particle_state);
		lbm_free_state(lya_lbm_state);
		flow_free_state(lya_flow_state);
		free(lya_state);
	}
}
Пример #20
0
    void save( std::ostream &s ) const { 
	write_double( s, p[0] );
	write_double( s, p[1] );
	write_double( s, p[2] ); 
	write_double( s, p[3] ); 
    }
Пример #21
0
static int writer_double(lua_State* L)
{
	writer_t* writer = lua_touserdata(L, 1);
	write_double(writer, luaL_checknumber(L, 2));
	return 0;
}