Exemple #1
0
locator::locator() :
	val_()
{
	hash_ = hash_value(val_);
	hash1_ = hash_value1(val_);
}
long double integrate_slowpath(
    boost::function<long double(long double)> const& f
  , long double lower_bound
  , long double upper_bound
  , long double tolerance
  , long double increment
) {
    long double total_area = 0.0L, temp_increment = increment;

    boost::uint64_t count_depth = 0
                  , last_count = 0
                  , iterations = 0
                  , rollbacks = 0
                  , refinements = 0;

    for (long double i = lower_bound; i < upper_bound; ++iterations)
    {
        const long double fi = f(i);

        boost::uint64_t count = 0;

        // When the difference between the function value at the middle of the
        // increment and the start of the increment is too big, decrease the
        // increment by a factor of two and retry.
        while ((abs(f(i + (temp_increment / 2.0L)) - fi)) > tolerance)
        {
            ++count;
            temp_increment /= 2.0L; // TODO: ensure that I am optimized away,
                                    // as I am computed at the head of the while
                                    // loop.
        }

        if (count != last_count)
            cout << ( format("growth rate of increment changed from 1/2^%1% to "
                             "1/2^%2% at f(%3%)\n")
                    % (last_count + count_depth)
                    % (count + count_depth)
                    % group(setprecision(ld_precision), i));

        refinements += count;

        last_count = count;
        count_depth += count;

        total_area += fi * temp_increment;
        i += temp_increment;

        // Rollback one level of resolution at the end of each for-loop
        // iteration to avoid unneeded resolution, if we were not within the 
        // tolerance.
        if (count) 
        {
            ++rollbacks;
            --count_depth;
            temp_increment *= 2.0L;
        }
    }

    cout << ( format("computation completed in %1% iterations\n"
                     "%2% refinements occurred\n"
                     "%3% rollbacks were performed\n")
            % iterations
            % refinements
            % rollbacks);

    return total_area;
}
Exemple #3
0
FlatStep::operator string() const
{
	return (format("{\"%1%\", \"%2%\", \"%3%\", \"%4%\"}") % source % input % action %
			target).str();
}
Exemple #4
0
int main(){
    using namespace std;
    using boost::format;
    using boost::io::group;
    using boost::io::str;
    string s;
    stringstream oss;



    //------------------------------------------------------------------------
    // storing the parsed format-string in a 'formatter' : 
    // format objects are regular objects that can be copied, assigned, 
    // fed arguments, dumped to a stream, re-fed arguments, etc... 
    // So users can use them the way they like.

    format fmter("%1% %2% %3% %1% \n");
    fmter % 10 % 20 % 30; 
    cout  << fmter;
    //          prints  "10 20 30 10 \n"
    
    // note that once the fmter got all its arguments, 
    // the formatted string stays available  (until next call to '%')
    //    The result is  available via function str() or stream's << :
    cout << fmter; 
    //          prints the same string again.


    // once you call operator% again, arguments are cleared inside the object
    // and it is an error to ask for the conversion string before feeding all arguments :
    fmter % 1001;
    try  { cout << fmter;   }
    catch (boost::io::too_few_args& exc) { 
      cout <<  exc.what() << "***Dont worry, that was planned\n";
    }

    // we just need to feed the last two arguments, and it will be ready for output again :
    cout << fmter % 1002 % 1003;
    //          prints  "1001 1002 1003 1001 \n"

    cout  << fmter % 10 % 1 % 2;
    //          prints  "10 1 2 10 \n"



    //---------------------------------------------------------------
    // using format objects 

    // modify the formatting options for a given directive :
    fmter = format("%1% %2% %3% %2% %1% \n");
    fmter.modify_item(4, group(setfill('_'), hex, showbase, setw(5)) );
    cout << fmter % 1 % 2 % 3;
    //          prints  "1 2 3 __0x2 1 \n"
    
    // bind one of the argumets :
    fmter.bind_arg(1, 18);
    cout << fmter % group(hex, showbase, 20) % 30;        // %2 is 20, and 20 == 0x14
    //          prints  "18 0x14 30  _0x14 18 \n"
    
    
    fmter.modify_item(4, setw(0)); // cancels previous width-5
    fmter.bind_arg(1, 77); // replace 18 with 77 for first argument.
    cout << fmter % 10 % 20;
    //          prints  "77 10 20 0xa 77 \n"

    try  
    { 
      cout << fmter % 6 % 7 % 8;   // Aye ! too many args, because arg1 is bound already
    }
    catch (boost::io::too_many_args& exc) 
    { 
      cout <<  exc.what() << "***Dont worry, that was planned\n";
    }

    // clear() clears regular arguments, but not bound arguments :
    fmter.clear();
    cout << fmter % 2 % 3;
    //          prints "77 2 3 0x2 77 \n"

    // use clear_binds() to clear both regular AND bound arguments :
    fmter.clear_binds(); 
    cout << fmter % 1 % 2 % 3;
    //          prints  "1 2 3 0x2 1 \n"
    
 
    // setting desired exceptions :
    fmter.exceptions( boost::io::all_error_bits ^( boost::io::too_many_args_bit ) );
    cout << fmter % 1 % 2 % 3 % 4 % 5 % 6 ;


   // -----------------------------------------------------------
    // misc:

    // unsupported printf directives %n and asterisk-fields are purely ignored.
    // do *NOT* provide an argument for them, it is an error.
    cout << format("|%5d| %n") % 7 << endl;
    //          prints  "|    7| "
    cout << format("|%*.*d|")  % 7 << endl;
    //          prints "|7|"


    // truncations of strings :
    cout << format("%|.2s| %|8c|.\n") % "root" % "user";
    //          prints  "ro        u.\n"


    // manipulators conflicting with format-string : manipulators win.
    cout << format("%2s")  % group(setfill('0'), setw(6), 1) << endl;
    //          prints  "000001"
    cout << format("%2$5s %1% %2$3s\n")  % 1    % group(setfill('X'), setw(4), 2) ;
    //          prints  "XXX2 1 XXX2\n"  
    //          width is 4, as set by manip, not the format-string.
    
    // nesting :
    cout << format("%2$014x [%1%] %2$05s\n") % (format("%05s / %s") % -18 % 7)
                                             % group(showbase, -100);
    //          prints   "0x0000ffffff9c [-0018 / 7] -0100\n"


    cout << "\n\nEverything went OK, exiting. \n";
    return 0;
}
Exemple #5
0
void natpmp::on_reply(asio::error_code const& e
	, std::size_t bytes_transferred)
{
	using namespace libtorrent::detail;
	if (e) return;

	try
	{

		if (m_remote != m_nat_endpoint)
		{
			m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
				, m_remote, bind(&natpmp::on_reply, this, _1, _2));
			return;
		}
		
		m_send_timer.cancel();

		assert(m_currently_mapping >= 0);
		int i = m_currently_mapping;
		mapping& m = m_mappings[i];

		char* in = m_response_buffer;
		int version = read_uint8(in);
		int cmd = read_uint8(in);
		int result = read_uint16(in);
		int time = read_uint32(in);
		int private_port = read_uint16(in);
		int public_port = read_uint16(in);
		int lifetime = read_uint32(in);

		(void)time; // to remove warning

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp")
			<< " local: " << private_port << " external: " << public_port
			<< " ttl: " << lifetime << std::endl;
#endif

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		if (version != 0)
		{
			m_log << "*** unexpected version: " << version << std::endl;
		}
#endif

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		if (private_port != m.local_port)
		{
			m_log << "*** unexpected local port: " << private_port << std::endl;
		}
#endif

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		if (cmd != 128 + m.protocol)
		{
			m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl;
		}
#endif

		if (public_port == 0 || lifetime == 0)
		{
			// this means the mapping was
			// successfully closed
			m.local_port = 0;
		}
		else
		{
			m.expires = time_now() + seconds(int(lifetime * 0.7f));
			m.external_port = public_port;
		}
		
		if (result != 0)
		{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
			m_log << "*** ERROR: " << result << std::endl;
#endif
			std::stringstream errmsg;
			errmsg << "NAT router reports error (" << result << ") ";
			switch (result)
			{
				case 1: errmsg << "Unsupported protocol version"; break;
				case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break;
				case 3: errmsg << "Network failure"; break;
				case 4: errmsg << "Out of resources"; break;
				case 5: errmsg << "Unsupported opcode"; break;
			}
			throw std::runtime_error(errmsg.str());
		}

		// don't report when we remove mappings
		if (m.local_port != 0)
		{
			int tcp_port = 0;
			int udp_port = 0;
			if (m.protocol == 1) udp_port = m.external_port;
			else tcp_port = public_port;
			m_callback(tcp_port, udp_port, "");
		}
	}
	catch (std::exception& e)
	{
		// try again in two hours
		m_mappings[m_currently_mapping].expires = time_now() + hours(2);
		m_callback(0, 0, e.what());
	}
	int i = m_currently_mapping;
	m_currently_mapping = -1;
	m_mappings[i].need_update = false;
	m_send_timer.cancel();
	update_expiration_timer();
	try_next_mapping(i);
}
Exemple #6
0
bool Application::init()
{
	//
	// seed da rand
	//
	std::srand(static_cast<unsigned int>(timer.get_mms()));

	//
	// setup new old time 
	//
	oldtime = timer.get_dt_s();

	//
	// init logger
	//
	f_log = std::fopen(BIN("planetz.log").c_str(),"w");
	log_add(LOG_STREAM(f_log),LOG_PRINTER(std::vfprintf));
#ifdef _RELEASE
	log_set_lev(INFO);
#endif

	//
	// init graphics
	//
	if( !gfx.window_init(window.getW(),window.getH()) ) return false;

	plz.setMaterials( data_mgr.loadMaterials() );
	plz.setTextures ( data_mgr.loadTextures () );

	//
	// init user interface
	//
	if( !ui.init() ) return false;

	// FIXME: where should be this done?
	ui.sigVideoResize.
		connect( 0 , bind(&Window::reshape_window,&window,_1,_2));
	ui.sigVideoResize.
		connect( 1 , bind(&GFX::Gfx::reshape_window,&gfx,_1,_2) );
	ui.sigVideoResize.
		connect( 2 , bind(&UI::PlanetzPicker::resize,&picker,_1,_2) );

	ui.add_listener( &setter , 1 );
	ui.add_listener( &camera , 2 );

	ui.sigKeyDown.
		connect( bind(&GFX::Background::on_key_down,&bkg,_1) );

	ui.sigMouseMotion.
		connect( bind(&GFX::Background::on_mouse_motion,&bkg,_1,_2));
	ui.sigMouseButtonUp.
		connect( bind(&GFX::Background::on_button_up,&bkg,_1,_2,_3));
	ui.sigMouseButtonDown.
		connect(1,bind(&GFX::Background::on_button_down,&bkg,_1,_2,_3));

	ui.sigMouseButtonDown.
		connect( bind(&UI::PlanetzPicker::on_button_down,&picker,_1,_2,_3) );

	camera.sigCamChanged.
		connect( 2 , bind(&GFX::DeferRender::on_camera_angle_changed,&plz,_1) );

	picker.sigPlanetPicked.
		connect( bind(&Application::set_picked_planet,this,_1) );
#ifndef _RELEASE
	picker.sigPlanetPicked.
		connect( bind(&PlanetPrinter::print,&pprnt,_1));
#endif

#ifndef _NOGUI
	//
	// init graphical user interface
	//
	try {
		pl = new PlanetzLayout( config ); 
	} catch(CEGUI::InvalidRequestException e) {
		log_printf(CRITICAL,"CEGUI exception: %s\n",e.getMessage().c_str());
		return false;
	}
	ui.set_layout(pl);


//        pl->on_cam_speed_changed.connect(
//                        bind(	&UI::CameraMgr::update,&camera
//                                ,UI::CameraMgr::FREELOOK,&boost::lambda::_1) );
	pl->on_cam_speed_changed.connect( bind(&Application::set_cam_speed,this,_1) );
	pl->on_sim_speed_changed.connect( bind(&Application::set_phx_speed,this,_1) );
	pl->on_pause_click.connect( bind(&Application::pause_toggle,this) );
	pl->on_reset_click.connect( bind(&Application::reset,this) );
	pl->on_save.connect( 1, bind(&MEM::DataFlowMgr::save,&data_mgr,_1) );
	pl->on_save.connect( 0, bind(&MEM::MISC::PlanetHolderCleaner::forceFilter,&phcleaner) );
	pl->on_load.connect( bind(&MEM::DataFlowMgr::load,&data_mgr,_1) );
	pl->on_load.connect( bind(&Application::pause_anim,this) );
	pl->on_load.connect( bind(&GFX::PlanetsTracer::clear,&trace) );
	pl->on_load.connect( bind(&UI::CameraMgr::clear,&camera) );
	pl->on_load.connect( bind(&UI::PlanetzSetter::clear,&setter) );
	pl->on_load.connect( bind(&PlanetzLayout::hide_show_window,pl) );
	pl->on_config_changed.connect(bind(&GFX::Gfx::update_configuration,&gfx,_1));
	pl->on_config_changed.connect(bind(&Application::update_configuration,this,_1));
	pl->on_planet_changed.connect( bind(&UI::PlanetzSetter::update,&setter,_1) );
	pl->on_planet_change.connect( bind(&UI::PlanetzSetter::change,&setter,_1) );
	pl->on_planet_add.connect( bind(&MEM::DataFlowMgr::createPlanet,&data_mgr,_1) );
	pl->on_planet_add.connect( bind(&UI::PlanetzSetter::clear,&setter) );
	pl->on_planet_delete.connect( bind(&MEM::DataFlowMgr::removePlanet,&data_mgr,_1) );
	pl->on_planet_delete.connect( bind(&MEM::MISC::PlanetHolderCleaner::notifyCheckNeeded,&phcleaner) );
	//planetz.on_planet_select.connect( bind(&PlanetzLayout::add_selected_planet,pl,_1) );

	setter.on_planet_changed.connect( bind(&PlanetzLayout::update_add_win,pl,_1) );
#endif

//        data_mgr.load(DATA("saves/qsave.sav"));

//        gfx.add( &bkg    , 0 );
	gfx.add( &camera , 1 );
	gfx.add( &plz    , 2 );
	gfx.add( &trace  , 3 );
	gfx.add( &setter , 4 );
#ifndef _NOGUI
	gfx.add( &ui     , 9 );
#endif

	update_configuration( config );
	gfx.update_configuration( config );

	camera.init();

//        bkg.set_img(DATA("text.tga"));

	data_mgr.registerCam( &camera );

	phx.registerCleaner( &phcleaner );

	return true;
}
Exemple #7
0
real Closure::G_h(real k) const {
    return k*k/(4*M_PI*M_PI) * 1/12. * Integrate<ExpSub>(bind(B_h, cref(P_i), k, _1), QMIN, QMAX, EPS);
}
    virtual void processRow() {
        if (!garbage.isNull()) {
            SINVARIANT(garbage.size() > 0);
            cout << garbage.stringval();
            return;
        }
        cout << format("%s %x.%04x %x.%04x %c %c%d %x %x %s")
                % timeConv(time.val(), true) 
                % source_ip.val() % source_port.val()
                % dest_ip.val() % dest_port.val() 
                % (is_udp.val() ? 'U' : 'T')
                % (is_call.val() ? 'C' : 'R') 
                % static_cast<int>(nfs_version.val())
                % rpc_transaction_id.val() 
                % static_cast<int>(rpc_function_id.val()) 
                % rpc_function.stringval();

        if (!is_call.val()) {
            INVARIANT(!return_value.isNull(), "?");
            if (return_value.val() == 0) {
                if (rpc_function_id.val() == 0) {
                    // do nothing, nulls don't print out OK
                } else {
                    cout << " OK";
                }
            } else {
                cout << format(" %x") % return_value.val();
            }
        }
        
        printany = false;

        printMaybe(fh);
        if (rpc_function.equal("rename")) { 
            // rename prints name between fh and fh2; most print it after
            printMaybeString(name);
        }

        if (nfs_version.val() == 2 && rpc_function_id.val() == 11) {
            printMaybeString(fn);
        }

        printMaybe(fh2);

        if (nfs_version.val() == 2 && rpc_function_id.val() != 11) {
            printMaybeString(fn);
        }

        printMaybe(pre_size);
        printMaybeTime(pre_mtime);
        printMaybeTime(pre_ctime);

        if (!rpc_function.equal("rename") && !rpc_function.equal("readlink")) {
            printMaybeString(name);
        }
        printMaybeString(name2);
        printMaybeChar(how);

        printMaybe(tsize);
        printMaybe(bsize);

        printMaybeString(fn2);

        printMaybe(ftype);
        printMaybe(mode);
        printMaybe(nlink);
        printMaybe(uid);
        printMaybe(gid);
        printMaybe(size);
        printMaybe(blksize);
        printMaybe(used);
        printMaybe(rdev);
        printMaybe(blocks);
        printMaybe(rdev2);
        printMaybe(fsid);
        printMaybe(fileid);
        printMaybeTime(atime);
        printMaybeTime(mtime);
        printMaybeTime(ctime);
        
        printMaybe(bfree);
        printMaybe(bavail);

        if (rpc_function.equal("readlink")) {
            printMaybeString(name);
        }

        printMaybe(ftype_dup);
        printMaybe(mode_dup);
        printMaybe(nlink_dup);
        printMaybe(uid_dup);
        printMaybe(gid_dup);
        printMaybe(size_dup);
        printMaybe(used_dup);
        printMaybe(rdev_dup);
        printMaybe(rdev2_dup);
        printMaybe(fsid_dup);
        printMaybe(fileid_dup);
        printMaybeTime(atime_dup);
        printMaybeTime(mtime_dup);
        printMaybeTime(ctime_dup);
        
        printMaybeAcc(acc);

        printMaybe(file);
        printMaybe(off);
        printMaybe(begoff);
        printMaybe(offset);
        printMaybe(cookie);
        printMaybe(count);
        printMaybe(tcount);
        printMaybe(maxcnt);
        printMaybe(eof);

        printMaybeString(sdata);
        printMaybeChar(stable);
        printMaybe(euid);
        printMaybe(egid);

        printMaybe(nfsstat);

        if (rpc_function_id.val() == 0) {
            printany = true;
            if (is_call.val()) {
                cout << " con = 82 len = 97";
            } else {
                cout << " status=0 pl = 0 con = 70 len = 70";
            }
        }
        if (printany == false) {
            cout << " ";
        }
        if (short_packet.val()) {
            cout << "SHORT PACKETcon = 130 len = 400";
        }
        if (is_call.val()) {
            cout << " con = XXX len = XXX\n";
        } else {
            cout << " status=XXX pl = XXX con = XXX len = XXX\n";
        }
    }
