Exemple #1
0
    std::unique_ptr<ImageIO::Base> MRtrix::create (Header& H) const
    {
      File::OFStream out (H.name(), std::ios::out | std::ios::binary);

      out << "mrtrix image\n";

      write_mrtrix_header (H, out);

      bool single_file = Path::has_suffix (H.name(), ".mif");

      int64_t offset = 0;
      out << "file: ";
      if (single_file) {
        offset = out.tellp() + int64_t(18);
        offset += ((4 - (offset % 4)) % 4);
        out << ". " << offset << "\nEND\n";
      }
      else out << Path::basename (H.name().substr (0, H.name().size()-4) + ".dat") << "\n";

      out.close();

      std::unique_ptr<ImageIO::Base> io_handler (new ImageIO::Default (H));
      if (single_file) {
        File::resize (H.name(), offset + footprint(H));
        io_handler->files.push_back (File::Entry (H.name(), offset));
      }
      else {
        std::string data_file (H.name().substr (0, H.name().size()-4) + ".dat");
        File::create (data_file, footprint(H));
        io_handler->files.push_back (File::Entry (data_file));
      }

      return io_handler;
    }
SuffixArray::SuffixArray(const std::string& base_name, bool print) :
  ok(false),
  data(0), sa(0), original_sa(0), ranks(0), data_size(0),
  sequences(0)
{
  std::ifstream data_file(base_name.c_str(), std::ios_base::binary);
  if(!data_file)
  {
    std::cerr << "Error: Cannot open data file " << base_name << std::endl;
    return;
  }
  this->data_size = fileSize(data_file);
  this->data = new uchar[this->data_size];
  data_file.read((char*)(this->data), data_size);
  data_file.close();

  std::string sa_name = base_name + SA_EXTENSION;
  std::ifstream sa_file(sa_name.c_str(), std::ios_base::binary);
  if(!sa_file)
  {
    std::cerr << "Error: Cannot open suffix array file " << sa_name << std::endl;
    return;
  }
  sa_file.read((char*)&(this->sequences), sizeof(uint));
  this->sa = new uint[this->data_size];
  sa_file.read((char*)(this->sa), this->data_size * sizeof(uint));
  sa_file.close();

  this->original_sa = this->sa; this->sa += this->sequences;
  this->ok = true;
}
Exemple #3
0
static void
cmd_include(void)
{
   char *pth, *fnm = NULL;
   int fnm_len;
#ifndef NO_DEPRECATED
   prefix *root_store;
#endif
   int ch_store;

   pth = path_from_fnm(file.filename);

   read_string(&fnm, &fnm_len);

#ifndef NO_DEPRECATED
   /* Since *begin / *end nesting cannot cross file boundaries we only
    * need to preserve the prefix if the deprecated *prefix command
    * can be used */
   root_store = root;
   root = pcs->Prefix; /* Root for include file is current prefix */
#endif
   ch_store = ch;

   data_file(pth, fnm);

#ifndef NO_DEPRECATED
   root = root_store; /* and restore root */
#endif
   ch = ch_store;

   s_free(&fnm);
   osfree(pth);
}
bool AmConfigReader::getMD5(const string& path, string& md5hash, bool lowercase) {
    std::ifstream data_file(path.c_str(), std::ios::in | std::ios::binary);
    if (!data_file) {
      DBG("could not read file '%s'\n", path.c_str());
      return false;
    }
    // that one is clever...
    // (see http://www.gamedev.net/community/forums/topic.asp?topic_id=353162 )
    string file_data((std::istreambuf_iterator<char>(data_file)),
		     std::istreambuf_iterator<char>());

    if (file_data.empty()) {
      return false;
    }

    MD5_CTX md5ctx;
    MD5Init(&md5ctx);
    MD5Update(&md5ctx, (unsigned char*)file_data.c_str(), file_data.length());
    unsigned char _md5hash[16];
    MD5Final(_md5hash, &md5ctx);
    md5hash = "";
    for (size_t i=0;i<16;i++) {
      md5hash+=char2hex(_md5hash[i], lowercase);
    }
    return true;
}
Exemple #5
0
/*
 * Hook and mod_cache callback functions
 */
