ParametersMap HikingTrailSearchFunction::run(
			std::ostream& stream,
			const Request& request
		) const {

			ParametersMap pm;

			HikingTrailTableSync::SearchResult trails(
				HikingTrailTableSync::Search(Env::GetOfficialEnv(), _searchName)
			);
			BOOST_FOREACH(
				HikingTrailTableSync::SearchResult::value_type& trail,
				trails
			){
				boost::shared_ptr<ParametersMap> itemMap(new ParametersMap);

				itemMap->insert(Request::PARAMETER_OBJECT_ID, trail->getKey());

				pm.insert(DATA_HIKING_TRAIL, itemMap);
			}
Example #2
0
		ParametersMap SQLService::run(
			std::ostream& stream,
			const Request& request
		) const {
			ParametersMap pm;

			DBResultSPtr rows = DBModule::GetDB()->execQuery(_query);

			while(rows->next ())
			{
				boost::shared_ptr<ParametersMap> rowPM(new ParametersMap);

				Record::FieldNames fieldNames(rows->getFieldNames());
				BOOST_FOREACH(const string& fieldName, fieldNames)
				{
					rowPM->insert(fieldName, rows->getText(fieldName));
				}

				pm.insert(TAG_RECORD, rowPM);
			}
Example #3
0
		ParametersMap Request::_getParametersMap(
		) const	{
			ParametersMap result;

			// Function
			if (_function.get())
			{
				result.insert(Request::PARAMETER_SERVICE, _function->getFactoryKey());
				ParametersMap::Map functionMap(_function->_getParametersMap().getMap());
				for (ParametersMap::Map::const_iterator it = functionMap.begin(); it != functionMap.end(); ++it)
					result.insert(it->first, it->second);
			}

			// Action name and parameters
			if (_action.get())
			{
				result.insert(Request::PARAMETER_ACTION, _action->getFactoryKey());
				ParametersMap::Map actionMap(_action->getParametersMap().getMap());
				for (ParametersMap::Map::const_iterator it = actionMap.begin(); it != actionMap.end(); ++it)
					result.insert(it->first, it->second);
				result.insert(Request::PARAMETER_ACTION_WILL_CREATE_OBJECT, _actionWillCreateObject);
			}

			// Object ID
			if (_actionCreatedId)
				result.insert(Request::PARAMETER_OBJECT_ID, *_actionCreatedId);

			// No redirection
			if(!_redirectAfterAction)
			{
				result.insert(Request::PARAMETER_NO_REDIRECT_AFTER_ACTION, 1);
			}

			if(!_actionErrorMessage.empty())
			{
				result.insert(Request::PARAMETER_ACTION_FAILED, true);
				result.insert(Request::PARAMETER_ERROR_MESSAGE, _actionErrorMessage);
			}

			return result;
		}
		ParametersMap StopAreaTransferAddAction::getParametersMap() const
		{
			ParametersMap map;
			if(_from.get())
			{
				map.insert(PARAMETER_FROM_ID, _from->getKey());
			}
			if(_to.get())
			{
				map.insert(PARAMETER_TO_ID, _to->getKey());
			}
			if(!_duration)
			{
				map.insert(PARAMETER_DURATION, StopAreaTableSync::FORBIDDEN_DELAY_SYMBOL);
			}
			else if(!_duration->is_not_a_date_time())
			{
				map.insert(PARAMETER_DURATION, _duration->total_seconds() / 60);
			}
			return map;
		}
void BaseImportableUpdateAction::_getImportableUpdateParametersMap(
    ParametersMap& map
) const	{
    // Data source links
    if(_dataSourceLinks)
    {
        map.insert(
            PARAMETER_DATA_SOURCE_LINKS,
            DataSourceLinks::Serialize(*_dataSourceLinks)
        );
    }
}
		ParametersMap FreeDRTAreaUpdateAction::getParametersMap() const
		{
			ParametersMap map;
			if(_area.get())
			{
				map.insert(PARAMETER_AREA_ID, _area->getKey());
			}
			if(_name)
			{
				map.insert(PARAMETER_NAME, *_name);
			}
			if(_cities)
			{
				map.insert(PARAMETER_CITIES, FreeDRTAreaTableSync::SerializeCities(*_cities));
			}
			if(_stopAreas)
			{
				map.insert(PARAMETER_STOP_AREAS, FreeDRTAreaTableSync::SerializeStopAreas(*_stopAreas));
			}
			if(_line && _line->get())
			{
				map.insert(PARAMETER_COMMERCIAL_LINE_ID, (*_line)->getKey());
			}
			return map;
		}
	MapOptimizer() :
		mapFrameId_("map"),
		odomFrameId_("odom"),
		globalOptimization_(true),
		optimizeFromLastNode_(false),
		mapToOdom_(rtabmap::Transform::getIdentity()),
		transformThread_(0)
	{
		ros::NodeHandle nh;
		ros::NodeHandle pnh("~");

		double epsilon = 0.0;
		bool robust = true;
		bool slam2d =false;
		int strategy = 0; // 0=TORO, 1=g2o, 2=GTSAM
		int iterations = 100;
		bool ignoreVariance = false;

		pnh.param("map_frame_id", mapFrameId_, mapFrameId_);
		pnh.param("odom_frame_id", odomFrameId_, odomFrameId_);
		pnh.param("iterations", iterations, iterations);
		pnh.param("ignore_variance", ignoreVariance, ignoreVariance);
		pnh.param("global_optimization", globalOptimization_, globalOptimization_);
		pnh.param("optimize_from_last_node", optimizeFromLastNode_, optimizeFromLastNode_);
		pnh.param("epsilon", epsilon, epsilon);
		pnh.param("robust", robust, robust);
		pnh.param("slam_2d", slam2d, slam2d);
		pnh.param("strategy", strategy, strategy);


		UASSERT(iterations > 0);

		ParametersMap parameters;
		parameters.insert(ParametersPair(Parameters::kOptimizerStrategy(), uNumber2Str(strategy)));
		parameters.insert(ParametersPair(Parameters::kOptimizerEpsilon(), uNumber2Str(epsilon)));
		parameters.insert(ParametersPair(Parameters::kOptimizerIterations(), uNumber2Str(iterations)));
		parameters.insert(ParametersPair(Parameters::kOptimizerRobust(), uBool2Str(robust)));
		parameters.insert(ParametersPair(Parameters::kOptimizerSlam2D(), uBool2Str(slam2d)));
		parameters.insert(ParametersPair(Parameters::kOptimizerVarianceIgnored(), uBool2Str(ignoreVariance)));
		optimizer_ = Optimizer::create(parameters);

		double tfDelay = 0.05; // 20 Hz
		bool publishTf = true;
		pnh.param("publish_tf", publishTf, publishTf);
		pnh.param("tf_delay", tfDelay, tfDelay);

		mapDataTopic_ = nh.subscribe("mapData", 1, &MapOptimizer::mapDataReceivedCallback, this);
		mapDataPub_ = nh.advertise<rtabmap_ros::MapData>(nh.resolveName("mapData")+"_optimized", 1);
		mapGraphPub_ = nh.advertise<rtabmap_ros::MapGraph>(nh.resolveName("mapData")+"Graph_optimized", 1);

		if(publishTf)
		{
			ROS_INFO("map_optimizer will publish tf between frames \"%s\" and \"%s\"", mapFrameId_.c_str(), odomFrameId_.c_str());
			ROS_INFO("map_optimizer: map_frame_id = %s", mapFrameId_.c_str());
			ROS_INFO("map_optimizer: odom_frame_id = %s", odomFrameId_.c_str());
			ROS_INFO("map_optimizer: tf_delay = %f", tfDelay);
			transformThread_ = new boost::thread(boost::bind(&MapOptimizer::publishLoop, this, tfDelay));
		}
	}
bool SetWindowRectCommandHandler::GetNumericParameter(
    const ParametersMap& command_parameters,
    const std::string& argument_name,
    int* argument_value,
    std::string* error_message) {
  ParametersMap::const_iterator parameter_iterator = command_parameters.find(argument_name);
  if (parameter_iterator != command_parameters.end()) {
    if (!parameter_iterator->second.isNumeric()) {
      *error_message = argument_name + " must be a numeric parameter.";
      return false;
    }
    int value = parameter_iterator->second.asInt();
    if (value < 0) {
      *error_message = argument_name + " must be a numeric parameter greater than zero.";
      return false;
    }

    *argument_value = value;
    return true;
  }
  return true;
}
		ParametersMap VehicleInformationsService::run(
			std::ostream& stream,
			const Request& request
		) const {

			ParametersMap map;
			
			// Informations about the vehicle
			if(_vehicle.get())
			{
				_vehicle->toParametersMap(map, true);
			}
			else if(VehicleModule::GetCurrentVehiclePosition().getVehicle())
			{
				VehicleModule::GetCurrentVehiclePosition().getVehicle()->toParametersMap(map, true);
			}

			// Position of the vehicle
			if(!_vehicle.get())
			{
				// Current vehicle position
				VehicleModule::GetCurrentVehiclePosition().toParametersMap(map, true);

				// Journey
				VehicleModule::GetCurrentJourney().toParametersMap(map);

				// Ignition
				map.insert(TAG_IGNITION, VehicleModule::getIgnition());

				// Screens
				boost::shared_ptr<ParametersMap> screenMap(new ParametersMap);
				BOOST_FOREACH(const VehicleModule::VehicleScreensMap::value_type& item, VehicleModule::GetVehicleScreens())
				{
					// Insert a submap for each screen
					boost::shared_ptr<ParametersMap> subScreenMap(new ParametersMap);
					item.second.toParametersMap(*subScreenMap, true);
					screenMap->insert(TAG_SCREEN, subScreenMap);
				}
Example #10
0
void ParametersToolBox::setupUi(const ParametersMap & parameters)
{
	parameters_ = parameters;
	QWidget * currentItem = 0;
	QStringList groups;
	for(ParametersMap::const_iterator iter=parameters.begin();
			iter!=parameters.end();
			++iter)
	{
		QStringList splitted = QString::fromStdString(iter->first).split('/');
		QString group = splitted.first();

		QString name = splitted.last();
		if(currentItem == 0 || currentItem->objectName().compare(group) != 0)
		{
			groups.push_back(group);
			QScrollArea * area = new QScrollArea(this);
			stackedWidget_->addWidget(area);
			currentItem = new QWidget();
			currentItem->setObjectName(group);
			QVBoxLayout * layout = new QVBoxLayout(currentItem);
			layout->setSizeConstraint(QLayout::SetMinimumSize);
			layout->setContentsMargins(0,0,0,0);
			layout->setSpacing(0);
			area->setWidget(currentItem);

			addParameter(layout, iter->first, iter->second);
		}
		else
		{
			addParameter((QVBoxLayout*)currentItem->layout(), iter->first, iter->second);
		}
	}
	comboBox_->addItems(groups);
	connect(comboBox_, SIGNAL(currentIndexChanged(int)), stackedWidget_, SLOT(setCurrentIndex(int)));

	updateParametersVisibility();
}
Example #11
0
void JoinEnumLoop::__repeatImpl(LoopFunction* func)
{
    ParametersMap* parametersMap = func->getParameters();
    tCurrentBranch = 0;

    for (tIndex = 0; tIndex < tValueVector.size(); ++tIndex) {

        parametersMap->putNumber(tKey, tValueVector[tIndex]);

        Loop* currentLoop = tInnerLoops[tIndex];
        if (currentLoop != NULL){
            currentLoop->setCallerLoop(this);
            currentLoop->__repeatImpl(func);
        } else if (tInnerLoop != NULL) {
            tInnerLoop->setCallerLoop(this);
            tInnerLoop->__repeatImpl(func);
        } else {
            func->execute(this);
        }
        // It will not call to Loop::repeat__Base
        ++tCurrentBranch;
    }
}
Example #12
0
void JunctionUpdateAction::_setFromParametersMap(const ParametersMap& map)
{
    if(map.isDefined(PARAMETER_JUNCTION_ID))
    {
        try
        {
            _junction = JunctionTableSync::GetEditable(map.get<RegistryKeyType>(PARAMETER_JUNCTION_ID), *_env);
        }
        catch (ObjectNotFoundException<Junction>&)
        {
            throw ActionException("No such junction");
        }
    }
    else
    {
        _junction = boost::shared_ptr<Junction>(new Junction);
    }

    if(map.isDefined(PARAMETER_FROM_ID))
    {
        try
        {
            _from = StopPointTableSync::GetEditable(map.get<RegistryKeyType>(PARAMETER_FROM_ID), *_env);
        }
        catch(ObjectNotFoundException<StopPoint>&)
        {
            throw ActionException("No such from stop point");
        }
    }

    if(map.isDefined(PARAMETER_TO_ID))
    {
        try
        {
            _to = StopPointTableSync::GetEditable(map.get<RegistryKeyType>(PARAMETER_TO_ID), *_env);
        }
        catch(ObjectNotFoundException<StopPoint>&)
        {
            throw ActionException("No such to stop point");
        }
    }

    if(map.isDefined(PARAMETER_LENGTH))
    {
        _length = map.get<double>(PARAMETER_LENGTH);
    }

    if(map.isDefined(PARAMETER_TIME))
    {
        _duration = minutes(map.get<long>(PARAMETER_TIME));
    }

    if(map.isDefined(PARAMETER_BIDIRECTIONAL))
    {
        _bidirectional = map.getDefault<bool>(PARAMETER_BIDIRECTIONAL);
    }
}
		ParametersMap HikingTrailUpdateAction::getParametersMap() const
		{
			ParametersMap map;
			if(_trail.get())
			{
				map.insert(PARAMETER_TRAIL_ID, _trail->getKey());
				map.insert(PARAMETER_DURATION, _duration);
				map.insert(PARAMETER_NAME, _name);
				map.insert(PARAMETER_MAP, _map);
				map.insert(PARAMETER_PROFILE, _profile);
				map.insert(PARAMETER_URL, _url);
			}
			return map;
		}
Example #14
0
void BayesFilter::parseParameters(const ParametersMap & parameters)
{
	ParametersMap::const_iterator iter;
	if((iter=parameters.find(Parameters::kBayesVirtualPlacePriorThr())) != parameters.end())
	{
		this->setVirtualPlacePrior(std::atof((*iter).second.c_str()));
	}
	if((iter=parameters.find(Parameters::kBayesPredictionLC())) != parameters.end())
	{
		this->setPredictionLC((*iter).second);
	}
	if((iter=parameters.find(Parameters::kBayesFullPredictionUpdate())) != parameters.end())
	{
		_fullPredictionUpdate = uStr2Bool((*iter).second.c_str());
	}

}
Example #15
0
		ParametersMap VersionService::run(
			std::ostream& stream,
			const Request& request
		) const {
			ParametersMap map;
			map.insert(ATTR_VERSION, ServerModule::VERSION);
			map.insert(ATTR_REVISION, ServerModule::REVISION);
			map.insert(ATTR_BUILD_DATE, ServerModule::BUILD_DATE);
			std::vector<std::string> urlVector;
			boost::algorithm::split(urlVector, ServerModule::SYNTHESE_URL, boost::is_any_of("/"));
			if (urlVector.size() > 0)
			{
				if (urlVector.at(urlVector.size()-1) == "trunk")
					map.insert(ATTR_BRANCH, urlVector.at(urlVector.size()-1));
				else if (urlVector.size() > 1)
					map.insert(ATTR_BRANCH, urlVector.at(urlVector.size()-2) + "/" + urlVector.at(urlVector.size()-1));
			}
			else
				map.insert(ATTR_BRANCH, "");
			return map;
		}
		ParametersMap ServiceTimetableUpdateAction::getParametersMap() const
		{
			ParametersMap map;
			if(_service.get())
			{
				map.insert(PARAMETER_SERVICE_ID, _service->getKey());
				map.insert(PARAMETER_RANK, _rank);
				map.insert(PARAMETER_UPDATE_ARRIVAL, _updateArrival);
				if(!_shifting_delay.is_not_a_date_time())
				{
					map.insert(PARAMETER_SHIFTING_DELAY, _shifting_delay.total_seconds() / 60);
				}
				else if(!_time.is_not_a_date_time())
				{
					map.insert(PARAMETER_TIME, _time);
				}
			}
			return map;
		}
void ExecuteAsyncScriptCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator script_parameter_iterator = command_parameters.find("script");
  ParametersMap::const_iterator args_parameter_iterator = command_parameters.find("args");
  if (script_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: script");
    return;
  } else if (args_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: args");
    return;
  } else {
    wchar_t page_id_buffer[GUID_STRING_LEN] = {0};
    GUID page_id_guid;
    ::CoCreateGuid(&page_id_guid);
    ::StringFromGUID2(page_id_guid, page_id_buffer, GUID_STRING_LEN);
    std::wstring page_id = &page_id_buffer[0];

    wchar_t pending_id_buffer[GUID_STRING_LEN] = {0};
    GUID pending_id_guid;
    ::CoCreateGuid(&pending_id_guid);
    ::StringFromGUID2(pending_id_guid, pending_id_buffer, GUID_STRING_LEN);
    std::wstring pending_id = &pending_id_buffer[0];

    Json::Value json_args = args_parameter_iterator->second;

    int timeout_value = executor.async_script_timeout();
    std::wstring timeout = std::to_wstring(static_cast<long long>(timeout_value));

    std::wstring script_body = StringUtilities::ToWString(script_parameter_iterator->second.asString());

    std::wstring async_script = L"(function() { return function(){\n";
    async_script += L"document.__$webdriverAsyncExecutor = {\n";
    async_script += L"  pageId: '" + page_id + L"',\n";
    async_script += L"  asyncTimeout: 0\n";
    async_script += L"};\n";
    async_script += L"var timeoutId = window.setTimeout(function() {\n";
    async_script += L"  window.setTimeout(function() {\n";
    async_script += L"    document.__$webdriverAsyncExecutor.asyncTimeout = 1;\n";
    async_script += L"  }, 0);\n";
    async_script += L"}," + timeout + L");\n";
    async_script += L"var callback = function(value) {\n";
    async_script += L"  document.__$webdriverAsyncExecutor.asyncTimeout = 0;\n";
    async_script += L"  document.__$webdriverAsyncExecutor.asyncScriptResult = value;\n";
    async_script += L"  window.clearTimeout(timeoutId);\n";
    async_script += L"};\n";
    async_script += L"var argsArray = Array.prototype.slice.call(arguments);\n";
    async_script += L"argsArray.push(callback);\n";
    async_script += L"if (document.__$webdriverAsyncExecutor.asyncScriptResult !== undefined) {\n";
    async_script += L"  delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
    async_script += L"}\n";
    async_script += L"(function() {" + script_body + L"}).apply(null, argsArray);\n";
    async_script += L"};})();";

    std::wstring polling_script = L"(function() { return function(){\n";
    polling_script += L"var pendingId = '" + pending_id + L"';\n";
    polling_script += L"if ('__$webdriverAsyncExecutor' in document) {\n";
    polling_script += L"  if (document.__$webdriverAsyncExecutor.pageId != '" + page_id + L"') {\n";
    polling_script += L"    return [pendingId, -1];\n";
    polling_script += L"  } else if ('asyncScriptResult' in document.__$webdriverAsyncExecutor) {\n";
    polling_script += L"    var value = document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
    polling_script += L"    delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
    polling_script += L"    return value;\n";
    polling_script += L"  } else {\n";
    polling_script += L"    return [pendingId, document.__$webdriverAsyncExecutor.asyncTimeout];\n";
    polling_script += L"  }\n";
    polling_script += L"} else {\n";
    polling_script += L"  return [pendingId, -1];\n";
    polling_script += L"}\n";
    polling_script += L"};})();";

    BrowserHandle browser_wrapper;
    int status_code = executor.GetCurrentBrowser(&browser_wrapper);
    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code, "Unable to get browser");
      return;
    }

    CComPtr<IHTMLDocument2> doc;
    browser_wrapper->GetDocument(&doc);
    Script async_script_wrapper(doc, async_script, json_args.size());
    status_code = this->PopulateArgumentArray(executor,
                                              async_script_wrapper,
                                              json_args);
    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code,
                                  "Error setting arguments for script");
      return;
    }

    status_code = async_script_wrapper.Execute();

    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code,
                                  "JavaScript error in async script.");
      return;
    } else {
      Script polling_script_wrapper(doc, polling_script, 0);
      while (true) {
        Json::Value polling_result;
        status_code = polling_script_wrapper.Execute();
        if (status_code != WD_SUCCESS) {
          // Assume that if the polling script errors, it's because
          // of a page reload. Note that experience shows this to
          // happen most frequently when a refresh occurs, since
          // the document object is not yet ready for accessing.
          // However, this is still a big assumption,and could be faulty.
          response->SetErrorResponse(EUNEXPECTEDJSERROR,
                                      "Page reload detected during async script");
          break;
        }

        polling_script_wrapper.ConvertResultToJsonValue(executor, &polling_result);
          
        Json::UInt index = 0;
        std::string narrow_pending_id = StringUtilities::ToString(pending_id);
        if (polling_result.isArray() &&
            polling_result.size() == 2 && 
            polling_result[index].isString() && 
            polling_result[index].asString() == narrow_pending_id) {
          int timeout_flag = polling_result[1].asInt();
          if (timeout_flag < 0) {
            response->SetErrorResponse(EUNEXPECTEDJSERROR,
                                        "Page reload detected during async script");
            break;
          }
          if (timeout_flag > 0) {
            response->SetErrorResponse(ESCRIPTTIMEOUT,
                                        "Timeout expired waiting for async script");
            break;
          }
        } else {
          response->SetSuccessResponse(polling_result);
          break;
        }
      }

      return;
    }
  }
}
		ParametersMap ReservationUserUpdateAction::getParametersMap() const
		{
			ParametersMap map;
			if(_user.get()) map.insert(PARAMETER_USER_ID, _user->getKey());
			return map;
		}
		bool UserPasswordRecoveryAction::sendPasswordRecoveryEMail(const User& user, const std::string sender) const 
		{
			/* Need a CMS in order to send a mail */
			if(!_cmsPasswordRecoveryEMail.get())
			{
				return false;
			}

			/* Build a mail and send it */
			try
			{
				EMail email(ServerModule::GetEMailSender());

				/* MIME type */
				string mimeType = _cmsPasswordRecoveryEMail.get()->getMimeType();
				if (mimeType == "text/html") {
					email.setFormat(EMail::EMAIL_HTML);
				}
				else
				{
					email.setFormat(EMail::EMAIL_TEXT);
				}

				/* Build header */
				email.setSender(sender);
				email.setSenderName(sender);

				stringstream subject;
				ParametersMap subjectMap;

				subjectMap.insert(DATA_SUBJECT_OR_CONTENT, TYPE_SUBJECT);

				_cmsPasswordRecoveryEMail.get()->display(subject, subjectMap);

				email.setSubject(subject.str());
				email.addRecipient(user.getEMail(), user.getName());

				/* Build content */
				stringstream content;
				ParametersMap contentMap;

				contentMap.insert(DATA_SUBJECT_OR_CONTENT, TYPE_CONTENT);
				contentMap.insert(DATA_USER_LOGIN, user.getLogin());
				contentMap.insert(DATA_USER_PASSWORD, user.getPassword());
				contentMap.insert(DATA_USER_EMAIL, user.getEMail());
				contentMap.insert(DATA_USER_PHONE, user.getPhone());
				contentMap.insert(DATA_USER_NAME, user.getName());
				contentMap.insert(DATA_USER_SURNAME, user.getSurname());

				_cmsPasswordRecoveryEMail.get()->display(content, contentMap);
				email.setContent(content.str());

				/* Send mail */
				email.send();

				return true;
			}
			catch(boost::system::system_error)
			{
				return false;
			}
		}
void ExecuteAsyncScriptCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator script_parameter_iterator = command_parameters.find("script");
  ParametersMap::const_iterator args_parameter_iterator = command_parameters.find("args");
  if (script_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "Missing parameter: script");
    return;
  }

  if (!script_parameter_iterator->second.isString()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "script parameter must be a string");
    return;
  }

  if (args_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "Missing parameter: args");
    return;
  }

  if (!args_parameter_iterator->second.isArray()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "args parameter must be an array");
    return;
  }

  std::vector<wchar_t> page_id_buffer(GUID_STRING_LEN);
  GUID page_id_guid;
  ::CoCreateGuid(&page_id_guid);
  ::StringFromGUID2(page_id_guid, &page_id_buffer[0], GUID_STRING_LEN);
  std::wstring page_id = &page_id_buffer[0];

  std::vector<wchar_t> pending_id_buffer(GUID_STRING_LEN);
  GUID pending_id_guid;
  ::CoCreateGuid(&pending_id_guid);
  ::StringFromGUID2(pending_id_guid, &pending_id_buffer[0], GUID_STRING_LEN);
  std::wstring pending_id = &pending_id_buffer[0];

  Json::Value json_args = args_parameter_iterator->second;

  unsigned long long timeout_value = executor.async_script_timeout();
  std::wstring timeout = std::to_wstring(static_cast<long long>(timeout_value));

  std::wstring script_body = StringUtilities::ToWString(script_parameter_iterator->second.asString());

  std::wstring async_script = L"(function() { return function(){\n";
  async_script += L"document.__$webdriverAsyncExecutor = {\n";
  async_script += L"  pageId: '" + page_id + L"',\n";
  async_script += L"  asyncTimeout: 0\n";
  async_script += L"};\n";
  async_script += L"var timeoutId = window.setTimeout(function() {\n";
  async_script += L"  window.setTimeout(function() {\n";
  async_script += L"    document.__$webdriverAsyncExecutor.asyncTimeout = 1;\n";
  async_script += L"  }, 0);\n";
  async_script += L"}," + timeout + L");\n";
  async_script += L"var callback = function(value) {\n";
  async_script += L"  document.__$webdriverAsyncExecutor.asyncTimeout = 0;\n";
  async_script += L"  document.__$webdriverAsyncExecutor.asyncScriptResult = value;\n";
  async_script += L"  window.clearTimeout(timeoutId);\n";
  async_script += L"};\n";
  async_script += L"var argsArray = Array.prototype.slice.call(arguments);\n";
  async_script += L"argsArray.push(callback);\n";
  async_script += L"if (document.__$webdriverAsyncExecutor.asyncScriptResult !== undefined) {\n";
  async_script += L"  delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
  async_script += L"}\n";
  async_script += L"(function() {\n" + script_body + L"\n}).apply(null, argsArray);\n";
  async_script += L"};})();";

  std::wstring polling_script = L"(function() { return function(){\n";
  polling_script += L"var pendingId = '" + pending_id + L"';\n";
  polling_script += L"if ('__$webdriverAsyncExecutor' in document) {\n";
  polling_script += L"  if (document.__$webdriverAsyncExecutor.pageId != '" + page_id + L"') {\n";
  polling_script += L"    return {'status': 'reload', 'id': pendingId, 'value': -1};\n";
  polling_script += L"  } else if ('asyncScriptResult' in document.__$webdriverAsyncExecutor) {\n";
  polling_script += L"    var value = document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
  polling_script += L"    delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
  polling_script += L"    return {'status': 'complete', 'id': pendingId, 'value': value};\n";
  polling_script += L"  } else if (document.__$webdriverAsyncExecutor.asyncTimeout == 0) {\n";
  polling_script += L"    return {'status': 'pending', 'id': pendingId, 'value': document.__$webdriverAsyncExecutor.asyncTimeout};\n";
  polling_script += L"  } else {\n";
  polling_script += L"    return {'status': 'timeout', 'id': pendingId, 'value': document.__$webdriverAsyncExecutor.asyncTimeout};\n";
  polling_script += L"  }\n";
  polling_script += L"} else {\n";
  polling_script += L"  return {'status': 'reload', 'id': pendingId, 'value': -1};\n";
  polling_script += L"}\n";
  polling_script += L"};})();";

  BrowserHandle browser_wrapper;
  int status_code = executor.GetCurrentBrowser(&browser_wrapper);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "Unable to get browser");
    return;
  }

  CComPtr<IHTMLDocument2> doc;
  browser_wrapper->GetDocument(&doc);

  HWND async_executor_handle;
  Script async_script_wrapper(doc, async_script);
  async_script_wrapper.set_polling_source_code(polling_script);
  status_code = async_script_wrapper.ExecuteAsync(executor,
                                                  json_args,
                                                  &async_executor_handle);
  browser_wrapper->set_script_executor_handle(async_executor_handle);

  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "JavaScript error");
  }
}
Example #21
0
		util::ParametersMap PTRouteDetailFunction::run(ostream& stream, const Request& request) const
		{
			const CommercialLine * commercialLine(_journeyPattern->getCommercialLine());

			ParametersMap m;

			// Properties
			m.insert(DATA_ID, _journeyPattern->getKey());
			m.insert(DATA_NAME, _journeyPattern->getName());
			m.insert(DATA_IS_MAIN, _journeyPattern->getMain());
			m.insert(DATA_LINE_ID, commercialLine->getKey());
			m.insert(DATA_LINE_NAME, commercialLine->getName());
			m.insert(DATA_LINE_SHORT_NAME, commercialLine->getShortName());
			m.insert(DATA_LINE_LONG_NAME, commercialLine->getLongName());
			m.insert(DATA_LINE_IMAGE, commercialLine->getImage());
			m.insert(DATA_LINE_STYLE, commercialLine->getStyle());
			if(commercialLine->getColor())
			{
				m.insert(DATA_LINE_COLOR, commercialLine->getColor()->toXMLColor());
			}
			m.insert(
				DATA_DIRECTION,
				_journeyPattern->getDirection().empty() && _journeyPattern->getDirectionObj() ?
					_journeyPattern->getDirectionObj()->getDisplayedText() :
					_journeyPattern->getDirection()
			);

			// Edges
			const StopArea* lastConnPlace(NULL);
			BOOST_FOREACH(const Edge* edge, _journeyPattern->getAllEdges())
			{
				if(	(!edge->isDepartureAllowed() || !_displayDepartureStops) &&
					(!edge->isArrivalAllowed() || !_displayArrivalStops)
				){
					continue;
				}

				const StopPoint* stopPoint(static_cast<const StopPoint *>(edge->getFromVertex()));
				const StopArea* connPlace(stopPoint->getConnectionPlace());

				// Display same stop area once
				if(_displaySameStopAreaOnce && connPlace == lastConnPlace)
				{
					continue;
				}
				lastConnPlace = connPlace;
				const LineStop* lineStop(static_cast<const LineStop*>(edge));

				boost::shared_ptr<ParametersMap> sm(new ParametersMap);
				sm->insert(DATA_ID, stopPoint->getKey());
				sm->insert(DATA_RANK, edge->getRankInPath());
				sm->insert(DATA_DEPARTURE_IS_ALLOWED, edge->isDepartureAllowed());
				sm->insert(DATA_ARRIVAL_IS_ALLOWED, edge->isArrivalAllowed());
				sm->insert(DATA_WITH_SCHEDULES, lineStop->getScheduleInput());
				sm->insert(DATA_RESERVATION_NEEDED, lineStop->getReservationNeeded());
				sm->insert(DATA_NAME, stopPoint->getName());
				sm->insert(DATA_OPERATOR_CODE, stopPoint->getCodeBySources());
				sm->insert(DATA_STOP_AREA_ID, connPlace->getKey());
				sm->insert(DATA_STOP_AREA_NAME, connPlace->getName());
				sm->insert(DATA_CITY_ID, connPlace->getCity()->getKey());
				sm->insert(DATA_CITY_NAME, connPlace->getCity()->getName());
				sm->insert(DATA_DIRECTION_ALIAS, connPlace->getName26());
				if(_service.get())
				{
					if(edge->isDepartureAllowed())
					{
						sm->insert(DATA_DEPARTURE_TIME, to_simple_string(Service::GetTimeOfDay(_service->getDepartureSchedule(false, edge->getRankInPath()))));
					}
					if(edge->isArrivalAllowed())
					{
						sm->insert(DATA_ARRIVAL_TIME, to_simple_string(Service::GetTimeOfDay(_service->getArrivalSchedule(false, edge->getRankInPath()))));
					}
				}

				m.insert(TAG_STOP, sm);
			}


			// CMS Display
			if(_mainPage.get())
			{
				// Template parameters
				m.merge(getTemplateParameters());

				// Stops
				if(_stopPage.get())
				{
					stringstream s;
					BOOST_FOREACH(const boost::shared_ptr<ParametersMap>& item, m.getSubMaps(TAG_STOP))
					{
						item->merge(getTemplateParameters());

						_stopPage->display(s, request, *item);
					}
					m.insert(DATA_STOPS, s.str());
				}
Example #22
0
int main(int argc, char * argv[])
{
	ULogger::setType(ULogger::kTypeConsole);
	ULogger::setLevel(ULogger::kWarning);

	std::string interfaceName = "wlan0";
	int driver = 0;
	bool mirroring = false;

	// parse options
	for(int i = 1; i<argc; ++i)
	{
		if(strcmp(argv[i], "-i") == 0)
		{
			++i;
			if(i < argc)
			{
				interfaceName = argv[i];
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-m") == 0)
		{
			mirroring = true;
			continue;
		}
		if(strcmp(argv[i], "-d") == 0)
		{
			++i;
			if(i < argc)
			{
				driver = atoi(argv[i]);
				if(driver < 0 || driver > 8)
				{
					UERROR("driver should be between 0 and 8.");
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}

		UERROR("Option \"%s\" not recognized!", argv[i]);
		showUsage();
	}

	// Here is the pipeline that we will use:
	// CameraOpenni -> "CameraEvent" -> OdometryThread -> "OdometryEvent" -> RtabmapThread -> "RtabmapEvent"

	// Create the OpenNI camera, it will send a CameraEvent at the rate specified.
	// Set transform to camera so z is up, y is left and x going forward
	Camera * camera = 0;
	Transform opticalRotation(0,0,1,0, -1,0,0,0, 0,-1,0,0);
	if(driver == 1)
	{
		if(!CameraOpenNI2::available())
		{
			UERROR("Not built with OpenNI2 support...");
			exit(-1);
		}
		camera = new CameraOpenNI2("", CameraOpenNI2::kTypeColorDepth, 0, opticalRotation);
	}
	else if(driver == 2)
	{
		if(!CameraFreenect::available())
		{
			UERROR("Not built with Freenect support...");
			exit(-1);
		}
		camera = new CameraFreenect(0, CameraFreenect::kTypeColorDepth, 0, opticalRotation);
	}
	else if(driver == 3)
	{
		if(!CameraOpenNICV::available())
		{
			UERROR("Not built with OpenNI from OpenCV support...");
			exit(-1);
		}
		camera = new CameraOpenNICV(false, 0, opticalRotation);
	}
	else if(driver == 4)
	{
		if(!CameraOpenNICV::available())
		{
			UERROR("Not built with OpenNI from OpenCV support...");
			exit(-1);
		}
		camera = new CameraOpenNICV(true, 0, opticalRotation);
	}
	else if (driver == 5)
	{
		if (!CameraFreenect2::available())
		{
			UERROR("Not built with Freenect2 support...");
			exit(-1);
		}
		camera = new CameraFreenect2(0, CameraFreenect2::kTypeColor2DepthSD, 0, opticalRotation);
	}
	else if (driver == 6)
	{
		if (!CameraStereoZed::available())
		{
			UERROR("Not built with ZED SDK support...");
			exit(-1);
		}
		camera = new CameraStereoZed(0, 2, 1, 1, 100, false, 0, opticalRotation);
	}
	else if (driver == 7)
	{
		if (!CameraRealSense::available())
		{
			UERROR("Not built with RealSense support...");
			exit(-1);
		}
		camera = new CameraRealSense(0, 0, 0, false, 0, opticalRotation);
	}
	else if (driver == 8)
	{
		if (!CameraRealSense2::available())
		{
			UERROR("Not built with RealSense2 support...");
			exit(-1);
		}
		camera = new CameraRealSense2("", 0, opticalRotation);
	}
	else
	{
		camera = new rtabmap::CameraOpenni("", 0, opticalRotation);
	}


	if(!camera->init())
	{
		UERROR("Camera init failed! Try another camera driver.");
		showUsage();
		exit(1);
	}
	CameraThread cameraThread(camera);
	if(mirroring)
	{
		cameraThread.setMirroringEnabled(true);
	}

	// GUI stuff, there the handler will receive RtabmapEvent and construct the map
	// We give it the camera so the GUI can pause/resume the camera
	QApplication app(argc, argv);
	MapBuilderWifi mapBuilderWifi(&cameraThread);

	// Create an odometry thread to process camera events, it will send OdometryEvent.
	OdometryThread odomThread(Odometry::create());

	// Create RTAB-Map to process OdometryEvent
	Rtabmap * rtabmap = new Rtabmap();
	ParametersMap param;
	param.insert(ParametersPair(Parameters::kMemRehearsalSimilarity(), "1.0")); // disable rehearsal (node merging when not moving)
	param.insert(ParametersPair(Parameters::kRGBDLinearUpdate(), "0")); // disable node ignored when not moving
	param.insert(ParametersPair(Parameters::kRGBDAngularUpdate(), "0")); // disable node ignored when not moving
	rtabmap->init(param);
	RtabmapThread rtabmapThread(rtabmap); // ownership is transfered

	// Create Wifi monitoring thread
	WifiThread wifiThread(interfaceName); // 0.5 Hz, should be under RTAB-Map rate (which is 1 Hz by default)

	// Setup handlers
	odomThread.registerToEventsManager();
	rtabmapThread.registerToEventsManager();
	mapBuilderWifi.registerToEventsManager();

	// The RTAB-Map is subscribed by default to CameraEvent, but we want
	// RTAB-Map to process OdometryEvent instead, ignoring the CameraEvent.
	// We can do that by creating a "pipe" between the camera and odometry, then
	// only the odometry will receive CameraEvent from that camera. RTAB-Map is
	// also subscribed to OdometryEvent by default, so no need to create a pipe between
	// odometry and RTAB-Map.
	UEventsManager::createPipe(&cameraThread, &odomThread, "CameraEvent");

	// Let's start the threads
	rtabmapThread.start();
	odomThread.start();
	cameraThread.start();
	wifiThread.start();

	mapBuilderWifi.show();
	app.exec(); // main loop

	// remove handlers
	mapBuilderWifi.unregisterFromEventsManager();
	rtabmapThread.unregisterFromEventsManager();
	odomThread.unregisterFromEventsManager();

	// Kill all threads
	cameraThread.kill();
	odomThread.join(true);
	rtabmapThread.join(true);
	wifiThread.join(true);

	return 0;
}
Example #23
0
int main(int argc, char * argv[])
{
	signal(SIGABRT, &sighandler);
	signal(SIGTERM, &sighandler);
	signal(SIGINT, &sighandler);

	/*for(int i=0; i<argc; i++)
	{
		printf("argv[%d] = %s\n", i, argv[i]);
	}*/
	const ParametersMap & defaultParameters = Parameters::getDefaultParameters();
	if(argc < 2)
	{
		showUsage();
	}
	else if(argc == 2 && strcmp(argv[1], "-v") == 0)
	{
		printf("%s\n", Rtabmap::getVersion().c_str());
		exit(0);
	}
	else if(argc == 2 && strcmp(argv[1], "-default_params") == 0)
	{
		for(ParametersMap::const_iterator iter = defaultParameters.begin(); iter!=defaultParameters.end(); ++iter)
		{
			printf("%s=%s\n", iter->first.c_str(), iter->second.c_str());
		}
		exit(0);
	}
	printf("\n");

	std::string path;
	float timeThreshold = 0.0;
	float rate = 0.0;
	int loopDataset = 0;
	int repeat = 0;
	bool createGT = false;
	int imageWidth = 0;
	int imageHeight = 0;
	int startAt = 1;
	ParametersMap pm;
	ULogger::Level logLevel = ULogger::kError;
	ULogger::Level exitLevel = ULogger::kFatal;

	for(int i=1; i<argc; ++i)
	{
		if(i == argc-1)
		{
			// The last must be the path
			path = argv[i];
			if(!UDirectory::exists(path.c_str()) && !UFile::exists(path.c_str()))
			{
				printf("Path not valid : %s\n", path.c_str());
				showUsage();
				exit(1);
			}
			break;
		}
		if(strcmp(argv[i], "-t") == 0)
		{
			++i;
			if(i < argc)
			{
				timeThreshold = std::atof(argv[i]);
				if(timeThreshold < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-rate") == 0)
		{
			++i;
			if(i < argc)
			{
				rate = std::atof(argv[i]);
				if(rate < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-rateHz") == 0)
		{
			++i;
			if(i < argc)
			{
				rate = std::atof(argv[i]);
				if(rate < 0)
				{
					showUsage();
				}
				else if(rate)
				{
					rate = 1/rate;
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-repeat") == 0)
		{
			++i;
			if(i < argc)
			{
				repeat = std::atoi(argv[i]);
				if(repeat < 1)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-image_width") == 0)
		{
			++i;
			if(i < argc)
			{
				imageWidth = std::atoi(argv[i]);
				if(imageWidth < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-image_height") == 0)
		{
			++i;
			if(i < argc)
			{
				imageHeight = std::atoi(argv[i]);
				if(imageHeight < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-start_at") == 0)
		{
			++i;
			if(i < argc)
			{
				startAt = std::atoi(argv[i]);
				if(startAt < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-createGT") == 0)
		{
			createGT = true;
			continue;
		}
		if(strcmp(argv[i], "-debug") == 0)
		{
			logLevel = ULogger::kDebug;
			continue;
		}
		if(strcmp(argv[i], "-info") == 0)
		{
			logLevel = ULogger::kInfo;
			continue;
		}
		if(strcmp(argv[i], "-warn") == 0)
		{
			logLevel = ULogger::kWarning;
			continue;
		}
		if(strcmp(argv[i], "-exit_warn") == 0)
		{
			exitLevel = ULogger::kWarning;
			continue;
		}
		if(strcmp(argv[i], "-exit_error") == 0)
		{
			exitLevel = ULogger::kError;
			continue;
		}

		// Check for RTAB-Map's parameters
		std::string key = argv[i];
		key = uSplit(key, '-').back();
		if(defaultParameters.find(key) != defaultParameters.end())
		{
			++i;
			if(i < argc)
			{
				std::string value = argv[i];
				if(value.empty())
				{
					showUsage();
				}
				else
				{
					value = uReplaceChar(value, ',', ' ');
				}
				std::pair<ParametersMap::iterator, bool> inserted = pm.insert(ParametersPair(key, value));
				if(inserted.second == false)
				{
					inserted.first->second = value;
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}

		printf("Unrecognized option : %s\n", argv[i]);
		showUsage();
	}

	if(repeat && createGT)
	{
		printf("Cannot create a Ground truth if repeat is on.\n");
		showUsage();
	}
	else if((imageWidth && imageHeight == 0) ||
			(imageHeight && imageWidth == 0))
	{
		printf("If imageWidth is set, imageHeight must be too.\n");
		showUsage();
	}

	UTimer timer;
	timer.start();
	std::queue<double> iterationMeanTime;

	Camera * camera = 0;
	if(UDirectory::exists(path))
	{
		camera = new CameraImages(path, startAt, false, 1/rate, imageWidth, imageHeight);
	}
	else
	{
		camera = new CameraVideo(path, 1/rate, imageWidth, imageHeight);
	}

	if(!camera || !camera->init())
	{
		printf("Camera init failed, using path \"%s\"\n", path.c_str());
		exit(1);
	}

	std::map<int, int> groundTruth;

	ULogger::setType(ULogger::kTypeConsole);
	//ULogger::setType(ULogger::kTypeFile, rtabmap.getWorkingDir()+"/LogConsole.txt", false);
	//ULogger::setBuffered(true);
	ULogger::setLevel(logLevel);
	ULogger::setExitLevel(exitLevel);

	// Create tasks : memory is deleted
	Rtabmap rtabmap;
	// Disable statistics (we don't need them)
	pm.insert(ParametersPair(Parameters::kRtabmapPublishStats(), "false"));
	// use default working directory
	pm.insert(ParametersPair(Parameters::kRtabmapWorkingDirectory(), Parameters::defaultRtabmapWorkingDirectory()));
	pm.insert(ParametersPair(Parameters::kRGBDEnabled(), "false"));

	rtabmap.init(pm);
	rtabmap.setTimeThreshold(timeThreshold); // in ms

	printf("Avpd init time = %fs\n", timer.ticks());

	// Start thread's task
	int loopClosureId;
	int count = 0;
	int countLoopDetected=0;

	printf("\nParameters : \n");
	printf(" Data set : %s\n", path.c_str());
	printf(" Time threshold = %1.2f ms\n", timeThreshold);
	printf(" Image rate = %1.2f s (%1.2f Hz)\n", rate, 1/rate);
	printf(" Repeating data set = %s\n", repeat?"true":"false");
	printf(" Camera width=%d, height=%d (0 is default)\n", imageWidth, imageHeight);
	printf(" Camera starts at image %d (default 1)\n", startAt);
	if(createGT)
	{
		printf(" Creating the ground truth matrix.\n");
	}
	printf(" INFO: All other parameters are set to defaults\n");
	if(pm.size()>1)
	{
		printf("   Overwritten parameters :\n");
		for(ParametersMap::iterator iter = pm.begin(); iter!=pm.end(); ++iter)
		{
			printf("    %s=%s\n",iter->first.c_str(), iter->second.c_str());
		}
	}
	if(rtabmap.getWM().size() || rtabmap.getSTM().size())
	{
		printf("[Warning] RTAB-Map database is not empty (%s)\n", (rtabmap.getWorkingDir()+Parameters::getDefaultDatabaseName()).c_str());
	}
	printf("\nProcessing images...\n");

	UTimer iterationTimer;
	UTimer rtabmapTimer;
	int imagesProcessed = 0;
	std::list<std::vector<float> > teleopActions;
	while(loopDataset <= repeat && g_forever)
	{
		cv::Mat img = camera->takeImage();
		int i=0;
		double maxIterationTime = 0.0;
		int maxIterationTimeId = 0;
		while(!img.empty() && g_forever)
		{
			++imagesProcessed;
			iterationTimer.start();
			rtabmapTimer.start();
			rtabmap.process(img);
			double rtabmapTime = rtabmapTimer.elapsed();
			loopClosureId = rtabmap.getLoopClosureId();
			if(rtabmap.getLoopClosureId())
			{
				++countLoopDetected;
			}
			img = camera->takeImage();
			if(++count % 100 == 0)
			{
				printf(" count = %d, loop closures = %d, max time (at %d) = %fs\n",
						count, countLoopDetected, maxIterationTimeId, maxIterationTime);
				maxIterationTime = 0.0;
				maxIterationTimeId = 0;
				std::map<int, int> wm = rtabmap.getWeights();
				printf(" WM(%d)=[", (int)wm.size());
				for(std::map<int, int>::iterator iter=wm.begin(); iter!=wm.end();++iter)
				{
					if(iter != wm.begin())
					{
						printf(";");
					}
					printf("%d,%d", iter->first, iter->second);
				}
				printf("]\n");
			}

			// Update generated ground truth matrix
			if(createGT)
			{
				if(loopClosureId > 0)
				{
					groundTruth.insert(std::make_pair(i, loopClosureId-1));
				}
			}

			++i;

			double iterationTime = iterationTimer.ticks();

			if(rtabmapTime > maxIterationTime)
			{
				maxIterationTime = rtabmapTime;
				maxIterationTimeId = count;
			}

			ULogger::flush();

			if(rtabmap.getLoopClosureId())
			{
				printf(" iteration(%d) loop(%d) hyp(%.2f) time=%fs/%fs *\n",
						count, rtabmap.getLoopClosureId(), rtabmap.getLcHypValue(), rtabmapTime, iterationTime);
			}
			else if(rtabmap.getRetrievedId())
			{
				printf(" iteration(%d) high(%d) hyp(%.2f) time=%fs/%fs\n",
						count, rtabmap.getRetrievedId(), rtabmap.getLcHypValue(), rtabmapTime, iterationTime);
			}
			else
			{
				printf(" iteration(%d) time=%fs/%fs\n", count, rtabmapTime, iterationTime);
			}

			if(timeThreshold && rtabmapTime > timeThreshold*100.0f)
			{
				printf(" ERROR,  there is  problem, too much time taken... %fs", rtabmapTime);
				break; // there is  problem, don't continue
			}
		}
		++loopDataset;
		if(loopDataset <= repeat)
		{
			camera->init();
			printf(" Beginning loop %d...\n", loopDataset);
		}
	}
	printf("Processing images completed. Loop closures found = %d\n", countLoopDetected);
	printf(" Total time = %fs\n", timer.ticks());

	if(imagesProcessed && createGT)
	{
		cv::Mat groundTruthMat = cv::Mat::zeros(imagesProcessed, imagesProcessed, CV_8U);

		for(std::map<int, int>::iterator iter = groundTruth.begin(); iter!=groundTruth.end(); ++iter)
		{
			groundTruthMat.at<unsigned char>(iter->first, iter->second) = 255;
		}

		// Generate the ground truth file
		printf("Generate ground truth to file %s, size of %d\n", (rtabmap.getWorkingDir()+GENERATED_GT_NAME).c_str(), groundTruthMat.rows);
		IplImage img = groundTruthMat;
		cvSaveImage((rtabmap.getWorkingDir()+GENERATED_GT_NAME).c_str(), &img);
		printf(" Creating ground truth file = %fs\n", timer.ticks());
	}

	if(camera)
	{
		delete camera;
		camera = 0 ;
	}

	rtabmap.close();

	printf(" Cleanup time = %fs\n", timer.ticks());

	return 0;
}
		void BaseCalendarUpdateAction::_getCalendarUpdateParametersMap(
			ParametersMap& map
		) const	{
			// Add
			if(!_add)
			{
				map.insert(PARAMETER_ADD, _add);
			}

			// Add link
			if(_addLink)
			{
				map.insert(PARAMETER_ADD_LINK, _addLink);
			}

			// Link to remove
			if(_linkToRemove)
			{
				map.insert(PARAMETER_LINK_TO_REMOVE, *_linkToRemove);
			}

			// Period
			if(!_period.is_special())
			{
				map.insert(PARAMETER_PERIOD, static_cast<int>(_period.days()));
			}

			// Calendar Template
			if(_calendarTemplate.get())
			{
				map.insert(PARAMETER_CALENDAR_TEMPLATE_ID, _calendarTemplate->getKey());
			}

			// Calendar Template 2
			if(_calendarTemplate2.get())
			{
				map.insert(PARAMETER_CALENDAR_TEMPLATE_ID2, _calendarTemplate2->getKey());
			}

			// Start date
			if(!_startDate.is_not_a_date())
			{
				map.insert(PARAMETER_START_DATE, _startDate);
			}

			// End date
			if(!_endDate.is_not_a_date() && _endDate != _startDate)
			{
				map.insert(PARAMETER_END_DATE, _endDate);
			}

			// Date to force to add
			if(!_dateToForceToAdd.is_not_a_date())
			{
				map.insert(PARAMETER_ADD_DATE_TO_FORCE, _dateToForceToAdd);
			}

			// Date to force to remove
			if(!_dateToForceToRemove.is_not_a_date())
			{
				map.insert(PARAMETER_REMOVE_DATE_TO_FORCE, _dateToForceToRemove);
			}

			// Date to force to add
			if(!_dateToBypassToAdd.is_not_a_date())
			{
				map.insert(PARAMETER_ADD_DATE_TO_BYPASS, _dateToBypassToAdd);
			}

			// Date to force to remove
			if(!_dateToBypassToRemove.is_not_a_date())
			{
				map.insert(PARAMETER_REMOVE_DATE_TO_BYPASS, _dateToBypassToRemove);
			}
		}
Example #25
0
		void OrService::_setFromParametersMap(const ParametersMap& map)
		{
			_left = map.isTrue(PARAMETER_LEFT);
			_right = map.isTrue(PARAMETER_RIGHT);
		}
Example #26
0
void TimetableWarning::toParametersMap(
    ParametersMap& pm,
    bool withDates
) const	{

    pm.insert(DATA_NUMBER, getNumber());
    pm.insert(DATA_TEXT, getText());

    // Active days
    const Calendar& calendar(getCalendar());
    date firstDate(calendar.getFirstActiveDate());
    date lastDate(calendar.getLastActiveDate());
    if(withDates)
    {
        for(date day(firstDate); day <lastDate; day += days(1))
        {
            // Jump over inactive days
            if(!calendar.isActive(day))
            {
                continue;
            }

            // Writing the active date to a sub map
            boost::shared_ptr<ParametersMap> datePM(new ParametersMap);
            datePM->insert(ATTR_DATE, day);
            pm.insert(TAG_DAY, datePM);
        }
    }

    // Active days bounds
    pm.insert(DATA_FIRST_DATE, firstDate);
    pm.insert(DATA_LAST_DATE, firstDate);

    // Active days bounds (old schema - deprecated)
    pm.insert(DATA_FIRST_DAY, firstDate.day());
    pm.insert(DATA_FIRST_MONTH, firstDate.month());
    pm.insert(DATA_FIRST_YEAR, firstDate.year());
    pm.insert(DATA_LAST_DAY, lastDate.day());
    pm.insert(DATA_LAST_MONTH, lastDate.month());
    pm.insert(DATA_LAST_YEAR, lastDate.year());

    // Calendar template
    if(_calendarTemplate)
    {
        boost::shared_ptr<ParametersMap> calendarPM(new ParametersMap);
        _calendarTemplate->toParametersMap(*calendarPM, true);
        pm.insert(TAG_CALENDAR, calendarPM);
    }
}
Example #27
0
		ParametersMap PackagesService::run(
			std::ostream& stream,
			const Request& request
		) const {
			ParametersMap map;

			HTMLPage p;
			p.setDefaultInlineCSS();
			
			if(request.getSession() &&
				request.getSession()->hasProfile() &&
				request.getSession()->getUser()->getProfile()->isAuthorized<CMSInstallRight>(READ)
			){
				// User right
				bool installRight(request.getSession()->getUser()->getProfile()->isAuthorized<CMSInstallRight>(WRITE));

				if(	installRight &&
					_packageToInstall
				){
					InterSYNTHESEPackage::PackageAddress address(*_packageToInstall);
					// Search for existing import based on this package
					shared_ptr<Import> import;
					Env env;
					BOOST_FOREACH(const Import::Registry::value_type& it, Env::GetOfficialEnv().getRegistry<Import>())
					{
						// Jump over non inter synthese imports
						if(it.second->get<FileFormatKey>() != InterSYNTHESEPackageFileFormat::FACTORY_KEY)
						{
							continue;
						}
						shared_ptr<InterSYNTHESEPackageFileFormat::Importer_> importer(
							dynamic_pointer_cast<InterSYNTHESEPackageFileFormat::Importer_, Importer>(
								it.second->getImporter(env, IMPORT_LOG_NOLOG, string(), optional<ostream&>(), it.second->get<Parameters>())
						)	);
						if(!importer.get())
						{
							continue;
						}
						try
						{
							importer->setFromParametersMap(it.second->get<Parameters>(), true);
						}
						catch(...)
						{
							continue;
						}
						if(	importer->getSmartURL() == address.smartURL &&
							importer->getUser() == _user &&
							importer->getPassword() == _password
						){
							import = it.second;
							break;
						}
					}

					// Create import if not exist
					if(!import.get())
					{
						import.reset(new Import);
						import->set<Name>(*_packageToInstall);
						import->set<FileFormatKey>(InterSYNTHESEPackageFileFormat::FACTORY_KEY);
						ParametersMap pm;
						pm.insert(InterSYNTHESEPackageFileFormat::Importer_::PARAMETER_URL, *_packageToInstall);
						pm.insert(InterSYNTHESEPackageFileFormat::Importer_::PARAMETER_USER, _user);
						pm.insert(InterSYNTHESEPackageFileFormat::Importer_::PARAMETER_PASSWORD, _password);
						import->set<Parameters>(pm);
						ImportTableSync::Save(import.get());
					}

					shared_ptr<Importer> importer(
						import->getImporter(env, IMPORT_LOG_NOLOG, string(), optional<ostream&>(), import->get<Parameters>())
					);
					bool success(true);
					importer->setFromParametersMap(import->get<Parameters>(), true);
					success &= importer->beforeParsing();
					success &= importer->parseFiles();
					success &= importer->afterParsing();
					if(success)
					{
						importer->save().run();
					}
				}
Example #28
0
int main(int argc, char * argv[])
{
	ULogger::setType(ULogger::kTypeConsole);
    ULogger::setLevel(ULogger::kWarning);

    ParametersMap pm = Parameters::parseArguments(argc, argv);
    pm.insert(ParametersPair(Parameters::kRtabmapWorkingDirectory(), "."));

	int argIndex = 1;

	int cameraRate = atoi(argv[argIndex++]);
	if(cameraRate <= 0)
	{
		printf("camera_rate should be > 0\n");
		showUsage();
	}
	int odomUpdate = atoi(argv[argIndex++]);
	if(odomUpdate <= 0)
	{
		printf("odom_update should be > 0\n");
		showUsage();
	}
	int mapUpdate = atoi(argv[argIndex++]);
	if(mapUpdate <= 0)
	{
		printf("map_update should be > 0\n");
		showUsage();
	}

	printf("Camera rate = %d Hz\n", cameraRate);
	printf("Odometry update rate = %d Hz\n", cameraRate/odomUpdate);
	printf("Map update rate = %d Hz\n", (cameraRate/odomUpdate)/mapUpdate);


	std::string calibrationDir = argv[argIndex++];
    std::string calibrationName = argv[argIndex++];
    std::string pathRGBImages = argv[argIndex++];
    std::string pathDepthImages = argv[argIndex++];

	Transform opticalRotation(0,0,1,0, -1,0,0,0, 0,-1,0,0);
	//CameraStereoImages camera(
	//		pathLeftImages,
	//		pathRightImages,
	//		false, // assume that images are already rectified
	//		(float)cameraRate,
	//		opticalRotation);
//	CameraFreenect2 camera(0, CameraFreenect2::Type::kTypeColor2DepthSD, 0.0, opticalRotation);
    CameraRGBDImages camera(pathRGBImages, pathDepthImages, 1, float(cameraRate), opticalRotation);

    std::ofstream stats_file;
    stats_file.open("statistics.txt");
    stats_file << "[" << std::endl;

	if(camera.init(calibrationDir, calibrationName))
	{
		OdometryF2M odom;
		Rtabmap rtabmap;
		rtabmap.init(pm);

		QApplication app(argc, argv);
		MapBuilder mapBuilder;
		mapBuilder.show();
		QApplication::processEvents();

		SensorData data = camera.takeImage();
		int cameraIteration = 0;
		int odometryIteration = 0;
		printf("Press \"Space\" in the window to pause\n");
		while(data.isValid() && mapBuilder.isVisible())
		{
			if(cameraIteration++ % odomUpdate == 0)
			{
				OdometryInfo info;
				Transform pose = odom.process(data, &info);

				if(odometryIteration++ % mapUpdate == 0)
				{
					if(rtabmap.process(data, pose))
					{
						mapBuilder.processStatistics(rtabmap.getStatistics());
						if(rtabmap.getLoopClosureId() > 0)
						{
							printf("Loop closure detected!\n");
						}

                        std::map<std::string, float> statz = rtabmap.getStatistics().data();
                        stats_file << "  {" << std::endl;
                        for(std::map<std::string,float>::iterator it = statz.begin(); it != statz.end(); ++it) {
                            std::string name = it->first;
                            std::replace(name.begin(), name.end(), '/', '.');

                            stats_file << "    \"" << name << "\": " << it->second << "," << std::endl;
                        }
                        stats_file << "  }," << std::endl;
					}
				}

				mapBuilder.processOdometry(data, pose, info);
			}

			QApplication::processEvents();

			while(mapBuilder.isPaused() && mapBuilder.isVisible())
			{
				uSleep(100);
				QApplication::processEvents();
			}

			data = camera.takeImage();
		}

		if(mapBuilder.isVisible())
		{
			printf("Processed all frames\n");
			app.exec();
		}
	}
	else
	{
		UERROR("Camera init failed!");
	}

    stats_file << "]" << std::endl;
    stats_file.close();

	return 0;
}
Example #29
0
		void ImportFunction::_setFromParametersMap(const ParametersMap& map)
		{
			// Import
			RegistryKeyType importId(map.get<RegistryKeyType>(PARAMETER_IMPORT_ID));
			try
			{
				boost::shared_ptr<const Import> import(ImportTableSync::Get(importId, *_env));
				if(!import->get<DataSource>())
				{
					throw RequestException("The id system of the specified import is not defined.");
				}

				// Log path
				bool outputLogs(map.getDefault<bool>(PARAMETER_OUTPUT_LOGS, false));

				// Min log force
				ImportLogLevel minLogLevel(import->get<MinLogLevel>());
				if(map.isDefined(PARAMETER_MIN_LOG_LEVEL))
				{
					minLogLevel = static_cast<ImportLogLevel>(map.get<int>(PARAMETER_MIN_LOG_LEVEL));
				}

				// Log path force
				string logPath(import->get<LogPath>());
				if(map.isDefined(PARAMETER_LOG_PATH))
				{
					logPath = map.get<string>(PARAMETER_LOG_PATH);
				}
				
				// Logger generation
				if(outputLogs)
				{
					// Importer generation
					_importer = import->getImporter(
						*_env,
						minLogLevel,
						logPath,
						_output,
						_result
					);
				}
				else
				{
					// Importer generation
					_importer = import->getImporter(
						*_env,
						minLogLevel,
						logPath,
						optional<ostream&>(),
						_result
					);
				}

				_importer->setFromParametersMap(map, true);

				_doImport = map.isTrue(PARAMETER_DO_IMPORT);
				_importDone = _importer->beforeParsing();
				_importDone &= _importer->parseFiles();
				_importDone &=_importer->afterParsing();
			}
			catch(ObjectNotFoundException<DataSource> e)
			{
				throw RequestException("Datasource not found");
			}
			catch(Exception e)
			{
				throw RequestException("Load failed : " + e.getMessage());
			}
		}
Example #30
0
		bool Function::outputParametersMap(
			const ParametersMap& pm,
			ostream& stream,
			const string& tag,
			const string& xmlSchemaLocation,
			bool sorted,/* = true */
			const string& xmlUnsortedSchemaLocation /* = "" */
		) const {

			if(_outputFormat == MimeTypes::JSON)
			{
				if(sorted)
				{
					pm.outputJSON(
						stream,
						tag
					);
				}
				else
				{
					(*pm.getSubMaps(tag).begin())->outputJSON(
						stream,
						tag
					);
				}
			}
			else if(_outputFormat == MimeTypes::XML)
			{
				if(sorted)
				{
					pm.outputXML(
						stream,
						tag,
						true,
						xmlSchemaLocation
					);
				}
				else
				{
					(*pm.getSubMaps(tag).begin())->outputXML(
						stream,
						tag,
						true,
						xmlUnsortedSchemaLocation
					);
				}
			}
			else if(_outputFormat == MimeTypes::CSV)
			{
				pm.outputCSV(
					stream,
					tag
				);
			}
			else
			{
				return false;
			}

			return true;
		}