int main(int, char* [])
{
  using boost::format;
  using boost::str;

#if !defined(BOOST_NO_STD_WSTRING) && !defined(BOOST_NO_STD_WSTREAMBUF)
  using boost::wformat;
  wformat wfmter(L"%%##%%##%%1 %1%00");
  if(str( wfmter % L"Escaped OK" ) != L"%##%##%1 Escaped OK00")
      BOOST_ERROR("Basic w-parsing Failed");
  if(str( wformat(L"%%##%#x ##%%1 %s00") % 20 % L"Escaped OK" ) != L"%##0x14 ##%1 Escaped OK00")
      BOOST_ERROR("Basic wp-parsing Failed") ;

  // testcase for https://svn.boost.org/trac10/ticket/7379 (for valgrind)
  wformat wfmt(L"%1$.1f");
  std::wstring ws = str(wfmt % 123.45f);
  BOOST_TEST_EQ(ws.compare(L"123.4"), 0);
  wformat wfmt2(L"%1$.0f %%");
  std::wstring ws2 = (wfmt2 % 123.45f).str();
  BOOST_TEST_EQ(ws2.compare(L"123 %"), 0);

#endif // wformat tests

  return boost::report_errors();
}
void write_to_dimacs( const circuit& circ, const std::string& filename )
{
  using boost::format;
  using boost::str;

  std::vector<unsigned> line_to_var( circ.lines() );
  boost::iota( line_to_var, 1u );

  auto next_var = circ.lines() + 1u;

  std::ofstream os( filename.c_str() );

  for ( const auto& g : circ )
  {
    assert( is_toffoli( g ) );
    const auto target = g.targets().front();

    switch ( g.controls().size() )
    {
    case 0u:
      os << format( "x%d %d 0" ) % line_to_var[target] % next_var << std::endl;
      line_to_var[target] = next_var++;
      break;

    case 1u:
      {
        const auto c = g.controls().front();
        os << format( "x%s%d %d -%d 0" ) % ( c.polarity() ? "" : "-" ) % line_to_var[c.line()] % line_to_var[target] % next_var << std::endl;
        line_to_var[target] = next_var++;
      }
      break;

    default:
      {
        std::string all;
        for ( const auto& c : g.controls() )
        {
          os << format( "%s%d -%d 0" ) % ( c.polarity() ? "" : "-" ) % line_to_var[c.line()] % next_var << std::endl;
          all += str( format( "%s%d " ) % ( c.polarity() ? "-" : "" ) % line_to_var[c.line()] );
        }
        os << format( "%s%d 0" ) % all % next_var << std::endl;
        os << format( "x%d %d -%d 0" ) % next_var % line_to_var[target] % ( next_var + 1 ) << std::endl;
        line_to_var[target] = next_var + 1;
        next_var += 2u;
      }
      break;
    }
  }

  std::string ors;
  for ( auto i = 0u; i < circ.lines(); ++i )
  {
    os << format( "x-%d %d %d 0" ) % ( next_var + i ) % ( i + 1 ) % line_to_var[i] << std::endl;
    ors += str( format( "%d " ) % ( next_var + i ) );
  }
  os << ors << "0" << std::endl;

  os.close();
}
Example #3
0
void writeData()
{
    std::string defs;
    fs::path defs_path = out_dir / (out_file_prepend + ".defs");

    print(format("write directory   = %s\n")     % out_dir);
    print(format("write file prefix = \"%s\"\n") % out_file_prepend);

    if(!dry_run) fs::create_directories(out_dir);

    for(int i = 0; i < packer.numSheets(); i++)
    {
        Sheet *s         = packer.getSheet(i);
        fs::path dst     = out_dir / str(format("%s%03d.%s") % out_file_prepend % i % "png");

        print(format("writing sheet to %s\n") % dst);
        s->saveImage(dst);
        defs += getSheetDefinitions(dst, s);
    }

    print(format("writing definitions to %s\n") % defs_path);
    if(!dry_run)
    {
        fs::ofstream out(defs_path);
        out << defs;

        if(out.fail())
            print(format("failed to write %s\n") % defs_path, VERBOSE);
    }
}
Example #4
0
std::string getSheetDefinitions(const fs::path &path, Sheet *s)
{
    std::string out;

    for(size_t i = 0; i < s->images.size(); i++)
    {
        Image *img = s->images[i];

        for(size_t j = 0; j < img->names.size(); j++)
        {
            out += str(format("%s\n") % img->names[j]);
            out += str(format("%s\n") % path.string());
            out += str(format("%d %d %d %d\n") % (img->sheet_x + img->source_x_offset) % (img->sheet_y + img->source_y_offset) % img->source_width % img->source_height);
            out += str(format("%f %f %f %f\n") % img->s0 % img->s1 % img->t0 % img->t1);
        }
    }

    return out;
}
Example #5
0
    std::string Version::VersionString()
    {
        using boost::format;
        using boost::str;

        std::string version = str(format("%d.%d.%d") % API_MAJOR % API_MINOR % API_PATCH);
#ifndef NDEBUG
        version += "-DEBUG";
#endif  // !NDEBUG
        return version;
    }