static int create_entity(cache_handle_t *h, request_rec *r, const char *key, apr_off_t len)
{
    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                 &disk_cache_module);
    cache_object_t *obj;
    disk_cache_object_t *dobj;

    if (conf->cache_root == NULL) {
        return DECLINED;
    }

    /* Allocate and initialize cache_object_t and disk_cache_object_t */
    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(*obj));
    obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(*dobj));

    obj->key = apr_pstrdup(r->pool, key);

    dobj->name = obj->key;
    dobj->prefix = NULL;
    /* Save the cache root */
    dobj->root = apr_pstrndup(r->pool, conf->cache_root, conf->cache_root_len);
    dobj->root_len = conf->cache_root_len;
    dobj->datafile = data_file(r->pool, conf, dobj, key);
    dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);

    return OK;
}
bool 
the_Printing_manager::Load_image_data( std::string& _file_name, 
				       std::string& _image_data_id )
{
  std::string prefix = "Data/images/";
  std::string suffix = ".data";
  Image_data* image_data_ptr = nullptr;
  try
    {
      std::ifstream data_file( prefix + _file_name + suffix );
      if( data_file.is_open() && data_file.good())
	{
	  image_data_ptr = this->Parser_image_data( data_file );

	  auto pair = m_image_data_map.insert( std::make_pair( _image_data_id, image_data_ptr ));
	  if( ! pair.second )
	    throw std::invalid_argument( "(xx) Printer ERROR! When LOADING 'Image-Data'. The ID: '"+ _image_data_id +"' is allready in use! " );

	  data_file.close();
	}
      else 
	throw std::ios::failure( "(xx) Printer ERROR! When opening 'Image-Data' file: '"+ prefix + _file_name + suffix +"'! " );
    }
  catch( const std::exception& e )
    {
      delete image_data_ptr;
      std::cerr <<"PRINTER ERROR :: When parsing the 'Image-Data' file: '"<< prefix << _file_name << suffix <<"'!\n";
      std::cerr <<"\t"<< e.what() <<'\n';
      return false;
    }
  return true;
}
void
SuffixArray::writeTo(const std::string& base_name, bool write_data) const
{
  if(!this->ok) { return; }

  if(write_data)
  {
    std::ofstream data_file(base_name.c_str(), std::ios_base::binary);
    if(!data_file)
    {
      std::cerr << "Error: Cannot open data file " << base_name << std::endl;
      return;
    }
    data_file.write((char*)(this->data), this->data_size);
    data_file.close();
  }

  std::string sa_name = base_name + SA_EXTENSION;
  std::ofstream sa_file(sa_name.c_str(), std::ios_base::binary);
  if(!sa_file)
  {
    std::cerr << "Error: Cannot open suffix array file " << sa_name << std::endl;
    return;
  }
  sa_file.write((char*)&(this->sequences), sizeof(uint));
  sa_file.write((char*)(this->original_sa), this->data_size * sizeof(uint));
  sa_file.close();
}
Exemple #8
0
int Base::Destroy(const char * _filename) {
    ifstream data_file(_filename);

    if(data_file.good()) {
        if((remove(_filename)) != 0) {
            cout << "Destroy(): " << "ERROR: Can't remove " << _filename << endl;
            return EXIT_FAILURE;
        }
    }
    return EXIT_SUCCESS;
}
Exemple #9
0
int main(int argc, char *argv[]) {
  if (argc < 3) {
    print_usage(argv[0]);
    exit(1);
  }

  if (argc == 4) {
    if (strncmp(argv[3], "-verbose", 8) == 0 ||
        strncmp(argv[3], "-v", 2) == 0) {
      verbose = true;
    } else {
      print_usage(argv[0]);
      exit(1);
    }
  }

  std::fstream data_file(argv[1]);

  if (data_file.peek() == std::fstream::traits_type::eof()) {
    exit(1);
  }

  int dimensions;
  int number_of_points;
  int clusters = atoi(argv[2]);

  data_file >> dimensions;
  data_file >> number_of_points;

  std::vector<DataPoint> points;

  for (int n = 0; n < number_of_points; ++n) {
    double *attributes = new double[dimensions];
    for (int i = 0; i < dimensions; ++i) {
      data_file >> attributes[i];
    }

    DataPoint point;
    point.n = dimensions;
    point.attr = attributes;
    point.distance = std::numeric_limits<double>::infinity();
    points.push_back(point);
  }

  if (verbose) {
    std::cout << "Finding  " << clusters << " clusters" << std::endl;
    std::cout << "Points read: " << points.size() << std::endl;
    print_data_points(points);
  }

  kmeans(points, clusters);
}
int main( int argc, char *argv[] )
{
    char *rev_file;

    if ( argc > 1 )
        rev_file = argv[ 1 ];
    else
        rev_file = "CHECKREV.DAT";
    cout << "Data file: " << rev_file << "\n";
    ifstream data_file( rev_file );
    if ( data_file.fail() )
        cerr << "Error opening data file!\n";
    else
        check_files( data_file );
    return( 0 );
}
Exemple #11
0
// Print the basic model
void createProperties(const bfs::path & example_model_path)
{
	Json::Value root;
	Json::Value & records = root["records"];
	records.resize(2);

	// Add time series
	records[0]["name"] = "test_ts";
	records[0]["ending"] = "open";
	records[0]["E_A"] = "";
	records[0]["E_B"] = "";
	records[0]["select"] = true;
	records[0]["recid"] = 0;
	records[0]["records"].resize(2);
	records[0]["records"][0]["V_B"] = "[0,1)";
	records[0]["records"][0]["recid"] = 0;
	records[0]["records"][0]["id"] = "A";
	records[0]["records"][1]["V_B"] = "(1,2]";
	records[0]["records"][1]["recid"] = 1;
	records[0]["records"][1]["id"] = "B";

	// Add a cycle
	records[1]["name"] = "test_cycle";
	records[1]["ending"] = "cyclic";
	records[1]["E_A"] = "";
	records[1]["E_B"] = "";
	records[1]["select"] = true;
	records[1]["recid"] = 1;
	records[1]["records"].resize(3);
	records[1]["records"][0]["V_B"] = "[0,1)";
	records[1]["records"][0]["recid"] = 0;
	records[1]["records"][0]["id"] = "A";
	records[1]["records"][1]["V_B"] = "[0,1)";
	records[1]["records"][1]["recid"] = 1;
	records[1]["records"][1]["id"] = "B";
	records[1]["records"][2]["V_B"] = "[1,1]";
	records[1]["records"][2]["recid"] = 2;
	records[1]["records"][2]["id"] = "C";

	Json::StyledWriter writer;
	ofstream data_file((example_model_path / DATA_FOLDER / PROPERTIES_FILENAME).string(), ios::out);
	string data = writer.write(root);
	data_file << data;
}
Exemple #12
0
int main(){
	
	const int DATA_SIZE = 15;
	const char *file = "test.dat";
	const char *out_f = "total.txt";
	
	int data_array[DATA_SIZE];
	std::ifstream data_file(file);

	


	if(data_file.bad()){

		std::cerr << "Errore nella lettura del file "<<file<<'\n';
		return(8);
	}

	for(int i = 0; i < DATA_SIZE; ++i){

		data_file >> data_array[i];
	}


	int total = 0;

	for(unsigned int i = 0; i <= (sizeof(data_array)/sizeof(data_array[0]));++i){
		std::cout << "Riga:" << i << " vale " << data_array[i] << '\n';
				
		total += data_array[i];
	}
	
	std::ofstream out_file(out_f, std::ios::out|std::ios::app|std::ios::ate);
	if(out_file.bad()){
		std::cerr << "Impossibile scrivere sul file " << out_file << '\n';
		return (8);
	}
	
	out_file << "Il totale è " << total << '\n';

	std::cout << "Totale:" << total << '\n';
	return (0);

}
std::vector<std::string> AbstractCachedMeshReader<ELEMENT_DIM, SPACE_DIM>::GetRawDataFromFile(
        const std::string& rFileName)
{
    // Open raw data file

    std::vector<std::string> raw_data;
    std::ifstream data_file(rFileName.c_str());

    // Checks that input file has been opened correctly. If not throws an
    // exception that should be caught by the user.
    if (!data_file.is_open())
    {
        EXCEPTION("Could not open data file " + rFileName);
    }

    // Read each line in turn
    std::string raw_line;
    getline(data_file, raw_line);

    while (data_file)
    {
        // Remove comments (everything from a hash to the end of the line)
        // If there is no hash, then hashLocation = string::npos = -1 = 4294967295 = UINT_MAX
        // (so it works with unsigneds but is a little nasty)
        long hash_location = raw_line.find('#', 0);
        if (hash_location >= 0)
        {
            raw_line = raw_line.substr(0, hash_location);
        }
        // Remove blank lines.  This is unnecessary, since the tokenizer will
        // ignore blank lines anyway.
        long not_blank_location = raw_line.find_first_not_of(" \t", 0);
        if (not_blank_location >= 0)
        {
            raw_data.push_back(raw_line);
        }

        // Move onto next line
        getline(data_file, raw_line);
    }

    data_file.close(); // Closes the data file
    return raw_data;
}
void VectorSpaceModel::guardarDiccionario(){
ofstream data_file("dic.dat", std::ios::binary);
const unsigned int  maxPalabra=16;
mapaDelDiccionario::iterator externo;
float idf;

 unsigned char * buf_ptr = new unsigned char [16];
  unsigned char * buf_grabar=buf_ptr;
        
  for (externo=miDiccionario->diccionario.begin(); externo!=miDiccionario->diccionario.end(); externo++){
	    fill_n(buf_ptr, 16,0);
	    idf=log10((TipoGuardado)cantDocs / (TipoGuardado)externo->second.size());
	    //externo->first es una palabra
        strncpy((char *) buf_ptr, externo->first.c_str(), maxPalabra);
		data_file.write((char *)&idf, 4);
        data_file.write((char *) buf_grabar, 16);
	}
    data_file.close();
    delete [] buf_ptr;
        }
Exemple #15
0
      RefPtr<Handler::Base> MRtrix::create (Header& H) const
      {
        if (!File::is_tempfile (H.name()))
          File::create (H.name());

        std::ofstream out (H.name().c_str(), std::ios::out | std::ios::binary);
        if (!out)
          throw Exception ("error creating file \"" + H.name() + "\":" + strerror (errno));

        out << "mrtrix image\n";

        write_mrtrix_header (H, out);

        bool single_file = Path::has_suffix (H.name(), ".mif");

        int64_t offset = 0;
        out << "file: ";
        if (single_file) {
          offset = out.tellp() + int64_t(18);
          offset += ((4 - (offset % 4)) % 4);
          out << ". " << offset << "\nEND\n";
        }
        else out << Path::basename (H.name().substr (0, H.name().size()-4) + ".dat") << "\n";

        out.close();

        RefPtr<Handler::Base> handler (new Handler::Default (H));
        if (single_file) {
          File::resize (H.name(), offset + Image::footprint(H));
          handler->files.push_back (File::Entry (H.name(), offset));
        }
        else {
          std::string data_file (H.name().substr (0, H.name().size()-4) + ".dat");
          File::create (data_file, Image::footprint(H));
          handler->files.push_back (File::Entry (data_file));
        }

        return handler;
      }