Exemple #9
0
void launcher::Launcher::loadSceneFromFile(string fileName, string initialStateGroup)
{
    Engine& engine = Engine::getInstance();

    // FIXME should we validate task file against xml schema?
    auto& ffls = FileFolderLookupService::getInstance();
    string fname = ffls.lookupFile(fileName);
    LOG_DEBUG("Loading scene from file " << fname);
// parse file
    Doc doc = Doc::fromFile(fname);
    xml::Node rootNode = doc.getRootElement();
    // read task parameters
    NodeList taskNodes = rootNode.xpath("/task");
    if( taskNodes.size() != 1 )
        THROW_INVALID_INPUT("Config file should contain one <task/> element");
    for(auto& taskNode: taskNodes)
    {
        int numberOfSnaps = lexical_cast<int>(taskNode["numberOfSnaps"]);
        int stepsPerSnap = lexical_cast<int>(taskNode["stepsPerSnap"]);
        engine.setNumberOfSnaps(numberOfSnaps);
        engine.setStepsPerSnap(stepsPerSnap);
    }

    NodeList loadPluginsList = rootNode.xpath("/task/system/loadPlugin");
    for (auto& plugin: loadPluginsList){
        engine.loadPlugin(plugin["name"]);
    }

    // reading system properties
    NodeList defaultContactCalculatorList = rootNode.xpath("/task/system/defaultContactCalculator");
    if( defaultContactCalculatorList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <defaultContactCalculator/> element");
    if( defaultContactCalculatorList.size() == 1 )
    {
        xml::Node defaultContactCalculator = defaultContactCalculatorList.front();
        string type = defaultContactCalculator["type"];
        if( engine.getContactCalculator(type) == NULL )
        {
            THROW_INVALID_INPUT("Unknown contact calculator requested: " + type);
        }
        engine.replaceDefaultContactCondition( 
                new ContactCondition(NULL, new StepPulseForm(-1, -1), engine.getContactCalculator(type) ) 
        );
        LOG_INFO("Default contact calculator set to: " + type);
        if (type == "AdhesionContactDestroyCalculator")
        {
            real adhesionThreshold = lexical_cast<real>(defaultContactCalculator["adhesionThreshold"]);
            engine.getContactCondition(0)->setConditionParam(adhesionThreshold);
        }
		if (type == "ClosedFractureContactCalculator")
        {
			NodeList areaNodes = defaultContactCalculator.getChildrenByName("area");
			if (areaNodes.size() != 1)
				THROW_INVALID_INPUT("Exactly one area element can be provided for ClosedFractureCalculator");
			Area* area = readArea(areaNodes[0]);
			(static_cast<gcm::ClosedFractureContactCalculator*>
				(engine.getContactCalculator(type)))->setFracArea(area);
        }
		if (type == "OpenFractureContactCalculator")
        {
			NodeList areaNodes = defaultContactCalculator.getChildrenByName("area");
			if (areaNodes.size() != 1)
				THROW_INVALID_INPUT("Exactly one area element can be provided for ClosedFractureCalculator");
			Area* area = readArea(areaNodes[0]);
			(static_cast<gcm::OpenFractureContactCalculator*>
				(engine.getContactCalculator(type)))->setFracArea(area);
        }
    }
    
    NodeList defaultBorderCalculatorList = rootNode.xpath("/task/system/defaultBorderCalculator");
    if( defaultBorderCalculatorList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <defaultBorderCalculator/> element");
    if( defaultBorderCalculatorList.size() == 1 )
    {
        xml::Node defaultBorderCalculator = defaultBorderCalculatorList.front();
        string type = defaultBorderCalculator["type"];
        if( engine.getBorderCalculator(type) == NULL )
        {
            THROW_INVALID_INPUT("Unknown border calculator requested: " + type);
        }
        engine.replaceDefaultBorderCondition( 
                new BorderCondition(NULL, new StepPulseForm(-1, -1), engine.getBorderCalculator(type) ) 
        );
        LOG_INFO("Default border calculator set to: " + type);
    }

    NodeList defaultRheoCalculatorList = rootNode.xpath("/task/system/defaultRheologyCalculator");
    if( defaultRheoCalculatorList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <defaultRheologyCalculator/> element");
    if( defaultRheoCalculatorList.size() == 1 )
    {
        xml::Node defaultRheoCalculator = defaultRheoCalculatorList.front();
        string type = defaultRheoCalculator["type"];
        engine.setDefaultRheologyCalculatorType(type);
        LOG_INFO("Default rheology calculator set to: " + type);
    }

    NodeList defaultFailureModelList = rootNode.xpath("/task/system/defaultFailureModel");
    if( defaultFailureModelList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <defaultFailureModelList/> element");
    if( defaultFailureModelList.size() == 1 )
    {
        xml::Node defaultFailureModel = defaultFailureModelList.front();
        string type = defaultFailureModel["type"];
        engine.setDefaultFailureModelType(type);
        LOG_INFO("Default failure model set to: " + type);
    }
    
    NodeList contactThresholdList = rootNode.xpath("/task/system/contactThreshold");
    if( contactThresholdList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <contactThreshold/> element");
    if( contactThresholdList.size() == 1 )
    {
        xml::Node contactThreshold = contactThresholdList.front();
        string measure = contactThreshold["measure"];
        real value = lexical_cast<real>(contactThreshold["value"]);
        if( measure == "avgH" )
        {
            engine.setContactThresholdType(CONTACT_THRESHOLD_BY_AVG_H);
            engine.setContactThresholdFactor(value);
        }
        else if( measure == "lambdaTau" )
        {
            engine.setContactThresholdType(CONTACT_THRESHOLD_BY_MAX_LT);
            engine.setContactThresholdFactor(value);
        }
        else if( measure == "abs" )
        {
            engine.setContactThresholdType(CONTACT_THRESHOLD_FIXED);
            engine.setContactThresholdFactor(value);
        }
        else
        {
            THROW_INVALID_INPUT("Unknown units of measure for <contactThreshold/>");
        }
    }

    NodeList collisionDetectorList = rootNode.xpath("/task/system/collisionDetector");
    if( collisionDetectorList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <collisionDetector/> element");
    if( collisionDetectorList.size() == 1 )
    {
        xml::Node collisionDetector = collisionDetectorList.front();
        string isStatic = collisionDetector["static"];
        if( isStatic == "true" )
        {
            engine.setCollisionDetectorStatic(true);
        }
        else if( isStatic == "false" )
        {
            engine.setCollisionDetectorStatic(false);
        }
    }
    
    NodeList meshMovementList = rootNode.xpath("/task/system/meshMovement");
    if( meshMovementList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <meshMovement/> element");
    if( meshMovementList.size() == 1 )
    {
        xml::Node meshMovement = meshMovementList.front();
        string meshMovementType = meshMovement["type"];
        if( meshMovementType == "none" )
        {
            engine.setMeshesMovable(false);
        }
    }
    
    NodeList timeStepList = rootNode.xpath("/task/system/timeStep");
    if( timeStepList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <timeStepList/> element");
    if( timeStepList.size() == 1 )
    {
        xml::Node timeStep = timeStepList.front();
        real value = lexical_cast<real>(timeStep["multiplier"]);
        engine.setTimeStepMultiplier(value);
        LOG_INFO("Using time step multiplier: " << value);
    }
    
    NodeList plasticityTypeList = rootNode.xpath("/task/system/plasticity");
    if( plasticityTypeList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <plasticity/> element");
    string plasticityType = PLASTICITY_TYPE_NONE;
    if( plasticityTypeList.size() == 1 )
    {
        plasticityType = plasticityTypeList.front()["type"];
    }
    
    NodeList failureModeList = rootNode.xpath("/task/system/failure");
    if( failureModeList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <failure/> element");
    string failureMode = FAILURE_MODE_DISCRETE;
    if( failureModeList.size() == 1 )
    {
        failureMode = failureModeList.front()["mode"];
    }

    string matrixDecompositionImplementation = "numerical";
    NodeList matrixDecompositionList = rootNode.xpath("/task/system/matrixDecomposition");
    if( matrixDecompositionList.size() > 1 )
        THROW_INVALID_INPUT("Config file can contain only one <matrixDecomposition/> element");
    if( matrixDecompositionList.size() == 1 )
    {
        xml::Node matrixDecomposition = matrixDecompositionList.front();
        matrixDecompositionImplementation = matrixDecomposition["implementation"];
    }

    LOG_INFO("Using matrix decomposition: " << matrixDecompositionImplementation);

    loadMaterialLibrary("materials");
    
    // reading materials
    loadMaterialsFromXml(rootNode.xpath("/task/materials/material"));


    AABB globalScene;

    // search for bodies
    NodeList bodyNodes = rootNode.xpath("/task/bodies/body");

    // prepare basic bodies parameters
    for(auto& bodyNode: bodyNodes)
    {
        string id = bodyNode.getAttributes()["id"];
        LOG_DEBUG("Loading body '" << id << "'");
        // create body instance
        Body* body = new Body(id);
        body->setRheologyCalculatorType(engine.getDefaultRheologyCalculatorType());
        // set rheology
        NodeList rheologyNodes = bodyNode.getChildrenByName("rheology");
        if (rheologyNodes.size() > 1)
            THROW_INVALID_INPUT("Only one rheology element allowed for body declaration");
        if (rheologyNodes.size()) {
            // We can do smth here when we have more than one rheology calculators
        }

        // preload meshes for dispatcher
        NodeList meshNodes = bodyNode.getChildrenByName("mesh");
        for(auto& meshNode: meshNodes)
        {         
            string type = meshNode["type"];

            LOG_INFO("Preparing mesh for body '" << id << "'");

            AABB localScene;
            int slicingDirection;
            int numberOfNodes;

            if (type == Geo2MeshLoader::MESH_TYPE)
                Geo2MeshLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == Msh2MeshLoader::MESH_TYPE)
                Msh2MeshLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == Ani3D2MeshLoader::MESH_TYPE)
                Ani3D2MeshLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == Vtu2MeshLoader::MESH_TYPE)
                Vtu2MeshLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == Vtu2MeshZoneLoader::MESH_TYPE)
                Vtu2MeshZoneLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == BasicCubicMeshLoader::MESH_TYPE)
                BasicCubicMeshLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == RectangularCutCubicMeshLoader::MESH_TYPE)
                RectangularCutCubicMeshLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else if (type == MarkeredMeshGeoLoader::MESH_TYPE)
                MarkeredMeshGeoLoader::getInstance().preLoadMesh(meshNode, localScene, slicingDirection, numberOfNodes);
            else
                THROW_UNSUPPORTED("Specified mesh loader is not supported");

            // transform meshes
            NodeList transformNodes = bodyNode.getChildrenByName("transform");
            for(auto& transformNode: transformNodes)
            {
                string transformType = transformNode["type"];
                if ( transformType == "translate" )
                {
                    real x = lexical_cast<real>(transformNode["moveX"]);
                    real y = lexical_cast<real>(transformNode["moveY"]);
                    real z = lexical_cast<real>(transformNode["moveZ"]);
                    LOG_DEBUG("Moving body: [" << x << "; " << y << "; " << z << "]");
                    localScene.transfer(x, y, z);
                } 
                if ( transformType == "scale" )
                {
                    real x0 = lexical_cast<real>(transformNode["x0"]);
                    real y0 = lexical_cast<real>(transformNode["y0"]);
                    real z0 = lexical_cast<real>(transformNode["z0"]);
                    real scaleX = lexical_cast<real>(transformNode["scaleX"]);
                    real scaleY = lexical_cast<real>(transformNode["scaleY"]);
                    real scaleZ = lexical_cast<real>(transformNode["scaleZ"]);
                    LOG_DEBUG("Scaling body: [" << x0 << "; " << scaleX << "; " 
                                        << y0 << "; " << scaleY << "; " << z0 << "; " << scaleZ << "]");
                    localScene.scale(x0, y0, z0, scaleX, scaleY, scaleZ);
                }
            }
            LOG_DEBUG("Mesh preloaded. Mesh size: " << localScene << " Number of nodes: " << numberOfNodes);

            engine.getDispatcher()->addBodyOutline(id, localScene);
            engine.getDispatcher()->addBodySlicingDirection(id, slicingDirection);
            engine.getDispatcher()->addBodyNodesNumber(id, numberOfNodes);

            if( isinf(globalScene.maxX) )
            {
                globalScene = localScene;
            }
            else
            {
                for( int k = 0; k < 3; k++ )
                {
                    if( globalScene.min_coords[k] > localScene.min_coords[k] )
                        globalScene.min_coords[k] = localScene.min_coords[k];
                    if( globalScene.max_coords[k] < localScene.max_coords[k] )
                        globalScene.max_coords[k] = localScene.max_coords[k];
                }
            }
        }

        // add body to scene
        engine.addBody(body);
    }

    engine.setScene(globalScene);
    LOG_DEBUG("Total scene: " << engine.getScene());

    // run dispatcher
    engine.getDispatcher()->prepare(engine.getNumberOfWorkers(), &globalScene);
    engine.getDataBus()->syncOutlines();
    for( int i = 0; i < engine.getNumberOfWorkers(); i++)
    {
        LOG_DEBUG("Area scheduled for worker " << i << ": " << *(engine.getDispatcher()->getOutline(i)));
    }

    // read meshes for all bodies
    for(auto& bodyNode: bodyNodes)
    {
        string id = bodyNode.getAttributes()["id"];
        LOG_DEBUG("Loading meshes for body '" << id << "'");
        // get body instance
        Body* body = engine.getBodyById(id);

        // FIXME - WA - we need this to determine isMine() correctly for moved points
        real dX = 0;
        real dY = 0;
        real dZ = 0;
        NodeList tmpTransformNodes = bodyNode.getChildrenByName("transform");
        for(auto& transformNode: tmpTransformNodes)
        {
            string transformType = transformNode["type"];
            if ( transformType == "translate" )
            {
                dX += lexical_cast<real>(transformNode["moveX"]);
                dY += lexical_cast<real>(transformNode["moveY"]);
                dZ += lexical_cast<real>(transformNode["moveZ"]);
            }
            if ( transformType == "scale" )
            {
                //real x0 = lexical_cast<real>(transformNode["x0"]);
                //real y0 = lexical_cast<real>(transformNode["y0"]);
                //real z0 = lexical_cast<real>(transformNode["z0"]);
                //real scaleX = lexical_cast<real>(transformNode["scaleX"]);
                //real scaleY = lexical_cast<real>(transformNode["scaleY"]);
                //real scaleZ = lexical_cast<real>(transformNode["scaleZ"]);
            }
        }
        engine.getDispatcher()->setTransferVector(dX, dY, dZ, id);

        // load meshes
        NodeList meshNodes = bodyNode.getChildrenByName("mesh");
        for(auto& meshNode: meshNodes)
        {
            LOG_INFO("Loading mesh for body '" << id << "'");

            string type = meshNode["type"];

            Mesh* mesh = nullptr;

            if (type == Geo2MeshLoader::MESH_TYPE)
                mesh = Geo2MeshLoader::getInstance().load(meshNode, body);
            else if (type == Msh2MeshLoader::MESH_TYPE)
                mesh = Msh2MeshLoader::getInstance().load(meshNode, body);
            else if (type == Ani3D2MeshLoader::MESH_TYPE)
                mesh = Ani3D2MeshLoader::getInstance().load(meshNode, body);
            else if (type == Vtu2MeshLoader::MESH_TYPE)
                mesh = Vtu2MeshLoader::getInstance().load(meshNode, body);
            else if (type == Vtu2MeshZoneLoader::MESH_TYPE)
                mesh = Vtu2MeshZoneLoader::getInstance().load(meshNode, body);
            else if (type == BasicCubicMeshLoader::MESH_TYPE)
                mesh = BasicCubicMeshLoader::getInstance().load(meshNode, body);
            else if (type == RectangularCutCubicMeshLoader::MESH_TYPE)
                mesh = RectangularCutCubicMeshLoader::getInstance().load(meshNode, body);
            else if (type == MarkeredMeshGeoLoader::MESH_TYPE)
                mesh = MarkeredMeshGeoLoader::getInstance().load(meshNode, body);            
	    LOG_INFO("Loaded mesh for body '" << id << "', started attaching to body");
            // attach mesh to body
            body->attachMesh(mesh);
            mesh->setBodyNum( engine.getBodyNum(id) );
            LOG_INFO("Mesh '" << mesh->getId() << "' of type '" <<  type << "' created. "
                        << "Number of nodes: " << mesh->getNodesNumber() << ".");
        }

        // transform meshes
        NodeList transformNodes = bodyNode.getChildrenByName("transform");
        for(auto& transformNode: transformNodes)
        {
            string transformType = transformNode["type"];
            if( transformType == "translate" )
            {
                real x = lexical_cast<real>(transformNode["moveX"]);
                real y = lexical_cast<real>(transformNode["moveY"]);
                real z = lexical_cast<real>(transformNode["moveZ"]);
                LOG_DEBUG("Moving body: [" << x << "; " << y << "; " << z << "]");
                body->getMeshes()->transfer(x, y, z);
            }
            if ( transformType == "scale" )
            {
                real x0 = lexical_cast<real>(transformNode["x0"]);
                real y0 = lexical_cast<real>(transformNode["y0"]);
                real z0 = lexical_cast<real>(transformNode["z0"]);
                real scaleX = lexical_cast<real>(transformNode["scaleX"]);
                real scaleY = lexical_cast<real>(transformNode["scaleY"]);
                real scaleZ = lexical_cast<real>(transformNode["scaleZ"]);
                LOG_DEBUG("Scaling body: [" << x0 << "; " << scaleX << "; " 
                                << y0 << "; " << scaleY << "; " << z0 << "; " << scaleZ << "]");
                body->getMeshes()->scale(x0, y0, z0, scaleX, scaleY, scaleZ);
            }
        }

        // FIXME - Part of the WA above
        if( engine.getNumberOfWorkers() != 1 )
            engine.getDispatcher()->setTransferVector(/*-dX, -dY, -dZ,*/0, 0, 0, id);

        // set material properties
        NodeList matNodes = bodyNode.getChildrenByName("material");
        if (matNodes.size() < 1)
            THROW_INVALID_INPUT("Material not set");
        for(auto& matNode: matNodes)
        {
            string id = matNode["id"];
            // FIXME this code seems to be dead
            //Material* mat = engine.getMaterial(id);
            Mesh* mesh = body->getMeshes();

            NodeList areaNodes = matNode.getChildrenByName("area");
            int matId = engine.getMaterialIndex(id);
            usedMaterialsIds.push_back(matId);
            
            if (areaNodes.size() == 0)
            {
                mesh->setRheology( matId );
            }
            else if (areaNodes.size() == 1)
            {
                Area* matArea = readArea(areaNodes.front());
                if(matArea == NULL)
                    THROW_INVALID_INPUT("Can not read area");
                mesh->setRheology( matId, matArea );
            }
            else
            {
                THROW_INVALID_INPUT("Only one or zero area elements are allowed for material");
            }
        }
        LOG_DEBUG("Body '" << id << "' loaded");
    }

    NodeList initialStateNodes = rootNode.xpath("/task/initialState" + (initialStateGroup == "" ? "" : "[@group=\"" + initialStateGroup + "\"]"));
    if (initialStateGroup != "" && initialStateNodes.size() == 0)
        THROW_INVALID_ARG("Initial state group not found");
    for(auto& initialStateNode: initialStateNodes)
    {
        NodeList areaNodes = initialStateNode.getChildrenByName("area");
        NodeList valuesNodes = initialStateNode.getChildrenByName("values");
        NodeList pWaveNodes = initialStateNode.getChildrenByName("pWave");
        if (areaNodes.size() == 0)
            THROW_INVALID_INPUT("Area element should be provided for initial state");
        if (valuesNodes.size() > 1)
            THROW_INVALID_INPUT("Only one values element allowed for initial state");
        if (pWaveNodes.size() > 1)
            THROW_INVALID_INPUT("Only one pWave element allowed for initial state");
        if ((valuesNodes.size() == 1 && pWaveNodes.size() == 1) || (valuesNodes.size() == 0 && pWaveNodes.size() == 0))
            THROW_INVALID_INPUT("You have to provide initial state by using exactly one tag of allowed ones: values, pWave");;

        auto useValues = valuesNodes.size() == 1;
        real values[9];

        std::function<void(CalcNode&)> setter;

        if (useValues)
        {
            xml::Node valuesNode = valuesNodes.front();

            vector<string> names = {"vx", "vy", "vz", "sxx", "sxy", "sxz", "syy", "syz", "szz"};

            int i = 0;
            for (auto value_name: names)
            {
                string v = valuesNode.getAttributes()[value_name];
                values[i++] = v.empty() ? 0.0 : lexical_cast<real>(v);

            }
            
            LOG_DEBUG("Initial state values: "
                            << values[0] << " " << values[1] << " " << values[2] << " "
                            << values[3] << " " << values[4] << " " << values[5] << " "
                            << values[6] << " " << values[7] << " " << values[8] );
            
        }
        else
        {
            xml::Node pWaveNode = pWaveNodes.front();

            auto attrs = pWaveNode.getAttributes();

            auto direction = attrs["direction"];
            if (direction.empty())
                THROW_INVALID_INPUT("P-wave direction is not specified");

            vector<string> _direction;
            split(_direction, direction, is_any_of(";"));

            if (_direction.size() != 3)
                THROW_INVALID_INPUT("Invalid P-wave direction specified");

            auto dx = lexical_cast<real>(_direction[0]);
            auto dy = lexical_cast<real>(_direction[1]);
            auto dz = lexical_cast<real>(_direction[2]);

            Vector3 dir({dx, dy, dz});

            if (dx == 0.0 && dy == 0.0 && dz == 0.0)
                THROW_INVALID_INPUT("Invalid P-wave direction specified");

            auto scale = attrs["amplitudeScale"];
            if (scale.empty())
                THROW_INVALID_INPUT("P-wave amplitude scale is not specified");

            auto amplitudeScale = lexical_cast<real>(scale);
            if (amplitudeScale <= 0.0)
                THROW_INVALID_INPUT("P-wave amplitude must be positive");

            auto type = attrs["type"];
            if (type.empty())
                THROW_INVALID_INPUT("P-wave type is not specified");
            if (type != "compression" && type != "rarefaction")
                THROW_INVALID_INPUT("Invalid P-wave type specified");
            auto compression = type == "compression";

            setter = [=](CalcNode& node)
            {
                setIsotropicElasticPWave(node, dir, amplitudeScale, compression);
            };

        }
        for(auto& areaNode: areaNodes)
        {
            Area* stateArea = readArea(areaNode);
            if(stateArea == NULL)
                THROW_INVALID_INPUT("Can not read area");

            for( int i = 0; i < engine.getNumberOfBodies(); i++ )
            {
                if (useValues)
                   engine.getBody(i)->setInitialState(stateArea, values);
                else
                   engine.getBody(i)->setInitialState(stateArea, setter);
                engine.getBody(i)->getMeshes()->processStressState();
            }
        }
    }
    
    NodeList borderConditionNodes = rootNode.xpath("/task/borderCondition");
    for(auto& borderConditionNode: borderConditionNodes)
    {
        string calculator = borderConditionNode["calculator"];
        if( engine.getBorderCalculator(calculator) == NULL )
        {
            THROW_INVALID_INPUT("Unknown border calculator requested: " + calculator);
        }
        
        // FIXME_ASAP: calculators became statefull
        engine.getBorderCalculator(calculator)->setParameters( borderConditionNode );
        
        float startTime = lexical_cast<real>(borderConditionNode.getAttributeByName("startTime", "-1"));
        float duration = lexical_cast<real>(borderConditionNode.getAttributeByName("duration", "-1"));
        
        unsigned int conditionId = engine.addBorderCondition(
                new BorderCondition(NULL, new StepPulseForm(startTime, duration), engine.getBorderCalculator(calculator) ) 
        );
        LOG_INFO("Border condition created with calculator: " + calculator);
        
        NodeList areaNodes = borderConditionNode.getChildrenByName("area");
        if (areaNodes.size() == 0)
            THROW_INVALID_INPUT("Area should be specified for border condition");
        
        for(auto& areaNode: areaNodes)
        {
            Area* conditionArea = readArea(areaNode);
            if(conditionArea == NULL)
                THROW_INVALID_INPUT("Can not read area");

            for( int i = 0; i < engine.getNumberOfBodies(); i++ )
            {
                engine.getBody(i)->setBorderCondition(conditionArea, conditionId);
            }
        }
    }
    
    NodeList contactConditionNodes = rootNode.xpath("/task/contactCondition");
    for(auto& contactConditionNode: contactConditionNodes)
    {
        string calculator = contactConditionNode["calculator"];
        if( engine.getContactCalculator(calculator) == NULL )
        {
            THROW_INVALID_INPUT("Unknown border calculator requested: " + calculator);
        }
        
        float startTime = lexical_cast<real>(contactConditionNode.getAttributeByName("startTime", "-1"));
        float duration = lexical_cast<real>(contactConditionNode.getAttributeByName("duration", "-1"));
        
        unsigned int conditionId = engine.addContactCondition(
                new ContactCondition(NULL, new StepPulseForm(startTime, duration), engine.getContactCalculator(calculator) ) 
        );
        if (calculator == "AdhesionContactDestroyCalculator")
        {
            real adhesionThreshold = lexical_cast<real>(contactConditionNode["adhesionThreshold"]);
            engine.getContactCondition(conditionId)->setConditionParam(adhesionThreshold);
        }
        LOG_INFO("Contact condition created with calculator: " + calculator);
        
        NodeList areaNodes = contactConditionNode.getChildrenByName("area");
        if (areaNodes.size() == 0)
            THROW_INVALID_INPUT("Area should be specified for contact condition");
        
        for(auto& areaNode: areaNodes)
        {
            Area* conditionArea = readArea(areaNode);
            if(conditionArea == NULL)
                THROW_INVALID_INPUT("Can not read area");

            for( int i = 0; i < engine.getNumberOfBodies(); i++ )
            {
                engine.getBody(i)->setContactCondition(conditionArea, conditionId);
            }
        }
    }

    // create rheology matrixes
    vector<RheologyMatrixPtr> matrices;
    for (int i = 0; i < engine.getNumberOfMaterials(); i++)
    {
        MaterialPtr material = engine.getMaterial(i);
        
        bool materialUsedInTask = (std::find(usedMaterialsIds.begin(), usedMaterialsIds.end(), i) != usedMaterialsIds.end());
        
        auto props = material->getPlasticityProperties();
        bool plasticityPropsPresent = ( (props[plasticityType].size() != 0) 
                                        || (plasticityType == PLASTICITY_TYPE_NONE) );
        
        SetterPtr setter;
        DecomposerPtr decomposer;
        CorrectorPtr corrector;
        RheologyMatrixPtr matrix;

        if (material->isIsotropic())
        {
            if(materialUsedInTask)
            {
                LOG_INFO("Using \"" << plasticityType << "\" plasticity model " 
                        << "and \""  + failureMode + "\" failure mode "
                        << "for isotropic material \"" << material->getName() << "\".");
                if( !plasticityPropsPresent )
                    THROW_UNSUPPORTED("Required plasticity properties were not found.");
            }
            
            if (plasticityType == PLASTICITY_TYPE_NONE)
            {
                corrector = nullptr;
                setter = makeSetterPtr<IsotropicRheologyMatrixSetter>();
                decomposer = makeDecomposerPtr<IsotropicRheologyMatrixDecomposer>();
            }
            else if (plasticityType == PLASTICITY_TYPE_PRANDTL_RAUSS)
            {
                corrector = nullptr;
                setter = makeSetterPtr<PrandtlRaussPlasticityRheologyMatrixSetter>();
                if (matrixDecompositionImplementation == "numerical")
                    decomposer = makeDecomposerPtr<NumericalRheologyMatrixDecomposer>();
                else
                    decomposer = makeDecomposerPtr<AnalyticalRheologyMatrixDecomposer>();
            }
            else if (plasticityType == PLASTICITY_TYPE_PRANDTL_RAUSS_CORRECTOR)
            {
                corrector = makeCorrectorPtr<IdealPlasticFlowCorrector>();
                setter = makeSetterPtr<IsotropicRheologyMatrixSetter>();
                decomposer = makeDecomposerPtr<IsotropicRheologyMatrixDecomposer>();
            }
            else
            {
                THROW_UNSUPPORTED("Plasticity type\"" + plasticityType + "\" is not supported.");
            }
            
            if (failureMode == FAILURE_MODE_DISCRETE)
            {
                corrector = nullptr;
                setter = makeSetterPtr<IsotropicRheologyMatrixSetter>();
                decomposer = makeDecomposerPtr<IsotropicRheologyMatrixDecomposer>();
            }
            else if (failureMode == FAILURE_MODE_CONTINUAL)
            {
                corrector = nullptr;
                setter = makeSetterPtr<IsotropicDamagedRheologyMatrixSetter>();
                decomposer = makeDecomposerPtr<IsotropicRheologyMatrixDecomposer>();
            }
            else
            {
                THROW_UNSUPPORTED("Failure mode \"" + failureMode + "\" is not supported.");
            }
        } else 
        {
            if(materialUsedInTask)
            {
                LOG_INFO("Using \"" << plasticityType << "\" plasticity model for anisotropic material \"" << material->getName() << "\".");
                if (plasticityType != PLASTICITY_TYPE_NONE)
                    LOG_WARN("Plasticity is not supported for anisotropic materials, using elastic instead.");
            }
            
            if (failureMode == FAILURE_MODE_DISCRETE)
            {
                corrector = nullptr;
                setter = makeSetterPtr<AnisotropicRheologyMatrixSetter>();
            }
            else if (failureMode == FAILURE_MODE_CONTINUAL)
            {
                corrector = nullptr;
                setter = makeSetterPtr<AnisotropicDamagedRheologyMatrixSetter>();
            }
            else
            {
                THROW_UNSUPPORTED("Failure mode \"" + failureMode + "\" is not supported.");
            }          
            
            if( matrixDecompositionImplementation == "numerical" )
                decomposer = makeDecomposerPtr<NumericalRheologyMatrixDecomposer>();
            else
                decomposer = makeDecomposerPtr<AnalyticalRheologyMatrixDecomposer>();
        }

        matrices.push_back(makeRheologyMatrixPtr(material, setter, decomposer, corrector));
    }

    engine.setRheologyMatrices([&matrices](const CalcNode& node) -> RheologyMatrixPtr
        {
            return matrices[node.getMaterialId()];
        }
    );

    LOG_DEBUG("Running plugin-specific initializations");

    for (auto plugin: engine.getPlugins())
        plugin ->parseTask(doc);

    LOG_DEBUG("Scene loaded");
}
void HeadFreeCameraEventReceiver::update(int ms)
{
	auto cam = this->getCamera();

	MoveEvent moveEvt = getMoveEvent();
	LookEvent lookEvt = getLookEvent();

	horizontalRotate_ += lookEvt.horizontalRotation * rotateSpeed * ms;
	if(horizontalRotate_ > 180.0f) {
		horizontalRotate_ -= 360.0f;
	} else if(horizontalRotate_ < -180.0f) {
		horizontalRotate_ += 360.0f;
	}

	verticalRotate_ += lookEvt.verticalRotation * rotateSpeed * ms;
	const float maxVerticalRotation = 80.0f;
	if(verticalRotate_ < -maxVerticalRotation) {
		verticalRotate_ = -maxVerticalRotation;
	} else if(verticalRotate_ > maxVerticalRotation) {
		verticalRotate_ = maxVerticalRotation;
	}

	//그냥 생각없이 카메라를 돌리자. 오큘러스 대응은 렌더리쪽에서 알아서 처리될거다
	cam->setRotation(core::vector3df(verticalRotate_, horizontalRotate_, 0));
	
	//카메라 처다보는 방향으로 로직을 구현하면 오큘러스에서 설정한 값하고 꼬인다
	//v/h 값으로 따로 계산해야될듯
	core::vector3df pos = cam->getPosition();
	core::vector3df up(0, 1, 0);
	float targetX = -cos(core::degToRad(verticalRotate_)) * sin(core::degToRad(horizontalRotate_));
	float targetY = sin(core::degToRad(verticalRotate_));
	float targetZ = -cos(core::degToRad(verticalRotate_)) * cos(core::degToRad(horizontalRotate_));
	core::vector3df target(targetX, targetY, targetZ);
	irr::core::vector3df side = up.crossProduct(target);
	up = target.crossProduct(side);
	cam->setUpVector(up);

	const float moveFactor = moveSpeed * ms;
	auto moveDelta = moveFactor * moveEvt.forwardBackward * target;
	auto sideDelta = moveFactor * moveEvt.leftRight * side;
	auto nextPos = pos + moveDelta + sideDelta;
	cam->setPosition(nextPos);

	bool displayInfo = false;
	if(displayInfo) {
		irr::video::SColor white(255, 255, 255, 255);
		auto rotateMsg = (wformat(L"rotate : h=%.2f, v=%.2f") % horizontalRotate_ % verticalRotate_).str();
		g_debugDrawMgr->addString(core::vector2di(0, 100), rotateMsg, white);

		auto evtMsg = (wformat(L"evt : fb=%.2f, lr=%.2f") % moveEvt.forwardBackward % moveEvt.leftRight).str();
		g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*1), evtMsg, white);

		auto targetMsg = (wformat(L"target : %.2f, %.2f, %.2f") % targetX % targetY % targetZ).str();
		g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*2), targetMsg, white);

		auto sideMsg = (wformat(L"side : %.2f, %.2f, %.2f") % side.X % side.Y % side.Z).str();
		g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*3), sideMsg, white);

		auto camPos = cam->getPosition();
		auto camPosMsg = (wformat(L"CamPos : %.2f, %.2f, %.2f") % camPos.X % camPos.Y % camPos.Z).str();
		g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*4), camPosMsg, white);

		auto upVecMsg = (wformat(L"UpVec : %.2f, %.2f, %.2f") % up.X % up.Y % up.Z).str();
		g_debugDrawMgr->addString(core::vector2di(0, 100 + 14*5), upVecMsg, white);

	}
}
Exemple #11
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;
}
Exemple #12
0
void test()
{
    BOOST_TEST( UDT_use_count == 0 );  // reality check

    //  test scoped_ptr with a built-in type
    long * lp = new long;
    boost::scoped_ptr<long> sp ( lp );
    BOOST_TEST( sp.get() == lp );
    BOOST_TEST( lp == sp.get() );
    BOOST_TEST( &*sp == lp );

    *sp = 1234568901L;
    BOOST_TEST( *sp == 1234568901L );
    BOOST_TEST( *lp == 1234568901L );
    ck( static_cast<long*>(sp.get()), 1234568901L );
    ck( lp, *sp );

    sp.reset();
    BOOST_TEST( sp.get() == 0 );

    //  test scoped_ptr with a user defined type
    boost::scoped_ptr<UDT> udt_sp ( new UDT( 999888777 ) );
    BOOST_TEST( udt_sp->value() == 999888777 );
    udt_sp.reset();
    udt_sp.reset( new UDT( 111222333 ) );
    BOOST_TEST( udt_sp->value() == 111222333 );
    udt_sp.reset( new UDT( 333222111 ) );
    BOOST_TEST( udt_sp->value() == 333222111 );

    //  test scoped_array with a build-in type
    char * sap = new char [ 100 ];
    boost::scoped_array<char> sa ( sap );
    BOOST_TEST( sa.get() == sap );
    BOOST_TEST( sap == sa.get() );

    strcpy( sa.get(), "Hot Dog with mustard and relish" );
    BOOST_TEST( strcmp( sa.get(), "Hot Dog with mustard and relish" ) == 0 );
    BOOST_TEST( strcmp( sap, "Hot Dog with mustard and relish" ) == 0 );

    BOOST_TEST( sa[0] == 'H' );
    BOOST_TEST( sa[30] == 'h' );

    sa[0] = 'N';
    sa[4] = 'd';
    BOOST_TEST( strcmp( sap, "Not dog with mustard and relish" ) == 0 );

    sa.reset();
    BOOST_TEST( sa.get() == 0 );

    //  test shared_ptr with a built-in type
    int * ip = new int;
    boost::shared_ptr<int> cp ( ip );
    BOOST_TEST( ip == cp.get() );
    BOOST_TEST( cp.use_count() == 1 );

    *cp = 54321;
    BOOST_TEST( *cp == 54321 );
    BOOST_TEST( *ip == 54321 );
    ck( static_cast<int*>(cp.get()), 54321 );
    ck( static_cast<int*>(ip), *cp );

    boost::shared_ptr<int> cp2 ( cp );
    BOOST_TEST( ip == cp2.get() );
    BOOST_TEST( cp.use_count() == 2 );
    BOOST_TEST( cp2.use_count() == 2 );

    BOOST_TEST( *cp == 54321 );
    BOOST_TEST( *cp2 == 54321 );
    ck( static_cast<int*>(cp2.get()), 54321 );
    ck( static_cast<int*>(ip), *cp2 );

    boost::shared_ptr<int> cp3 ( cp );
    BOOST_TEST( cp.use_count() == 3 );
    BOOST_TEST( cp2.use_count() == 3 );
    BOOST_TEST( cp3.use_count() == 3 );
    cp.reset();
    BOOST_TEST( cp2.use_count() == 2 );
    BOOST_TEST( cp3.use_count() == 2 );
    cp.reset( new int );
    *cp =  98765;
    BOOST_TEST( *cp == 98765 );
    *cp3 = 87654;
    BOOST_TEST( *cp3 == 87654 );
    BOOST_TEST( *cp2 == 87654 );
    cp.swap( cp3 );
    BOOST_TEST( *cp == 87654 );
    BOOST_TEST( *cp2 == 87654 );
    BOOST_TEST( *cp3 == 98765 );
    cp.swap( cp3 );
    BOOST_TEST( *cp == 98765 );
    BOOST_TEST( *cp2 == 87654 );
    BOOST_TEST( *cp3 == 87654 );
    cp2 = cp2;
    BOOST_TEST( cp2.use_count() == 2 );
    BOOST_TEST( *cp2 == 87654 );
    cp = cp2;
    BOOST_TEST( cp2.use_count() == 3 );
    BOOST_TEST( *cp2 == 87654 );
    BOOST_TEST( cp.use_count() == 3 );
    BOOST_TEST( *cp == 87654 );

#if defined( BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP )
    using boost::swap;
#endif

    boost::shared_ptr<int> cp4;
    swap( cp2, cp4 );
    BOOST_TEST( cp4.use_count() == 3 );
    BOOST_TEST( *cp4 == 87654 );
    BOOST_TEST( cp2.get() == 0 );

    std::set< boost::shared_ptr<int> > scp;
    scp.insert(cp4);
    BOOST_TEST( scp.find(cp4) != scp.end() );
    BOOST_TEST( scp.find(cp4) == scp.find( boost::shared_ptr<int>(cp4) ) );

    //  test shared_array with a built-in type
    char * cap = new char [ 100 ];
    boost::shared_array<char> ca ( cap );
    BOOST_TEST( ca.get() == cap );
    BOOST_TEST( cap == ca.get() );
    BOOST_TEST( &ca[0] == cap );

    strcpy( ca.get(), "Hot Dog with mustard and relish" );
    BOOST_TEST( strcmp( ca.get(), "Hot Dog with mustard and relish" ) == 0 );
    BOOST_TEST( strcmp( cap, "Hot Dog with mustard and relish" ) == 0 );

    BOOST_TEST( ca[0] == 'H' );
    BOOST_TEST( ca[30] == 'h' );

    boost::shared_array<char> ca2 ( ca );
    boost::shared_array<char> ca3 ( ca2 );

    ca[0] = 'N';
    ca[4] = 'd';
    BOOST_TEST( strcmp( ca.get(), "Not dog with mustard and relish" ) == 0 );
    BOOST_TEST( strcmp( ca2.get(), "Not dog with mustard and relish" ) == 0 );
    BOOST_TEST( strcmp( ca3.get(), "Not dog with mustard and relish" ) == 0 );
    BOOST_TEST( ca.use_count() == 3 );
    BOOST_TEST( ca2.use_count() == 3 );
    BOOST_TEST( ca3.use_count() == 3 );
    ca2.reset();
    BOOST_TEST( ca.use_count() == 2 );
    BOOST_TEST( ca3.use_count() == 2 );
    BOOST_TEST( ca2.use_count() == 0 );

    ca.reset();
    BOOST_TEST( ca.get() == 0 );

    boost::shared_array<char> ca4;
    swap( ca3, ca4 );
    BOOST_TEST( ca4.use_count() == 1 );
    BOOST_TEST( strcmp( ca4.get(), "Not dog with mustard and relish" ) == 0 );
    BOOST_TEST( ca3.get() == 0 );

    std::set< boost::shared_array<char> > sca;
    sca.insert(ca4);
    BOOST_TEST( sca.find(ca4) != sca.end() );
    BOOST_TEST( sca.find(ca4) == sca.find( boost::shared_array<char>(ca4) ) );

    //  test shared_array with user defined type
    boost::shared_array<UDT> udta ( new UDT[3] );

    udta[0].value( 111 );
    udta[1].value( 222 );
    udta[2].value( 333 );
    boost::shared_array<UDT> udta2 ( udta );

    BOOST_TEST( udta[0].value() == 111 );
    BOOST_TEST( udta[1].value() == 222 );
    BOOST_TEST( udta[2].value() == 333 );
    BOOST_TEST( udta2[0].value() == 111 );
    BOOST_TEST( udta2[1].value() == 222 );
    BOOST_TEST( udta2[2].value() == 333 );
    udta2.reset();
    BOOST_TEST( udta2.get() == 0 );
    BOOST_TEST( udta.use_count() == 1 );
    BOOST_TEST( udta2.use_count() == 0 );

    BOOST_TEST( UDT_use_count == 4 );  // reality check

    //  test shared_ptr with a user defined type
    UDT * up = new UDT;
    boost::shared_ptr<UDT> sup ( up );
    BOOST_TEST( up == sup.get() );
    BOOST_TEST( sup.use_count() == 1 );

    sup->value( 54321 ) ;
    BOOST_TEST( sup->value() == 54321 );
    BOOST_TEST( up->value() == 54321 );

    boost::shared_ptr<UDT> sup2;
    sup2 = sup;
    BOOST_TEST( sup2->value() == 54321 );
    BOOST_TEST( sup.use_count() == 2 );
    BOOST_TEST( sup2.use_count() == 2 );
    sup2 = sup2;
    BOOST_TEST( sup2->value() == 54321 );
    BOOST_TEST( sup.use_count() == 2 );
    BOOST_TEST( sup2.use_count() == 2 );

    std::cout << "OK\n";

    new char[12345]; // deliberate memory leak to verify leaks detected
}
Exemple #13
0
BAData::BAData(stochasticInput &input, BAContext &ctx) : ctx(ctx) {
	int nscen = input.nScenarios();
	ctx.initializeAssignment(nscen); // must do this first
	dims = BADimensions(input,ctx); 

	const vector<int> &localScen = ctx.localScenarios();
	
	l.allocate(dims, ctx, PrimalVector);
	u.allocate(dims, ctx, PrimalVector);
	c.allocate(dims, ctx, PrimalVector);
	vartype.allocate(dims, ctx, PrimalVector);
	names.allocate(dims, ctx, PrimalVector);


	formBAVector(l, input.getFirstStageColLB(),
			bind(&stochasticInput::getSecondStageColLB,&input,_1),
			input.getFirstStageRowLB(),
			bind(&stochasticInput::getSecondStageRowLB,&input,_1),ctx);

	formBAVector(u, input.getFirstStageColUB(),
			bind(&stochasticInput::getSecondStageColUB,&input,_1),
			input.getFirstStageRowUB(),
			bind(&stochasticInput::getSecondStageRowUB,&input,_1),ctx);

	formBAVector(c, input.getFirstStageObj(),
			bind(&stochasticInput::getSecondStageObj,&input,_1),
			vector<double>(input.nFirstStageCons(),0.0),
			emptyRowVector(input), ctx);

	formBAVector(names, input.getFirstStageColNames(),
			bind(&stochasticInput::getSecondStageColNames,&input,_1),
			input.getFirstStageRowNames(),
			bind(&stochasticInput::getSecondStageRowNames,&input,_1),ctx);

	for (unsigned i = 0; i < localScen.size(); i++) {
		int scen = localScen[i];
		checkConstraintType(l.getVec(scen),u.getVec(scen),vartype.getVec(scen));
	}

	Acol.reset(new CoinPackedMatrix(input.getFirstStageConstraints()));
	Arow.reset(new CoinPackedMatrix());
	Arow->reverseOrderedCopyOf(*Acol);

	Tcol.resize(nscen); Trow.resize(nscen);
	Wcol.resize(nscen); Wrow.resize(nscen);

	/*
	We can save memory by not duplicating the constraint matrices, but
	as soon as we add individual scenario cuts these need to be duplicated anyway.
	One could think about adding identical cuts (with different RHSs)
	to each scenario to restore this optimization.
	
	onlyBoundsVary = input.onlyBoundsVary();
	if (onlyBoundsVary) {
		Tcol[0].reset(new CoinPackedMatrix(input.getLinkingConstraints(0)));
		Trow[0].reset(new CoinPackedMatrix());
		Trow[0]->reverseOrderedCopyOf(*Tcol[0]);

		Wcol[0].reset(new CoinPackedMatrix(input.getSecondStageConstraints(0)));
		Wrow[0].reset(new CoinPackedMatrix());
		Wrow[0]->reverseOrderedCopyOf(*Wcol[0]);

		for (int i = 1; i < nscen; i++) {
			Tcol[i] = Tcol[0];
			Trow[i] = Trow[0];
			Wcol[i] = Wcol[0];
			Wrow[i] = Wrow[0];
		}
	} else {*/
		for (int i = 0; i < nscen; i++) {
			if (!ctx.assignedScenario(i)) continue;
			Tcol[i].reset(new CoinPackedMatrix(input.getLinkingConstraints(i)));
			Trow[i].reset(new CoinPackedMatrix());
			Trow[i]->reverseOrderedCopyOf(*Tcol[i]);

			Wcol[i].reset(new CoinPackedMatrix(input.getSecondStageConstraints(i)));
			Wrow[i].reset(new CoinPackedMatrix());
			Wrow[i]->reverseOrderedCopyOf(*Wcol[i]);
		}
	/*
	}*/

	out1Send.reserve(dims.numFirstStageVars());
	
}
Exemple #14
0
locator::locator(const std::string &filename, const std::string& modifications) :
	val_(filename, modifications)
{
	hash_ = hash_value(val_);
	hash1_ = hash_value1(val_);
}
Exemple #15
0
void InputRule::unitTest() {
    BOOST_CHECK(true);

    sqlite3* db;

//    // test Ruleset class
//    path dbFileName = initial_path<path>()/"unitTest_InputRule.db3";
//
//    if (exists(dbFileName))
//        boost::filesystem::remove(dbFileName);
//
//    if(sqlite3_open(dbFileName.file_string().c_str(), &db)) {
    if(sqlite3_open(":memory:", &db)) {
        sqlite3_close(db);
        throw std::runtime_error("could not open database file");
    }
    BOOST_REQUIRE(db!=NULL);

    BOOST_CHECKPOINT("create Tables");
    InputRule::createTables(db);
    Replacement::createTables(db);
    Replacements::createTables(db);
    Gem::createTables(db);

    BOOST_CHECKPOINT("InputRule constructor(regex)");
    InputRule ruleAlpha(db, regex("(.*)\\.avi"), -1);
    InputRule ruleBeta(db, regex("(.*)\\.mpg"), -1);
    InputRule ruleGamma(db, regex("(.*)\\.jpg"), -1);
    ruleAlpha.updateGems("$fileName$");
    ruleBeta.updateGems("$fileName$");
    ruleGamma.updateGems("$fileName$");
    BOOST_CHECK(ruleAlpha.getGems().size() == 1);
    BOOST_CHECK(ruleBeta.getGems().size() == 1);
    BOOST_CHECK(ruleGamma.getGems().size() == 1);

    BOOST_CHECKPOINT("get gem");
    BOOST_REQUIRE(ruleAlpha.getGems().size() == 1);
    BOOST_CHECK(ruleAlpha.getGems()[0]->getName() == "fileName");

    BOOST_CHECKPOINT("getRegex(), first time");
    BOOST_CHECK( ruleAlpha.getRegex() == "(.*)\\.avi" );
    BOOST_CHECK( ruleBeta.getRegex() == "(.*)\\.mpg" );
    BOOST_CHECK( ruleGamma.getRegex() == "(.*)\\.jpg" );

    BOOST_CHECKPOINT("getRegex(), second time");
    BOOST_CHECK( ruleAlpha.getRegex() == "(.*)\\.avi" );
    BOOST_CHECK( ruleBeta.getRegex() == "(.*)\\.mpg" );
    BOOST_CHECK( ruleGamma.getRegex() == "(.*)\\.jpg" );


    vector<GemValue> gems;
    BOOST_CHECKPOINT("applyTo()");
    BOOST_CHECK(ruleAlpha.getGems().size() == 1);
    BOOST_CHECK_NO_THROW(ruleAlpha.applyTo("Test.avi", gems, true));
    BOOST_CHECK_NO_THROW(!ruleAlpha.applyTo("Test.mpg", gems, true));
    BOOST_CHECK_NO_THROW(!ruleAlpha.applyTo("Test.jpg", gems, true));

    BOOST_CHECKPOINT("applyTo() 048f97dc");
    BOOST_CHECK(!ruleBeta.applyTo("Test.avi", gems, true));
    BOOST_CHECK(ruleBeta.applyTo("Test.mpg", gems, true));
    BOOST_CHECK(!ruleBeta.applyTo("Test.jpg", gems, true));

    BOOST_CHECKPOINT("applyTo() 092aed5a");
    BOOST_CHECK(!ruleGamma.applyTo("Test.avi", gems, true));
    BOOST_CHECK(!ruleGamma.applyTo("Test.mpg", gems, true));
    BOOST_CHECK(ruleGamma.applyTo("Test.jpg", gems, true));

    BOOST_CHECKPOINT("applyTo() 6d984e20");

    BOOST_CHECK(ruleAlpha.applyTo("Name mit Blank.avi", gems, true));
    BOOST_CHECK(!ruleAlpha.applyTo("Name mit Blank.mpg", gems, true));
    BOOST_CHECK(!ruleAlpha.applyTo("Name mit Blank.jpg", gems, true));

    BOOST_CHECK(!ruleBeta.applyTo("Name mit Blank.avi", gems, true));
    BOOST_CHECK(ruleBeta.applyTo("Name mit Blank.mpg", gems, true));
    BOOST_CHECK(!ruleBeta.applyTo("Name mit Blank.jpg", gems, true));

    BOOST_CHECK(!ruleGamma.applyTo("Name mit Blank.avi", gems, true));
    BOOST_CHECK(!ruleGamma.applyTo("Name mit Blank.mpg", gems, true));
    BOOST_CHECK(ruleGamma.applyTo("Name mit Blank.jpg", gems, true));


    BOOST_CHECKPOINT("setRegex()");
    BOOST_CHECK(ruleAlpha.setRegex("([\\w ]*)\\.avi"));
    BOOST_CHECK(!ruleAlpha.setRegex("([\\w ]*)\\.mpg"));
    BOOST_CHECK(!ruleAlpha.setRegex("Test\\..*"));

    BOOST_CHECK(!ruleBeta.setRegex("([\\w ]*)\\.avi"));
    BOOST_CHECK(ruleBeta.setRegex("([\\w ]*)\\.mpg"));
    BOOST_CHECK(!ruleBeta.setRegex("Test\\..*"));

    BOOST_CHECK(ruleGamma.setRegex("([\\w ]*)\\.jpg"));
    BOOST_CHECK(!ruleGamma.setRegex("([\\w ]*)\\.mpg"));
    BOOST_CHECK(!ruleGamma.setRegex("Test\\..*"));

    BOOST_CHECKPOINT("getRegex(), third time");
    BOOST_CHECK( ruleAlpha.getRegex() == "([\\w ]*)\\.avi" );
    BOOST_CHECK( ruleBeta.getRegex() == "([\\w ]*)\\.mpg" );
    BOOST_CHECK( ruleGamma.getRegex() == "([\\w ]*)\\.jpg" );


    BOOST_CHECKPOINT("InputRule constructor(regex)");
    InputRule ruleDelta(db, ruleAlpha.getRowId());
    BOOST_CHECK(ruleAlpha.getRowId() == ruleDelta.getRowId());
    BOOST_CHECK(ruleAlpha.getRegex() == ruleDelta.getRegex());


    BOOST_CHECKPOINT("replacements");
    InputRule ruleEpsilon(db, regex("Family Guy S06E13"), -1);
    ruleEpsilon.getReplacements().addReplacement("PDTV|XviD|-LOL","");
    ruleEpsilon.getReplacements().addReplacement(" *$","");
    ruleEpsilon.getReplacements().addReplacement("\\."," ");
    ruleEpsilon.getReplacements().addReplacement("avi$","");

    BOOST_CHECK(ruleEpsilon.applyTo("Family.Guy.S06E13.PDTV.XviD-LOL.avi", gems, true));
    BOOST_CHECK(!ruleAlpha.applyTo("Family.Guy.S06E13.PDTV.XviD-LOL.avi", gems, true));

    BOOST_CHECKPOINT("gems");
    ruleEpsilon.updateGems("lalala $test$ dsklkdsalk$foobar$kjjlk");
    BOOST_REQUIRE(ruleEpsilon.getGems().size() == 2);
    BOOST_CHECK(ruleEpsilon.getGems()[0]->getPosition() == 1);
    BOOST_CHECK(ruleEpsilon.getGems()[1]->getPosition() == 2);


    BOOST_CHECKPOINT("ruleZeta");
    InputRule ruleZeta(db, regex("Numb3rs\\.S(\\d+)E(\\d+)\\.HDTV\\.XviD-(NoTV|LOL)"), -1);
    ruleZeta.updateGems("Numb3rs - $season$x$episode$");
    BOOST_REQUIRE(ruleZeta.getGems().size() == 2);
    BOOST_CHECK(ruleZeta.getGems()[0]->getPosition() == 1);
    BOOST_CHECK(ruleZeta.getGems()[1]->getPosition() == 2);
    BOOST_CHECK(ruleZeta.getGems()[0]->getName() == "season");
    BOOST_CHECK(ruleZeta.getGems()[1]->getName() == "episode");

    gems.clear();
    BOOST_CHECK(!ruleZeta.applyTo("Numb3rs.S03E13.Mein Titel.HDTV.XviD-NoTV", gems, true));
    BOOST_CHECK(ruleZeta.applyTo("Numb3rs.S03E13.HDTV.XviD-NoTV", gems, true));
    BOOST_REQUIRE(gems.size() == 2);
    BOOST_CHECK(gems[0].name == "season");
    BOOST_CHECK(gems[0].value == "03");
    BOOST_CHECK(gems[1].name == "episode");
    BOOST_CHECK(gems[1].value == "13");

    gems.clear();
    BOOST_CHECK(ruleZeta.applyTo("Numb3rs.S03E16.HDTV.XviD-LOL", gems, true));
    BOOST_CHECK(gems[0].name == "season");
    BOOST_CHECK(gems[0].value == "03");
    BOOST_CHECK(gems[1].name == "episode");
    BOOST_CHECK(gems[1].value == "16");

    BOOST_CHECKPOINT("clean up");
//    ruleAlpha.remove();
//    ruleBeta.remove();
//    ruleGamma.remove();
//    ruleEpsilon.remove();
//    ruleZeta.remove();
    BOOST_CHECK_EQUAL(query("SELECT COUNT(*) FROM regexes", db) , "0");
    BOOST_CHECK_EQUAL(query("SELECT COUNT(*) FROM gems", db) , "0");

    sqlite3_close(db);
}
bool D3D10ShaderInfo::DumpDX10ShaderDebugInfo(const D3D10ShaderObject::D3D10_ChunkHeader* pSDBGChunk, std::string& strDebugInfo)
{
    if (pSDBGChunk == NULL)
    {
        return false;
    }

    char* pszDebugInfo = (char*)(pSDBGChunk + 1);
    D3D10_SHADER_DEBUG_INFO* pDebugInfo = (D3D10_SHADER_DEBUG_INFO*)(pszDebugInfo);
    char* pszDebugDataOffset = pszDebugInfo + pDebugInfo->Size;
    char* pszStringTable = pszDebugDataOffset +  pDebugInfo->StringOffset;
    UINT* puiUintTable = (UINT*)(pszDebugDataOffset +  pDebugInfo->UintOffset);

    D3D10_SHADER_DEBUG_FILE_INFO* pFileInfo = (D3D10_SHADER_DEBUG_FILE_INFO*)(pszDebugDataOffset + pDebugInfo->FileInfo);
    D3D10_SHADER_DEBUG_INST_INFO* pInstructionInfo = (D3D10_SHADER_DEBUG_INST_INFO*)(pszDebugDataOffset + pDebugInfo->InstructionInfo);
    D3D10_SHADER_DEBUG_VAR_INFO* pVariableInfo = (D3D10_SHADER_DEBUG_VAR_INFO*)(pszDebugDataOffset + pDebugInfo->VariableInfo);
    D3D10_SHADER_DEBUG_INPUT_INFO* pInputVariableInfo = (D3D10_SHADER_DEBUG_INPUT_INFO*)(pszDebugDataOffset + pDebugInfo->InputVariableInfo);
    D3D10_SHADER_DEBUG_TOKEN_INFO* pTokenInfo = (D3D10_SHADER_DEBUG_TOKEN_INFO*)(pszDebugDataOffset + pDebugInfo->TokenInfo);
    D3D10_SHADER_DEBUG_SCOPE_INFO* pScopeInfo = (D3D10_SHADER_DEBUG_SCOPE_INFO*)(pszDebugDataOffset + pDebugInfo->ScopeInfo);
    D3D10_SHADER_DEBUG_SCOPEVAR_INFO* pScopeVariableInfo = (D3D10_SHADER_DEBUG_SCOPEVAR_INFO*)(pszDebugDataOffset + pDebugInfo->ScopeVariableInfo);

    std::string strLine, strTemp;
    strDebugInfo += "ShaderDebugInfo\n";
    strLine = str(format("Size = %i\n") % pDebugInfo->Size);
    strDebugInfo += strLine;
    strLine = str(format("Creator = \"%s\"\n") % (pszStringTable + pDebugInfo->Creator));
    strDebugInfo += strLine;
    strLine = str(format("EntrypointName = \"%s\"\n") % (pszStringTable + pDebugInfo->EntrypointName));
    strDebugInfo += strLine;
    strLine = str(format("ShaderTarget = \"%s\"\n") % (pszStringTable + pDebugInfo->ShaderTarget));
    strDebugInfo += strLine;
    strLine = str(format("CompileFlags = %08x\n") % pDebugInfo->CompileFlags);
    strDebugInfo += strLine;

    strLine = str(format("Files = %i\n") % pDebugInfo->Files);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->Files; i++)
    {
        strLine = str(format("\tFile %i\n") % i);
        strDebugInfo += strLine;

        if (pFileInfo[i].FileNameLen)
        {
            strLine = str(format("\t\tFileName = \"%s\"\n") % (pszStringTable + pFileInfo[i].FileName));
        }
        else
        {
            strLine = "\t\tFileName = NULL\n";
        }

        strLine = str(format("\t\tFileLen = %i\n") % pFileInfo[i].FileLen);
        strDebugInfo += strLine;
    }

    strLine = str(format("Instructions = %i\n") % pDebugInfo->Instructions);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->Instructions; i++)
    {

        strLine = str(format("\tInstruction %i\n") % i);
        strDebugInfo += strLine;
        strLine = str(format("\t\tId = %i\n") % pInstructionInfo[i].Id);
        strDebugInfo += strLine;
        strLine = str(format("\t\tOp = %s\n") % D3D10ShaderUtils::GetOpCodeName(DECODE_D3D10_SB_OPCODE_TYPE(pInstructionInfo[i].Opcode)));
        strDebugInfo += strLine;

        strLine = str(format("\t\tuOutputs = %i\n") % pInstructionInfo[i].uOutputs);
        strDebugInfo += strLine;

        for (UINT j = 0; j < pInstructionInfo[i].uOutputs; j++)
        {
            strLine = str(format("\t\t\tOutput %i\n") % j);
            strDebugInfo += strLine;
            strLine = str(format("\t\t\t\tOutputRegisterSet = %s\n") % pszRegSet[pInstructionInfo[i].pOutputs[j].OutputRegisterSet]);
            strDebugInfo += strLine;
            strLine = str(format("\t\t\t\tOutputReg = %i\n") % pInstructionInfo[i].pOutputs[j].OutputReg);
            strDebugInfo += strLine;
            strLine = str(format("\t\t\t\tTempArrayReg = %i\n") % pInstructionInfo[i].pOutputs[j].TempArrayReg);
            strDebugInfo += strLine;
            strLine = str(format("\t\t\t\tOutputComponents = {%i, %i, %i, %i}\n") % pInstructionInfo[i].pOutputs[j].OutputComponents[0] % pInstructionInfo[i].pOutputs[j].OutputComponents[1] % pInstructionInfo[i].pOutputs[j].OutputComponents[2] % pInstructionInfo[i].pOutputs[j].OutputComponents[3]);
            strDebugInfo += strLine;

            for (UINT k = 0; k < 4; k++)
            {
                UINT nVar = 0;
                //                     if(pInstructionInfo[i].pOutputs[j].OutputReg == -1)
                //                     {
                //                     }
                //                     else
                nVar = pInstructionInfo[i].pOutputs[j].OutputVars[k].Var;

                if (nVar != 0xffffffff)
                {
                    std::string strVariableInfo("");
                    PrintVariableInfo(pDebugInfo, nVar, strVariableInfo);

                    strLine = str(format("\t\t\t\t\tVar %i = %i - %s\n") % k % nVar % strVariableInfo);
                    strDebugInfo += strLine;

                    if (pVariableInfo[nVar].Type == D3D10_SVT_UINT)
                    {
                        strLine = str(format("\t\t\t\t\t\tUint Range = %u - %u\n") % pInstructionInfo[i].pOutputs[j].OutputVars[k].uValueMin % pInstructionInfo[i].pOutputs[j].OutputVars[k].uValueMax);
                        strDebugInfo += strLine;
                    }
                    else if (pVariableInfo[nVar].Type == D3D10_SVT_INT)
                    {
                        strLine = str(format("\t\t\t\t\t\tInt Range = %i - %i\n") % pInstructionInfo[i].pOutputs[j].OutputVars[k].iValueMin % pInstructionInfo[i].pOutputs[j].OutputVars[k].iValueMax);
                        strDebugInfo += strLine;
                    }
                    else if (pVariableInfo[nVar].Type == D3D10_SVT_FLOAT)
                    {
                        strLine = str(format("\t\t\t\t\t\tFloat Range = %f - %f\n\t\t\t\t\t\tbNaNPossible = %s, bInfPossible = %s\n") %
                                      pInstructionInfo[i].pOutputs[j].OutputVars[k].fValueMin % pInstructionInfo[i].pOutputs[j].OutputVars[k].fValueMax %
                                      (pInstructionInfo[i].pOutputs[j].OutputVars[k].bNaNPossible ? "TRUE" : "FALSE") % (pInstructionInfo[i].pOutputs[j].OutputVars[k].bInfPossible ? "TRUE" : "FALSE"));
                        strDebugInfo += strLine;
                    }
                }
                else
                {
                    strLine = str(format("\t\t\t\t\tVar %i = %i\n") % k % nVar);
                    strDebugInfo += strLine;
                }
            }

            strLine = str(format("\t\t\t\tIndexReg = %i\n") % pInstructionInfo[i].pOutputs[j].IndexReg);
            strDebugInfo += strLine;
            strLine = str(format("\t\t\t\tIndexComp = %i\n") % pInstructionInfo[i].pOutputs[j].IndexComp);
            strDebugInfo += strLine;
        }

        strLine = str(format("\t\tToken = %s\n") % PrintTokenInfo(pDebugInfo, pInstructionInfo[i].TokenId, strTemp));
        strDebugInfo += strLine;
        strLine = str(format("\t\tuNestingLevel = %i\n") % pInstructionInfo[i].NestingLevel);
        strDebugInfo += strLine;

        strLine = str(format("\t\tScopes = %i\n") % pInstructionInfo[i].Scopes);
        strDebugInfo += strLine;
        UINT* pScopeNum = (UINT*)(((char*) puiUintTable) + pInstructionInfo[i].ScopeInfo);

        for (UINT j = 0; j < pInstructionInfo[i].Scopes; j++)
        {
            std::string strScopeInfo;
            PrintScopeInfo(pDebugInfo, *pScopeNum, strScopeInfo);

            strLine = str(format("\t\t\tScope %i = %i - %s\n") % j % *pScopeNum % strScopeInfo);
            strDebugInfo += strLine;
            pScopeNum++;
        }

        strLine = str(format("\t\tAccessedVars = %i\n") % pInstructionInfo[i].AccessedVars);
        strDebugInfo += strLine;
        UINT* pAccessedVarNum = (UINT*)(((char*) puiUintTable) + pInstructionInfo[i].AccessedVarsInfo);

        for (UINT j = 0; j < pInstructionInfo[i].AccessedVars; j++)
        {
            std::string strScopeVarInfo;
            PrintScopeVariableInfo(pDebugInfo, *pAccessedVarNum, strScopeVarInfo);

            strLine = str(format("\t\t\tAccessedVars %i = %i - %s\n") % j % *pAccessedVarNum % strScopeVarInfo);
            strDebugInfo += strLine;
            *pAccessedVarNum++;
        }
    }

    strLine = str(format("Variables = %i\n") % pDebugInfo->Variables);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->Variables; i++)
    {
        std::string strTokenInfo;
        PrintTokenInfo(pDebugInfo, pVariableInfo[i].TokenId, strTokenInfo);

        strLine = str(format("\tVariable %i\n") % i);
        strDebugInfo += strLine;
        strLine = str(format("\t\tToken = %s\n") % strTokenInfo);
        strDebugInfo += strLine;
        strLine = str(format("\t\tType = %s\n") % pszVarType[pVariableInfo[i].Type]);
        strDebugInfo += strLine;

        if (pVariableInfo[i].Type == D3D10_SVT_TEXTURE1DARRAY || pVariableInfo[i].Type == D3D10_SVT_TEXTURE2DARRAY ||
            pVariableInfo[i].Type == D3D10_SVT_TEXTURE2DMSARRAY || pVariableInfo[i].Type == D3D10_SVT_TEXTURECUBEARRAY)
        {
            strLine = str(format("\t\tRegister = %i\n") % pVariableInfo[i].Register);
            strDebugInfo += strLine;
            strLine = str(format("\t\tComponent = %i\n") % pVariableInfo[i].Component);
            strDebugInfo += strLine;
        }

        strLine = str(format("\t\tScopeVar = %i\n") % pVariableInfo[i].ScopeVar);
        strDebugInfo += strLine;
        strLine = str(format("\t\tScopeVarOffset = %i\n") % pVariableInfo[i].ScopeVarOffset);
        strDebugInfo += strLine;
    }

    strLine = str(format("InputVariables = %i\n") % pDebugInfo->InputVariables);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->InputVariables; i++)
    {
        std::string strTokenInfo;
        PrintTokenInfo(pDebugInfo, pVariableInfo[pInputVariableInfo[i].Var].TokenId, strTokenInfo);

        strLine = str(format("\tInputVariable %i\n") % i);
        strDebugInfo += strLine;
        strLine = str(format("\t\tVar = %s\n") % strTokenInfo);
        strDebugInfo += strLine;
        strLine = str(format("\t\tInitialRegisterSet = %s\n") % pszRegSet[pInputVariableInfo[i].InitialRegisterSet]);
        strDebugInfo += strLine;

        if (pInputVariableInfo[i].InitialBank != -1)
        {
            strLine = str(format("\t\tInitialBank = %i\n") % pInputVariableInfo[i].InitialBank);
            strDebugInfo += strLine;
        }

        if (pInputVariableInfo[i].InitialRegister != -1)
        {
            strLine = str(format("\t\tInitialRegister = %i\n") % pInputVariableInfo[i].InitialRegister);
            strDebugInfo += strLine;
        }

        if (pInputVariableInfo[i].InitialComponent != -1)
        {
            strLine = str(format("\t\tInitialComponent = %i\n") % pInputVariableInfo[i].InitialComponent);
            strDebugInfo += strLine;
        }

        if (pInputVariableInfo[i].InitialRegisterSet == D3D10_SHADER_DEBUG_REG_LITERAL)
        {
            strLine = str(format("\t\tInitialValue = %i\n") % pInputVariableInfo[i].InitialValue);
            strDebugInfo += strLine;
        }
    }

    strLine = str(format("Tokens = %i\n") % pDebugInfo->Tokens);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->Tokens; i++)
    {
        strLine = str(format("\tToken %i\n") % i);
        strDebugInfo += strLine;
        strLine = str(format("\t\tFile = %i\n") % pTokenInfo[i].File);
        strDebugInfo += strLine;
        strLine = str(format("\t\tLine = %i\n") % pTokenInfo[i].Line);
        strDebugInfo += strLine;
        strLine = str(format("\t\tColumn = %i\n") % pTokenInfo[i].Column);
        strDebugInfo += strLine;
        strLine = str(format("\t\tTokenLength = %i\n") % pTokenInfo[i].TokenLength);
        strDebugInfo += strLine;

        std::string strTokenName;

        if (pTokenInfo[i].TokenLength)
        {
            strTokenName = std::string((pszStringTable + pTokenInfo[i].TokenId), pTokenInfo[i].TokenLength);
        }
        else
        {
            strTokenName = "NULL";
        }

        strLine = str(format("\t\tTokenId = %s\n") % strTokenName);
        strDebugInfo += strLine;
    }

    strLine = str(format("Scopes = %i\n") % pDebugInfo->Scopes);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->Scopes; i++)
    {
        strLine = str(format("\tScope %i\n") % i);
        strDebugInfo += strLine;
        strLine = str(format("\t\tScopeType = %s\n") % pszScopeType[pScopeInfo[i].ScopeType]);
        strDebugInfo += strLine;
        strLine = str(format("\t\tuName = %s\n") % std::string((pszStringTable + pScopeInfo[i].Name), pScopeInfo[i].uNameLen));
        strDebugInfo += strLine;

        strLine = str(format("\t\tuVariables = %i\n") % pScopeInfo[i].uVariables);
        strDebugInfo += strLine;
        strLine = str(format("\t\tuVariableData = %i\n") % pScopeInfo[i].VariableData);
        strDebugInfo += strLine;
        //             for(UINT j = 0; j < pScopeInfo[i].uVariables; j++)
        //             {
        //                 strLine = str(format("\t\t\tVariable %i = %s\n") % j ,PrintVariableInfo(pScopeInfo[i], puiUintTable[j], strTemp));
        //                 strDebugInfo += strLine;
        //             }
    }

    strLine = str(format("ScopeVariables = %i\n") % pDebugInfo->ScopeVariables);
    strDebugInfo += strLine;

    for (UINT i = 0; i < pDebugInfo->ScopeVariables; i++)
    {
        std::string strTokenInfo;
        PrintTokenInfo(pDebugInfo, pScopeVariableInfo[i].TokenId, strTokenInfo);

        strLine = str(format("\tScopeVariable %i\n") % i);
        strDebugInfo += strLine;
        strLine = str(format("\t\tToken = %s\n") % PrintTokenInfo(pDebugInfo, pScopeVariableInfo[i].TokenId, strTemp));
        strDebugInfo += strLine;
        strLine = str(format("\t\tVarType = %s\n") % pszDebugVarType[pScopeVariableInfo[i].VarType]);
        strDebugInfo += strLine;
        strLine = str(format("\t\tClass = %s\n") % pszVarClass[pScopeVariableInfo[i].Class]);
        strDebugInfo += strLine;
        strLine = str(format("\t\tRows = %i\n") % pScopeVariableInfo[i].Rows);
        strDebugInfo += strLine;
        strLine = str(format("\t\tColumns = %i\n") % pScopeVariableInfo[i].Columns);
        strDebugInfo += strLine;
        strLine = str(format("\t\tStructMemberScope = %i\n") % pScopeVariableInfo[i].StructMemberScope);
        strDebugInfo += strLine;

        if (pScopeVariableInfo[i].uArrayIndices > 0)
        {
            strLine = str(format("\t\tuArrayIndices = %i\n") % pScopeVariableInfo[i].uArrayIndices);
            strDebugInfo += strLine;
            strLine = str(format("\t\tArrayElements = NOT DONE\n"/* % pScopeVariableInfo[i].ArrayElements*/));
            strDebugInfo += strLine;
            strLine = str(format("\t\tArrayStrides = NOT DONE\n"/* % pScopeVariableInfo[i].ArrayStrides*/));
            strDebugInfo += strLine;
        }

        strLine = str(format("\t\tuVariables = %i\n") % pScopeVariableInfo[i].uVariables);
        strDebugInfo += strLine;

        if (pScopeVariableInfo[i].uVariables > 0)
        {
            strLine = str(format("\t\tuFirstVariable = %i\n") % pScopeVariableInfo[i].uFirstVariable);
            strDebugInfo += strLine;

            std::string strVariableInfo;
            PrintVariableInfo(pDebugInfo, pScopeVariableInfo[i].uFirstVariable, strVariableInfo);

            strLine = str(format("\t\tVariables = %s\n") % strVariableInfo);
            strDebugInfo += strLine;
        }
    }

    return true;
}
int main(int argc, char* argv[])
{
  if (argc < 2) { fprintf(stderr, "Usage: %s <spidev>", argv[0]); return 1; }

  shared_ptr<SX1276Platform> platform = SX1276Platform::GetInstance(argv[1]);
  if (!platform) { PR_ERROR("Unable to create platform instance. Note, use /dev/tty... for BusPirate, otherwise, /dev/spidevX.Y\n"); return 1; }

  shared_ptr<SPI> spi = platform->GetSPI();
  if (!spi) { PR_ERROR("Unable to get SPI instance\n"); return 1; }

  // Pass a small value in for RTL-SDK spectrum analyser to show up
  unsigned inter_msg_delay_us = 200000;
  if (getenv("BEACON_INTERVAL")) { inter_msg_delay_us = atoi(getenv("BEACON_INTERVAL")); }

  Misc::UserTraceSettings(spi);

  // TODO work out how to run without powering off / resetting the module

  usleep(100);
  SX1276Radio radio(spi);

  cout << format("SX1276 Version: %.2x\n") % radio.version();

  platform->ResetSX1276();

  radio.ChangeCarrier(919000000);
  radio.ApplyDefaultLoraConfiguration();
  cout << format("Check read Carrier Frequency: %uHz\n") % radio.carrier();

  if (radio.fault()) return 1;

  char msg[128];
  printf("Beacon message: '%s'\n", safe_str(msg).c_str());
  printf("Predicted time on air: %fs\n", radio.PredictTimeOnAir(msg));

  int total = 0;
  int faultCount = 0;
  while (true) {
    total++;

    time_t rawt;
    struct tm *ti;
    char buft[80];
    time(&rawt);
    ti = localtime(&rawt);
    strftime(buft,80,"%d-%m-%Y %I:%M:%S", ti);
    snprintf(msg, sizeof(msg), "TX BEACON %6d %s\n", total, buft);
	
    if (radio.SendSimpleMessage(msg)) { printf("%d ", total); fflush(stdout); radio.Standby(); usleep(inter_msg_delay_us); continue; }
    radio.Standby();
    printf("\n");
    faultCount++;
    PR_ERROR("Fault on send detected: %d of %d\n", faultCount, total);
    printf("Beacon message: '%s'\n", safe_str(msg).c_str());
    printf("Predicted time on air: %fs\n", radio.PredictTimeOnAir(msg));
    radio.reset_fault();
    platform->ResetSX1276();
    radio.ChangeCarrier(919000000);
    radio.ApplyDefaultLoraConfiguration();
    usleep(500000);
  }
  return 1;
}
Exemple #18
0
core::Error initialize()
{
   git::initialize();
   svn::initialize();

   // http endpoints
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "vcs_clone", vcsClone));
   Error error = initBlock.execute();
   if (error)
      return error;

   // If VCS is disabled, or we're not in a project, do nothing
   const projects::ProjectContext& projContext = projects::projectContext();
   FilePath workingDir = projContext.directory();

   if (!session::options().allowVcs() || !userSettings().vcsEnabled() || workingDir.empty())
      return Success();


   // If Git or SVN was explicitly specified, choose it if valid
   projects::RProjectVcsOptions vcsOptions;
   if (projContext.hasProject())
   {
      Error vcsError = projContext.readVcsOptions(&vcsOptions);
      if (vcsError)
         LOG_ERROR(vcsError);
   }

   if (vcsOptions.vcsOverride == kVcsIdNone)
   {
      return Success();
   }
   else if (vcsOptions.vcsOverride == git::kVcsId)
   {
      if (git::isGitInstalled() && git::isGitDirectory(workingDir))
         return git::initializeGit(workingDir);
      return Success();
   }
   else if (vcsOptions.vcsOverride == svn::kVcsId)
   {
      if (svn::isSvnInstalled() && svn::isSvnDirectory(workingDir))
         return svn::initializeSvn(workingDir);
      return Success();
   }

   if (git::isGitInstalled() && git::isGitDirectory(workingDir))
   {
      return git::initializeGit(workingDir);
   }
   else if (svn::isSvnInstalled() && svn::isSvnDirectory(workingDir))
   {
      return svn::initializeSvn(workingDir);
   }
   else
   {
      return Success();  // none specified or detected
   }
}
Exemple #19
0
void GuideSemantics::CreateGuideMapping()
{
    m_GuideTypeMapping[ GuideSemantics::Cover ]
        = make_tuple(QString("cover"),           QObject::tr("Cover"));
    m_GuideTypeMapping[ GuideSemantics::TitlePage ]
        = make_tuple(QString("title-page"),      QObject::tr("Title Page"));
    m_GuideTypeMapping[ GuideSemantics::TableOfContents ]
        = make_tuple(QString("toc"),             QObject::tr("Table Of Contents"));
    m_GuideTypeMapping[ GuideSemantics::Index ]
        = make_tuple(QString("index"),           QObject::tr("Index"));
    m_GuideTypeMapping[ GuideSemantics::Glossary ]
        = make_tuple(QString("glossary"),        QObject::tr("Glossary"));
    m_GuideTypeMapping[ GuideSemantics::Acknowledgements ]
        = make_tuple(QString("acknowledgements"), QObject::tr("Acknowledgements"));
    m_GuideTypeMapping[ GuideSemantics::Bibliography ]
        = make_tuple(QString("bibliography"),    QObject::tr("Bibliography"));
    m_GuideTypeMapping[ GuideSemantics::Colophon ]
        = make_tuple(QString("colophon"),        QObject::tr("Colophon"));
    m_GuideTypeMapping[ GuideSemantics::CopyrightPage ]
        = make_tuple(QString("copyright-page"),  QObject::tr("Copyright Page"));
    m_GuideTypeMapping[ GuideSemantics::Dedication ]
        = make_tuple(QString("dedication"),      QObject::tr("Dedication"));
    m_GuideTypeMapping[ GuideSemantics::Epigraph ]
        = make_tuple(QString("epigraph"),        QObject::tr("Epigraph"));
    m_GuideTypeMapping[ GuideSemantics::Foreword ]
        = make_tuple(QString("foreword"),        QObject::tr("Foreword"));
    m_GuideTypeMapping[ GuideSemantics::ListOfIllustrations ]
        = make_tuple(QString("loi"),             QObject::tr("List Of Illustrations"));
    m_GuideTypeMapping[ GuideSemantics::ListOfTables ]
        = make_tuple(QString("lot"),             QObject::tr("List Of Tables"));
    m_GuideTypeMapping[ GuideSemantics::Notes ]
        = make_tuple(QString("notes"),           QObject::tr("Notes"));
    m_GuideTypeMapping[ GuideSemantics::Preface ]
        = make_tuple(QString("preface"),         QObject::tr("Preface"));
    m_GuideTypeMapping[ GuideSemantics::Text ]
        = make_tuple(QString("text"),            QObject::tr("Text"));
}
/// \brief Combine a dssp_file and pdb representing the same structure in a sensible protein object
///
/// \relates dssp_file
///
/// \TODO Consider taking an ostream_ref_opt argument rather than assuming cerr
///       (fix all errors, *then* provide default of boost::none)
protein cath::file::protein_from_dssp_and_pdb(const dssp_file        &arg_dssp_file,        ///< The dssp_file object for a given structure
                                              const pdb              &arg_pdb_file,         ///< The dssp_file object for a given structure
                                              const dssp_skip_policy &arg_dssp_skip_policy, ///< Whether to exclude residues that are in the PDB but not the DSSP
                                              const string           &arg_name,             ///< The name to set as the title of the protein
                                              const ostream_ref_opt  &arg_ostream           ///< An optional reference to an ostream to which any logging should be sent
                                              ) {
	// Build a rough protein object from the pdb object
	const auto pdb_protein       = build_protein_of_pdb(
		arg_pdb_file,
		arg_ostream,
		( arg_dssp_skip_policy == dssp_skip_policy::SKIP__BREAK_ANGLES )
			? dssp_skip_policy::DONT_SKIP__BREAK_ANGLES
			: arg_dssp_skip_policy
	);
	const auto pdb_skip_indices  = get_protein_res_indices_that_dssp_might_skip( arg_pdb_file, arg_ostream );

	// Grab the number of residues in the protein and dssp_file objects
	const auto num_dssp_residues = arg_dssp_file.get_num_residues();
	const auto num_pdb_residues  = pdb_protein.get_length();

	// Grab the residues names from the DSSP and PDB and then tally them up
	const auto pdb_res_names     = get_residue_ids  ( pdb_protein );
	const auto dssp_res_names    = get_residue_ids  ( arg_dssp_file, false );
	const auto alignment         = tally_residue_ids(
		pdb_res_names,
		dssp_res_names,
		false,
		true,
		pdb_skip_indices
	);

	// Prepare a list of new residue to populate
	residue_vec new_residues;
	new_residues.reserve( ( arg_dssp_skip_policy == dssp_skip_policy::SKIP__BREAK_ANGLES ) ? num_dssp_residues : num_pdb_residues );

	// Loop over the residues
	size_t alignment_ctr = 0;
	for (const size_t &pdb_residue_ctr : irange( 0_z, num_pdb_residues ) ) {
		const residue &the_pdb_residue = pdb_protein.get_residue_ref_of_index( pdb_residue_ctr );

		// If this PDB residue is in the alignment then it can be combined with the equivalent DSSP residue
		const bool is_in_alignment     = ( (alignment_ctr < alignment.size() ) && ( alignment[alignment_ctr].first == pdb_residue_ctr ) );
		if ( is_in_alignment ) {
			// Combine the two residues and add them to the back
			const residue &the_dssp_residue = arg_dssp_file.get_residue_of_index( alignment[alignment_ctr].second );
			new_residues.push_back(
				combine_residues_from_dssp_and_pdb(
					the_dssp_residue,
					the_pdb_residue,
					angle_skipping_of_dssp_skip_policy( arg_dssp_skip_policy )
				)
			);

			// Increment the alignment counter
			++alignment_ctr;
		}
		else if ( res_skipping_of_dssp_skip_policy( arg_dssp_skip_policy ) == dssp_skip_res_skipping::DONT_SKIP ) {
			new_residues.push_back( the_pdb_residue );
		}
	}

	// Construct a new protein from the new list of residues
	return { arg_name, new_residues };
}
Exemple #21
0
real Closure::G_i(real k) const {
    return -k*k/(4*M_PI*M_PI) * 1/36. * Integrate<ExpSub>(bind(B_i, cref(P_i), k, _1), QMIN, QMAX, EPS);
}
Exemple #22
0
    void readFromMultilineAdjacencyList( const string& fname, GraphT& G ) {
        typedef typename boost::graph_traits< GraphT >::vertex_descriptor Vertex;
        typedef typename boost::graph_traits< GraphT >::edge_descriptor Edge;

        typedef unordered_map<string,Vertex> svMap;

        svMap namePosMap;
        bool inserted;
        Vertex u,v;
        typename unordered_map<string,Vertex>::iterator pos;

        bool headLine = false;
        size_t remEdgeLine = 0;
        string line;
        typedef vector< string > splitVectorT;
        ifstream gfile(fname);
        if ( gfile.is_open() ) {
            while( gfile.good() ) {
                getline( gfile, line, '\n' );
                if ( gfile.eof() ) { break; }
                boost::algorithm::trim(line);
                auto vline = line.substr( 0, line.find_first_of('#') );

                if (vline.length() == 0) { continue; }

                splitVectorT splitVec;
                split( splitVec, vline, is_any_of(" \t"), token_compress_on );

                if ( splitVec.size() > 0  and vline.size() > 0 ) {
                    auto fromVert = splitVec[0];
                    remEdgeLine = lexical_cast<size_t>(splitVec[1]);

                    boost::tie( pos, inserted ) = namePosMap.insert( std::make_pair(fromVert,Vertex()) );
                    if (inserted) {
                        u = add_vertex(G);
                        G[u].name = fromVert;
                        // This will happen later
                        // G[u].idx = nameMap[fromVert];
                        pos->second = u;
                    } else {
                        u = pos->second;
                    }

                    while ( remEdgeLine > 0 ) {

                        getline( gfile, line, '\n' );
                        boost::algorithm::trim(line);
                        vline = line.substr( 0, line.find_first_of('#') );
                        split( splitVec, vline, is_any_of(" \t"), token_compress_on );

                        auto toVert = splitVec[0];
                        double weight = lexical_cast<double>(splitVec[1]);


                        boost::tie(pos, inserted) = namePosMap.insert(std::make_pair(toVert, Vertex()));
                        if (inserted) {
                            v = add_vertex(G);
                            G[v].name = toVert;
                            // This will happen later
                            // G[v].idx = nameMap[toVert];
                            pos->second = v;
                        } else {
                            v = pos->second;
                        }

                        Edge e; bool i;
                        boost::tie(e,i) = add_edge(u,v,G);
                        G[e].weight = weight;
                        remEdgeLine--;
                    }
                }

            }

            if ( namePosMap.size() != boost::num_vertices(G) ) {
                std::cerr << "(namePosMap.size() = " << namePosMap.size() << ") != ("
                          << "(order(G) = " << boost::num_vertices(G) << ") : Error building the graph, aborting\n";
                std::abort();
            }
        }
        gfile.close();

    }