Example #6
0
FileWriter::FileWriter(std::wstring fileName, const std::shared_ptr<concurrent_queue<std::string>>& queue) :
    queue_(queue),
    exit_(false)
{
    file_ = CreateFile(fileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (file_ == INVALID_HANDLE_VALUE)
    {
        throw new exception(str(format("Could not create file %1%") % string(fileName.begin(), fileName.end())).c_str());
    }

    thread_ = unique_ptr<thread>(new thread(&FileWriter::ThreadFunc, this));
}
FloatVectorDataPtr ImageCompositeOp::getChannelData( ImagePrimitive * image, const std::string &channelName, bool mustExist )
{
	assert( image );

	PrimitiveVariableMap::iterator it = image->variables.find( channelName );
	if( it==image->variables.end() )
	{
		if ( mustExist )
		{
			throw Exception( str( format( "ImageCompositeOp: Channel \"%s\" does not exist." ) % channelName ) );
		}
		else
		{
			return 0;
		}
	}

	if( it->second.interpolation!=PrimitiveVariable::Vertex &&
		it->second.interpolation!=PrimitiveVariable::Varying &&
		it->second.interpolation!=PrimitiveVariable::FaceVarying )
	{
		throw Exception( str( format( "ImageCompositeOp: Primitive variable \"%s\" has inappropriate interpolation." ) % channelName ) );
	}

	if( !it->second.data )
	{
		throw Exception( str( format( "ImageCompositeOp: Primitive variable \"%s\" has no data." ) % channelName ) );
	}

	ChannelConverter converter( channelName );

	return despatchTypedData<
			ChannelConverter,
			TypeTraits::IsNumericVectorTypedData,
			ChannelConverter::ErrorHandler
		>( it->second.data.get(), converter );
}
void SslConnector::connected(const Socket&) {
    connector = 0;
    aio = AsynchIO::create(socket,
                           boost::bind(&SslConnector::readbuff, this, _1, _2),
                           boost::bind(&SslConnector::eof, this, _1),
                           boost::bind(&SslConnector::disconnected, this, _1),
                           boost::bind(&SslConnector::socketClosed, this, _1, _2),
                           0, // nobuffs
                           boost::bind(&SslConnector::writebuff, this, _1));

    aio->createBuffers(maxFrameSize);
    identifier = str(format("[%1%]") % socket.getFullAddress());
    ProtocolInitiation init(version);
    writeDataBlock(init);
    aio->start(poller);
}
Example #9
0
void utils::thumb_lightmap(Params params) {
  illum::GrayLightfield lightmap(params.alt_spacing);
  if(params.lightmap_dir.empty())
    throw std::runtime_error("no lightmap directory specified");
  log("LOADING lightmap ...");
  lightmap.load(params.lightmap_dir);
  for(double alt = 0; alt < 1000; alt += params.alt_spacing) {
    try {
      Mat raw_avg;
      lightmap.getAverage(raw_avg, alt);
      // now do a quick-and-dirty conversion to color
      Mat bgr_avg = demosaic_thumb_lq(raw_avg, params.bayer_pattern);
      // now convert to 8u
      bgr_avg *= 255.0 / 65535.0;
      fs::path p(params.lightmap_dir);
      p /= str(boost::format("thumb_slice_%.02f.jpg") % alt);
      log("SAVING thumbnail %s") % p.string();
      imwrite(p.string(), bgr_avg);
    } catch(std::exception const &e) {
      log_error("ERROR thumbnailing: %s") % e.what();
    }
  }
}
Example #10
0
void LinkRegistry::notifyConnection(const std::string& key, amqp_0_10::Connection* c)
{
    // find a link that is attempting to connect to the remote, and
    // create a mapping from connection id to link
    QPID_LOG(debug, "LinkRegistry::notifyConnection(); key=" << key );
    std::string host;
    Link::shared_ptr link;
    {
        Mutex::ScopedLock locker(lock);
        LinkMap::iterator l = pendingLinks.find(key);
        if (l != pendingLinks.end()) {
            link = l->second;
            pendingLinks.erase(l);
            connections[key] = link->getName();
            QPID_LOG(debug, "LinkRegistry:: found pending =" << link->getName());
        }
    }

    if (link) {
        link->established(c);
        c->setUserId(str(format("%1%@%2%") % link->getUsername() % realm));
    }
}
Example #11
0
/**
 * Display the modal dialog and start the download.
 *
 * This dialog is modal; it will block until the download is finished
 * or fails.
 *
 * @param hinst The app instance handle.
 * @param parent The parent window handle.
 * @return @c true If the download was successful (the track is now
 *         available) or @c false if the download failed.
 */
bool TrackDownloadDialog::ShowModal(HINSTANCE hinst, HWND parent)
{
    bufSize = 0;
    bufTotal = 0;
    cancel = false;

    // Ask to download the track.
    std::string msg =
        str(format(_("Would you like to download the track \"%s\" now?")) % name);
    std::ostringstream oss;
    if (MessageBoxW(parent, Str::UW(msg.c_str()), Str::UW(_("Track Download")), MB_YESNO) == IDNO) {
        return false;
    }

    boost::thread thread(boost::bind(&TrackDownloadDialog::ThreadProc, this));

    DWORD dlgRetv = DialogBoxParamW(hinst, MAKEINTRESOURCEW(IDD_DOWNLOAD_PROGRESS),
                                    parent, DlgFunc, reinterpret_cast<LPARAM>(this));
    if (dlgRetv == IDCANCEL) cancel = true;

    thread.join();

    return !cancel;
}
Example #12
0
void parseCmdLine(int argc, char *argv[])
{
    opts::options_description desc("Options");

    desc.add_options()
        ("help,h", "Print this message.\n")

        ("output,o", 
         opts::value<std::string>(&cmd_output)->required(),
         "Path to prepend to all files written.\n")

        ("input,i",
         opts::value< std::vector<std::string> >(&input_paths),
         "Path a files or folder to pack. Multiple inputs can be specified as positional arguments.\n")

        ("stdin",
         opts::bool_switch(&read_stdin),
         "Read input paths from the standard input. Any paths read are appended to those specified by --input.\n")

        ("recursive,r",
         opts::bool_switch(&recursive),
         "Recurse into any directories specified.\n")

        ("image-size,s",
         opts::value<std::string>(&cmd_img_size),
         str(format("Size of the packed images. This is a maximum size if --compact is specified and a minimum size if --power-of-two is specified. Default size is set to %s. Example: --image-size 1024x1024\n") % cmd_img_size).c_str())

        ("power-of-two,p",
         opts::bool_switch(&power_of_two),
         "Keep sheet sizes a power of two. If a dimension in --image-size is not a power of two it is rounded up to the nearst power.\n")

        ("extrude,e",
         opts::value<int>(&extrude),
         "Number of pixels to extrude the edges of source images by. Example: --extrude 1. default = 0.\n")

        ("compact,c",
         opts::bool_switch(&compact),
         "Create sheets smaller than --image-size if possible.\n")

        ("tex-coord-origin,t",
         opts::value<std::string>(&cmd_tex_coord_origin),
         "Origin to use when computing sprite texture coordinates. Either bottom-left or top-left.\n")

        ("dry-run,d",
         opts::bool_switch(&dry_run),
         "Don't write any files.\n")

        ("no-cache",
         opts::bool_switch(&no_cache),
         "Disables caching of image data and causes images to be loaded and unloaded on demand. Useful when packing more images than can fit into memory.\n")

        ("silent,S",
         opts::bool_switch(&silent),
         "Disables printing.\n")

        ("verbose,v",
         opts::bool_switch(&verbose),
         "Print detailed information.\n")
    ;

    opts::positional_options_description p;
    p.add("input", -1);

    opts::variables_map vars;

    try
    {
        opts::store(opts::command_line_parser(argc, argv).options(desc).positional(p).run(), vars);

        if(vars.count("help"))
        {
            print(cmd_help);
            print(format("%1%") % desc);
            exit(EXIT_SUCCESS);
        }

        opts::notify(vars);
    }
    catch(const opts::error &e)
    {
        print(format("%1%\n\n") % e.what());
        print(cmd_help);
        fatal(format("%1%") % desc);
    }


    std::vector<std::string> strs;
    boost::split(strs, cmd_img_size, boost::is_any_of("x"));

    if(strs.size() != 2)
        fatal("error parsing image-size\n");

    try
    {
        cmd_sheet_width  = boost::lexical_cast<int>(strs[0]);
        cmd_sheet_height = boost::lexical_cast<int>(strs[1]);
    }
    catch(const boost::bad_lexical_cast&)
    {
        fatal("error parsing image-size\n");
    }

    if(cmd_tex_coord_origin == "bottom-left")
        tex_coord_origin = BOTTOM_LEFT;
    else if(cmd_tex_coord_origin == "top-left")
        tex_coord_origin = TOP_LEFT;
}
Example #13
0
DicomConfig::DicomConfig( const std::string &configFileName ):config_( new DcmQueryRetrieveConfig ) {
  if (config_->init( configFileName.c_str() )!=1) throw runtime_error( 
    str( format("error reading config file:%1%") % configFileName ) );
  readDBMap( config_, dbMap_ );
  maxPDU_ = config_->getMaxPDUSize();
}
int test_main(int, char* [])
{
    using namespace std;
    using boost::format;
    using boost::io::group;
    using boost::str;

    string s, s2;
    // special paddings 
    s = str( format("[%=6s] [%+6s] [%+6s] [% 6s] [%+6s]\n") 
                      % 123
                      % group(internal, setfill('W'), 234)
                      % group(internal, setfill('X'), -345)
                      % group(setfill('Y'), 456)
                      % group(setfill('Z'), -10 ) );

    if(s != "[  123 ] [+WW234] [-XX345] [YY 456] [ZZZ-10]\n" ) {
      cerr << s ;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    s = str( format("[% 6.8s] [% 8.6s] [% 7.7s]\n") 
                      % group(internal, setfill('x'), Rational(12345,54321))
                      % group(internal, setfill('x'), Rational(123,45))
                      % group(internal, setfill('x'), Rational(123,321))
             );
    if(s != (s2="[ 12345/5] [ xx123/4] [ 123/32]\n" )) {
        cerr << s << s2;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    s = str( format("[% 6.8s] [% 6.8s] [% 6.8s] [% 6.8s] [%6.8s]\n") 
                      % 1234567897
                      % group(setfill('x'), 12)
                      % group(internal, setfill('x'), 12)
                      % group(internal, setfill('x'), 1234567890)
                      % group(internal, setfill('x'), 123456) 
             );
    if(s != (s2="[ 1234567] [xxx 12] [ xxx12] [ 1234567] [123456]\n") ) {
        cerr << s << s2;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    s = str( format("[% 8.6s] [% 6.4s] [% 6.4s] [% 8.6s] [% 8.6s]\n")
                      % 1234567897
                      % group(setfill('x'), 12)
                      % group(internal, setfill('x'), 12)
                      % group(internal, setfill('x'), 1234567890)
                      % group(internal, setfill('x'), 12345) 
             );
    if(s != (s2="[   12345] [xxx 12] [ xxx12] [ xx12345] [ xx12345]\n") ) {
        cerr << s << s2;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    // nesting formats :
    s = str( format("%2$014x [%1%] %|2$05|\n") % (format("%05s / %s") % -18 % 7)
             %group(showbase, -100)
             );
    if( s != "0x0000ffffff9c [-0018 / 7] -0100\n" ){
      cerr << s ;
      BOOST_ERROR("nesting did not work");
    }

    // testcase for bug reported at 
    // http://lists.boost.org/boost-users/2006/05/19723.php
    format f("%40t%1%");
    int x = 0;
    f.bind_arg(1, x);
    f.clear();

    // testcase for bug reported at
    // http://lists.boost.org/boost-users/2005/11/15454.php
    std::string l_param;
    std::string l_str = (boost::format("here is an empty string: %1%") % l_param).str(); 

    // testcase for SourceForge bug #1506914
    std::string arg; // empty string  
    s = str(format("%=8s") % arg);

    return 0;
}
Example #15
0
int handle_request(const char* func_name, struct soap* soap,
        soap_request_t* soap_req, response_container_t* response_container,
        response_t** soap_resp)
{

    storm::logging_traits<request_t> logger;

    using boost::format;
    using boost::str;

    boost::posix_time::ptime const start_time =
            boost::posix_time::microsec_clock::local_time();

    try {

        request_t request(soap, soap_req);

        logger.log_request(func_name, request);

        bool const request_is_blacklisted =
                storm::Authorization::checkBlacklist(request.getSoapRequest());

        if (request_is_blacklisted) {

            *soap_resp = storm::build_error_message_response<response_t>(soap,
                    SRM_USCOREAUTHORIZATION_USCOREFAILURE,
                    "Request authorization error: user is blacklisted.");

            storm::request::register_request_error<request_t>(func_name,
                    SRM_USCOREAUTHORIZATION_USCOREFAILURE, start_time,
                    "Request authorization error: user is blacklisted.\n");

            return SOAP_OK;
        }

        // Request is authorized, handle it
        int const soap_return_value = request.performXmlRpcCall(response_container);

        storm::MonitoringHelper::registerOperation(
                request.getStartTime(),
                soap_return_value,
                request_t::MONITOR_NAME,
                request.getStatus()
        );

        storm::log_request_outcome(func_name, request);

        return soap_return_value;

    } catch (storm::invalid_request& e) {

        *soap_resp = storm::build_error_message_response<response_t>(soap,
                SRM_USCOREINVALID_USCOREREQUEST, e.what());

        storm::request::register_request_error<request_t>(func_name,
                SRM_USCOREINVALID_USCOREREQUEST, start_time,
                str(format("%s\n") % e.what()));

        return SOAP_OK;

    } catch (storm::authorization_error& e) {

        *soap_resp = storm::build_error_message_response<response_t>(soap,
                SRM_USCOREFAILURE, e.what());

        storm::request::register_request_error<request_t>(func_name, SRM_USCOREFAILURE,
                start_time,
                str(format("Error authorizing request: %s\n") % e.what()));

        return SOAP_OK;

    }
}
Example #16
0
int main(int argc, char **argv)
{
    std::string environment_uri;
    std::string robot_name;
    std::string plugin_name;
    size_t num_trials;
    bool self = false;
    bool profile = false;

    // Parse arguments.
    po::options_description desc("Profile OpenRAVE's memory usage.");
    desc.add_options()
        ("num-samples", po::value<size_t>(&num_trials)->default_value(10000),
            "number of samples to run")
        ("self", po::value<bool>(&self)->zero_tokens(),
            "run self-collision checks")
        ("profile", po::value<bool>(&profile)->zero_tokens(),
            "remove objects from environment")
        ("environment_uri",
            po::value<std::string>(&environment_uri)->required(),
            "number of samples to run")
        ("robot", po::value<std::string>(&robot_name)->required(),
            "robot_name")
        ("collision_checker",
            po::value<std::string>(&plugin_name)->required(),
            "collision checker name")
        ("help",
            "print usage information")
        ;

    po::positional_options_description pd;
    pd.add("environment_uri", 1);
    pd.add("robot", 1);
    pd.add("collision_checker", 1);

    po::variables_map vm;
    po::store(
        po::command_line_parser(argc, argv)
            .options(desc)
            .positional(pd).run(),
        vm
    );
    po::notify(vm);    

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

    // Create the OpenRAVE environment.
    RaveInitialize(true);

    EnvironmentBasePtr const env = RaveCreateEnvironment();
    CollisionCheckerBasePtr const collision_checker
            = RaveCreateCollisionChecker(env, plugin_name);
    env->SetCollisionChecker(collision_checker);

    env->StopSimulation();

    // "/usr/share/openrave-0.9/data/wamtest1.env.xml"
    env->Load(environment_uri);
    KinBodyPtr const body = env->GetKinBody(robot_name);

    // Generate random configuations.
    std::vector<OpenRAVE::dReal> lower;
    std::vector<OpenRAVE::dReal> upper;
    body->GetDOFLimits(lower, upper);
	std::vector<std::vector<double> > data;
    data = benchmarks::DataUtils::GenerateRandomConfigurations(
            num_trials, lower, upper);

    //
    RAVELOG_INFO("Running %d collision checks.\n", num_trials);

    boost::timer const timer;
    if (profile) {
        std::string const prof_name = str(
                format("CheckCollision.%s.prof") %  plugin_name);
        RAVELOG_INFO("Writing gperftools information to '%s'.\n",
            prof_name.c_str()
        );

        ProfilerStart(prof_name.c_str());
    }

    size_t num_collision = 0;
    for (size_t i = 0; i < num_trials; ++i) {
        body->SetDOFValues(data[i]);

        bool is_collision;
        if (self) {
            is_collision = body->CheckSelfCollision();
        } else {
            is_collision = env->CheckCollision(body);
        }
        num_collision += !!is_collision;
    }

    if (profile) {
        ProfilerStop();
    }

    double const duration = timer.elapsed();
    RAVELOG_INFO(
        "Ran %d collision checks (%d in collision) in %f seconds (%f checks per second).\n",
        num_trials, num_collision, duration, num_trials / duration
    );


    return 0;
}
Example #17
0
void FBasisSetLibraryImpl::ImportMolproLib(std::string const &FileName, std::ostream *pxout)
{
   // how this files look:
   //   Note: Lines with * are comments.
      // He s STO-3G STO3G : 3 1 1.3
      // STO-3G
      // 6.3624214 1.158923 0.31364979 0.15432897 0.53532814 0.44463454
      // Li s STO-3G STO3G : 6 2 1.3 4.6
      // STO-3G
      // 16.119575 2.9362007 0.7946505 0.6362897 0.1478601 0.0480887 0.15432897
      // 0.53532814 0.44463454 -0.09996723 0.39951283 0.70011547
      // Li p STO-3G STO3G : 3 1 1.3
      // STO-3G
      // 0.6362897 0.1478601 0.0480887 0.15591627 0.60768372 0.39195739
      // B s cc-pVDZ VDZ : 9 3 1.9 1.9 9.9
      // cc-pVDZ
      // 4570 685.9 156.5 44.47 14.48 5.131 1.898 0.3329 0.1043 0.000696
      // 0.005353 0.027134 0.10138 0.272055 0.448403 0.290123 0.014322 -0.003486
      // -0.000139 -0.001097 -0.005444 -0.021916 -0.059751 -0.138732 -0.131482
      // 0.539526 0.580774 1
   // interpretation: First Line:
   //      ElementName OrbitalType N*[AlternativeNameI] :
   //            #PrimOrbitals #OrbitalsTheyAreContractedTo N*[ContractFrom.ContractTo]
   //      Any string, usually reference to be cited for the basis set
   //      M*[PrimitiveOrbitalExponents] L*[PrimitiveOrbitalCoefficients]
   //   for each contraction contraction length coefficients are supplied.
   // and data sets like this are also seen:
      // H  P 6-311G2P :   2  0
      // G92 6-311G polarization
      //    .15000000D+01   .37500000D+00
      // H  P 6-311G3P :   3  0
      // G92 6-311G polarization
      //    .30000000D+01   .75000000D+00   .18750000D+00
      // H  S 6-31G** 6-31G* 6-31G :   4  1      1.3
      // G92 6-31G**
       // .18731137D+02   .28253944D+01   .64012169D+00   .16127776D+00   .33494604D-01
      // .23472695D+00   .81375733D+00
   // all/some primitive orbitals are probably left uncontracted. Therefore no
   // contraction coefficients are supplied for these (only exponents).

   // Also I originally tought that the names of the basis set after the first
   // one were alternative Names of the set (like cc-pVDZ = VDZ). This is
   // however not how it works, at least not in all cases: It seems that names
   // which are supplied actually mean that the currently described elements
   // have to be inserted into the basis sets of ALL names provided, which
   // may or may not be identical basis sets (for example, for the s and p
   // orbitals of the 931G basis set, also the starred names are listed, which
   // means that these basis sets share these orbitals, altough in general they
   // are different).

   // so.. let's begin the mess.
   // read the entire file into a stringstream object (we need to modify it).
   TArray<char>
      pFileContent;
   if (!LoadFileIntoMemory(pFileContent, FileName))
      throw std::runtime_error( "FBasisSetLibraryImpl: Failed to open file '"+FileName+"' for basis library import." );

   // okay, now this is very bad. This FORTRAN stuff (sometimes) denotes
   // exponents in scientific notation not as "23423e-3" but as "23423D-03". We
   // do a lame attempt to convert that. This might break in some situations.
   // FIXME: correct this somehow.
   for (uint i = 0; i < pFileContent.size() - 2; ++i) {
      if (pFileContent[i]=='D' &&
          (pFileContent[i+1]=='+' || pFileContent[i+1]=='-') &&
          pFileContent[i+2]=='0')
         pFileContent[i] = 'E';
   }

   FBasisNameSet
      AllBasisNames;
   std::stringstream
      str(&pFileContent[0], std::stringstream::in);
   // ^- NOTE: "in" means from stream, into local data, not
   // into stream (file naming convention)

   try {
      while(str.good())
      {
         // clear exception mask, now stream will not throw() when something
         // unexpected happens.
         str.exceptions(std::ios::goodbit);
         std::string
            s;
         std::getline( str, s );
         if (s.size() == 0 || s[0] == '*' || s[0] == '!')
            // empty or comment line, throw it away and go on with the next
            continue;
         if (!str.good()) // eof, bad etc.
            break;
         str.exceptions(std::ios::failbit);
         // ^- when something fails, throw an exception. this will happen
         // if the actual file format does not match the one I had in mind
         // when coding this.

         // expected format: ElementName[w]OrbitalType[w]AlternativeNames[w] :
         // using namespace std;
         // cout << "** read line: '" << s << "'" << endl;
         std::stringstream
            line(s, std::stringstream::in);
         line.exceptions(std::ios::badbit | std::ios::failbit);
         std::string
            Element, Type;
         line >> Element >> Type;
         if ( Type.size() != 1 )
            throw std::runtime_error( "Parsing error, cannot interpret orbital type '" + Type + "'" );

         int
            AngMom;
         std::vector<std::pair<int,int> >
            Cos;
         std::vector<double>
            Exps;
         char
            cAngMom = ::tolower(Type[0]);
         for (AngMom = 0; AngMom < 9; ++ AngMom)
            if (cAngMom == "spdfghikl"[AngMom])
               break;
         if (AngMom == 9)
            throw std::runtime_error((format("Failed to understand angular momentum '%s'.") % cAngMom).str());
//          std::cout << "Element " << Element << " Type " << Type << std::endl;

         FStringList
            BasisNames; // all names of basis sets in which the
                     // current entry is to be inserted.
         for (line >> s; s != ":"; line >> s) {
//             std::cout << "Alternative Name:" << s << std::endl;
            BasisNames.push_back( tolower(stripwhitespace(s)) );
            AllBasisNames.insert(stripwhitespace(s));
         }

         // expected format: #prim orbitals #contractions (#contr.)*[a.b]
         // denoting indices of begin and end of a contraction with the
         // following exponents/contraction coefficients.
         int
            nExp,
            nCo,
            nCoeff(0), // total number of contraction coefficients to read (in all contractions).
            nHighestExpInCo(0); // 1-based index.
         line >> nExp >> nCo;
//          std::cout << "#Prim " << nExp << " #Co " << nCo << std::endl;
         Cos.reserve(nCo);
         for (int i = 0; i < nCo; ++ i){
            std::pair<int,int>
               iCo;
            char Dot;
            line >> iCo.first >> Dot >> iCo.second;
            iCo.first -= 1; // convert to 0-based [begin,end).
            if (Dot != '.')
               throw std::runtime_error("GTO-Contraction read format error.");
//             std::cout << "  Co: #" << iCo.first << "-#" << iCo.second << std::endl;
            if (iCo.second <= iCo.first || iCo.second > nExp)
               throw std::runtime_error("GTO-Contraction logical error.");
            nCoeff += iCo.second - iCo.first;
            nHighestExpInCo = std::max(nHighestExpInCo, iCo.second);
            Cos.push_back(iCo);
         }

         std::string
            EntryComment;
         do{ // read name, maybe skip comments.
            getline(str, EntryComment);
         } while (EntryComment.size() != 0 && EntryComment[0] == '*');
         // cout << "Entry Comment: " << EntryComment << endl;

         // now read exponents and contraction coefficients;
         // (this will break if comments are present in between)
         Exps.resize(nExp);
         std::vector<double>
            Coeffs(nCoeff, 0);
         for ( int i = 0; i < nExp; ++ i ){
            str >> Exps[i];
            // cout << "Exp: " << Exps.back() << endl;
         }

         // read in contraction coefficients.
         if ( nCo != 0 )
            for ( int i = 0; i < nCoeff; ++ i ){
               double Coeff;
               str >> Coeff;
               // cout << "Coeff: " << Coeff << endl;
               Coeffs[i] = Coeff;
            }
         // copy over the contraction coefficients to the contractions.
         std::vector<double>
            CoMatrix(Exps.size() * nCo, 0.);
         int
            iCoeff = 0;
         for ( int i = 0; i < nCo; ++ i ){
            for (int j = Cos[i].first; j != Cos[i].second; ++ j)
               CoMatrix[j + i*Exps.size()] = Coeffs[iCoeff + j - Cos[i].first];
            iCoeff += (Cos[i].second - Cos[i].first);
         }

         // in some files some primitive orbitals are left uncontracted.
         // but these are not stored as 1-GTO contractions but the
         // coefficients for these are just not present in the file.
         // Make 1-GTO contractions for them.
         int
            nAdditionalCo = nExp - nHighestExpInCo;
         if (0 != nAdditionalCo)
         {   // generate 1-GTO-each contractions manually.
            int nCoExplicit = nCo;
            nCo += nAdditionalCo;
            CoMatrix.resize(Exps.size() * nCo, 0.);
            int
               iStart = nHighestExpInCo;
               // ^- 0 based index, the rhs one is 1-based.
            for ( int i = 0; i < nAdditionalCo; ++ i ) {
               int iCo = i + nCoExplicit;
               CoMatrix[(i + iStart) + Exps.size() * iCo] = 1.;
            }
         }

         // import all names of the basis function
         FStringList::const_iterator
            itName;
         _for_each(itName, BasisNames)
            m_BasisNames.insert(*itName);

         // make the actual basis function and link it to all the names.
         FAtomShellPtr
            pBfn(new FAtomShell(AngMom, &Exps[0], Exps.size(), &CoMatrix[0],
                                CoMatrix.size()/Exps.size()));
         int
            iElement = ElementNumberFromName(Element);
         _for_each(itName, BasisNames)
            m_BasisFns.insert( FBasisFnMap::value_type(MakeKey(*itName, iElement), pBfn) );

         // chew the EOL marker if present, leave loop otherwise.
         str.exceptions(std::ios::goodbit);
         str.ignore(0xbad, '\n');
      };
   } catch (std::ios_base::failure &e){
      // this is not exactly something i would usually
      // call "error handling" but i really hate this string-
      // fiddling stuff and we can't really do anything better
      // about it anyway.
      std::cerr << "PARSER EXCEPTION:" << e.what() << std::endl;
      throw std::runtime_error( "Parsing of LIBMOL file FAILED because the actual syntax did not match the expected one. Last entry successfully processed: ");
   } catch (std::exception &e){
      std::cerr << "Exception during LibmolFile parsing: " << e.what() << std::endl;
      throw;
   };


   // if provided, write some imporant looking comments about what
   // we loaded to the standard output.
   if (pxout) {
      std::ostream
         &xout = *pxout;
      std::size_t
         iDirSep = FileName.rfind('/');
      if ( iDirSep == std::string::npos )
         iDirSep = 0;
      else
         iDirSep += 1;
      xout << format(" LOADED %-25s") % FileName.substr(iDirSep);
      if ( 1 ) {
         xout << "[";
         FBasisNameSet::const_iterator
            itSet;
         uint
            nLen = 0;
         _for_each(itSet, AllBasisNames) {
            if ( nLen >= 40 ) {
               xout << ",...";
               break;
            }

            if (itSet != AllBasisNames.begin())
               xout << ", ";
            xout << *itSet;
            nLen += itSet->size();
         }
         xout << "]";
      }
      xout << std::endl;
   }
Example #18
0
int main(int, char* [])
{
    using namespace std;
    using boost::format;
    using boost::io::group;
    using boost::str;

    Rational r(16,9);
    const Rational cr(9,16);

    string s;
    s = str(format("%5%. %5$=6s . %1% format %5%, c'%3% %1% %2%.\n")
            % "le" % "bonheur" % "est" % "trop" % group(setfill('_'), "bref") );

    if(s  != "bref. _bref_ . le format bref, c'est le bonheur.\n") {
      cerr << s;
      BOOST_ERROR("centered alignement : formatting result incorrect");
    }


    s = str(format("%+8d %-8d\n") % r % cr );
    if(s  != "  +16/+9 9/16    \n") {
      cerr << s;
      BOOST_ERROR("(user-type) formatting result incorrect");
    }

    s = str(format("[%0+4d %0+8d %-08d]\n") % 8 % r % r);
    if(s  != "[+008 +0016/+9 16/9    ]\n") {
      cerr << s;
      BOOST_ERROR("(zero-padded user-type) formatting result incorrect");
    }


    s = str( format("%1%, %20T_ (%|2$5|,%|3$5|)\n") % "98765" % 1326 % 88 ) ;
    if( s != "98765, _____________ ( 1326,   88)\n" )
            BOOST_ERROR("(tabulation) formatting result incorrect");
    s = str( format("%s, %|20t|=") % 88 ) ;
    if( s != "88,                 =" ) {
      cout << s << endl;
      BOOST_ERROR("(tabulation) formatting result incorrect");
    }


    s = str(format("%.2s %8c.\n") % "root" % "user" );
    if(s  != "ro        u.\n") {
      cerr << s;
      BOOST_ERROR("(truncation) formatting result incorrect");
    }

   // width in format-string is overridden by setw manipulator :
    s = str( format("%|1$4| %|1$|") % group(setfill('0'), setw(6), 1) );
    if( s!= "000001 000001")
      BOOST_ERROR("width in format VS in argument misbehaved");

    s = str( format("%|=s|") % group(setfill('_'), setw(6), r) );
    if( s!= "_16/9_") {
      cerr << s << endl;
      BOOST_ERROR("width in group context is not handled correctly");
    }


    // options that uses internal alignment : + 0 #
    s = str( format("%+6d %0#6x %s\n")  % 342 % 33 % "ok" );
    if( s !="  +342 0x0021 ok\n")
      BOOST_ERROR("(flags +, 0, or #) formatting result incorrect");

    // flags in the format string are not sticky
    // and hex in argument overrrides type-char d (->decimal) :
    s = str( format("%2$#4d %|1$4| %|2$#4| %|3$|")
             % 101
             % group(setfill('_'), hex, 2)
             % 103 );
    if(s != "_0x2  101 _0x2 103")
      BOOST_ERROR("formatting error. (not-restoring state ?)");



    // flag '0' is tricky .
    // left-align cancels '0':
    s = str( format("%2$0#12X %2$0#-12d %1$0#10d \n") % -20 % 10 );
    if( s != "0X000000000A 10           -000000020 \n"){
      cerr << s;
      BOOST_ERROR("formatting error. (flag 0)");
    }

    // actually testing floating point output is implementation
    // specific so we're just going to do minimal checking...
    double dbl = 1234567.890123f;

#if (__cplusplus >= 201103L) || (BOOST_VERSION_NUMBER_MAJOR(BOOST_COMP_MSVC) >= 12)
    // msvc-12.0 and later have support for hexfloat but do not set __cplusplus to a C++11 value
    BOOST_TEST(boost::starts_with((boost::format("%A") % dbl).str(), "0X"));
    BOOST_TEST(boost::starts_with((boost::format("%a") % dbl).str(), "0x"));
#endif

    BOOST_TEST(boost::contains((boost::format("%E") % dbl).str(), "E"));
    BOOST_TEST(boost::contains((boost::format("%e") % dbl).str(), "e"));
    BOOST_TEST(boost::contains((boost::format("%F") % dbl).str(), "."));
    BOOST_TEST(boost::contains((boost::format("%f") % dbl).str(), "."));
    BOOST_TEST(!(boost::format("%G") % dbl).str().empty());
    BOOST_TEST(!(boost::format("%g") % dbl).str().empty());

    // testing argument type parsing - remember argument types are ignored
    // because operator % presents the argument type.
    unsigned int value = 456;
    BOOST_TEST_EQ((boost::format("%hhu") % value).str(), "456");
    BOOST_TEST_EQ((boost::format("%hu") % value).str(), "456");
    BOOST_TEST_EQ((boost::format("%lu") % value).str(), "456");
    BOOST_TEST_EQ((boost::format("%llu") % value).str(), "456");
    BOOST_TEST_EQ((boost::format("%ju") % value).str(), "456");
    BOOST_TEST_EQ((boost::format("%zu") % value).str(), "456");
    BOOST_TEST(boost::starts_with((boost::format("%Lf") % value).str(), "456"));

#if !defined(BOOST_NO_STD_LOCALE)
    // boolalpha support
    std::locale loc;
    const std::numpunct<char>& punk(std::use_facet<std::numpunct<char> >(loc));

    // Demonstrates how to modify the default string to something else
    std::locale custom(std::locale(), new custom_tf);
    boost::ignore_unused(locale::global(custom));
    BOOST_TEST_EQ((boost::format("%b") % false).str(), "NEGATIVE");
    BOOST_TEST_EQ((boost::format("%b") % true).str(), "POSITIVE");

    // restore system default
    locale::global(loc);
    BOOST_TEST_EQ((boost::format("%b") % false).str(), punk.falsename());
    BOOST_TEST_EQ((boost::format("%b") % true).str(), punk.truename());
#endif

    // Support for microsoft argument type specifiers: 'w' (same as 'l'), I, I32, I64
    BOOST_TEST_EQ((boost::format("%wc") % '5').str(), "5");
    BOOST_TEST_EQ((boost::format("%Id") % 123).str(), "123");
    BOOST_TEST_EQ((boost::format("%I32d") % 456).str(), "456");
    BOOST_TEST_EQ((boost::format("%I64d") % 789).str(), "789");

    // issue-36 volatile (and const) keyword
    volatile int vint = 1234567;
    BOOST_TEST_EQ((boost::format("%1%") % vint).str(), "1234567");
    volatile const int vcint = 7654321;
    BOOST_TEST_EQ((boost::format("%1%") % vcint).str(), "7654321");

    // skip width if '*'
    BOOST_TEST_EQ((boost::format("%*d") % vint).str(), "1234567");

    // internal ios flag
    BOOST_TEST_EQ((boost::format("%_6d") % -77).str(), "-   77");

    // combining some flags
    BOOST_TEST_EQ((boost::format("%+05.5d"  ) %  77).str(), "+0077");
    BOOST_TEST_EQ((boost::format("%+ 5.5d"  ) %  77).str(), "  +77");
    BOOST_TEST_EQ((boost::format("%+_ 5.5d" ) %  77).str(), "+  77");
    BOOST_TEST_EQ((boost::format("%+- 5.5d" ) %  77).str(), "+77  ");
    BOOST_TEST_EQ((boost::format("%+05.5d"  ) % -77).str(), "-0077");
    BOOST_TEST_EQ((boost::format("%+ 5.5d"  ) % -77).str(), "  -77");
    BOOST_TEST_EQ((boost::format("%+_ 5.5d" ) % -77).str(), "-  77");
    BOOST_TEST_EQ((boost::format("%+- 5.5d" ) % -77).str(), "-77  ");

    // reuse state and reset format flags
    std::string mystr("abcdefghijklmnop");
    BOOST_TEST_EQ((boost::format("%2.2s %-4.4s % 8.8s")
        % mystr % mystr % mystr).str(), "ab abcd  abcdefg");

    // coverage, operator =
    format fmt("%1%%2%%3%");
    fmt = fmt;

    return boost::report_errors();
}
Example #19
0
int test_main(int, char* [])
{
    using namespace std;
    using boost::format;
    using boost::io::group;
    using boost::str;

    string s, s2;
    // special paddings 
    s = str( format("[%=6s] [%+6s] [%+6s] [% 6s] [%+6s]\n") 
                      % 123
                      % group(internal, setfill('W'), 234)
                      % group(internal, setfill('X'), -345)
                      % group(setfill('Y'), 456)
                      % group(setfill('Z'), -10 ) );

    if(s != "[  123 ] [+WW234] [-XX345] [YY 456] [ZZZ-10]\n" ) {
      cerr << s ;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    s = str( format("[% 6.8s] [% 8.6s] [% 7.7s]\n") 
                      % group(internal, setfill('x'), Rational(12345,54321))
                      % group(internal, setfill('x'), Rational(123,45))
                      % group(internal, setfill('x'), Rational(123,321))
             );
    if(s != (s2="[ 12345/5] [ xx123/4] [ 123/32]\n" )) {
        cerr << s << s2;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    s = str( format("[% 6.8s] [% 6.8s] [% 6.8s] [% 6.8s] [%6.8s]\n") 
                      % 1234567897
                      % group(setfill('x'), 12)
                      % group(internal, setfill('x'), 12)
                      % group(internal, setfill('x'), 1234567890)
                      % group(internal, setfill('x'), 123456) 
             );
    if(s != (s2="[ 1234567] [xxx 12] [ xxx12] [ 1234567] [123456]\n") ) {
        cerr << s << s2;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    s = str( format("[% 8.6s] [% 6.4s] [% 6.4s] [% 8.6s] [% 8.6s]\n")
                      % 1234567897
                      % group(setfill('x'), 12)
                      % group(internal, setfill('x'), 12)
                      % group(internal, setfill('x'), 1234567890)
                      % group(internal, setfill('x'), 12345) 
             );
    if(s != (s2="[   12345] [xxx 12] [ xxx12] [ xx12345] [ xx12345]\n") ) {
        cerr << s << s2;
      BOOST_ERROR("formatting error. (with special paddings)");
    }

    // nesting formats :
    s = str( format("%2$014x [%1%] %|2$05|\n") % (format("%05s / %s") % -18 % 7)
             %group(showbase, -100)
             );
    if( s != "0x0000ffffff9c [-0018 / 7] -0100\n" ){
      cerr << s ;
      BOOST_ERROR("nesting did not work");
    }
   
    return 0;
}
Example #20
0
int test_main(int, char* [])
{
    using namespace std;
    using boost::format;
    using boost::io::group;
    using boost::str;

    Rational r(16,9);

    string s;
    s = str(format("%5%. %5$=6s . %1% format %5%, c'%3% %1% %2%.\n")
            % "le" % "bonheur" % "est" % "trop" % group(setfill('_'), "bref") );

    if(s  != "bref. _bref_ . le format bref, c'est le bonheur.\n") {
        cerr << s;
        BOOST_ERROR("centered alignement : formatting result incorrect");
    }


    s = str(format("%+8d %-8d\n") % r % r );
    if(s  != "  +16/+9 16/9    \n") {
        cerr << s;
        BOOST_ERROR("(user-type) formatting result incorrect");
    }

    s = str(format("[%0+4d %0+8d %-08d]\n") % 8 % r % r);
    if(s  != "[+008 +0016/+9 16/9    ]\n") {
        cerr << s;
        BOOST_ERROR("(zero-padded user-type) formatting result incorrect");
    }


    s = str( format("%1%, %20T_ (%|2$5|,%|3$5|)\n") % "98765" % 1326 % 88 ) ;
    if( s != "98765, _____________ ( 1326,   88)\n" )
        BOOST_ERROR("(tabulation) formatting result incorrect");
    s = str( format("%s, %|20t|=") % 88 ) ;
    if( s != "88,                 =" ) {
        cout << s << endl;
        BOOST_ERROR("(tabulation) formatting result incorrect");
    }


    s = str(format("%.2s %8c.\n") % "root" % "user" );
    if(s  != "ro        u.\n") {
        cerr << s;
        BOOST_ERROR("(truncation) formatting result incorrect");
    }

    // width in format-string is overridden by setw manipulator :
    s = str( format("%|1$4| %|1$|") % group(setfill('0'), setw(6), 1) );
    if( s!= "000001 000001")
        BOOST_ERROR("width in format VS in argument misbehaved");

    s = str( format("%|=s|") % group(setfill('_'), setw(6), r) );
    if( s!= "_16/9_") {
        cerr << s << endl;
        BOOST_ERROR("width in group context is not handled correctly");
    }


    // options that uses internal alignment : + 0 #
    s = str( format("%+6d %0#6x %s\n")  % 342 % 33 % "ok" );
    if( s !="  +342 0x0021 ok\n")
        BOOST_ERROR("(flags +, 0, or #) formatting result incorrect");

    // flags in the format string are not sticky
    // and hex in argument overrrides type-char d (->decimal) :
    s = str( format("%2$#4d %|1$4| %|2$#4| %|3$|")
             % 101
             % group(setfill('_'), hex, 2)
             % 103 );
    if(s != "_0x2  101 _0x2 103")
        BOOST_ERROR("formatting error. (not-restoring state ?)");



    // flag '0' is tricky .
    // left-align cancels '0':
    s = str( format("%2$0#12X %2$0#-12d %1$0#10d \n") % -20 % 10 );
    if( s != "0X000000000A 10           -000000020 \n") {
        cerr << s;
        BOOST_ERROR("formatting error. (flag 0)");
    }

    return 0;
}