Exemple #16
0
static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *info)
{
    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                 &disk_cache_module);
    apr_status_t rv;
    apr_size_t amt;
    disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;

    disk_cache_info_t disk_info;
    struct iovec iov[2];

    /* This is flaky... we need to manage the cache_info differently */
    h->cache_obj->info = *info;

    if (r->headers_out) {
        const char *tmp;

        tmp = apr_table_get(r->headers_out, "Vary");

        if (tmp) {
            apr_array_header_t* varray;
            apr_uint32_t format = VARY_FORMAT_VERSION;

            /* If we were initially opened as a vary format, rollback
             * that internal state for the moment so we can recreate the
             * vary format hints in the appropriate directory.
             */
            if (dobj->prefix) {
                dobj->hdrsfile = dobj->prefix;
                dobj->prefix = NULL;
            }

            mkdir_structure(conf, dobj->hdrsfile, r->pool);

            rv = apr_file_mktemp(&dobj->tfd, dobj->tempfile,
                                 APR_CREATE | APR_WRITE | APR_BINARY | APR_EXCL,
                                 r->pool);

            if (rv != APR_SUCCESS) {
                return rv;
            }

            amt = sizeof(format);
            apr_file_write(dobj->tfd, &format, &amt);

            amt = sizeof(info->expire);
            apr_file_write(dobj->tfd, &info->expire, &amt);

            varray = apr_array_make(r->pool, 6, sizeof(char*));
            tokens_to_array(r->pool, tmp, varray);

            store_array(dobj->tfd, varray);

            apr_file_close(dobj->tfd);

            dobj->tfd = NULL;

            rv = safe_file_rename(conf, dobj->tempfile, dobj->hdrsfile,
                                  r->pool);
            if (rv != APR_SUCCESS) {
                ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server,
                    "disk_cache: rename tempfile to varyfile failed: %s -> %s",
                    dobj->tempfile, dobj->hdrsfile);
                apr_file_remove(dobj->tempfile, r->pool);
                return rv;
            }

            dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
            tmp = regen_key(r->pool, r->headers_in, varray, dobj->name);
            dobj->prefix = dobj->hdrsfile;
            dobj->hashfile = NULL;
            dobj->datafile = data_file(r->pool, conf, dobj, tmp);
            dobj->hdrsfile = header_file(r->pool, conf, dobj, tmp);
        }
    }


    rv = apr_file_mktemp(&dobj->hfd, dobj->tempfile,
                         APR_CREATE | APR_WRITE | APR_BINARY |
                         APR_BUFFERED | APR_EXCL, r->pool);

    if (rv != APR_SUCCESS) {
        return rv;
    }

    disk_info.format = DISK_FORMAT_VERSION;
    disk_info.date = info->date;
    disk_info.expire = info->expire;
    disk_info.entity_version = dobj->disk_info.entity_version++;
    disk_info.request_time = info->request_time;
    disk_info.response_time = info->response_time;
    disk_info.status = info->status;

    disk_info.name_len = strlen(dobj->name);

    iov[0].iov_base = (void*)&disk_info;
    iov[0].iov_len = sizeof(disk_cache_info_t);
    iov[1].iov_base = (void*)dobj->name;
    iov[1].iov_len = disk_info.name_len;

    rv = apr_file_writev(dobj->hfd, (const struct iovec *) &iov, 2, &amt);
    if (rv != APR_SUCCESS) {
        return rv;
    }

    if (r->headers_out) {
        apr_table_t *headers_out;

        headers_out = ap_cache_cacheable_hdrs_out(r->pool, r->headers_out,
                                                  r->server);

        if (!apr_table_get(headers_out, "Content-Type")
            && r->content_type) {
            apr_table_setn(headers_out, "Content-Type",
                           ap_make_content_type(r, r->content_type));
        }

        headers_out = apr_table_overlay(r->pool, headers_out,
                                        r->err_headers_out);
        rv = store_table(dobj->hfd, headers_out);
        if (rv != APR_SUCCESS) {
            return rv;
        }
    }

    /* Parse the vary header and dump those fields from the headers_in. */
    /* FIXME: Make call to the same thing cache_select calls to crack Vary. */
    if (r->headers_in) {
        apr_table_t *headers_in;

        headers_in = ap_cache_cacheable_hdrs_out(r->pool, r->headers_in,
                                                 r->server);
        rv = store_table(dobj->hfd, headers_in);
        if (rv != APR_SUCCESS) {
            return rv;
        }
    }

    apr_file_close(dobj->hfd); /* flush and close */

    /* Remove old file with the same name. If remove fails, then
     * perhaps we need to create the directory tree where we are
     * about to write the new headers file.
     */
    rv = apr_file_remove(dobj->hdrsfile, r->pool);
    if (rv != APR_SUCCESS) {
        mkdir_structure(conf, dobj->hdrsfile, r->pool);
    }

    rv = safe_file_rename(conf, dobj->tempfile, dobj->hdrsfile, r->pool);
    if (rv != APR_SUCCESS) {
        ap_log_error(APLOG_MARK, APLOG_WARNING, rv, r->server,
                     "disk_cache: rename tempfile to hdrsfile failed: %s -> %s",
                     dobj->tempfile, dobj->hdrsfile);
        apr_file_remove(dobj->tempfile, r->pool);
        return rv;
    }

    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);

    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                 "disk_cache: Stored headers for URL %s",  dobj->name);
    return APR_SUCCESS;
}
 std::string loadFromFile(const std::string &path) {
   std::ifstream data_file(path.c_str());
   std::string result((std::istreambuf_iterator<char>(data_file)), std::istreambuf_iterator<char>());
   data_file.close();
   return result;
 }