karaoke_match_result auto_match_karaoke(std::vector<std::string> const& source_strings, std::string const& dest_string) {
	karaoke_match_result result = { 0, 0 };
	if (source_strings.empty()) return result;

	using namespace boost::locale::boundary;
	using boost::starts_with;

	result.source_length = 1;
	ssegment_index destination_characters(character, begin(dest_string), end(dest_string));
	auto src = boost::to_lower_copy(source_strings[0]);
	auto dst = destination_characters.begin();
	auto dst_end = destination_characters.end();

	// Eat all the whitespace at the beginning of the source and destination
	// syllables and exit if either ran out.
	auto eat_whitespace = [&]() -> bool {
		size_t i = 0, first_non_whitespace = 0;
		while (is_whitespace(next_codepoint(src.c_str(), &i)))
			first_non_whitespace = i;
		if (first_non_whitespace)
			src = src.substr(first_non_whitespace);

		while (dst != dst_end && is_whitespace(dst->str())) {
			++dst;
			++result.destination_length;
		}

		// If we ran out of dest then this needs to match the rest of the
		// source syllables (this probably means the user did something wrong)
		if (dst == dst_end) {
			result.source_length = source_strings.size();
			return true;
		}

		return src.empty();
	};

	if (eat_whitespace()) return result;

	// We now have a non-whitespace character at the beginning of both source
	// and destination. Check if the source starts with a romanized kana, and
	// if it does then check if the destination also has the appropriate
	// character. If it does, match them and repeat.
	while (!src.empty()) {
		// First check for a basic match of the first character of the source and dest
		auto first_src_char = ssegment_index(character, begin(src), end(src)).begin()->str();
		if (compare(first_src_char, dst->str()) == 0) {
			++dst;
			++result.destination_length;
			src.erase(0, first_src_char.size());
			if (eat_whitespace()) return result;
			continue;
		}

		auto check = [&](kana_pair const& kp) -> bool {
			if (!starts_with(&*dst->begin(), kp.kana)) return false;

			src = src.substr(strlen(kp.romaji));
			for (size_t i = 0; kp.kana[i]; ) {
				i += dst->length();
				++result.destination_length;
				++dst;
			}
			return true;
		};

		bool matched = false;
		for (auto const& match : romaji_to_kana(src)) {
			if (check(match)) {
				if (eat_whitespace()) return result;
				matched = true;
				break;
			}
		}
		if (!matched) break;
	}

	// Source and dest are now non-empty and start with non-whitespace.
	// If there's only one character left in the dest, it obviously needs to
	// match all of the source syllables left.
	if (std::distance(dst, dst_end) == 1) {
		result.source_length = source_strings.size();
		++result.destination_length;
		return result;
	}

	// We couldn't match the current character, but if we can match the *next*
	// syllable then we know that everything in between must belong to the
	// current syllable. Do this by looking up to KANA_SEARCH_DISTANCE
	// characters ahead in destination and seeing if we can match them against
	// the beginning of a syllable after this syllable.
	// If a match is found, make a guess at how much source and destination
	// should be selected based on the distances it was found at.

	// The longest kanji are 'uketamawa.ru' and 'kokorozashi', each with a
	// reading consisting of five kana. This means each each character from
	// the destination can match at most five syllables from the source.
	static const int max_character_length = 5;

	// Arbitrarily chosen limit on the number of dest characters to try
	// skipping. Higher numbers probably increase false-positives.
	static const int dst_lookahead_max = 3;

	for (size_t lookahead = 0; lookahead < dst_lookahead_max; ++lookahead) {
		if (++dst == dst_end) break;

		// Transliterate this character if it's a known hiragana or katakana character
		std::vector<const char *> translit;
		auto next = std::next(dst);
		if (next != dst_end)
			boost::copy(kana_to_romaji(dst->str() + next->str()), back_inserter(translit));
		boost::copy(kana_to_romaji(dst->str()), back_inserter(translit));

		// Search for it and the transliterated version in the source
		int src_lookahead_max = (lookahead + 1) * max_character_length;
		int src_lookahead_pos = 0;
		for (auto const& syl : source_strings) {
			// Don't count blank syllables in the max search distance
			if (is_whitespace(syl)) continue;
			if (++src_lookahead_pos == 1) continue;
			if (src_lookahead_pos > src_lookahead_max) break;

			std::string lsyl = boost::to_lower_copy(syl);
			if (!(starts_with(syl, dst->str()) || util::any_of(translit, [&](const char *str) { return starts_with(lsyl, str); })))
				continue;

			// The syllable immediately after the current one matched, so
			// everything up to the match must go with the current syllable.
			if (src_lookahead_pos == 2) {
				result.destination_length += lookahead + 1;
				return result;
			}

			// The match was multiple syllables ahead, so just divide the
			// destination characters evenly between the source syllables
			result.destination_length += 1;
			result.source_length = static_cast<size_t>((src_lookahead_pos - 1.0) / (lookahead + 1.0) + .5);
			return result;
		}
	}

	// We wouldn't have gotten here if the dest was empty, so make sure at
	// least one character is selected
	result.destination_length = std::max<size_t>(result.destination_length, 1u);

	return result;
}
Exemple #24
0
    void readFromAdjacencyList( const string& fname, GraphT& G ) {
        typedef typename boost::graph_traits< GraphT >::vertex_descriptor Vertex;
        typedef typename boost::graph_traits< GraphT >::edge_descriptor Edge;
        typedef unordered_map<string,Vertex> svMap;

        svMap namePosMap;
        bool inserted;
        Vertex u,v;
        typename unordered_map<string,Vertex>::iterator pos;

        string line;
        typedef vector< string > splitVectorT;
        ifstream gfile(fname);
        size_t numInsertedVerts = 0;
        if ( gfile.is_open() ) {
            while( gfile.good() ) {
                getline( gfile, line, '\n' );
                if ( gfile.eof() ) { break; }
                boost::algorithm::trim(line);
                auto vline = line.substr( 0, line.find_first_of('#') );
                splitVectorT splitVec;
                split( splitVec, vline, is_any_of(" \t"), token_compress_on );

                if ( splitVec.size() > 0  and vline.size() > 0 ) {
                    auto fromVert = splitVec[0];
                    boost::tie( pos, inserted ) = namePosMap.insert( std::make_pair(fromVert,Vertex()) );
                    if (inserted) {
                        ++numInsertedVerts;
                        u = add_vertex(G);
                        G[u].name = fromVert;
                        // This will happen later
                        // G[u].idx = nameMap[fromVert];
                        pos->second = u;
                    } else {
                        u = pos->second;
                    }

                    for( auto tgtIt = splitVec.begin() + 1; tgtIt != splitVec.end(); ++tgtIt ) {
                        auto& tgt = *tgtIt;
                        boost::tie(pos, inserted) = namePosMap.insert(std::make_pair(tgt, Vertex()));
                        if (inserted) {
                            ++numInsertedVerts;
                            v = add_vertex(G);
                            G[v].name = tgt;
                            // This will happen later
                            // G[v].idx = nameMap[tgt];
                            pos->second = v;
                        } else {
                            v = pos->second;
                        }

                        Edge e; bool i;
                        boost::tie(e,i) = add_edge(u,v,G); 
                        G[e].weight = 1.0;
                    } 
                }

            }
            
            if ( namePosMap.size() != boost::num_vertices(G) ) {
                std::cerr << "(namePosMap.size() = " << namePosMap.size() << ") != ("
                          << "(order(G) = " << boost::num_vertices(G) << ") : Error building the graph, aborting\n";
                std::abort();
            }
        }
        gfile.close();

    }