Exemple #18
0
static int open_entity(cache_handle_t *h, request_rec *r, const char *key)
{
    apr_uint32_t format;
    apr_size_t len;
    const char *nkey;
    apr_status_t rc;
    static int error_logged = 0;
    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                 &disk_cache_module);
    apr_finfo_t finfo;
    cache_object_t *obj;
    cache_info *info;
    disk_cache_object_t *dobj;
    int flags;

    h->cache_obj = NULL;

    /* Look up entity keyed to 'url' */
    if (conf->cache_root == NULL) {
        if (!error_logged) {
            error_logged = 1;
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                         "disk_cache: Cannot cache files to disk without a CacheRoot specified.");
        }
        return DECLINED;
    }

    /* Create and init the cache object */
    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
    obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));

    info = &(obj->info);

    /* Open the headers file */
    dobj->prefix = NULL;

    /* Save the cache root */
    dobj->root = apr_pstrndup(r->pool, conf->cache_root, conf->cache_root_len);
    dobj->root_len = conf->cache_root_len;

    dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
    flags = APR_READ|APR_BINARY|APR_BUFFERED;
    rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
    if (rc != APR_SUCCESS) {
        return DECLINED;
    }

    /* read the format from the cache file */
    len = sizeof(format);
    apr_file_read_full(dobj->hfd, &format, len, &len);

    if (format == VARY_FORMAT_VERSION) {
        apr_array_header_t* varray;
        apr_time_t expire;

        len = sizeof(expire);
        apr_file_read_full(dobj->hfd, &expire, len, &len);

        varray = apr_array_make(r->pool, 5, sizeof(char*));
        rc = read_array(r, varray, dobj->hfd);
        if (rc != APR_SUCCESS) {
            ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
                         "disk_cache: Cannot parse vary header file: %s",
                         dobj->hdrsfile);
            return DECLINED;
        }
        apr_file_close(dobj->hfd);

        nkey = regen_key(r->pool, r->headers_in, varray, key);

        dobj->hashfile = NULL;
        dobj->prefix = dobj->hdrsfile;
        dobj->hdrsfile = header_file(r->pool, conf, dobj, nkey);

        flags = APR_READ|APR_BINARY|APR_BUFFERED;
        rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
        if (rc != APR_SUCCESS) {
            return DECLINED;
        }
    }
    else if (format != DISK_FORMAT_VERSION) {
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
                     "cache_disk: File '%s' has a version mismatch. File had version: %d.",
                     dobj->hdrsfile, format);
        return DECLINED;
    }
    else {
        apr_off_t offset = 0;
        /* This wasn't a Vary Format file, so we must seek to the
         * start of the file again, so that later reads work.
         */
        apr_file_seek(dobj->hfd, APR_SET, &offset);
        nkey = key;
    }

    obj->key = nkey;
    dobj->key = nkey;
    dobj->name = key;
    dobj->datafile = data_file(r->pool, conf, dobj, nkey);
    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);

    /* Open the data file */
    flags = APR_READ|APR_BINARY;
#ifdef APR_SENDFILE_ENABLED
    flags |= APR_SENDFILE_ENABLED;
#endif
    rc = apr_file_open(&dobj->fd, dobj->datafile, flags, 0, r->pool);
    if (rc != APR_SUCCESS) {
        /* XXX: Log message */
        return DECLINED;
    }

    rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, dobj->fd);
    if (rc == APR_SUCCESS) {
        dobj->file_size = finfo.size;
    }

    /* Read the bytes to setup the cache_info fields */
    rc = file_cache_recall_mydata(dobj->hfd, info, dobj, r);
    if (rc != APR_SUCCESS) {
        /* XXX log message */
        return DECLINED;
    }

    /* Initialize the cache_handle callback functions */
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                 "disk_cache: Recalled cached URL info header %s",  dobj->name);
    return OK;
}
Exemple #19
0
void input_manager::load(const std::string &file_name, bool is_user_preferences)
{
    std::ifstream data_file(file_name.c_str(), std::ifstream::in | std::ifstream::binary);

    if(!data_file.good()) {
        // Only throw if this is the first file to load, that file _must_ exist,
        // otherwise the keybindings can not be read at all.
        if (action_contexts.empty()) {
            throw "Could not read " + file_name;
        }
        return;
    }

    JsonIn jsin(data_file);

    //Crawl through once and create an entry for every definition
    jsin.start_array();
    while (!jsin.end_array()) {
        // JSON object representing the action
        JsonObject action = jsin.get_object();

        const std::string action_id = action.get_string("id");
        const std::string context = action.get_string("category", default_context_id);
        t_actions &actions = action_contexts[context];
        if (!is_user_preferences && action.has_member("name")) {
            // Action names are not user preferences. Some experimental builds
            // post-0.A had written action names into the user preferences
            // config file. Any names that exist in user preferences will be
            // ignored.
            actions[action_id].name = action.get_string("name");
        }

        // Iterate over the bindings JSON array
        JsonArray bindings = action.get_array("bindings");
        t_input_event_list events;
        while (bindings.has_more()) {
            JsonObject keybinding = bindings.next_object();
            std::string input_method = keybinding.get_string("input_method");
            input_event new_event;
            if(input_method == "keyboard") {
                new_event.type = CATA_INPUT_KEYBOARD;
            } else if(input_method == "gamepad") {
                new_event.type = CATA_INPUT_GAMEPAD;
            } else if(input_method == "mouse") {
                new_event.type = CATA_INPUT_MOUSE;
            }

            if (keybinding.has_array("key")) {
                JsonArray keys = keybinding.get_array("key");
                while (keys.has_more()) {
                    new_event.sequence.push_back(
                        get_keycode(keys.next_string())
                    );
                }
            } else { // assume string if not array, and throw if not string
                new_event.sequence.push_back(
                    get_keycode(keybinding.get_string("key"))
                );
            }

            events.push_back(new_event);
        }

        // An invariant of this class is that user-created, local keybindings
        // with an empty set of input_events do not exist in the
        // action_contexts map. In prior versions of this class, this was not
        // true, so users of experimental builds post-0.A will have empty
        // local keybindings saved in their keybindings.json config.
        //
        // To be backwards compatible with keybindings.json from prior
        // experimental builds, we will detect user-created, local keybindings
        // with empty input_events and disregard them. When keybindings are
        // later saved, these remnants won't be saved.
        if (!is_user_preferences ||
            !events.empty() ||
            context == default_context_id ||
            actions.count(action_id) > 0) {
            // In case this is the second file containing user preferences,
            // this replaces the default bindings with the user's preferences.
            action_attributes &attributes = actions[action_id];
            attributes.input_events = events;
            if (action.has_member("is_user_created")) {
                attributes.is_user_created = action.get_bool("is_user_created");
            }
        }
    }
}
Exemple #20
0
extern CDECL int
main(int argc, char **argv)
{
   int d;
   time_t tmUserStart = time(NULL);
   clock_t tmCPUStart = clock();
   {
       /* FIXME: localtime? */
       struct tm * t = localtime(&tmUserStart);
       int y = t->tm_year + 1900;
       current_days_since_1900 = days_since_1900(y, t->tm_mon + 1, t->tm_mday);
   }

   /* Always buffer by line for aven's benefit. */
   setvbuf(stdout, NULL, _IOLBF, 0);

   msg_init(argv);

#if OS_WIN32 || OS_UNIX_MACOSX
   pj_set_finder(msg_proj_finder);
#endif

   pcs = osnew(settings);
   pcs->next = NULL;
   pcs->Translate = ((short*) osmalloc(ossizeof(short) * 257)) + 1;
   pcs->meta = NULL;
   pcs->proj = NULL;
   pcs->declination = HUGE_REAL;
   pcs->convergence = 0.0;

   /* Set up root of prefix hierarchy */
   root = osnew(prefix);
   root->up = root->right = root->down = NULL;
   root->stn = NULL;
   root->pos = NULL;
   root->ident = NULL;
   root->min_export = root->max_export = 0;
   root->sflags = BIT(SFLAGS_SURVEY);
   root->filename = NULL;

   nosurveyhead = NULL;

   stnlist = NULL;
   cLegs = cStns = cComponents = 0;
   totadj = total = totplan = totvert = 0.0;

   for (d = 0; d <= 2; d++) {
      min[d] = HUGE_REAL;
      max[d] = -HUGE_REAL;
      pfxHi[d] = pfxLo[d] = NULL;
   }

   /* at least one argument must be given */
   cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 1, -1);
   while (1) {
      int opt = cmdline_getopt();
      if (opt == EOF) break;
      switch (opt) {
       case 'p':
	 /* Ignore for compatibility with older versions. */
	 break;
       case 'o': {
	 osfree(fnm_output_base); /* in case of multiple -o options */
	 /* can be a directory (in which case use basename of leaf input)
	  * or a file (in which case just trim the extension off) */
	 if (fDirectory(optarg)) {
	    /* this is a little tricky - we need to note the path here,
	     * and then add the leaf later on (in datain.c) */
	    fnm_output_base = base_from_fnm(optarg);
	    fnm_output_base_is_dir = 1;
	 } else {
	    fnm_output_base = base_from_fnm(optarg);
	 }
	 break;
       }
       case 'q':
	 if (fQuiet) fMute = 1;
	 fQuiet = 1;
	 break;
       case 's':
	 fSuppress = 1;
	 break;
       case 'v': {
	 int v = atoi(optarg);
	 if (v < IMG_VERSION_MIN || v > IMG_VERSION_MAX)
	    fatalerror(/*3d file format versions %d to %d supported*/88,
		       IMG_VERSION_MIN, IMG_VERSION_MAX);
	 img_output_version = v;
	 break;
       }
       case 'w':
	 f_warnings_are_errors = 1;
	 break;
       case 'z': {
	 /* Control which network optimisations are used (development tool) */
	 static int first_opt_z = 1;
	 char c;
	 if (first_opt_z) {
	    optimize = 0;
	    first_opt_z = 0;
	 }
	 /* Lollipops, Parallel legs, Iterate mx, Delta* */
	 while ((c = *optarg++) != '\0')
	    if (islower((unsigned char)c)) optimize |= BITA(c);
	 break;
       case 1:
	 fLog = fTrue;
	 break;
#if OS_WIN32
       case 2:
	 atexit(pause_on_exit);
	 break;
#endif
       }
      }
   }

   if (fLog) {
      char *fnm;
      if (!fnm_output_base) {
	 char *p;
	 p = baseleaf_from_fnm(argv[optind]);
	 fnm = add_ext(p, EXT_LOG);
	 osfree(p);
      } else if (fnm_output_base_is_dir) {
	 char *p;
	 fnm = baseleaf_from_fnm(argv[optind]);
	 p = use_path(fnm_output_base, fnm);
	 osfree(fnm);
	 fnm = add_ext(p, EXT_LOG);
	 osfree(p);
      } else {
	 fnm = add_ext(fnm_output_base, EXT_LOG);
      }

      if (!freopen(fnm, "w", stdout))
	 fatalerror(/*Failed to open output file “%s”*/47, fnm);

      osfree(fnm);
   }

   if (!fMute) {
      const char *p = COPYRIGHT_MSG;
      puts(PRETTYPACKAGE" "VERSION);
      while (1) {
	  const char *q = p;
	  p = strstr(p, "(C)");
	  if (p == NULL) {
	      puts(q);
	      break;
	  }
	  fwrite(q, 1, p - q, stdout);
	  fputs(msg(/*©*/0), stdout);
	  p += 3;
      }
   }

   atexit(delete_output_on_error);

   /* end of options, now process data files */
   while (argv[optind]) {
      const char *fnm = argv[optind];

      if (!fExplicitTitle) {
	 char *lf;
	 lf = baseleaf_from_fnm(fnm);
	 if (survey_title) s_catchar(&survey_title, &survey_title_len, ' ');
	 s_cat(&survey_title, &survey_title_len, lf);
	 osfree(lf);
      }

      /* Select defaults settings */
      default_all(pcs);
      data_file(NULL, fnm); /* first argument is current path */

      optind++;
   }

   validate();

   solve_network(/*stnlist*/); /* Find coordinates of all points */
   validate();

   /* close .3d file */
   if (!img_close(pimg)) {
      char *fnm = add_ext(fnm_output_base, EXT_SVX_3D);
      fatalerror(img_error2msg(img_error()), fnm);
   }
   if (fhErrStat) safe_fclose(fhErrStat);

   out_current_action(msg(/*Calculating statistics*/120));
   if (!fMute) do_stats();
   if (!fQuiet) {
      /* clock() typically wraps after 72 minutes, but there doesn't seem
       * to be a better way.  Still 72 minutes means some cave!
       * We detect if clock() could have wrapped and suppress CPU time
       * printing in this case.
       */
      double tmUser = difftime(time(NULL), tmUserStart);
      double tmCPU;
      clock_t now = clock();
#define CLOCK_T_WRAP \
	(sizeof(clock_t)<sizeof(long)?(1ul << (CHAR_BIT * sizeof(clock_t))):0)
      tmCPU = (now - (unsigned long)tmCPUStart)
	 / (double)CLOCKS_PER_SEC;
      if (now < tmCPUStart)
	 tmCPU += CLOCK_T_WRAP / (double)CLOCKS_PER_SEC;
      if (tmUser >= tmCPU + CLOCK_T_WRAP / (double)CLOCKS_PER_SEC)
	 tmCPU = 0;

      /* tmUser is integer, tmCPU not - equivalent to (ceil(tmCPU) >= tmUser) */
      if (tmCPU + 1 > tmUser) {
	 printf(msg(/*CPU time used %5.2fs*/140), tmCPU);
      } else if (tmCPU == 0) {
	 if (tmUser != 0.0) {
	    printf(msg(/*Time used %5.2fs*/141), tmUser);
	 } else {
	    fputs(msg(/*Time used unavailable*/142), stdout);
	 }
      } else {
	 printf(msg(/*Time used %5.2fs (%5.2fs CPU time)*/143), tmUser, tmCPU);
      }
      putnl();
   }
   if (msg_warnings || msg_errors) {
      if (msg_errors || (f_warnings_are_errors && msg_warnings)) {
	 printf(msg(/*There were %d warning(s) and %d error(s) - no output files produced.*/113),
		msg_warnings, msg_errors);
	 putnl();
	 return EXIT_FAILURE;
      }
      printf(msg(/*There were %d warning(s).*/16), msg_warnings);
      putnl();
   }
   return EXIT_SUCCESS;
}
Exemple #21
0
int main(int argc, char* argv[]) {
    std::ios_base::sync_with_stdio(false);

    static struct option long_options[] = {
        {"help",      no_argument, 0, 'h'},
        {0, 0, 0, 0}
    };

    while (true) {
        int c = getopt_long(argc, argv, "h", long_options, 0);
        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                print_help();
                exit(0);
            default:
                exit(2);
        }
    }

    int remaining_args = argc - optind;

    if (remaining_args != 2) {
        std::cerr << "Usage: " << argv[0] << " OSMFILE DIR\n";
        exit(2);
    }

    std::string dir(argv[optind+1]);

    int result = ::mkdir(dir.c_str(), 0777);
    if (result == -1 && errno != EEXIST) {
        std::cerr << "Problem creating directory '" << dir << "': " << strerror(errno) << "\n";
        exit(2);
    }

    std::string data_file(dir + "/data.osm.ser");
    int data_fd = ::open(data_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (data_fd < 0) {
        std::cerr << "Can't open data file '" << data_file << "': " << strerror(errno) << "\n";
        exit(2);
    }

    offset_index_type node_index;
    offset_index_type way_index;
    offset_index_type relation_index;

    osmium::handler::DiskStore disk_store_handler(data_fd, node_index, way_index, relation_index);

    map_type map_node2way;
    map_type map_node2relation;
    map_type map_way2relation;
    map_type map_relation2relation;

    osmium::handler::ObjectRelations object_relations_handler(map_node2way, map_node2relation, map_way2relation, map_relation2relation);

    osmium::io::Reader reader(argv[1]);
    osmium::io::Header header = reader.open();

    while (osmium::memory::Buffer buffer = reader.read()) {
        disk_store_handler(buffer);
        object_relations_handler(buffer);
    }

    {
        std::string index_file(dir + "/nodes.idx");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open nodes index file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        node_index.dump_as_list(fd);
        close(fd);
    }

    {
        std::string index_file(dir + "/ways.idx");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open ways index file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        way_index.dump_as_list(fd);
        close(fd);
    }

    {
        std::string index_file(dir + "/relations.idx");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open relations index file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        relation_index.dump_as_list(fd);
        close(fd);
    }

    {
        map_node2way.sort();
        std::string index_file(dir + "/node2way.map");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open node->way map file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        map_node2way.dump_as_list(fd);
        close(fd);
    }

    {
        map_node2relation.sort();
        std::string index_file(dir + "/node2rel.map");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open node->rel map file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        map_node2relation.dump_as_list(fd);
        close(fd);
    }

    {
        map_way2relation.sort();
        std::string index_file(dir + "/way2rel.map");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open way->rel map file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        map_way2relation.dump_as_list(fd);
        close(fd);
    }

    {
        map_relation2relation.sort();
        std::string index_file(dir + "/rel2rel.map");
        int fd = ::open(index_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (fd < 0) {
            std::cerr << "Can't open rel->rel map file '" << index_file << "': " << strerror(errno) << "\n";
            exit(2);
        }
        map_relation2relation.dump_as_list(fd);
        close(fd);
    }

    google::protobuf::ShutdownProtobufLibrary();
}
Exemple #22
0
void IOPolly::obsFromTextFile (std::string filePath, int angle_unit_type)
{
  // The input file
  std::ifstream data_file (filePath.c_str());

  // testa a abertura do ficheiro
  if (!data_file.is_open()) 
    {
      std::cerr << "Error: Could not open " << filePath << "\n";
      exit (8); //faz parte da cstdlib
    }

  std::string current_line; // alberga cada linha do ficheiro
  
  double horizontal_dir, vertical_dir; // alberga os valores angulares convertidos para rad
  SIUnits *ang_conv = new SIUnits(); // responsavel pelas conversoes


  while(!data_file.eof())
    {
      std::getline(data_file, current_line); // recolhe a linha
      
      if (!current_line.empty()) // se n leu uma linha em branco
	{

	  std::vector<std::string> elements;  // linha nos seus elementos
	  
	  // faz o split ah string para elements
	  std::istringstream iss(current_line);	  
	  std::copy(std::istream_iterator<std::string>(iss),
		    std::istream_iterator<std::string>(),
		    std::back_inserter<std::vector<std::string> >(elements));


	  if(elements.size() == 2)
	    {
	      //cria uma estacao
	      addStation(TCStations->getEnzPoint(elements[0]), 
			 std::atof(elements[1].c_str()));
	    }
	  else if(elements.size() == 5)
	    {
	      //cria um reading
	      
	      switch(angle_unit_type) // conversao dos angulos
		{
		case 1:
		  horizontal_dir = std::atof(elements[1].c_str()); 
		  vertical_dir = std::atof(elements[2].c_str());
		  break;
		case 2:
		  horizontal_dir = ang_conv->degree2rad (std::atof(elements[1].c_str())); 
		  vertical_dir = ang_conv->degree2rad (std::atof(elements[2].c_str()));
		  break;
		case 3:
		  horizontal_dir = ang_conv->gon2rad (std::atof(elements[1].c_str())); 
		  vertical_dir = ang_conv->gon2rad (std::atof(elements[2].c_str()));
		  break;
		}
	      
	      addReading((*(--(obs->end()))).from,
			 TCStations->getEnzPoint(elements[0]), horizontal_dir, 
			 vertical_dir, std::atof(elements[3].c_str()),
			 std::atof(elements[4].c_str()));
	    
	      
	    }

	}       
    }

  delete ang_conv;

  data_file.close();
}
Exemple #23
0
//
// generate
//
int CUTS_Dmac_File_Vertical_Generator::
generate (ACE_CString & db_file, int round)
{
  ifstream data_file (db_file.c_str ());
  this->row_count_ = 0;

  if (data_file.is_open())
  {
    CUTS_DMAC_UTILS::sequence_details word_index;
    vertical_list_t vertical_list;
    std::set <std::string> word_list;
    std::set <std::string>::iterator it1;


    std::string delim (this->delims_.c_str ());
    int count = 1;

    // Read line by line and tokenize
    while (data_file.good ())
    {
      std::string row;
      getline (data_file, row);

      CUTS_Dmac_Vertical_Format * format =
        new CUTS_Dmac_Vertical_Format ();

      this->tokenize (row, word_list, delim, format);
      format->tid (count);
      vertical_list.push_back (format);
      count++;
    }
    this->row_count_ = count - 1;

    int number = 1;

    // print the vertical list to the file
    for (it1 = word_list.begin (); it1 != word_list.end (); it1++)
    {
      word_index.insert (std::pair <std::string, int> (*it1, number));
      number++;
    }

    std::stringstream output_file;
    std::ofstream output;

    output_file << round << ".data";
    output.open (output_file.str ().c_str ());

    v_iter it2;
    for (it2 = vertical_list.begin (); it2 != vertical_list.end (); it2++)
    {
      ((CUTS_Dmac_Vertical_Format *)(*it2))->populate (word_index);
      ((CUTS_Dmac_Vertical_Format *)(*it2))->print_row_words (output);
    }
    output.close ();
    data_file.close ();

    return 1;
  }
  else
  {
    ACE_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("%T (%t) - %M - failed to open %s\n"),
                       db_file.c_str ()),
                       -1);
  }
}
Exemple #24
0
int main(int argc, char *argv[]) {
  namespace po=boost::program_options;
  po::options_description desc("Well-mixed SIR with demographics.");
  int64_t individual_cnt=100000;
  int64_t infected_cnt=individual_cnt*0.1;
  int64_t recovered_cnt=individual_cnt*0.8;

  int run_cnt=1;
  size_t rand_seed=1;
  // Time is in years.
  std::vector<Parameter> parameters;
  parameters.emplace_back(Parameter{SIRParam::Beta0, "beta0", 400,
    "main infection rate"});
  parameters.emplace_back(Parameter{SIRParam::Beta1, "beta1", 0.6,
    "seasonality ratio"});
  parameters.emplace_back(Parameter{SIRParam::SeasonalPhase, "phase", 0,
    "seasonality phase start between (0,1]"});
  parameters.emplace_back(Parameter{SIRParam::Gamma, "gamma", 365/14.0,
    "recovery rate"});
  parameters.emplace_back(Parameter{SIRParam::Birth, "birth", 1/70.0,
    "crude rate, before multiplying by number of individuals"});
  parameters.emplace_back(Parameter{SIRParam::Mu, "mu", 1/70.0,
    "death rate"});
  double end_time=30.0;
  bool exacttraj=true;
  bool exactinfect=false;
  int thread_cnt=1;
  std::string log_level;
  std::string data_file("sirexp.h5");
  bool save_file=false;
  std::string translation_file;
  bool test=false;

  desc.add_options()
    ("help", "show help message")
    ("threadcnt,j",
      po::value<int>(&thread_cnt)->default_value(thread_cnt),
      "number of threads")
    ("runcnt",
      po::value<int>(&run_cnt)->default_value(run_cnt),
      "number of runs")
    ("size,s",
      po::value<int64_t>(&individual_cnt)->default_value(individual_cnt),
      "size of the population")
    ("infected,i",
      po::value<int64_t>(&infected_cnt),
      "number of infected")
    ("recovered,r",
      po::value<int64_t>(&recovered_cnt),
      "number of recovered")
    ("seed",
      po::value<size_t>(&rand_seed)->default_value(rand_seed),
      "seed for random number generator")
    ("endtime",
      po::value<double>(&end_time)->default_value(end_time),
      "how many years to run")
    ("exacttraj",
      po::value<bool>(&exacttraj)->default_value(exacttraj),
      "save trajectory only when it changes by a certain amount")
    ("exactinfect",
      po::value<bool>(&exactinfect)->default_value(exactinfect),
      "set true to use exact distribution for seasonal infection")
    ("datafile",
      po::value<std::string>(&data_file)->default_value(data_file),
      "Write to this data file.")
    ("save",
      po::value<bool>(&save_file)->default_value(save_file),
      "Add data to file instead of erasing it with new data.")
    ("loglevel", po::value<std::string>(&log_level)->default_value("info"),
      "Set the logging level to trace, debug, info, warning, error, or fatal.")
    ("translate",
      po::value<std::string>(&translation_file)->default_value(""),
      "write file relating place ids to internal ids")
    ("info", "show provenance of program")
    ;

  for (auto& p : parameters) {
    desc.add_options()(p.name.c_str(),
      po::value<double>(&p.value)->default_value(p.value),
      p.description.c_str());
  }

  po::variables_map vm;
  auto parsed_options=po::parse_command_line(argc, argv, desc);
  po::store(parsed_options, vm);
  po::notify(vm);

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return 0;
  }

  std::map<std::string,std::string> compile_info {
    {"VERSION", VERSION}, {"COMPILETIME", COMPILETIME},
    {"CONFIG", CFG}
  };
  if (vm.count("info")) {
    for (auto& kv : compile_info) {
      std::cout << kv.second << "\n\n";
    }
    return 0;
  }

  afidd::LogInit(log_level);

  if (test) {
    double tolerance=TestSeasonal(0.6);
    std::cout << "Seasonal tolerance " << tolerance << std::endl;
  }

  std::map<SIRParam,double*> params;
  for (auto& pm : parameters) {
    params[pm.kind]=&pm.value;
  }

  // Birthrate is not frequency-dependent. It scales differently
  // which creates a fixed point in the phase plane.
  (*params[SIRParam::Birth])*=individual_cnt;

  if (std::abs(*params[SIRParam::Beta1])>1) {
    std::cout << "beta1 should be fractional, between 0 and 1: beta1=" <<
      *params[SIRParam::Beta1] << std::endl;
    return -4;
  }

  if (vm.count("infected") and !vm.count("recovered") ||
      !vm.count("infected") and vm.count("recovered")) {
    std::cout << "You have so set the total and I and R, not just some of them."
      << std::endl;
    return -3;
  } else if (!vm.count("infected") && !vm.count("recovered")) {
    double b=*params[SIRParam::Beta0];
    double m=*params[SIRParam::Mu];
    double g=*params[SIRParam::Gamma];
    double B=*params[SIRParam::Birth];
    // Long-time averages for fixed forcing for ODE model.
    int64_t susceptible_start=std::floor((m+g)*individual_cnt/b);
    infected_cnt=std::floor(individual_cnt*(b-m-g)*m/(b*(m+g)));
    recovered_cnt=individual_cnt-(susceptible_start+infected_cnt);
  }

  int64_t susceptible_cnt=individual_cnt-(infected_cnt+recovered_cnt);
  assert(susceptible_cnt>0);
  if (susceptible_cnt<0) {
    BOOST_LOG_TRIVIAL(error)<<"Number of susceptibles is "<<susceptible_cnt;
    return -2;
  }
  std::vector<int64_t> sir_init{susceptible_cnt, infected_cnt, recovered_cnt};
  BOOST_LOG_TRIVIAL(info)<<"Starting with sir="<<sir_init[0]<<" "<<sir_init[1]
    <<" "<<sir_init[2];

  for (auto& showp : parameters) {
    BOOST_LOG_TRIVIAL(info)<<showp.name<<" "<<showp.value;
  }

  HDFFile file(data_file);
  if (!file.Open(!save_file)) {
    BOOST_LOG_TRIVIAL(error)<<"could not open output file: "<<data_file;
    return -1;
  }
  file.WriteExecutableData(compile_info, parsed_options, sir_init);

  auto runnable=[=](RandGen& rng, size_t single_seed, size_t idx)->void {
    std::shared_ptr<TrajectoryObserver> observer=0;
    if (exacttraj) {
      observer=std::make_shared<TrajectorySave>();
    } else {
      observer=std::make_shared<PercentTrajectorySave>();
    }

    SIR_run(end_time, sir_init, parameters, *observer, rng, exactinfect);
    file.SaveTrajectory(parameters, single_seed, idx, observer->Trajectory());
  };

  Ensemble<decltype(runnable)> ensemble(runnable, thread_cnt, run_cnt,
    rand_seed);
  ensemble.Run();
  BOOST_LOG_TRIVIAL(debug)<<"Finished running ensemble.";

  file.Close();

  return 0;
}
int main(const int argc, const char* const argv[]) {
  if (argc != 4) {
    std::cerr << err << "Exactly three arguments are needed, the data-file,\n"
     " the instance-directory, and the number of files.\n";
    return errcode_parameter;
  }

  const std::string data_filename = argv[1];
  std::ifstream data_file(data_filename.c_str());
  if (not data_file) {
    std::cerr << err << "Could not open data-file \"" << data_filename << "\".\n";
    return errcode_data;
  }
  const std::string dirname = argv[2];
  const std::string decisions_filename = dirname + "/decisions";
  std::ifstream decisions_file(decisions_filename.c_str());
  if (not decisions_file) {
    std::cerr << err << "Could not open decisions-file \"" << decisions_filename << "\".\n";
    return errcode_decisions_file;
  }
  count_type N;
  {std::stringstream read_number;
   read_number << argv[3];
   read_number >> N;
   if (not read_number) {
     std::cerr << err << "The third argument must be a natural number of appropriate size.\n";
    return errcode_N;
   }
  }

  typedef std::vector<indexvector_type> table_t;
  table_t T; T.reserve(N);
  for (count_type i = 0; i < N; ++i) {
    index_type number_decisions = 0;
    decisions_file >> number_decisions;
    if (not decisions_file) {
      std::cerr << err << "Reading error for number of decisions in \"" << decisions_filename << "\".\n";
      return errcode_number_decisions;
    }
    indexvector_type I(number_decisions);
    for (index_type j = 0; j < number_decisions; ++j) {
      decisions_file >> I[j];
      if (not decisions_file) {
        std::cerr << err << "Reading error in \"" << decisions_filename << "\".\n";
        return errcode_reading_decisions;
      }
    }
    T.push_back(I);
  }
  assert(T.size() == N);

  data_file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
  for (count_type counter = 1; counter <= N; ++counter) {

    count_type running_number;
    data_file >> running_number;
    count_type file_number;
    data_file >> file_number;
    index_type number_assignments;
    data_file >> number_assignments;
    data_file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    if (not data_file) {
      std::cerr << err << "Reading error in \"" << data_filename << "\".\n";
      return errcode_reading_data;
    }
    if (running_number != counter) {
      std::cerr << err << "A non-consecutive running-number " << running_number << " in \"" << data_filename << "\".\n";
      return errcode_running_number;
    }
    if (file_number == 0) {
      std::cerr << err << "A file-index of 0 in \"" << data_filename << "\".\n";
      return errcode_file_number_0;
    }
    if (file_number > N) {
      std::cerr << err << "A file-index " << file_number << " in \""
        << data_filename << "\", which is greater than the parameter " << N
        << ".\n";
      return errcode_file_number_N;
    }

    std::stringstream pa_name;
    pa_name << dirname << "/" << file_number;
    std::ifstream pa(pa_name.str().c_str());
    pa.ignore(std::numeric_limits<std::streamsize>::max(),' ');
    literalvector_type P(number_assignments);
    for (index_type i = 0; i < number_assignments; ++i) pa >> P[i];
    if (not pa) {
      std::cerr << err << "Reading error for \"" << pa_name << "\".\n";
      return errcode_reading_pa;
    }
    const indexvector_type& I = T[file_number-1];
    const index_type number_decisions = I.size();
    for (index_type i = 0; i < number_decisions; ++i) {
      const index_type j = I[i];
      if (j >= number_assignments) {
        std::cerr << err << "For running number " << running_number <<
          " in file " << data_filename << "\n the index " << j <<
          " is more than the number " << number_assignments <<
          " of assignments.\n";
        return errcode_index;
      }
      std::cout << P[j];
      if (i < number_decisions-1) std::cout << " ";
    }
    std::cout << "\n";
  }
}
Exemple #26
0
int main(int argc, char** argv)
{
  if (argc < 5) {
    std::cout << "Usage: patt_rec [data_matrix.txt] [pattern_matrix.txt] [mode 0: serial, 1: parallel] [number of threads]" << std::endl;
    return 1;
  }

  int data_n_rows, data_n_cols;

  std::ifstream data_file(argv[1]);
  if (!data_file) error_exit("Data file not found!");
  data_file >> data_n_rows >> data_n_cols;

  int data[data_n_rows][data_n_cols];

  for (int i = 0; i < data_n_rows; ++i)
  {
    for (int j = 0; j < data_n_cols; ++j)
    {
      data_file >> data[i][j];
    }
  }

  int pattern_n_rows, pattern_n_cols;

  std::ifstream pattern_file(argv[2]);
  if (!pattern_file) error_exit("Pattern file not found");
  pattern_file >> pattern_n_rows >> pattern_n_cols;

  int pattern[pattern_n_rows][pattern_n_cols];

  std::vector<int> pattern_elements;

  for (int i = 0; i < pattern_n_rows; ++i)
  {
    for (int j = 0; j < pattern_n_cols; ++j)
    {
      pattern_file >> pattern[i][j];
      pattern_elements.push_back(pattern[i][j]);
    }
  }

  std::nth_element(pattern_elements.begin(),
                   pattern_elements.begin() + pattern_elements.size()/2,
                   pattern_elements.end());
  const int median_pattern = pattern_elements[pattern_elements.size()/2];


  std::vector<std::tuple<int, int, double>> matches;

  double size_of_pattern_matrix = (double) pattern_n_cols * pattern_n_rows; //Evil C way.

  bool is_parallel {atoi(argv[3]) == 1}; //Absolutly horribly... but works. Should be checked with a stream.

  double time_start = omp_get_wtime();
  int num_of_threads = atoi(argv[4]);
  int chunk_size = data_n_rows / (num_of_threads * 10);
  #pragma omp parallel for num_threads(num_of_threads) if(is_parallel) schedule(guided, chunk_size)
  for (int i = 0; i < data_n_rows - pattern_n_rows; ++i) {
    std::cout << omp_get_thread_num() << std::endl;
    for (int j = 0; j < data_n_cols - pattern_n_cols; ++j) {
      double current_goodness = 0;
      std::vector<int>submatrix_elements;

      for (int m_i = 0; m_i < pattern_n_rows; ++m_i) {
        for (int m_j = 0; m_j < pattern_n_cols; ++m_j) {
          int diff = absolute_value(data[i+m_i][j+m_j] - pattern[m_i][m_j]);
          current_goodness += (double)diff;
          submatrix_elements.push_back(data[i+m_i][j+m_j]);
          if (diff > 9)
            goto BREAK_OUUUUUUUT;
        }
      }

      std::nth_element(submatrix_elements.begin(),
                       submatrix_elements.begin() + submatrix_elements.size()/2,
                       submatrix_elements.end());

      if (absolute_value(submatrix_elements[submatrix_elements.size()/2] - median_pattern) > 2)
        goto BREAK_OUUUUUUUT;

      current_goodness /= size_of_pattern_matrix;

      #pragma omp critical
      matches.push_back(std::make_tuple(i, j, current_goodness));


BREAK_OUUUUUUUT : ;
    }
  }

  double time_end = omp_get_wtime();

  std::cout << "Took " << (time_end - time_start) << " seconds" << std::endl;

  std::cout << "Matches (row, col, goodness)" << std::endl;
  double min_goodness {std::numeric_limits<double>::max()}, max_goodness {std::numeric_limits<double>::min()}, average_goodness {0};
  for (auto p : matches) {
    std::cout << "(" << std::get<0>(p) << ", " << std::get<1>(p) << ", " << std::get<2>(p) << ")" << std::endl;
    double current_goodness = std::get<2>(p);
    if (current_goodness < min_goodness) min_goodness = current_goodness;
    if (current_goodness > max_goodness) max_goodness = current_goodness;
    average_goodness += current_goodness;
  }

  std::cout << "Min goodness: " << min_goodness << std::endl
            << "Max goodness: " << max_goodness << std::endl
            << "Average goodness: " << average_goodness / matches.size() << std::endl;

  return 0;
}
Exemple #27
0
int main(int argc, char* argv[]) {
	if(argc<2) {
		std::cout << "Usage: " << argv[0] << "data location" << std::endl;
	}

	// Things to initialize to parse the file.	
	std::string line;
	std::ifstream data_file (argv[1]);

	// Just to count the number of lines.
	std::ifstream data_file_count (argv[1]);
	int v_count = std::count(std::istreambuf_iterator<char>(data_file_count), std::istreambuf_iterator<char>(), '\n');
	data_file_count.close();

	int i=0;
	std::vector<std::string> file_by_line[v_count];
	std::string names[v_count];
        std::vector<std::string> temp;

	printf("%d\n",v_count);

	// Store names, load up the split vectors.
	if(data_file.is_open()) {
		while(getline(data_file,line)) {
			
			temp = split(line,' ');
			names[i] = temp[0];
			temp.erase(temp.begin());
			file_by_line[i] = temp;
			i++;
		}
		data_file.close();
	}

	// Finally, build the adjacency matrix.
	int adj_matrix[v_count*v_count];
	for(int i=0; i<v_count; i++) {
		for(int j=0; j<v_count; j++) {
			adj_matrix[i*v_count+j] = atoi( file_by_line[i][j].c_str() );
                        std::cout << adj_matrix[i*v_count+j] << " ";
		}
		std::cout << std::endl;
	}

	std::cout << "--------------------" << std::endl;

	int dist[v_count*v_count];
	for(int i=0; i<v_count; i++) {
		for(int j=0; j<v_count; j++) {
			if(adj_matrix[i*v_count+j] == 0 && i!=j) {
				dist[i*v_count+j] = 1000;
			}
			else {
				dist[i*v_count+j] = adj_matrix[i*v_count+j];
			}
		}
	}

	do_floyd_warshall(v_count, dist);

	for(int i=0; i<v_count; i++) {
		for(int j=0; j<v_count; j++) {
			std::cout << dist[i*v_count+j] << " ";
		}
		std::cout << std::endl;
	}

	return 0;
}