int main(int argc, char* argv[]){

  // Configurable parameters
  int max_events;                 // Maximum number of events to process
  string filelist;                // The file containing a list of files to use as input
  string input_prefix;            // A prefix that will be added to the path of each input file
  string output_name;             // Name of the ouput ROOT File
  string output_folder;           // Folder to write the output in
  
  po::options_description config("Configuration");
  po::variables_map vm;
  po::notify(vm);

  config.add_options()    
      ("max_events",          po::value<int>(&max_events)-> default_value(-1))
      ("filelist",            po::value<string>(&filelist)->required())
      ("input_prefix",        po::value<string>(&input_prefix)->default_value(""))
      ("output_name",         po::value<string>(&output_name)->required())
      ("output_folder",       po::value<string>(&output_folder)->default_value(""))
    ;
    po::store(po::command_line_parser(argc, argv).
              options(config).allow_unregistered().run(), vm);
    po::notify(vm);
  
  
  std::cout << "-------------------------------------" << std::endl;
  std::cout << "JetTauFakeRateStudy" << std::endl;
  std::cout << "-------------------------------------" << std::endl;      string param_fmt = "%-25s %-40s\n";
  
 
  // Load necessary libraries for ROOT I/O of custom classes
  gSystem->Load("libFWCoreFWLite.dylib");
  gSystem->Load("libUserCodeICHiggsTauTau.dylib");
  AutoLibraryLoader::enable();

  // Build a vector of input files
  vector<string> files = ParseFileLines(filelist);
  for (unsigned i = 0; i < files.size(); ++i) files[i] = input_prefix + files[i];
  
  // Create ROOT output fileservice
  fwlite::TFileService *fs = new fwlite::TFileService((output_folder+output_name).c_str());
  
  //Optional configurable parameters with which you can filter the collection you are interested in.
  double jet_pt, jet_eta, tau_pt, tau_eta;
  jet_pt = 20.0;
  jet_eta = 2.3; 
  tau_pt = 20.0;
  tau_eta = 2.3; 
   
  std::cout << "** Kinematics **" << std::endl;
  std::cout << boost::format(param_fmt) % "jet_pt" % jet_pt;
  std::cout << boost::format(param_fmt) % "jet_eta" % jet_eta;
  std::cout << boost::format(param_fmt) % "tau_pt" % tau_pt;
  std::cout << boost::format(param_fmt) % "tau_eta" % tau_eta;
 
 //Defining an analysis using this class removes all the need for any for loops through the events. An "analysis" loops through all the events up to max_events and runs the modules which you define at the end of this script using analysis.AddModule
  
  ic::AnalysisBase analysis(
    "JetTauFakeRateStudy",// Analysis name
    files,                // Input files
    "icEventProducer/EventTree", // TTree name
    max_events);          // Max. events to process (-1 = all)
  analysis.SetTTreeCaching(true);
  analysis.StopOnFileFailure(true);
  analysis.RetryFileAfterFailure(7, 3);

  //For now, read in all the jets and taus within the pt and eta range of interest. Using Andrew's modules makes it much easier to 
  //add other things later, if we need a certain type of ID (or flavour selection) applied to the jets/taus
  
  SimpleFilter<Tau> TauFilter = SimpleFilter<Tau>("TauFilter")
  .set_input_label("taus")
  .set_predicate(bind(MinPtMaxEta, _1, tau_pt, tau_eta));
  
  SimpleFilter<PFJet> JetFilter = SimpleFilter<PFJet>("JetFilter")
  .set_input_label("pfJetsPFlow")
  .set_predicate(bind(MinPtMaxEta, _1, jet_pt, jet_eta));

  JetTauFakeRateExample jetTauFakeRate = JetTauFakeRateExample("jetTauFakeRate")
  .set_write_plots(false)
  .set_write_tree(true);

 //Add module here which reads in the filtered taus and jets and makes the plots/performs the fake rate study
 
  analysis.AddModule(&TauFilter); 
  analysis.AddModule(&JetFilter); 
  analysis.AddModule(&jetTauFakeRate); 


  analysis.RunAnalysis();
  delete fs;
  return 0;
}
int main()
{
    using boost::mem_fn;

    X x;

    X const & rcx = x;
    X const * pcx = &x;

    boost::shared_ptr<X> sp(new X);

    mem_fn(&X::f0)(x);
    mem_fn(&X::f0)(&x);
    mem_fn(&X::f0)(sp);

    mem_fn(&X::g0)(x);
    mem_fn(&X::g0)(rcx);
    mem_fn(&X::g0)(&x);
    mem_fn(&X::g0)(pcx);
    mem_fn(&X::g0)(sp);

    mem_fn(&X::f1)(x, 1);
    mem_fn(&X::f1)(&x, 1);
    mem_fn(&X::f1)(sp, 1);

    mem_fn(&X::g1)(x, 1);
    mem_fn(&X::g1)(rcx, 1);
    mem_fn(&X::g1)(&x, 1);
    mem_fn(&X::g1)(pcx, 1);
    mem_fn(&X::g1)(sp, 1);

    mem_fn(&X::f2)(x, 1, 2);
    mem_fn(&X::f2)(&x, 1, 2);
    mem_fn(&X::f2)(sp, 1, 2);

    mem_fn(&X::g2)(x, 1, 2);
    mem_fn(&X::g2)(rcx, 1, 2);
    mem_fn(&X::g2)(&x, 1, 2);
    mem_fn(&X::g2)(pcx, 1, 2);
    mem_fn(&X::g2)(sp, 1, 2);

    mem_fn(&X::f3)(x, 1, 2, 3);
    mem_fn(&X::f3)(&x, 1, 2, 3);
    mem_fn(&X::f3)(sp, 1, 2, 3);

    mem_fn(&X::g3)(x, 1, 2, 3);
    mem_fn(&X::g3)(rcx, 1, 2, 3);
    mem_fn(&X::g3)(&x, 1, 2, 3);
    mem_fn(&X::g3)(pcx, 1, 2, 3);
    mem_fn(&X::g3)(sp, 1, 2, 3);

    mem_fn(&X::f4)(x, 1, 2, 3, 4);
    mem_fn(&X::f4)(&x, 1, 2, 3, 4);
    mem_fn(&X::f4)(sp, 1, 2, 3, 4);

    mem_fn(&X::g4)(x, 1, 2, 3, 4);
    mem_fn(&X::g4)(rcx, 1, 2, 3, 4);
    mem_fn(&X::g4)(&x, 1, 2, 3, 4);
    mem_fn(&X::g4)(pcx, 1, 2, 3, 4);
    mem_fn(&X::g4)(sp, 1, 2, 3, 4);

    mem_fn(&X::f5)(x, 1, 2, 3, 4, 5);
    mem_fn(&X::f5)(&x, 1, 2, 3, 4, 5);
    mem_fn(&X::f5)(sp, 1, 2, 3, 4, 5);

    mem_fn(&X::g5)(x, 1, 2, 3, 4, 5);
    mem_fn(&X::g5)(rcx, 1, 2, 3, 4, 5);
    mem_fn(&X::g5)(&x, 1, 2, 3, 4, 5);
    mem_fn(&X::g5)(pcx, 1, 2, 3, 4, 5);
    mem_fn(&X::g5)(sp, 1, 2, 3, 4, 5);

    mem_fn(&X::f6)(x, 1, 2, 3, 4, 5, 6);
    mem_fn(&X::f6)(&x, 1, 2, 3, 4, 5, 6);
    mem_fn(&X::f6)(sp, 1, 2, 3, 4, 5, 6);

    mem_fn(&X::g6)(x, 1, 2, 3, 4, 5, 6);
    mem_fn(&X::g6)(rcx, 1, 2, 3, 4, 5, 6);
    mem_fn(&X::g6)(&x, 1, 2, 3, 4, 5, 6);
    mem_fn(&X::g6)(pcx, 1, 2, 3, 4, 5, 6);
    mem_fn(&X::g6)(sp, 1, 2, 3, 4, 5, 6);

    mem_fn(&X::f7)(x, 1, 2, 3, 4, 5, 6, 7);
    mem_fn(&X::f7)(&x, 1, 2, 3, 4, 5, 6, 7);
    mem_fn(&X::f7)(sp, 1, 2, 3, 4, 5, 6, 7);

    mem_fn(&X::g7)(x, 1, 2, 3, 4, 5, 6, 7);
    mem_fn(&X::g7)(rcx, 1, 2, 3, 4, 5, 6, 7);
    mem_fn(&X::g7)(&x, 1, 2, 3, 4, 5, 6, 7);
    mem_fn(&X::g7)(pcx, 1, 2, 3, 4, 5, 6, 7);
    mem_fn(&X::g7)(sp, 1, 2, 3, 4, 5, 6, 7);

    mem_fn(&X::f8)(x, 1, 2, 3, 4, 5, 6, 7, 8);
    mem_fn(&X::f8)(&x, 1, 2, 3, 4, 5, 6, 7, 8);
    mem_fn(&X::f8)(sp, 1, 2, 3, 4, 5, 6, 7, 8);

    mem_fn(&X::g8)(x, 1, 2, 3, 4, 5, 6, 7, 8);
    mem_fn(&X::g8)(rcx, 1, 2, 3, 4, 5, 6, 7, 8);
    mem_fn(&X::g8)(&x, 1, 2, 3, 4, 5, 6, 7, 8);
    mem_fn(&X::g8)(pcx, 1, 2, 3, 4, 5, 6, 7, 8);
    mem_fn(&X::g8)(sp, 1, 2, 3, 4, 5, 6, 7, 8);

    return detect_errors(x.hash == 17610 && sp->hash == 2155);
}
int main(int argc, char** argv)
{
    variables_map vm;

    options_description
        desc_cmdline("Usage: " HPX_APPLICATION_STRING " [options]");
   
    const long double pi_ = pi<long double>();

    long double tolerance(0.0L)
              , lower_bound(0.0L)
              , upper_bound(0.0L)
              , increment(0.0L); 

    desc_cmdline.add_options()
        ( "help,h"
        , "print out program usage (this message)")

        ( "tolerance"
        , value<long double>(&tolerance)->default_value(5.0e-08L, "5e-08") 
        , "resolution tolerance")

        ( "lower-bound"
        , value<long double>(&lower_bound)->default_value(0.0L, "0") 
        , "lower bound of integration")

        ( "upper-bound"
        , value<long double>(&upper_bound)->default_value(2.0L * pi_, "2*pi")
        , "upper bound of integration")

        ( "increment"
        , value<long double>(&increment)->default_value(pi_, "pi") 
        , "initial integration increment")

        ( "path"
        , value<std::string>()->default_value("fast")
        , "select implementation: options are `fast' (no statistics/debug "
          "info) or `slow' (statistics and debug info collected and displayed)")
    ;

    store(command_line_parser(argc, argv).options(desc_cmdline).run(), vm);

    notify(vm);

    // print help screen
    if (vm.count("help"))
    {
        cout << desc_cmdline;
        return 0;
    }

    implementation impl;

    if (vm["path"].as<std::string>() == "fast")
        impl = fastpath; 

    else if (vm["path"].as<std::string>() == "slow")
        impl = slowpath; 

    else
    {
        cerr << ( format("error: unknown implementation '%1%'\n")
                % vm["path"].as<std::string>());
        return 1;
    }

    long double r(0.0L);
    double elapsed(0.0);

    if (fastpath == impl)
    {
        high_resolution_timer t;

        r = integrate_fastpath(sine(_1) * sine(_1)
                             , lower_bound
                             , upper_bound
                             , tolerance
                             , increment);

        elapsed = t.elapsed();
    }

    else if (slowpath == impl)
    {
        high_resolution_timer t;

        r = integrate_slowpath(sine(_1) * sine(_1)
                             , lower_bound
                             , upper_bound
                             , tolerance
                             , increment);

        elapsed = t.elapsed();
    }

    // the integral of sin(x) * sin(x) from 0 to 2 pi is pi
    cout << ( format("%1% integral of sin(x) * sin(x) from %2% to %3% is %4%\n"
                     "computation took %5% seconds\n")
            % ((fastpath == impl) ? "fastpath" : "slowpath")
            % group(setprecision(ld_precision), lower_bound)
            % group(setprecision(ld_precision), upper_bound)
            % group(setprecision(ld_precision), r)
            % group(setprecision(d_precision), elapsed));
}
Exemple #28
0
SetupDialog::SetupDialog(GraphBarImpl* barImpl)
    : connections(barImpl->connections),
      focusedGraphWidget(barImpl->focusedGraphWidget)
{
    using boost::bind;
    
    setWindowTitle(_("Graph Setup"));

    QVBoxLayout* vbox = new QVBoxLayout();
    setLayout(vbox);

    QHBoxLayout* hbox = new QHBoxLayout();        
    hbox->addWidget(new QLabel(_("Line width")));
    
    lineWidthSpin.setRange(1, 9);
    lineWidthSpin.setValue(1);
    connections.add(
        lineWidthSpin.sigValueChanged().connect(
            bind(&SetupDialog::onLineWidthChanged, this, _1)));
    hbox->addWidget(&lineWidthSpin);
    hbox->addStretch();
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(_("y-range, 10^")));
    
    verticalValueRangeSpin.setDecimals(1);
    verticalValueRangeSpin.setRange(-99.8, 99.8);
    verticalValueRangeSpin.setSingleStep(0.1);
    verticalValueRangeSpin.setValue(1.0);
    connections.add(
        verticalValueRangeSpin.sigValueChanged().connect(
            bind(&SetupDialog::onVerticalValueRangeChanged, this, _1)));
    hbox->addWidget(&verticalValueRangeSpin);

    showLimitCheck.setText(_("Show limit values"));
    showLimitCheck.setChecked(true);
    connections.add(
        showLimitCheck.sigToggled().connect(
            bind(&SetupDialog::onShowLimitToggled, this, _1)));
    hbox->addWidget(&showLimitCheck);
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    gridCheck.setText(_("Show grid"));
    connections.add(
        gridCheck.sigToggled().connect(
            bind(&SetupDialog::onGridToggled, this, _1)));
    hbox->addWidget(&gridCheck);
    
    gridSizeSpin.setDecimals(3);
    gridSizeSpin.setRange(-999.999, 999.999);
    gridSizeSpin.setSingleStep(0.001);
    gridSizeSpin.setValue(0.2);
    connections.add(
        gridSizeSpin.sigValueChanged().connect(
            bind(&SetupDialog::onGridSizeChanged, this, _1)));
    hbox->addWidget(&gridSizeSpin);
    
    rulerCheck.setText(_("Show rulers"));
    rulerCheck.setEnabled(false);
    connections.add(
        rulerCheck.sigToggled().connect(
            bind(&SetupDialog::onRulerToggled, this, _1)));
    hbox->addWidget(&rulerCheck);
    hbox->addStretch();
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    editModeCheck.setText(_("Edit mode"));
    connections.add(
        editModeCheck.sigToggled().connect(
            bind(&SetupDialog::onEditModeToggled, this, _1)));
    hbox->addWidget(&editModeCheck);

    radioGroup.addButton(&freeLineModeRadio);
    radioGroup.addButton(&lineModeRadio);
    
    freeLineModeRadio.setText(_("Free line"));
    freeLineModeRadio.setChecked(true);
    connections.add(
        freeLineModeRadio.sigToggled().connect(
            bind(&SetupDialog::onFreeLineModeToggled, this, _1)));
    hbox->addWidget(&freeLineModeRadio);
    
    lineModeRadio.setText(_("Line edit"));
    connections.add(
        lineModeRadio.sigToggled().connect(
            bind(&SetupDialog::onLineModeToggled, this, _1)));
    hbox->addWidget(&lineModeRadio);
    hbox->addStretch();
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    highlightingControlPointCheck.setText(_("Control points"));
    connections.add(
        highlightingControlPointCheck.sigToggled().connect(
            bind(&SetupDialog::onHighlightingControlPointToggled, this, _1)));
    hbox->addWidget(&highlightingControlPointCheck);
    
    hbox->addWidget(new QLabel(_("Step")));
    controlPointStepSpin.setRange(1, 999);
    controlPointStepSpin.setValue(1);
    connections.add(
        controlPointStepSpin.sigValueChanged().connect(
            bind(&SetupDialog::onControlPointStepOrOffsetChanged, this)));
    hbox->addWidget(&controlPointStepSpin);
    
    hbox->addWidget(new QLabel(_("Offset")));
    controlPointOffsetSpin.setRange(0, 999);
    controlPointOffsetSpin.setValue(0);
    connections.add(
        controlPointOffsetSpin.sigValueChanged().connect(
            bind(&SetupDialog::onControlPointStepOrOffsetChanged, this)));
    hbox->addWidget(&controlPointOffsetSpin);
    hbox->addStretch();
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    timeBarSyncToggle.setText(_("Time bar sync"));
    timeBarSyncToggle.setChecked(true);
    connections.add(
        timeBarSyncToggle.sigToggled().connect(
            bind(&SetupDialog::onTimeBarSyncToggled, this, _1)));
    hbox->addWidget(&timeBarSyncToggle);

    autoScrollModeCombo.addItem(_("off"));
    autoScrollModeCombo.addItem(_("cont."));
    autoScrollModeCombo.addItem(_("page"));
    autoScrollModeCombo.setCurrentIndex(1);
    connections.add(
        autoScrollModeCombo.sigCurrentIndexChanged().connect(
            bind(&SetupDialog::onAutoScrollModeChanged, this, _1)));
    hbox->addWidget(&autoScrollModeCombo);
    hbox->addStretch();
    vbox->addLayout(hbox);
}
int
main()
{
  dummyT array[] = { dummyT(0), dummyT(1), dummyT(2), 
                     dummyT(3), dummyT(4), dummyT(5) };
  const int N = sizeof(array)/sizeof(dummyT);

# if BOOST_WORKAROUND(BOOST_MSVC, == 1200)
  boost::shared_ptr<dummyT> zz((dummyT*)0);  // Why? I don't know, but it suppresses a bad instantiation.
# endif
  
  typedef std::vector<boost::shared_ptr<dummyT> > shared_t;
  shared_t shared;
  
  // Concept checks
  {
    typedef boost::indirect_iterator<shared_t::iterator> iter_t;

    BOOST_STATIC_ASSERT(
        has_element_type<
            boost::detail::iterator_traits<shared_t::iterator>::value_type
        >::value
        );
    
    typedef boost::indirect_iterator<
        shared_t::iterator
      , boost::iterator_value<shared_t::iterator>::type const
    > c_iter_t;

# ifndef NO_MUTABLE_CONST_RA_ITERATOR_INTEROPERABILITY
    boost::function_requires< boost_concepts::InteroperableIteratorConcept<iter_t, c_iter_t> >();
# endif 
  }

  // Test indirect_iterator_generator
  {
      for (int jj = 0; jj < N; ++jj)
          shared.push_back(boost::shared_ptr<dummyT>(new dummyT(jj)));
      
      dummyT* ptr[N];
      for (int k = 0; k < N; ++k)
          ptr[k] = array + k;

      typedef boost::indirect_iterator<dummyT**> indirect_iterator;

      typedef boost::indirect_iterator<dummyT**, dummyT const>
          const_indirect_iterator;

      indirect_iterator i(ptr);
      boost::random_access_iterator_test(i, N, array);

      boost::random_access_iterator_test(
          boost::indirect_iterator<shared_t::iterator>(shared.begin())
          , N, array);

      boost::random_access_iterator_test(boost::make_indirect_iterator(ptr), N, array);
    
      // check operator->
      assert((*i).m_x == i->foo());

      const_indirect_iterator j(ptr);
      boost::random_access_iterator_test(j, N, array);
    
      dummyT const*const* const_ptr = ptr;
      boost::random_access_iterator_test(boost::make_indirect_iterator(const_ptr), N, array);
      
      boost::const_nonconst_iterator_test(i, ++j);

      more_indirect_iterator_tests();
  }
  return boost::report_errors();
}
console_result send_tx_node::invoke(std::ostream& output, std::ostream& error)
{
    // Bound parameters.
    const auto& host = get_host_option();
    const auto& port = get_port_option();
    const tx_type& transaction = get_transaction_argument();
    const auto& debug_file = get_logging_debug_file_setting();
    const auto& error_file = get_logging_error_file_setting();
    const auto retries = get_general_connect_retries_setting();
    const auto connect = get_general_connect_timeout_seconds_setting();
    const auto handshake = get_general_channel_handshake_seconds_setting();

    // TODO: give option to send errors to console vs. file.
    static const auto header = format("=========== %1% ==========") % symbol();
    bc::ofstream debug_log(debug_file.string(), log_open_mode);
    bind_debug_log(debug_log);
    log_debug(LOG_NETWORK) << header;
    bc::ofstream error_log(error_file.string(), log_open_mode);
    bind_error_log(error_log);
    log_error(LOG_NETWORK) << header;

    // Not listening, no tx relay, no seeded host pool or address requests.
    static constexpr bool relay = false;
    static constexpr size_t threads = 2;
    static constexpr uint16_t listen = 0;
    static constexpr size_t host_pool_size = 0;
    const network::timeout timeouts(connect, handshake);

    async_client client(threads);
    network::hosts hosts(client.pool(), host_pool_size);
    network::handshake shake(client.pool());
    network::peer net(client.pool(), timeouts);
    network::protocol proto(client.pool(), hosts, shake, net, listen);

    callback_state state(error, output);

    const auto handle_send = [&state](const std::error_code& code)
    {
        if (state.succeeded(code))
            state.output(format(BX_SEND_TX_NODE_OUTPUT) % now());

        --state;
    };

    const auto handle_connect = [&state, &transaction, &handle_send](
        const std::error_code& code, network::channel_ptr node)
    {
        if (state.succeeded(code))
            node->send(transaction, handle_send);
    };

    // One node always specified.
    ++state;

    // Handle each successful connection.
    proto.subscribe_channel(handle_connect);

    // No need to start or stop the protocol since we only use manual.
    // Connect to the one specified host and retry up to the specified limit.
    proto.maintain_connection(host, port, relay, retries);

    // Catch C signals for aborting the program.
    signal(SIGABRT, handle_signal);
    signal(SIGTERM, handle_signal);
    signal(SIGINT, handle_signal);

    client.poll(state.stopped());
    client.stop();

    return state.get_result();
}