AveragingMSRowProvider::AveragingMSRowProvider(double nWavelengthsAveraging, const string& msPath, const MSSelection& selection, const std::map<size_t, size_t>& selectedDataDescIds, const string& dataColumnName, bool requireModel) :
	MSRowProvider(msPath, selection, selectedDataDescIds, dataColumnName, requireModel)
{
	casacore::MSAntenna antennaTable(_ms.antenna());
	_nAntennae = antennaTable.nrow();
	
	casacore::ROArrayColumn<double> positionColumn(antennaTable, casacore::MSAntenna::columnName(casacore::MSAntennaEnums::POSITION));
	std::vector<Pos> positions(_nAntennae);

	casacore::Array<double> posArr(casacore::IPosition(1, 3));
	for(size_t i=0; i!=_nAntennae; ++i)
	{
		positionColumn.get(i, posArr);
		positions[i] = Pos(posArr.data()[0], posArr.data()[1], posArr.data()[2]);
	}
	
	// dataDescId x ant x ant
	_nElements = selectedDataDescIds.size() * _nAntennae * _nAntennae;
	_averagingFactors.assign(_nElements, 0.0);
	_buffers.resize(_nElements);
	MultiBandData bands(_ms.spectralWindow(), _ms.dataDescription());
	
	double dt = (EndTime() - StartTime()) / (EndTimestep() - StartTimestep());
	Logger::Debug << "Assuming integration time of " << dt * (24.0*60.0*60.0) << " seconds.\n";
	
	size_t element = 0;
	size_t averagingSum = 0, minAvgFactor = std::numeric_limits<size_t>::max(), maxAvgFactor = 0;
	for(size_t a1=0; a1!=_nAntennae; ++a1)
	{
		Pos pos1 = positions[a1];
		for(size_t a2=0; a2!=_nAntennae; ++a2)
		{
			Pos pos2 = positions[a2];
			double dx = std::get<0>(pos1) - std::get<0>(pos2);
			double dy = std::get<1>(pos1) - std::get<1>(pos2);
			double dz = std::get<2>(pos1) - std::get<2>(pos2);
			double dist = sqrt(dx*dx + dy*dy + dz*dz);
			for(std::map<size_t, size_t>::const_iterator spwIter=selectedDataDescIds.begin();
					spwIter!=selectedDataDescIds.end(); ++spwIter)
			{
				BandData band = bands[spwIter->first];
				double lambda = band.SmallestWavelength();
				double nWavelengthsPerIntegration = 2.0 * M_PI * dist / lambda * dt;
				_averagingFactors[element] = std::max<size_t>(size_t(floor(nWavelengthsAveraging / nWavelengthsPerIntegration)), 1);
				averagingSum += _averagingFactors[element];
				if(a1 != a2)
				{
					minAvgFactor = std::min<size_t>(minAvgFactor, _averagingFactors[element]);
					maxAvgFactor = std::max<size_t>(maxAvgFactor, _averagingFactors[element]);
				}
				//Logger::Debug << a1 << '\t' << a2 << '\t' << _averagingFactors[element] << '\n';
				++element;
			}
		}
	}
	Logger::Info << "Averaging factor for longest baseline: " << minAvgFactor << " x . For the shortest: " << maxAvgFactor << " x \n";
	
	_spwIndexToDataDescId.resize(selectedDataDescIds.size());
	for(std::map<size_t, size_t>::const_iterator spwIter=selectedDataDescIds.begin();
		spwIter!=selectedDataDescIds.end(); ++spwIter)
	{
		_spwIndexToDataDescId[spwIter->second] = spwIter->first;
	}
	
	_averageFactorSum = 0.0;
	_rowCount = 0;
	_averagedRowCount = 0;

	_currentData = DataArray(DataShape());
	_currentModel = DataArray(DataShape());
	_currentFlags = FlagArray(DataShape());
	_currentWeights = WeightArray(DataShape());
	_averagedDataDescId = _currentDataDescId;
	_flushPosition = 0;
	
	if(!MSRowProvider::AtEnd())
	{
		bool timestepAvailable = processCurrentTimestep();
		if(!timestepAvailable)
			NextRow();
	}
}
Example #2
0
File: tree.cpp Project: gejza/xcdev
	int Search(const char* k)
	{
		std::map<std::string, int>::iterator i = tree.find(std::string(k));
		return i != tree.end() ? i->second:0;
	}
Example #3
0
fostlib::headers_base::content::content(
    const string &val, const std::map< string, string > &args)
: m_subvalues( args.begin(), args.end() ), value( val ) {
}
QString QAutoGenDialog::GetAssocModel(const QString & strParam, const QString & strType, std::map<QString, QString> & mapAssocModels, const std::map<QString, QString> & mapAssocModelTypes, std::map<QString, std::map<QString, AutoGenParameter> > & mapAssocParams, unsigned int iVehicle)
{
	// first, check list of models to see if one of the right type exists
	std::map<QString, QString>::iterator iterModel = mapAssocModels.find(strParam);

	if (iterModel == mapAssocModels.end())
	{
		if (strType.compare(NULLMODEL_NAME) == 0)
			iterModel = mapAssocModels.insert(std::pair<QString, QString>(strParam, "NULL")).first;
		else
		{
			// no such luck, let's make a new model
			std::map<QString, std::map<QString, ModelParameter> >::iterator iterModelParams = m_pMapParams->find(strType);
			std::map<QString, ModelParameter>::iterator iterParam;
			std::map<QString, unsigned int>::iterator iterModelIndex = m_mapModelIndexes.find(strType);
			std::map<QString, QString>::const_iterator iterModelType;
			std::map<QString, QString> mapParams;
			std::map<QString, std::map<QString, AutoGenParameter> >::iterator iterAutoParams = mapAssocParams.find(strParam);
			std::map<QString, AutoGenParameter>::iterator iterAutoParam;
			QStringList listDepends;
			QStringList::iterator iterDepend;
			std::set<QString> setDepends;
			std::set<QString>::iterator iterSetDepend;
			QString strName;
			unsigned iModel = iterModelIndex == m_mapModelIndexes.end() ? 0 : iterModelIndex->second;
			while (m_pModelNames->find(strName = QString("%1%2").arg(strType).arg(iModel)) != m_pModelNames->end())
				iModel++;
			if (iterModelParams != m_pMapParams->end() && iterAutoParams != mapAssocParams.end())
			{
				for (iterAutoParam = iterAutoParams->second.begin(); iterAutoParam != iterAutoParams->second.end(); ++iterAutoParam)
				{
					iterParam = iterModelParams->second.find(iterAutoParam->first);
					switch (iterAutoParam->second.eType)
					{
					case AutoGenParamTypeDepends:
						listDepends = QStringList::split(';', iterAutoParam->second.strValue);
						for (iterDepend = listDepends.begin(); iterDepend != listDepends.end(); ++iterDepend)
							setDepends.insert(*iterDepend);
						break;
					case AutoGenParamTypeNewModel:
						iterModelType = mapAssocModelTypes.find(iterAutoParam->first);
						if (iterModelType == mapAssocModelTypes.end())
							mapParams[iterAutoParam->first] = GetAssocModel(iterAutoParam->first, iterAutoParam->second.strValue, mapAssocModels, mapAssocModelTypes, mapAssocParams, iVehicle);
						else
							mapParams[iterAutoParam->first] = GetAssocModel(iterAutoParam->first, iterModelType->second, mapAssocModels, mapAssocModelTypes, mapAssocParams, iVehicle);
						setDepends.insert(mapParams[iterAutoParam->first]);
						break;
					case AutoGenParamTypeRandom: // randomize
						mapParams[iterAutoParam->first] = GetRandomParameter(iterAutoParam->first, iterAutoParam->second.strValue, iterParam->second);
						break;
					case AutoGenParamTypeFile: // choose file
						mapParams[iterAutoParam->first] = GetFileParameter(iterAutoParam->first, iterAutoParam->second.strValue, iVehicle);
						break;
					default:
						mapParams[iterAutoParam->first] = iterAutoParam->second.strValue;
						break;
					}
				}
			}
			setDepends.erase("NULL");
			mapParams[PARAM_DEPENDS] = QString::null;
			for (iterSetDepend = setDepends.begin(); iterSetDepend != setDepends.end(); ++iterSetDepend)
			{
				if (mapParams[PARAM_DEPENDS].isEmpty())
					mapParams[PARAM_DEPENDS] = *iterSetDepend;
				else
					mapParams[PARAM_DEPENDS] += (';' + *iterSetDepend);
			}
			iterModel = mapAssocModels.insert(std::pair<QString, QString>(strParam, strName)).first;
			m_pModels->insert(std::pair<QString, std::map<QString, QString> >(strName, mapParams));
			m_pModelList->push_back(std::pair<QString, QString>(strName, strType));
			m_pModelNames->insert(strName);
			listDepends.clear();
			if (iterModelIndex != m_mapModelIndexes.end())
				iterModelIndex->second = iModel + 1;
			else
				m_mapModelIndexes[strType] = iModel + 1;
		}
	}
	return iterModel->second;
}
Example #5
0
bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
                           unsigned LineNumber) {
  this->LineNumber = LineNumber;
  PatternLoc = SMLoc::getFromPointer(PatternStr.data());

  // Ignore trailing whitespace.
  while (!PatternStr.empty() &&
         (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
    PatternStr = PatternStr.substr(0, PatternStr.size()-1);

  // Check that there is something on the line.
  if (PatternStr.empty()) {
    SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
                    "found empty check string with prefix '" +
                    CheckPrefix+":'");
    return true;
  }

  // Check to see if this is a fixed string, or if it has regex pieces.
  if (PatternStr.size() < 2 ||
      (PatternStr.find("{{") == StringRef::npos &&
       PatternStr.find("[[") == StringRef::npos)) {
    FixedStr = PatternStr;
    return false;
  }

  // Paren value #0 is for the fully matched string.  Any new parenthesized
  // values add from there.
  unsigned CurParen = 1;

  // Otherwise, there is at least one regex piece.  Build up the regex pattern
  // by escaping scary characters in fixed strings, building up one big regex.
  while (!PatternStr.empty()) {
    // RegEx matches.
    if (PatternStr.startswith("{{")) {
      // This is the start of a regex match.  Scan for the }}.
      size_t End = PatternStr.find("}}");
      if (End == StringRef::npos) {
        SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
                        SourceMgr::DK_Error,
                        "found start of regex string with no end '}}'");
        return true;
      }

      // Enclose {{}} patterns in parens just like [[]] even though we're not
      // capturing the result for any purpose.  This is required in case the
      // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
      // want this to turn into: "abc(x|z)def" not "abcx|zdef".
      RegExStr += '(';
      ++CurParen;

      if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
        return true;
      RegExStr += ')';

      PatternStr = PatternStr.substr(End+2);
      continue;
    }

    // Named RegEx matches.  These are of two forms: [[foo:.*]] which matches .*
    // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
    // second form is [[foo]] which is a reference to foo.  The variable name
    // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
    // it.  This is to catch some common errors.
    if (PatternStr.startswith("[[")) {
      // Find the closing bracket pair ending the match.  End is going to be an
      // offset relative to the beginning of the match string.
      size_t End = FindRegexVarEnd(PatternStr.substr(2));

      if (End == StringRef::npos) {
        SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
                        SourceMgr::DK_Error,
                        "invalid named regex reference, no ]] found");
        return true;
      }

      StringRef MatchStr = PatternStr.substr(2, End);
      PatternStr = PatternStr.substr(End+4);

      // Get the regex name (e.g. "foo").
      size_t NameEnd = MatchStr.find(':');
      StringRef Name = MatchStr.substr(0, NameEnd);

      if (Name.empty()) {
        SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
                        "invalid name in named regex: empty name");
        return true;
      }

      // Verify that the name/expression is well formed. FileCheck currently
      // supports @LINE, @LINE+number, @LINE-number expressions. The check here
      // is relaxed, more strict check is performed in \c EvaluateExpression.
      bool IsExpression = false;
      for (unsigned i = 0, e = Name.size(); i != e; ++i) {
        if (i == 0 && Name[i] == '@') {
          if (NameEnd != StringRef::npos) {
            SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
                            SourceMgr::DK_Error,
                            "invalid name in named regex definition");
            return true;
          }
          IsExpression = true;
          continue;
        }
        if (Name[i] != '_' && !isalnum(Name[i]) &&
            (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
          SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
                          SourceMgr::DK_Error, "invalid name in named regex");
          return true;
        }
      }

      // Name can't start with a digit.
      if (isdigit(Name[0])) {
        SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
                        "invalid name in named regex");
        return true;
      }

      // Handle [[foo]].
      if (NameEnd == StringRef::npos) {
        // Handle variables that were defined earlier on the same line by
        // emitting a backreference.
        if (VariableDefs.find(Name) != VariableDefs.end()) {
          unsigned VarParenNum = VariableDefs[Name];
          if (VarParenNum < 1 || VarParenNum > 9) {
            SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
                            SourceMgr::DK_Error,
                            "Can't back-reference more than 9 variables");
            return true;
          }
          AddBackrefToRegEx(VarParenNum);
        } else {
          VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
        }
        continue;
      }

      // Handle [[foo:.*]].
      VariableDefs[Name] = CurParen;
      RegExStr += '(';
      ++CurParen;

      if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
        return true;

      RegExStr += ')';
    }

    // Handle fixed string matches.
    // Find the end, which is the start of the next regex.
    size_t FixedMatchEnd = PatternStr.find("{{");
    FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
    AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
    PatternStr = PatternStr.substr(FixedMatchEnd);
  }

  return false;
}
Example #6
0
 gcc_pure
 bool IsUserKnown(uint32_t id) const {
   return user_names.find(id) != user_names.end();
 }
Example #7
0
/**
 * Return the confidence with with this algorithm can load the file
 * @param eventEntries map of the file entries that have events
 * @param outputGroup pointer to the workspace group
 * @param nxFile Reads data from inside first first top entry
 */
void LoadMcStas::readEventData(
    const std::map<std::string, std::string> &eventEntries,
    WorkspaceGroup_sptr &outputGroup, ::NeXus::File &nxFile) {
  std::string filename = getPropertyValue("Filename");
  auto entries = nxFile.getEntries();
  bool errorBarsSetTo1 = getProperty("ErrorBarsSetTo1");
  // will assume that each top level entry contain one mcstas
  // generated IDF and any event data entries within this top level
  // entry are data collected for that instrument
  // This code for loading the instrument is for now adjusted code from
  // ExperimentalInfo.

  // Close data folder and go back to top level. Then read and close the
  // Instrument folder.
  nxFile.closeGroup();

  Geometry::Instrument_sptr instrument;

  // Initialize progress reporting
  int reports = 2;
  const double progressFractionInitial = 0.1;
  Progress progInitial(this, 0.0, progressFractionInitial, reports);

  try {
    nxFile.openGroup("instrument", "NXinstrument");
    std::string instrumentXML;
    nxFile.openGroup("instrument_xml", "NXnote");
    nxFile.readData("data", instrumentXML);
    nxFile.closeGroup();
    nxFile.closeGroup();

    progInitial.report("Loading instrument");

    std::string instrumentName = "McStas";
    Geometry::InstrumentDefinitionParser parser(filename, instrumentName, instrumentXML);
    std::string instrumentNameMangled = parser.getMangledName();

    // Check whether the instrument is already in the InstrumentDataService
    if (InstrumentDataService::Instance().doesExist(instrumentNameMangled)) {
      // If it does, just use the one from the one stored there
      instrument =
          InstrumentDataService::Instance().retrieve(instrumentNameMangled);
    } else {
      // Really create the instrument
      instrument = parser.parseXML(NULL);
      // Add to data service for later retrieval
      InstrumentDataService::Instance().add(instrumentNameMangled, instrument);
    }
  } catch (...) {
    // Loader should not stop if there is no IDF.xml
    g_log.warning()
        << "\nCould not find the instrument description in the Nexus file:"
        << filename << " Ignore evntdata from data file" << std::endl;
    return;
  }
  // Finished reading Instrument. Then open new data folder again
  nxFile.openGroup("data", "NXdetector");

  // create and prepare an event workspace ready to receive the mcstas events
  progInitial.report("Set up EventWorkspace");
  EventWorkspace_sptr eventWS(new EventWorkspace());
  // initialize, where create up front number of eventlists = number of
  // detectors
  eventWS->initialize(instrument->getNumberDetectors(), 1, 1);
  // Set the units
  eventWS->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
  eventWS->setYUnit("Counts");
  // set the instrument
  eventWS->setInstrument(instrument);
  // assign detector ID to eventlists

  std::vector<detid_t> detIDs = instrument->getDetectorIDs();

  for (size_t i = 0; i < instrument->getNumberDetectors(); i++) {
    eventWS->getEventList(i).addDetectorID(detIDs[i]);
    // spectrum number are treated as equal to detector IDs for McStas data
    eventWS->getEventList(i).setSpectrumNo(detIDs[i]);
  }
  // the one is here for the moment for backward compatibility
  eventWS->rebuildSpectraMapping(true);

  bool isAnyNeutrons = false;
  // to store shortest and longest recorded TOF
  double shortestTOF(0.0);
  double longestTOF(0.0);

  const size_t numEventEntries = eventEntries.size();
  Progress progEntries(this, progressFractionInitial, 1.0, numEventEntries * 2);
  for (auto eit = eventEntries.begin(); eit != eventEntries.end(); ++eit) {
    std::string dataName = eit->first;
    std::string dataType = eit->second;

    // open second level entry
    nxFile.openGroup(dataName, dataType);
    std::vector<double> data;
    nxFile.openData("events");
    progEntries.report("read event data from nexus");

    // Need to take into account that the nexus readData method reads a
    // multi-column data entry
    // into a vector
    // The number of data column for each neutron is here hardcoded to (p, x,
    // y,  n, id, t)
    // Thus  we have
    // column  0 : p 	neutron wight
    // column  1 : x 	x coordinate
    // column  2 : y 	y coordinate
    // column  3 : n 	accumulated number of neutrons
    // column  4 : id 	pixel id
    // column  5 : t 	time

    // get info about event data
    ::NeXus::Info id_info = nxFile.getInfo();
    if (id_info.dims.size() != 2) {
      g_log.error() << "Event data in McStas nexus file not loaded. Expected "
                       "event data block to be two dimensional" << std::endl;
      return;
    }
    int64_t nNeutrons = id_info.dims[0];
    int64_t numberOfDataColumn = id_info.dims[1];
    if (nNeutrons && numberOfDataColumn != 6) {
      g_log.error() << "Event data in McStas nexus file expecting 6 columns"
                    << std::endl;
      return;
    }
    if (isAnyNeutrons == false && nNeutrons > 0)
      isAnyNeutrons = true;

    std::vector<int64_t> start(2);
    std::vector<int64_t> step(2);

    // read the event data in blocks. 1 million event is 1000000*6*8 doubles
    // about 50Mb
    int64_t nNeutronsInBlock = 1000000;
    int64_t nOfFullBlocks = nNeutrons / nNeutronsInBlock;
    int64_t nRemainingNeutrons = nNeutrons - nOfFullBlocks * nNeutronsInBlock;
    // sum over number of blocks + 1 to cover the remainder
    for (int64_t iBlock = 0; iBlock < nOfFullBlocks + 1; iBlock++) {
      if (iBlock == nOfFullBlocks) {
        // read remaining neutrons
        start[0] = nOfFullBlocks * nNeutronsInBlock;
        start[1] = 0;
        step[0] = nRemainingNeutrons;
        step[1] = numberOfDataColumn;
      } else {
        // read neutrons in a full block
        start[0] = iBlock * nNeutronsInBlock;
        start[1] = 0;
        step[0] = nNeutronsInBlock;
        step[1] = numberOfDataColumn;
      }
      const int64_t nNeutronsForthisBlock =
          step[0]; // number of neutrons read for this block
      data.resize(nNeutronsForthisBlock * numberOfDataColumn);

      // Check that the type is what it is supposed to be
      if (id_info.type == ::NeXus::FLOAT64) {
        nxFile.getSlab(&data[0], start, step);
      } else {
        g_log.warning()
            << "Entry event field is not FLOAT64! It will be skipped.\n";
        continue;
      }

      // populate workspace with McStas events
      const detid2index_map detIDtoWSindex_map =
          eventWS->getDetectorIDToWorkspaceIndexMap(true);

      progEntries.report("read event data into workspace");
      for (int64_t in = 0; in < nNeutronsForthisBlock; in++) {
        const int detectorID =
            static_cast<int>(data[4 + numberOfDataColumn * in]);
        const double detector_time = data[5 + numberOfDataColumn * in] *
                                     1.0e6; // convert to microseconds
        if (in == 0 && iBlock == 0) {
          shortestTOF = detector_time;
          longestTOF = detector_time;
        } else {
          if (detector_time < shortestTOF)
            shortestTOF = detector_time;
          if (detector_time > longestTOF)
            longestTOF = detector_time;
        }

        const size_t workspaceIndex =
            detIDtoWSindex_map.find(detectorID)->second;

        int64_t pulse_time = 0;
        // eventWS->getEventList(workspaceIndex) +=
        // TofEvent(detector_time,pulse_time);
        // eventWS->getEventList(workspaceIndex) += TofEvent(detector_time);
        // The following line puts the events into the weighted event instance
        //Originally this was coded so the error squared is 1 it should be 
        //data[numberOfDataColumn * in]*data[numberOfDataColumn * in]
        //introduced flag to allow old usage 
        if (errorBarsSetTo1){
          eventWS->getEventList(workspaceIndex) += WeightedEvent(
              detector_time, pulse_time, data[numberOfDataColumn * in], 1.0);
        } else{    
          eventWS->getEventList(workspaceIndex) += WeightedEvent(
            detector_time, pulse_time, data[numberOfDataColumn * in], data[numberOfDataColumn * in]*data[numberOfDataColumn * in]);
        }
        
      }
    } // end reading over number of blocks of an event dataset

    // nxFile.getData(data);
    nxFile.closeData();
    nxFile.closeGroup();

  } // end reading over number of event datasets

  // Create a default TOF-vector for histogramming, for now just 2 bins
  // 2 bins is the standard. However for McStas simulation data it may make
  // sense to
  // increase this number for better initial visual effect
  Kernel::cow_ptr<MantidVec> axis;
  MantidVec &xRef = axis.access();
  xRef.resize(2, 0.0);
  // if ( nNeutrons > 0)
  if (isAnyNeutrons) {
    xRef[0] = shortestTOF - 1; // Just to make sure the bins hold it all
    xRef[1] = longestTOF + 1;
  }
  // Set the binning axis
  eventWS->setAllX(axis);

  // ensure that specified name is given to workspace (eventWS) when added to
  // outputGroup
  std::string nameOfGroupWS = getProperty("OutputWorkspace");
  std::string nameUserSee = std::string("EventData_") + nameOfGroupWS;
  std::string extraProperty =
      "Outputworkspace_dummy_" +
      boost::lexical_cast<std::string>(m_countNumWorkspaceAdded);
  declareProperty(new WorkspaceProperty<Workspace>(extraProperty, nameUserSee,
                                                   Direction::Output));
  setProperty(extraProperty, boost::static_pointer_cast<Workspace>(eventWS));
  m_countNumWorkspaceAdded++; // need to increment to ensure extraProperty are
                              // unique

  outputGroup->addWorkspace(eventWS);
}
Example #8
0
void CAirPlayServer::CTCPClient::PushBuffer(CAirPlayServer *host, const char *buffer,
                                            int length, CStdString &sessionId, std::map<CStdString,
                                            int> &reverseSockets)
{
  HttpParser::status_t status = m_httpParser->addBytes(buffer, length);

  if (status == HttpParser::Done)
  {
    // Parse the request
    CStdString responseHeader;
    CStdString responseBody;
    CStdString reverseHeader;
    CStdString reverseBody;
    int status = ProcessRequest(responseHeader, responseBody, reverseHeader, reverseBody, sessionId);
    CStdString statusMsg = "OK";
    int reverseSocket = INVALID_SOCKET;

    switch(status)
    {
      case AIRPLAY_STATUS_NOT_IMPLEMENTED:
        statusMsg = "Not Implemented";
        break;
      case AIRPLAY_STATUS_SWITCHING_PROTOCOLS:
        statusMsg = "Switching Protocols";
        reverseSockets[sessionId] = m_socket;//save this socket as reverse http socket for this sessionid
        break;
      case AIRPLAY_STATUS_NEED_AUTH:
        statusMsg = "Unauthorized";
        break;
    }

    // Prepare the response
    CStdString response;
    const time_t ltime = time(NULL);
    char *date = asctime(gmtime(&ltime)); //Fri, 17 Dec 2010 11:18:01 GMT;
    date[strlen(date) - 1] = '\0'; // remove \n
    response.Format("HTTP/1.1 %d %s\nDate: %s\r\n", status, statusMsg.c_str(), date);
    if (responseHeader.size() > 0)
    {
      response += responseHeader;
    }

    if (responseBody.size() > 0)
    {
      response.Format("%sContent-Length: %d\r\n", response.c_str(), responseBody.size());
    }
    response += "\r\n";

    if (responseBody.size() > 0)
    {
      response += responseBody;
    }

    // Send the response
    //don't send response on AIRPLAY_STATUS_NO_RESPONSE_NEEDED
    if (status != AIRPLAY_STATUS_NO_RESPONSE_NEEDED)
    {
      send(m_socket, response.c_str(), response.size(), 0);
    }

    // Send event status per reverse http socket (play, loading, paused)
    // if we have a reverse header and a reverse socket
    if (reverseHeader.size() > 0 && reverseSockets.find(sessionId) != reverseSockets.end())
    {
      //search the reverse socket to this sessionid
      response.Format("POST /event HTTP/1.1\r\n");
      reverseSocket = reverseSockets[sessionId]; //that is our reverse socket
      response += reverseHeader;
    }
    response += "\r\n";

    if (reverseBody.size() > 0)
    {
      response += reverseBody;
    }

    if (reverseSocket != INVALID_SOCKET)
    {
      send(reverseSocket, response.c_str(), response.size(), 0);//send the event status on the eventSocket
    }

    // We need a new parser...
    delete m_httpParser;
    m_httpParser = new HttpParser;
  }
}
Example #9
0
static void parseMeshInfo(MeshModel* root, float curr_time)
{
	_log("OBJECT_NODE_TAG");
	enterChunk();
	std::string    name, inst;
	Vector         pivot;
	Animation      anim;
	unsigned short id = 65535, parent = 65535, flags1, flags2;
	Box            box = Box(Vector(), Vector());
	Vector         box_centre;
	while (int chunk_id = nextChunk()) {
		switch (chunk_id) {
		case 0xb030: //NODE_ID
			in.sgetn((char*)&id, 2);
			_log("NODE_ID: " + itoa(id));
			break;
		case 0xb010: //NODE_HDR
			name = parseString();
			in.sgetn((char*)&flags1, 2);
			in.sgetn((char*)&flags2, 2);
			in.sgetn((char*)&parent, 2);
			_log("NODE_HDR: name=" + name + " parent=" + itoa(parent));
			break;
		case 0xb011: //INSTANCE NAME
			inst = parseString();
			_log("INSTANCE_NAME: " + inst);
			break;
		case 0xb013: //PIVOT
			in.sgetn((char*)&pivot, 12);
			if (conv)
				pivot = conv_tform * pivot;
			_log("PIVOT: " + ftoa(pivot.x) + "," + ftoa(pivot.y) + "," + ftoa(pivot.z));
			break;
		case 0xb014: //BOUNDBOX
			in.sgetn((char*)&(box.a), 12);
			in.sgetn((char*)&(box.b), 12);
			box_centre = box.centre();
			if (conv)
				box_centre = conv_tform * box_centre;
			_log("BOUNDBOX: min=" + ftoa(box.a.x) + "," + ftoa(box.a.y) + "," + ftoa(box.a.z) + " max=" + ftoa(box.b.x)
				 + "," + ftoa(box.b.y) + "," + ftoa(box.b.z));
			break;
		case 0xb020: //POS_TRACK_TAG
		case 0xb021: //ROT_TRACK_TAG
		case 0xb022: //SCALE_TRACK_TAG
			if (!collapse)
				parseAnimKeys(&anim, chunk_id);
			break;
		}
	}
	leaveChunk();

	MeshModel* p = root;
	if (parent != 65535) {
		std::map<int, MeshModel*>::const_iterator it = id_map.find(parent);
		if (it == id_map.end())
			return;
		p = it->second;
	}
	MeshModel* mesh = 0;
	if (name == "$$$DUMMY") {
		mesh = new MeshModel();
		mesh->SetName(inst);
		mesh->SetParent(p);
	} else {
		std::map<std::string, MeshModel*>::const_iterator it = name_map.find(name);
		if (it == name_map.end())
			return;
		mesh = it->second;
		name_map.erase(name);
		if (pivot != Vector()) {
			mesh->transform(-pivot);
		}
		Transform t = mesh->GetWorldTransform();
		mesh->SetParent(p);
		mesh->SetWorldTransform(t);
	}

	mesh->setAnimation(anim);

	if (id != 65535)
		id_map[id] = mesh;
}
Example #10
0
static AuCtx *getAacCtx(u32 id) {
	if (aacMap.find(id) == aacMap.end())
		return NULL;
	return aacMap[id];
}
Example #11
0
void __AACShutdown() {
	for (auto it = aacMap.begin(), end = aacMap.end(); it != end; it++) {
		delete it->second;
	}
	aacMap.clear();
}
Example #12
0
returnValue ExportCommonHeader::configure(	const std::string& _moduleName,
											bool _useSinglePrecision,
											bool _useComplexArithmetic,
											QPSolverName _qpSolver,
											const std::map<std::string, std::pair<std::string, std::string> >& _options,
											const std::string& _variables,
											const std::string& _workspace,
											const std::string& _functions
											)
{
	// Configure the template
	string foo = _moduleName;
	transform(foo.begin(), foo.end(), foo.begin(), ::toupper);
	dictionary[ "@MODULE_NAME@" ] = foo;

	stringstream ss;
	if( _useComplexArithmetic ) ss << "\n#include <complex.h>\n" << endl;

	ss 	<< "/** qpOASES QP solver indicator. */" << endl
		<< "#define ACADO_QPOASES  0" << endl
		<< "#define ACADO_QPOASES3 1" << endl
		<< "/** FORCES QP solver indicator.*/" << endl
		<< "#define ACADO_FORCES   2" << endl
		<< "/** qpDUNES QP solver indicator.*/" << endl
		<< "#define ACADO_QPDUNES  3" << endl
		<< "/** HPMPC QP solver indicator. */" << endl
		<< "#define ACADO_HPMPC    4" << endl
		<< "/** Indicator for determining the QP solver used by the ACADO solver code. */" << endl;

	switch ( _qpSolver )
	{
	case QP_QPOASES:
		ss << "#define ACADO_QP_SOLVER ACADO_QPOASES\n" << endl;
		ss << "#include \"" << _moduleName << "_qpoases_interface.hpp\"\n";

		break;

	case QP_QPOASES3:
		ss << "#define ACADO_QP_SOLVER ACADO_QPOASES3\n" << endl;
		ss << "#include \"" << _moduleName << "_qpoases3_interface.h\"\n";

		break;

	case QP_FORCES:
	case QP_HPMPC:
	case QP_QPDUNES:
		if (_qpSolver == QP_FORCES)
			ss << "#define ACADO_QP_SOLVER ACADO_FORCES\n" << endl;
		else if (_qpSolver == QP_HPMPC)
			ss << "#define ACADO_QP_SOLVER ACADO_HPMPC\n" << endl;
		else
			ss << "#define ACADO_QP_SOLVER ACADO_QPDUNES\n" << endl;

		ss << "\n#include <string.h>\n\n" << endl;

		ss << "/** Definition of the floating point data type. */\n";
		if (_useSinglePrecision == true)
			ss << "typedef float real_t;\n";
		else
			ss << "typedef double real_t;\n";

		break;
	
	case QP_NONE:
		ss << "/** Definition of the floating point data type. */\n";
		if (_useSinglePrecision == true)
			ss << "typedef float real_t;\n";
		else
			ss << "typedef double real_t;\n";

		break;

	default:
		return ACADOERROR( RET_INVALID_OPTION );

	}
	dictionary[ "@QP_SOLVER_INTERFACE@" ] = ss.str();

	ss.str( string() );
	// Key: define name
	// Value.first: value
	// Value.second: comment
	std::map<std::string, std::pair<std::string, std::string> >::const_iterator it;
	for (it = _options.begin(); it != _options.end(); ++it)
	{
		ss << "/** " << it->second.second << " */" << endl;
		ss << "#define " << it->first << " " << it->second.first << endl;
	}

	dictionary[ "@COMMON_DEFINITIONS@" ] = ss.str();

	dictionary[ "@VARIABLES_DECLARATION@" ] = _variables;

	dictionary[ "@WORKSPACE_DECLARATION@" ] = _workspace;

	dictionary[ "@FUNCTION_DECLARATIONS@" ] = _functions;

	// And then fill a template file
	fillTemplate();

	return SUCCESSFUL_RETURN;
}
Example #13
0
std::string convertDVBUTF8(const char *data, int len, int table, int tsidonid)
{
	int newtable = 0;
	bool twochar = false;
	if (!len)
		return "";

	int i=0, t=0;

	if ( tsidonid )
	{
		std::map<int, int>::iterator it =
			TransponderDefaultMapping.find(tsidonid);
		if ( it != TransponderDefaultMapping.end() )
			table = it->second;
		twochar = TransponderUseTwoCharMapping.find(tsidonid) != TransponderUseTwoCharMapping.end();
	}
//printf("table %d tsidonid %04x twochar %d : %20s\n", table, tsidonid, twochar, data);
	switch(data[0])
	{
		case 1 ... 12:
			newtable=data[i++]+4;
//			eDebug("(1..12)text encoded in ISO-8859-%d",table);
			break;
		case 0x10:
		{
//			eDebug("(0x10)text encoded in ISO-8859-%d",n);
			int n=(data[i+1]<<8)|(data[i+2]);
			i += 3;
			switch(n)
			{
				case 12: 
					{} //eDebug("unsup. ISO8859-12 enc.", n);
				default:
					newtable=n;
					break;
			}
			break;
		}
		case 0x11:
			{} //eDebug("unsup. Basic Multilingual Plane of ISO/IEC 10646-1 enc.");
			++i;
			break;
		case 0x12:
			++i;
			{} //eDebug("unsup. KSC 5601 enc.");
			break;
		case 0x13:
			++i;
			{} //eDebug("unsup. GB-2312-1980 enc.");
			break;
		case 0x14:
			++i;
			{} //eDebug("unsup. Big5 subset of ISO/IEC 10646-1 enc.");
			break;
		case 0x0:
		case 0xD ... 0xF:
		case 0x15 ... 0x1F:
			{} //eDebug("reserved %d", data[0]);
			++i;
			break;
	}
	if(!table)
		table = newtable;
//dprintf("recode:::: tsidonid %X table %d two-char %d len %d\n", tsidonid, table, twochar, len);
	unsigned char res[2048];
	while (i < len)
	{
		unsigned long code=0;

		if ( i+1 < len && twochar && (code=doVideoTexSuppl(data[i], data[i+1])) ) {
			i+=2;
//dprintf("recode:::: doVideoTexSuppl code %lX\n", code);
		}

		if (!code)
			code=recode(data[i++], table);
		if (!code)
			continue;
				// Unicode->UTF8 encoding
		if (code < 0x80) // identity ascii <-> utf8 mapping
			res[t++]=char(code);
		else if((table == 5) && (code == 0x8A))
			res[t++]= 0x20;
		else if (code < 0x800) // two byte mapping
		{
			res[t++]=(code>>6)|0xC0;
			res[t++]=(code&0x3F)|0x80;
		} else if (code < 0x10000) // three bytes mapping
Example #14
0
void filter_dlg::ExecFilter() {
	std::unique_ptr<dbseltweetmsg> loadmsg;

	SetNoUpdateFlag_All();

	fdg->shared_state->apply_filter.EnableUndo();

	tweetidset dbset;

	for (auto id : fdg->selectedset) {
		optional_tweet_ptr tobj = ad.GetExistingTweetById(id);
		if (!tobj) {
			if (ad.unloaded_db_tweet_ids.find(id) != ad.unloaded_db_tweet_ids.end()) {
				// This is in DB
				dbset.insert(id);
				continue;
			}

			// fallback, shouldn't happen too often
			tobj = ad.GetTweetById(id);
		}

		if (CheckFetchPendingSingleTweet(tobj, std::shared_ptr<taccount>(), &loadmsg, PENDING_REQ::USEREXPIRE, PENDING_RESULT::CONTENT_READY)) {
			FilterOneTweet(fdg->shared_state->apply_filter, tobj);
		} else {
			tobj->AddNewPendingOp(std::unique_ptr<pending_op>(new applyfilter_pending_op(fdg->shared_state)));
		}
	}
	if (loadmsg) {
		loadmsg->flags |= DBSTMF::CLEARNOUPDF;
		DBC_PrepareStdTweetLoadMsg(*loadmsg);
		DBC_SendMessage(std::move(loadmsg));
	} else {
		CheckClearNoUpdateFlag_All();
	}

	if (!dbset.empty()) {
		filter_set fs;
		LoadFilter(fdg->shared_state->apply_filter.filter_text, fs);

		// Do not send shared_state to the completion callback/DB thread, as this would
		// cause major problems if for whatever reason a reply was not sent and the message and
		// thus callback was destructed in the DB thread, in the case where it held the last reference
		// to the shared_state. The shared_state destructor may not be run in the DB thread.

		static std::map<uint64_t, std::shared_ptr<filter_dlg_shared_state>> pending_db_filters;
		static uint64_t next_id;
		uint64_t this_id = next_id++;
		pending_db_filters[this_id] = fdg->shared_state;

		filter_set::DBFilterTweetIDs(std::move(fs), std::move(dbset), true, [this_id](std::unique_ptr<undo::action> undo) {
			auto it = pending_db_filters.find(this_id);
			if (it != pending_db_filters.end()) {
				it->second->db_undo_action = std::move(undo);
				pending_db_filters.erase(it);
				LogMsgFormat(LOGT::FILTERTRACE, "filter_dlg::ExecFilter: DB filter complete, %zu pending", pending_db_filters.size());
			} else {
				LogMsgFormat(LOGT::FILTERERR, "filter_dlg::ExecFilter: DB filter completion: item missing from pending_db_filters!");
			}
		});
	}
}
Example #15
0
//
// Creates an iterator over a collection of ties represented by the
// given map. The values of the pairs in the map represent the values
// of ties, and the keys represent the corresponding neighbors.
//
IncidentTieIterator::IncidentTieIterator(const std::map<int, int> & ties) :
		ITieIterator(), //
		lstart(ties.begin()), //
		lcurrent(lstart), //
		lend(ties.end()) {
}
static bool
check_session_props(std::map<std::string, std::string> session_props)
{
        std::map<std::string, std::string>::iterator it;

        it = session_props.find(DUPLEX_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(MUST_INITIATE_LOGON_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(RESET_SEQ_NUMBERS_AT_LOGON_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(SESSION_DAYS_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(FIX_APPLICATION_VER_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(FIX_SESSION_VER_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(HEARTBEAT_INTERVAL_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(TEST_REQUEST_DELAY_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(SESSION_WARM_UP_TIME_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(SESSION_START_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(SESSION_END_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        it = session_props.find(TIMEZONE_KEY);
        if (session_props.end() == it) {
                M_CRITICAL("session config check failed");
                return false;
        }

        return true;
}
Example #17
0
const json_flag &json_flag::get( const std::string &id )
{
    static json_flag null_flag;
    auto iter = json_flags_all.find( id );
    return iter != json_flags_all.end() ? iter->second : null_flag;
}
std::vector<CIMSettings> InterwovenServers::CreateCollectionForRegistration(const std::map<CStdString, CIMSettings>& interwovenServers, const std::map<CStdString, CIMSettings>& workshareServers)
{
	LOG_WS_FUNCTION_SCOPE();

	std::vector<CIMSettings> synchronizeServers;

	if(interwovenServers.empty() && workshareServers.empty())
	{
		// No servers registered with either Interwoven or Workshare
		return synchronizeServers;
	}	

	for(std::map<CStdString, CIMSettings>::const_iterator it = workshareServers.begin(); it != workshareServers.end(); ++it)
	{
		CIMSettings wsServer = it->second;		
					
		// Is this server registered with Interwoven?
		std::map<CStdString, CIMSettings>::const_iterator iServer = interwovenServers.find(wsServer.GetServerName().ToUpper());
		
		// Delete Workshare entries with the incorrect registry key name (should start with 'instance' and not contain punctuation or whitespaces).	
		// Delete servers registered with Workshare but not registered with Interwoven.		
		if( InterwovenServers::ContainsInvalidChars(wsServer.GetRegistryKeyName()) || 
			iServer == interwovenServers.end())
		{
			wsServer.SetActionType(CIMSettings::REGISTRATION_ACTION_REMOVE);
			synchronizeServers.push_back(wsServer);			
		}
	}

	// Add servers registered with Interwoven but not with Workshare
	// Check for modifications to Interwoven servers and update Workshare
	for(std::map<CStdString, CIMSettings>::const_iterator it = interwovenServers.begin(); it != interwovenServers.end(); ++it)
	{
		CIMSettings iServer = it->second;

		// Is this server registrered with Interwoven also registered with Workshare?
		std::map<CStdString, CIMSettings>::const_iterator wsServer = workshareServers.find(iServer.GetServerName().ToUpper());
		
		// Add server if Interwoven server not registered with Workshare or
		// registry key name containts invalid chars and needs to be replaced
		if( wsServer == workshareServers.end() ||
			InterwovenServers::ContainsInvalidChars(wsServer->second.GetRegistryKeyName()))
		{
			iServer.SetRegistryKeyName(GetOptionApiGroupInstanceName(iServer.GetServerName()));
			iServer.SetActionType(CIMSettings::REGISTRATION_ACTION_ADD);
			
			// For Truseted loging we always set the username & password to empty values.
			// This would seem correct for most cases...
			// For Non-Trusted login we set these values to empty string to force the user 
			// to enter the credentials on first use. This is because we can't migrate the 
			// Interwoven password and can't differentiate between a blank password as being 
			// a valid password or if the password is not set. 
			iServer.SetUserID(L"");
			iServer.SetPassword(L"");
			
			synchronizeServers.push_back(iServer);
			continue;
		}
		
		// Check for modifications to UserId, AutoLogin or TrustedLogin.
		// We can't decrypt the Interwoven Password, so ignore...
		if(!iServer.Compare(wsServer->second))
		{	
			iServer.SetRegistryKeyName(wsServer->second.GetRegistryKeyName());
			iServer.SetActionType(CIMSettings::REGISTRATION_ACTION_UPDATE);
			synchronizeServers.push_back(iServer);			
		}
	}

	return synchronizeServers;
}
Example #19
0
void ASObject::serialize(ByteArray* out, std::map<tiny_string, uint32_t>& stringMap,
				std::map<const ASObject*, uint32_t>& objMap,
				std::map<const Class_base*, uint32_t>& traitsMap)
{
	//0x0A -> object marker
	out->writeByte(object_marker);
	//Check if the object has been already serialized to send it by reference
	auto it=objMap.find(this);
	if(it!=objMap.end())
	{
		//The least significant bit is 0 to signal a reference
		out->writeU29(it->second << 1);
		return;
	}

	Class_base* type=getClass();
	assert_and_throw(type);

	//Check if an alias is registered
	auto aliasIt=getSys()->aliasMap.begin();
	const auto aliasEnd=getSys()->aliasMap.end();
	//Linear search for alias
	tiny_string alias;
	for(;aliasIt!=aliasEnd;++aliasIt)
	{
		if(aliasIt->second==type)
		{
			alias=aliasIt->first;
			break;
		}
	}
	bool serializeTraits = alias.empty()==false;

	if(type->isSubClass(InterfaceClass<IExternalizable>::getClass()))
	{
		//Custom serialization necessary
		if(!serializeTraits)
			throw Class<TypeError>::getInstanceS("#2004: IExternalizable class must have an alias registered");
		out->writeU29(0x7);
		out->writeStringVR(stringMap, alias);

		//Invoke writeExternal
		multiname writeExternalName(NULL);
		writeExternalName.name_type=multiname::NAME_STRING;
		writeExternalName.name_s_id=getSys()->getUniqueStringId("writeExternal");
		writeExternalName.ns.push_back(nsNameAndKind("",NAMESPACE));
		writeExternalName.isAttribute = false;

		_NR<ASObject> o=getVariableByMultiname(writeExternalName,SKIP_IMPL);
		assert_and_throw(!o.isNull() && o->getObjectType()==T_FUNCTION);
		IFunction* f=o->as<IFunction>();
		this->incRef();
		out->incRef();
		ASObject* const tmpArg[1] = {out};
		f->call(this, tmpArg, 1);
		return;
	}

	//Add the object to the map
	objMap.insert(make_pair(this, objMap.size()));

	uint32_t traitsCount=0;
	const variables_map::const_var_iterator beginIt = Variables.Variables.begin();
	const variables_map::const_var_iterator endIt = Variables.Variables.end();
	//Check if the class traits has been already serialized to send it by reference
	auto it2=traitsMap.find(type);
	if(it2!=traitsMap.end())
		out->writeU29((it2->second << 2) | 1);
	else
	{
		traitsMap.insert(make_pair(type, traitsMap.size()));
		for(variables_map::const_var_iterator varIt=beginIt; varIt != endIt; ++varIt)
		{
			if(varIt->second.kind==DECLARED_TRAIT)
			{
				if(!varIt->first.ns.hasEmptyName())
				{
					//Skip variable with a namespace, like protected ones
					continue;
				}
				traitsCount++;
			}
		}
		uint32_t dynamicFlag=(type->isSealed)?0:(1 << 3);
		out->writeU29((traitsCount << 4) | dynamicFlag | 0x03);
		out->writeStringVR(stringMap, alias);
		for(variables_map::const_var_iterator varIt=beginIt; varIt != endIt; ++varIt)
		{
			if(varIt->second.kind==DECLARED_TRAIT)
			{
				if(!varIt->first.ns.hasEmptyName())
				{
					//Skip variable with a namespace, like protected ones
					continue;
				}
				out->writeStringVR(stringMap, getSys()->getStringFromUniqueId(varIt->first.nameId));
			}
		}
	}
	for(variables_map::const_var_iterator varIt=beginIt; varIt != endIt; ++varIt)
	{
		if(varIt->second.kind==DECLARED_TRAIT)
		{
			if(!varIt->first.ns.hasEmptyName())
			{
				//Skip variable with a namespace, like protected ones
				continue;
			}
			varIt->second.var->serialize(out, stringMap, objMap, traitsMap);
		}
	}
	if(!type->isSealed)
		serializeDynamicProperties(out, stringMap, objMap, traitsMap);
}
std::vector<CIMSettings> InterwovenServers::GetDuplicateEntries(const std::map<CStdString, CIMSettings>& uniqueIntewovenServers, const std::multimap<CStdString, CIMSettings>& duplicateIntewovenServers)
{
	LOG_WS_FUNCTION_SCOPE();
	
	std::vector<CIMSettings> duplications;
	
	if(uniqueIntewovenServers.size() == duplicateIntewovenServers.size())
	{
		return duplications;
	}

	for(std::map<CStdString, CIMSettings>::const_iterator it = uniqueIntewovenServers.begin(); it != uniqueIntewovenServers.end(); ++it)
	{
		CStdString key = it->first;		
		
		if(duplicateIntewovenServers.count(key) == 1)
		{
			continue;
		}

		pair<multimap<CStdString, CIMSettings>::const_iterator, multimap<CStdString, CIMSettings>::const_iterator> equalRange = duplicateIntewovenServers.equal_range(key);
		for(multimap<CStdString, CIMSettings>::const_iterator it = equalRange.first; it != equalRange.second; ++it)
		{
			CIMSettings wsServer = it->second;
			wsServer.SetActionType(CIMSettings::REGISTRATION_ACTION_REMOVE);
			duplications.push_back(wsServer);		
		}
	}
	
	return duplications;
}
Example #21
0
/**
 * Return the confidence with with this algorithm can load the file
 * @param histogramEntries map of the file entries that have histogram
 * @param outputGroup pointer to the workspace group
 * @param nxFile Reads data from inside first first top entry
 * @returns An integer specifying the confidence level. 0 indicates it will not
 * be used
 */
void LoadMcStas::readHistogramData(
    const std::map<std::string, std::string> &histogramEntries,
    WorkspaceGroup_sptr &outputGroup, ::NeXus::File &nxFile) {

  std::string nameAttrValueYLABEL;

  for (auto eit = histogramEntries.begin(); eit != histogramEntries.end();
       ++eit) {
    std::string dataName = eit->first;
    std::string dataType = eit->second;

    // open second level entry
    nxFile.openGroup(dataName, dataType);

    // grap title to use to e.g. create workspace name
    std::string nameAttrValueTITLE;
    nxFile.getAttr("filename", nameAttrValueTITLE);

    if (nxFile.hasAttr("ylabel")) {
      nxFile.getAttr("ylabel", nameAttrValueYLABEL);
    }

    // Find the axis names
    auto nxdataEntries = nxFile.getEntries();
    std::string axis1Name, axis2Name;
    for (auto nit = nxdataEntries.begin(); nit != nxdataEntries.end(); ++nit) {
      if (nit->second == "NXparameters")
        continue;
      if (nit->first == "ncount")
        continue;
      nxFile.openData(nit->first);

      if (nxFile.hasAttr("axis")) {
        int axisNo(0);
        nxFile.getAttr("axis", axisNo);
        if (axisNo == 1)
          axis1Name = nit->first;
        else if (axisNo == 2)
          axis2Name = nit->first;
        else
          throw std::invalid_argument("Unknown axis number");
      }
      nxFile.closeData();
    }

    std::vector<double> axis1Values, axis2Values;
    nxFile.readData<double>(axis1Name, axis1Values);
    if (axis2Name.length() == 0) {
      axis2Name = nameAttrValueYLABEL;
      axis2Values.push_back(0.0);
    } else {
      nxFile.readData<double>(axis2Name, axis2Values);
    }

    const size_t axis1Length = axis1Values.size();
    const size_t axis2Length = axis2Values.size();
    g_log.debug() << "Axis lengths=" << axis1Length << " " << axis2Length
                  << std::endl;

    // Require "data" field
    std::vector<double> data;
    nxFile.readData<double>("data", data);

    // Optional errors field
    std::vector<double> errors;
    try {
      nxFile.readData<double>("errors", errors);
    } catch (::NeXus::Exception &) {
      g_log.information() << "Field " << dataName
                          << " contains no error information." << std::endl;
    }

    // close second level entry
    nxFile.closeGroup();

    MatrixWorkspace_sptr ws = WorkspaceFactory::Instance().create(
        "Workspace2D", axis2Length, axis1Length, axis1Length);
    Axis *axis1 = ws->getAxis(0);
    axis1->title() = axis1Name;
    // Set caption
    boost::shared_ptr<Units::Label> lblUnit(new Units::Label);
    lblUnit->setLabel(axis1Name, "");
    axis1->unit() = lblUnit;

    Axis *axis2 = new NumericAxis(axis2Length);
    axis2->title() = axis2Name;
    // Set caption
    lblUnit = boost::shared_ptr<Units::Label>(new Units::Label);
    lblUnit->setLabel(axis2Name, "");
    axis2->unit() = lblUnit;

    ws->setYUnit(axis2Name);
    ws->replaceAxis(1, axis2);

    for (size_t wsIndex = 0; wsIndex < axis2Length; ++wsIndex) {
      auto &dataY = ws->dataY(wsIndex);
      auto &dataE = ws->dataE(wsIndex);
      auto &dataX = ws->dataX(wsIndex);

      for (size_t j = 0; j < axis1Length; ++j) {
        // Data is stored in column-major order so we are translating to
        // row major for Mantid
        const size_t fileDataIndex = j * axis2Length + wsIndex;

        dataY[j] = data[fileDataIndex];
        dataX[j] = axis1Values[j];
        if (!errors.empty())
          dataE[j] = errors[fileDataIndex];
      }
      axis2->setValue(wsIndex, axis2Values[wsIndex]);
    }

    // set the workspace title
    ws->setTitle(nameAttrValueTITLE);

    // use the workspace title to create the workspace name
    std::replace(nameAttrValueTITLE.begin(), nameAttrValueTITLE.end(), ' ',
                 '_');

    // ensure that specified name is given to workspace (eventWS) when added to
    // outputGroup
    std::string nameOfGroupWS = getProperty("OutputWorkspace");
    std::string nameUserSee = nameAttrValueTITLE + "_" + nameOfGroupWS;
    std::string extraProperty =
        "Outputworkspace_dummy_" +
        boost::lexical_cast<std::string>(m_countNumWorkspaceAdded);
    declareProperty(new WorkspaceProperty<Workspace>(extraProperty, nameUserSee,
                                                     Direction::Output));
    setProperty(extraProperty, boost::static_pointer_cast<Workspace>(ws));
    m_countNumWorkspaceAdded++; // need to increment to ensure extraProperty are
                                // unique

    // Make Mantid store the workspace in the group
    outputGroup->addWorkspace(ws);
  }
  nxFile.closeGroup();

} // finish
/*
 * The sim-side LLSD is in newsim/llagentinfo.cpp:forwardViewerStats.
 *
 * There's also a compatibility shim for the old fixed-format sim
 * stats in newsim/llagentinfo.cpp:processViewerStats.
 *
 * If you move stats around here, make the corresponding changes in
 * those locations, too.
 */
void send_stats()
{
	// IW 9/23/02 I elected not to move this into LLViewerStats
	// because it depends on too many viewer.cpp globals.
	// Someday we may want to merge all our stats into a central place
	// but that day is not today.

	// Only send stats if the agent is connected to a region.
	if (!gAgent.getRegion() || gNoRender)
	{
		return;
	}

	LLSD body;
	std::string url = gAgent.getRegion()->getCapability("ViewerStats");

	if (url.empty()) {
		llwarns << "Could not get ViewerStats capability" << llendl;
		return;
	}
	
	body["session_id"] = gAgentSessionID;
	
	LLSD &agent = body["agent"];
	
	time_t ltime;
	time(&ltime);
	F32 run_time = F32(LLFrameTimer::getElapsedSeconds());

	agent["start_time"] = S32(ltime - S32(run_time));

	// The first stat set must have a 0 run time if it doesn't actually
	// contain useful data in terms of FPS, etc.  We use half the
	// SEND_STATS_PERIOD seconds as the point at which these statistics become
	// valid.  Data warehouse uses a 0 value here to easily discard these
	// records with non-useful FPS values etc.
	if (run_time < (SEND_STATS_PERIOD / 2))
	{
		agent["run_time"] = 0.0f;
	}
	else
	{
		agent["run_time"] = run_time;
	}

	// send fps only for time app spends in foreground
	agent["fps"] = (F32)gForegroundFrameCount / gForegroundTime.getElapsedTimeF32();
	agent["version"] = gCurrentVersion;
	std::string language = LLUI::getLanguage();
	agent["language"] = language;
	
	agent["sim_fps"] = ((F32) gFrameCount - gSimFrames) /
		(F32) (gRenderStartTime.getElapsedTimeF32() - gSimLastTime);

	gSimLastTime = gRenderStartTime.getElapsedTimeF32();
	gSimFrames   = (F32) gFrameCount;

	agent["agents_in_view"] = LLVOAvatar::sNumVisibleAvatars;
	agent["ping"] = gAvgSimPing;
	agent["meters_traveled"] = gAgent.getDistanceTraveled();
	agent["regions_visited"] = gAgent.getRegionsVisited();
	agent["mem_use"] = LLMemory::getCurrentRSS() / 1024.0;

	LLSD &system = body["system"];
	
	system["ram"] = (S32) gSysMemory.getPhysicalMemoryKB();
	system["os"] = LLAppViewer::instance()->getOSInfo().getOSStringSimple();
	system["cpu"] = gSysCPU.getCPUString();
	unsigned char MACAddress[MAC_ADDRESS_BYTES];
	LLUUID::getNodeID(MACAddress);
	std::string macAddressString = llformat("%02x-%02x-%02x-%02x-%02x-%02x",
											MACAddress[0],MACAddress[1],MACAddress[2],
											MACAddress[3],MACAddress[4],MACAddress[5]);
	system["mac_address"] = macAddressString;
	system["serial_number"] = LLAppViewer::instance()->getSerialNumber();
	std::string gpu_desc = llformat(
		"%-6s Class %d ",
		gGLManager.mGLVendorShort.substr(0,6).c_str(),
		(S32)LLFeatureManager::getInstance()->getGPUClass())
		+ LLFeatureManager::getInstance()->getGPUString();

	system["gpu"] = gpu_desc;
	system["gpu_class"] = (S32)LLFeatureManager::getInstance()->getGPUClass();
	system["gpu_vendor"] = gGLManager.mGLVendorShort;
	system["gpu_version"] = gGLManager.mDriverVersionVendorString;

	LLSD &download = body["downloads"];

	download["world_kbytes"] = gTotalWorldBytes / 1024.0;
	download["object_kbytes"] = gTotalObjectBytes / 1024.0;
	download["texture_kbytes"] = gTotalTextureBytes / 1024.0;
	download["mesh_kbytes"] = LLMeshRepository::sBytesReceived/1024.0;

	LLSD &in = body["stats"]["net"]["in"];

	in["kbytes"] = gMessageSystem->mTotalBytesIn / 1024.0;
	in["packets"] = (S32) gMessageSystem->mPacketsIn;
	in["compressed_packets"] = (S32) gMessageSystem->mCompressedPacketsIn;
	in["savings"] = (gMessageSystem->mUncompressedBytesIn -
					 gMessageSystem->mCompressedBytesIn) / 1024.0;
	
	LLSD &out = body["stats"]["net"]["out"];
	
	out["kbytes"] = gMessageSystem->mTotalBytesOut / 1024.0;
	out["packets"] = (S32) gMessageSystem->mPacketsOut;
	out["compressed_packets"] = (S32) gMessageSystem->mCompressedPacketsOut;
	out["savings"] = (gMessageSystem->mUncompressedBytesOut -
					  gMessageSystem->mCompressedBytesOut) / 1024.0;

	LLSD &fail = body["stats"]["failures"];

	fail["send_packet"] = (S32) gMessageSystem->mSendPacketFailureCount;
	fail["dropped"] = (S32) gMessageSystem->mDroppedPackets;
	fail["resent"] = (S32) gMessageSystem->mResentPackets;
	fail["failed_resends"] = (S32) gMessageSystem->mFailedResendPackets;
	fail["off_circuit"] = (S32) gMessageSystem->mOffCircuitPackets;
	fail["invalid"] = (S32) gMessageSystem->mInvalidOnCircuitPackets;

	// Misc stats, two strings and two ints
	// These are not expecticed to persist across multiple releases
	// Comment any changes with your name and the expected release revision
	// If the current revision is recent, ping the previous author before overriding
	LLSD &misc = body["stats"]["misc"];

	// Screen size so the UI team can figure out how big the widgets
	// appear and use a "typical" size for end user tests.

	S32 window_width = gViewerWindow->getWindowWidthRaw();
	S32 window_height = gViewerWindow->getWindowHeightRaw();
	S32 window_size = (window_width * window_height) / 1024;
	misc["string_1"] = llformat("%d", window_size);
	if (gDebugTimers.find(0) != gDebugTimers.end() && gFrameTimeSeconds > 0)
	{
		misc["string_2"] = llformat("Texture Time: %.2f, Total Time: %.2f", gDebugTimers[0].getElapsedTimeF32(), gFrameTimeSeconds);
	}

// 	misc["int_1"] = LLSD::Integer(gSavedSettings.getU32("RenderQualityPerformance")); // Steve: 1.21
// 	misc["int_2"] = LLSD::Integer(gFrameStalls); // Steve: 1.21

	F32 unbaked_time = LLVOAvatar::sUnbakedTime * 1000.f / gFrameTimeSeconds;
	misc["int_1"] = LLSD::Integer(unbaked_time); // Steve: 1.22
	F32 grey_time = LLVOAvatar::sGreyTime * 1000.f / gFrameTimeSeconds;
	misc["int_2"] = LLSD::Integer(grey_time); // Steve: 1.22

	llinfos << "Misc Stats: int_1: " << misc["int_1"] << " int_2: " << misc["int_2"] << llendl;
	llinfos << "Misc Stats: string_1: " << misc["string_1"] << " string_2: " << misc["string_2"] << llendl;

	body["DisplayNamesEnabled"] = gSavedSettings.getS32("PhoenixNameSystem") == 1 || gSavedSettings.getS32("PhoenixNameSystem") == 2;
	body["DisplayNamesShowUsername"] = gSavedSettings.getS32("PhoenixNameSystem") == 1;
	
	body["MinimalSkin"] = false;
	
	LLViewerStats::getInstance()->addToMessage(body);
	LLHTTPClient::post(url, body, new ViewerStatsResponder);
}
Example #23
0
CIoConfig::CIoConfig(QSettings *settings, std::map<QString, QVariant> &devList, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CIoConfig),
    m_settings(settings)
{
    unsigned int i=0;
    QString devstr;
    bool cfgmatch=false; //flag to indicate that device from config was found

    ui->setupUi(this);

    QString indev = settings->value("input/device", "").toString();

    // insert the device list in device combo box
    std::map<QString, QVariant>::iterator I = devList.begin();
    i = 0;
    while (I != devList.end())
    {
        devstr = (*I).second.toString();
        ui->inDevCombo->addItem((*I).first, devstr);

        // is this the device stored in config?
        if (indev == devstr)
        {
            ui->inDevCombo->setCurrentIndex(i);
            ui->inDevEdit->setText(devstr);
            cfgmatch = true;
        }
        ++I;
        ++i;
    }


    ui->inDevCombo->addItem(tr("Other..."), QVariant(""));

    // If device string from config is not one of the detected devices
    // it could be that device is not plugged in (in which case we select
    // other) or that this is the first time (select the first detected device).
    if (!cfgmatch)
    {
        if (indev.isEmpty())
        {
            // First time config: select the first detected device
            ui->inDevCombo->setCurrentIndex(0);
            ui->inDevEdit->setText(ui->inDevCombo->itemData(0).toString());
            if (ui->inDevEdit->text().isEmpty())
                ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
        }
        else
        {
            // Select other
            ui->inDevCombo->setCurrentIndex(i);
            ui->inDevEdit->setText(indev);
        }
    }

    // input rate
    updateInputSampleRates(settings->value("input/sample_rate", 0).toInt());

    // decimation
    int idx = decim2idx(settings->value("input/decimation", 0).toInt());
    ui->decimCombo->setCurrentIndex(idx);
    decimationChanged(idx);

    // Analog bandwidth
    ui->bwSpinBox->setValue(1.0e-6*settings->value("input/bandwidth", 0.0).toDouble());

    // LNB LO
    ui->loSpinBox->setValue(1.0e-6*settings->value("input/lnb_lo", 0.0).toDouble());

    // Output device
    QString outdev = settings->value("output/device", "").toString();

#ifdef WITH_PULSEAUDIO
    // get list of output devices
    pa_device_list devices;
    outDevList = devices.get_output_devices();

    qDebug() << __FUNCTION__ << ": Available output devices:";
    for (i = 0; i < outDevList.size(); i++)
    {
        qDebug() << "   " << i << ":" << QString(outDevList[i].get_description().c_str());
        //qDebug() << "     " << QString(outDevList[i].get_name().c_str());
        ui->outDevCombo->addItem(QString(outDevList[i].get_description().c_str()));

        // note that item #i in devlist will be item #(i+1)
        // in combo box due to "default"
        if (outdev == QString(outDevList[i].get_name().c_str()))
            ui->outDevCombo->setCurrentIndex(i+1);
    }

#elif defined(GQRX_OS_MACX)
    // get list of output devices
    osxaudio_device_list devices;
    outDevList = devices.get_output_devices();

    qDebug() << __FUNCTION__ << ": Available output devices:";
    for (i = 0; i < outDevList.size(); i++)
    {
        qDebug() << "   " << i << ":" << QString(outDevList[i].get_name().c_str());
        ui->outDevCombo->addItem(QString(outDevList[i].get_name().c_str()));

        // note that item #i in devlist will be item #(i+1)
        // in combo box due to "default"
        if (outdev == QString(outDevList[i].get_name().c_str()))
            ui->outDevCombo->setCurrentIndex(i+1);
    }

#else
    ui->outDevCombo->addItem(settings->value("output/device", "Default").toString(),
                             settings->value("output/device", "Default").toString());
    ui->outDevCombo->setEditable(true);
#endif // WITH_PULSEAUDIO

    // Signals and slots
    connect(this, SIGNAL(accepted()), this, SLOT(saveConfig()));
    connect(ui->inDevCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(inputDeviceSelected(int)));
    connect(ui->inDevEdit, SIGNAL(textChanged(QString)), this, SLOT(inputDevstrChanged(QString)));
    connect(ui->inSrCombo, SIGNAL(editTextChanged(QString)), this, SLOT(inputRateChanged(QString)));
    connect(ui->decimCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(decimationChanged(int)));
}
Example #24
0
//---------------------------------------------------------------------------
void DeveloperConsole::ExecuteCommandString( const std::string& commandString )
{
	ConsoleCommandArguments arguments;
	std::string currentTokenString;
	char currentCharacter;
	for ( unsigned int index = 0; index < commandString.length(); ++index )
	{
		currentCharacter = commandString[ index ];

		if ( currentCharacter == ' ' )
		{
			if ( !currentTokenString.empty() )
			{
				arguments.m_argumentList.push_back( currentTokenString );
				currentTokenString.clear();
			}
		}
		else if ( currentCharacter == '\"' )
		{
			++index;
			currentCharacter = commandString[ index ];
			while ( currentCharacter != '\"' && index < commandString.length() )
			{
				currentTokenString += currentCharacter;
				++index;
				currentCharacter = commandString[ index ];
			}
			arguments.m_argumentList.push_back( currentTokenString );
			currentTokenString.clear();
		}
		else
		{
			currentTokenString += currentCharacter;
		}
	}

	if ( !currentTokenString.empty() )
	{
		arguments.m_argumentList.push_back( currentTokenString );
	}

	arguments.m_rawArgumentString = commandString;

	if ( !arguments.m_argumentList.empty() && g_registeredCommands.find( arguments.m_argumentList[ 0 ] ) != g_registeredCommands.end() )
	{
		g_registeredCommands[ arguments.m_argumentList[ 0 ] ]->m_function( arguments );
	}
	else
	{
		AddCommandLogLine( commandString, Colors::WHITE );
		if ( !arguments.m_argumentList.empty() )
		{
			AddCommandLogLine( "ERROR: Command \"" + arguments.m_argumentList[ 0 ] + "\" is not valid. Type \"help\" for a list of commands.",
				Colors::RED );
		}
		else
		{
			AddCommandLogLine( "ERROR: Command \"" + arguments.m_rawArgumentString + "\" is not valid. Type \"help\" for a list of commands.",
				Colors::RED );
		}
	}
}
Example #25
0
/// Match - Match the pattern string against the input buffer Buffer.  This
/// returns the position that is matched or npos if there is no match.  If
/// there is a match, the size of the matched string is returned in MatchLen.
size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
                      StringMap<StringRef> &VariableTable) const {
  // If this is the EOF pattern, match it immediately.
  if (MatchEOF) {
    MatchLen = 0;
    return Buffer.size();
  }

  // If this is a fixed string pattern, just match it now.
  if (!FixedStr.empty()) {
    MatchLen = FixedStr.size();
    return Buffer.find(FixedStr);
  }

  // Regex match.

  // If there are variable uses, we need to create a temporary string with the
  // actual value.
  StringRef RegExToMatch = RegExStr;
  std::string TmpStr;
  if (!VariableUses.empty()) {
    TmpStr = RegExStr;

    unsigned InsertOffset = 0;
    for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
      std::string Value;

      if (VariableUses[i].first[0] == '@') {
        if (!EvaluateExpression(VariableUses[i].first, Value))
          return StringRef::npos;
      } else {
        StringMap<StringRef>::iterator it =
          VariableTable.find(VariableUses[i].first);
        // If the variable is undefined, return an error.
        if (it == VariableTable.end())
          return StringRef::npos;

        // Look up the value and escape it so that we can plop it into the regex.
        AddFixedStringToRegEx(it->second, Value);
      }

      // Plop it into the regex at the adjusted offset.
      TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
                    Value.begin(), Value.end());
      InsertOffset += Value.size();
    }

    // Match the newly constructed regex.
    RegExToMatch = TmpStr;
  }


  SmallVector<StringRef, 4> MatchInfo;
  if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
    return StringRef::npos;

  // Successful regex match.
  assert(!MatchInfo.empty() && "Didn't get any match");
  StringRef FullMatch = MatchInfo[0];

  // If this defines any variables, remember their values.
  for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
                                                     E = VariableDefs.end();
       I != E; ++I) {
    assert(I->second < MatchInfo.size() && "Internal paren error");
    VariableTable[I->first] = MatchInfo[I->second];
  }

  MatchLen = FullMatch.size();
  return FullMatch.data()-Buffer.data();
}
Example #26
0
// dynamics plugin entry point, signature per tas plugin requirement as defined in coordinator
void init( int argc, char** argv ) {

    const unsigned ONECHAR_ARG = 3, TWOCHAR_ARG = 4;

    #ifdef USE_OSG
    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
    viewer_pointer = &viewer;
    #endif

    // setup some default options
    std::string scene_path;
    THREED_IVAL = 0;
    IMAGE_IVAL = 0;

    // check that syntax is ok
    if (argc < 2)
    {
      std::cerr << "syntax: driver [OPTIONS] <xml file>" << std::endl;
      std::cerr << "        (see README for OPTIONS)" << std::endl;
      //return -1;
      return;
    }

    // get all options
    for (int i=1; i< argc-1; i++)
    {
      // get the option
      std::string option(argv[i]);

      // process options
      if (option == "-r")
      {
        ONSCREEN_RENDER = true;
        UPDATE_GRAPHICS = true;
        check_osg();
      }
      else if (option.find("-of") != std::string::npos)
        OUTPUT_FRAME_RATE = true;
      else if (option.find("-ot") != std::string::npos)
        OUTPUT_TIMINGS = true;
      else if (option.find("-oi") != std::string::npos)
        OUTPUT_ITER_NUM = true;
      else if (option.find("-or") != std::string::npos)
        OUTPUT_SIM_RATE = true;
      else if (option.find("-v=") != std::string::npos)
      {
        UPDATE_GRAPHICS = true;
        check_osg();
        THREED_IVAL = std::atoi(&argv[i][ONECHAR_ARG]);
        assert(THREED_IVAL >= 0);
      }
      else if (option.find("-i=") != std::string::npos)
      {
        check_osg();
        UPDATE_GRAPHICS = true;
        IMAGE_IVAL = std::atoi(&argv[i][ONECHAR_ARG]);
        assert(IMAGE_IVAL >= 0);
      }
      else if (option.find("-t") != std::string::npos)
        OUTPUT_TO_TIME = true;
      else if (option.find("-s=") != std::string::npos)
      {
        STEP_SIZE = std::atof(&argv[i][ONECHAR_ARG]);
        assert(STEP_SIZE >= 0.0 && STEP_SIZE < 1);
      }
      else if (option.find("-lf=") != std::string::npos)
      {
        std::string fname(&argv[i][TWOCHAR_ARG]);
        OutputToFile::stream.open(fname.c_str());
      }
      else if (option.find("-l=") != std::string::npos)
      {
        LOG_REPORTING_LEVEL = std::atoi(&argv[i][ONECHAR_ARG]);
        Log<OutputToFile>::reporting_level = LOG_REPORTING_LEVEL;
      }
      else if (option.find("-lt=") != std::string::npos)
      {
        LOG_START = std::atoi(&argv[i][TWOCHAR_ARG]);
      }
      else if (option.find("-lp=") != std::string::npos)
      {
        LOG_STOP = std::atoi(&argv[i][TWOCHAR_ARG]);
      }
      else if (option.find("-mi=") != std::string::npos)
      {
        MAX_ITER = std::atoi(&argv[i][TWOCHAR_ARG]);
        assert(MAX_ITER > 0);
      }
      else if (option.find("-mt=") != std::string::npos)
      {
        MAX_TIME = std::atof(&argv[i][TWOCHAR_ARG]);
        assert(MAX_TIME > 0);
      }
      else if (option.find("-x=") != std::string::npos)
      {
        check_osg();
        scene_path = std::string(&argv[i][ONECHAR_ARG]);
      }
      else if (option.find("-p=") != std::string::npos) {
        /// read_plugin(&argv[i][ONECHAR_ARG]);
      } else if (option.find("-y=") != std::string::npos)
      {
        strcpy(THREED_EXT, &argv[i][ONECHAR_ARG]);
      } else if (option.find("-vcp") != std::string::npos)
        RENDER_CONTACT_POINTS = true;

    }

    // setup the simulation
    READ_MAP = XMLReader::read(std::string(argv[argc-1]));

    // setup the offscreen renderer if necessary
    #ifdef USE_OSG
    if (IMAGE_IVAL > 0)
    {
      // TODO: setup offscreen renderer here
    }
    #endif

    // get the (only) simulation object

    for (std::map<std::string, BasePtr>::const_iterator i = READ_MAP.begin(); i != READ_MAP.end(); i++)
    {
      sim = boost::dynamic_pointer_cast<Simulator>(i->second);
      if (sim)
        break;
    }

    // make sure that a simulator was found
    if (!sim)
    {
      std::cerr << "driver: no simulator found in " << argv[argc-1] << std::endl;
      //return -1;
      return;
    }

    // setup osg window if desired
    #ifdef USE_OSG
    if (ONSCREEN_RENDER)
    {
      // setup any necessary handlers here
      viewer.setCameraManipulator(new osgGA::TrackballManipulator());
      viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));
      viewer.addEventHandler(new osgViewer::WindowSizeHandler);
      viewer.addEventHandler(new osgViewer::StatsHandler);
    }

    // init the main group
    MAIN_GROUP = new osg::Group;
    #endif

    /**
      // Note: In this architecture, Moby doesn't have any direct relationship to
      // controllers, so the ability to load control plugins is removed

    // call the initializers, if any
    if (!INIT.empty())
    {
      #ifdef USE_OSG
      BOOST_FOREACH(init_t i, INIT)
        (*i)(MAIN_GROUP, READ_MAP, STEP_SIZE);
      #else
      BOOST_FOREACH(init_t i, INIT)
        (*i)(NULL, READ_MAP, STEP_SIZE);
      #endif
    }
    */

    // look for a scene description file
    #ifdef USE_OSG
    if (scene_path != "")
    {
      std::ifstream in(scene_path.c_str());
      if (in.fail())
      {
        std::cerr << "driver: unable to find scene description from " << scene_path << std::endl;
        add_lights();
      }
      else
      {
        in.close();
        osg::Node* node = osgDB::readNodeFile(scene_path);
        if (!node)
        {
          std::cerr << "driver: unable to open scene description file!" << std::endl;
          add_lights();
        }
        else
          MAIN_GROUP->addChild(node);
      }
    }
    else
      add_lights();
    #endif

    // process XML options
    process_xml_options(std::string(argv[argc-1]));

    // get the simulator visualization
    #ifdef USE_OSG
    MAIN_GROUP->addChild(sim->get_persistent_vdata());
    MAIN_GROUP->addChild(sim->get_transient_vdata());
    #endif

    // setup the timers
    FIRST_STEP_TIME = get_current_time();
    LAST_STEP_TIME = FIRST_STEP_TIME;

    // begin timing
    start_time = clock();

    // prepare to render
    #ifdef USE_OSG
    if (ONSCREEN_RENDER)
    {
      viewer.setSceneData(MAIN_GROUP);
      viewer.realize();
    }
    #endif

    // custom implementation follows

    // Get reference to the pendulum for usage in the command publish and response
    if( READ_MAP.find("pendulum") == READ_MAP.end() )
      printf( "dynamics.cpp:init()- unable to find pendulum!\n" );
    pendulum = dynamic_pointer_cast<Moby::RCArticulatedBody>( READ_MAP.find("pendulum")->second  );
    if( !pendulum )
        printf( "dynamics.cpp:init()- unable to cast pendulum to type RCArticulatedBody\n" );

    // open the command buffer
    //amsgbuffer = ActuatorMessageBuffer( &amsgbuffer_mutex, 8811, getpid( ), 0 );

    //attach_mutex( );
    //amsgbuffer = ActuatorMessageBuffer( amsgbuffer_mutex );
    //amsgbuffer.open();   // TODO : sanity/safety checking

    amsgbuffer = ActuatorMessageBuffer( ACTUATOR_MESSAGE_BUFFER_NAME, ACTUATOR_MESSAGE_BUFFER_MUTEX_NAME );
    amsgbuffer.open( );

    printf( "(dynamics::initialized)\n" );
}
Example #27
0
		void RegisterNoCheck(T* newinst){

			if(	_inst.find((*newinst)())==_inst.end())
				_inst[(*newinst)()] = newinst;
		}
const mgen::Field * PlayerJoined::_fieldByName(const std::string& name) const {
	static const std::map<std::string, const mgen::Field*> name2meta = mgen::make_map<std::string, const mgen::Field*>()("playerId", &PlayerJoined::_field_playerId_metadata());
	const std::map<std::string, const mgen::Field*>::const_iterator it = name2meta.find(name);
	return it != name2meta.end() ? it->second : 0;
}
Example #29
0
int main(int argc_, const char* argv_[])
{
  const std::string env_filename = "metashell_environment.hpp";

  try
  {
    using metashell::parse_config;
    using metashell::parse_config_result;

    const std::map<std::string, metashell::engine_entry> engines{
        {"internal", metashell::get_internal_templight_entry()},
        {"clang", metashell::get_engine_clang_entry()}};

    metashell::default_environment_detector det(argv_[0]);

    const parse_config_result r =
        parse_config(argc_, argv_, engines, det, &std::cout, &std::cerr);

    metashell::console_config ccfg(
        r.cfg.con_type, r.cfg.indent, r.cfg.syntax_highlight);

    metashell::fstream_file_writer file_writer;
    metashell::logger logger(ccfg.displayer(), file_writer);
    switch (r.cfg.log_mode)
    {
    case metashell::data::logging_mode::none:
      // do nothing
      break;
    case metashell::data::logging_mode::console:
      logger.log_to_console();
      break;
    case metashell::data::logging_mode::file:
      logger.log_into_file(r.cfg.log_file);
      break;
    }

    METASHELL_LOG(&logger, "Start logging");

    const auto eentry = engines.find(r.cfg.engine);
    if (eentry == engines.end())
    {
      throw std::runtime_error(
          "Engine " + r.cfg.engine + " not found. Available engines: " +
          boost::algorithm::join(engines | boost::adaptors::map_keys, ", "));
    }
    else
    {
      if (r.should_run_shell())
      {
        METASHELL_LOG(&logger, "Running shell");

        just::temp::directory dir;

        std::unique_ptr<metashell::shell> shell(new metashell::shell(
            r.cfg, ccfg.processor_queue(), dir.path(), env_filename,
            eentry->second.build(r.cfg, dir.path(), env_filename, det,
                                 ccfg.displayer(), &logger),
            &logger));

        if (r.cfg.splash_enabled)
        {
          shell->display_splash(ccfg.displayer(), get_dependency_versions());
        }

        ccfg.processor_queue().push(move(shell));

        METASHELL_LOG(&logger, "Starting input loop");

        metashell::input_loop(
            ccfg.processor_queue(), ccfg.displayer(), ccfg.reader());

        METASHELL_LOG(&logger, "Input loop finished");
      }
      else
      {
        METASHELL_LOG(&logger, "Not running shell");
      }
      return r.should_error_at_exit() ? 1 : 0;
    }
  }
  catch (std::exception& e_)
  {
    std::cerr << "Error: " << e_.what() << std::endl;
    return 1;
  }
}
Example #30
0
/**
 * Reads in a vehicle part from a JsonObject.
 */
void vpart_info::load( JsonObject &jo )
{
    vpart_info next_part;

    next_part.id = vpart_str_id( jo.get_string( "id" ) );
    next_part.name = _(jo.get_string("name").c_str());
    next_part.sym = jo.get_string("symbol")[0];
    next_part.color = color_from_string(jo.get_string("color"));
    next_part.sym_broken = jo.get_string("broken_symbol")[0];
    next_part.color_broken = color_from_string(jo.get_string("broken_color"));
    next_part.dmg_mod = jo.has_member("damage_modifier") ? jo.get_int("damage_modifier") : 100;
    next_part.durability = jo.get_int("durability");
    next_part.power = jo.get_int("power", 0);
    next_part.epower = jo.get_int("epower", 0);
    next_part.folded_volume = jo.get_int("folded_volume", 0);
    next_part.range = jo.get_int( "range", 12 );
    next_part.size = jo.get_int( "size", 0 );

    //Handle the par1 union as best we can by accepting any ONE of its elements
    int element_count = (jo.has_member("par1") ? 1 : 0)
                        + (jo.has_member("wheel_width") ? 1 : 0)
                        + (jo.has_member("bonus") ? 1 : 0);

    if(element_count == 0) {
        //If not specified, assume 0
        next_part.par1 = 0;
    } else if(element_count == 1) {
        if(jo.has_member("par1")) {
            next_part.par1 = jo.get_int("par1");
        } else if(jo.has_member("wheel_width")) {
            next_part.par1 = jo.get_int("wheel_width");
        } else { //bonus
            next_part.par1 = jo.get_int("bonus");
        }
    } else {
        //Too many
        debugmsg("Error parsing vehicle part '%s': \
               Use AT MOST one of: par1, wheel_width, bonus",
                 next_part.name.c_str());
        //Keep going to produce more messages if other parts are wrong
        next_part.par1 = 0;
    }
    next_part.fuel_type = jo.get_string( "fuel_type", "null" );
    next_part.item = jo.get_string("item");
    next_part.difficulty = jo.get_int("difficulty");
    next_part.location = jo.has_member("location") ? jo.get_string("location") : "";

    JsonArray jarr = jo.get_array("flags");
    while (jarr.has_more()) {
        next_part.set_flag( jarr.next_string() );
    }

    if( jo.has_member( "breaks_into" ) ) {
        JsonIn& stream = *jo.get_raw( "breaks_into" );
        next_part.breaks_into_group = item_group::load_item_group( stream, "collection" );
    } else {
        next_part.breaks_into_group = "EMPTY_GROUP";
    }

    //Calculate and cache z-ordering based off of location
    // list_order is used when inspecting the vehicle
    if(next_part.location == "on_roof") {
        next_part.z_order = 9;
        next_part.list_order = 3;
    } else if(next_part.location == "on_cargo") {
        next_part.z_order = 8;
        next_part.list_order = 6;
    } else if(next_part.location == "center") {
        next_part.z_order = 7;
        next_part.list_order = 7;
    } else if(next_part.location == "under") {
        //Have wheels show up over frames
        next_part.z_order = 6;
        next_part.list_order = 10;
    } else if(next_part.location == "structure") {
        next_part.z_order = 5;
        next_part.list_order = 1;
    } else if(next_part.location == "engine_block") {
        //Should be hidden by frames
        next_part.z_order = 4;
        next_part.list_order = 8 ;
    } else if (next_part.location == "on_battery_mount"){
        //Should be hidden by frames
        next_part.z_order = 3;
        next_part.list_order = 10;
    } else if(next_part.location == "fuel_source") {
        //Should be hidden by frames
        next_part.z_order = 3;
        next_part.list_order = 9;
    } else if(next_part.location == "roof") {
        //Shouldn't be displayed
        next_part.z_order = -1;
        next_part.list_order = 4;
    } else if(next_part.location == "armor") {
        //Shouldn't be displayed (the color is used, but not the symbol)
        next_part.z_order = -2;
        next_part.list_order = 2;
    } else {
        //Everything else
        next_part.z_order = 0;
        next_part.list_order = 5;
    }

    auto const iter = vehicle_part_types.find( next_part.id );
    if( iter != vehicle_part_types.end() ) {
        // Entry in the map already exists, so the pointer in the vector is already correct
        // and does not need to be changed, only the int-id needs to be taken from the old entry.
        next_part.loadid = iter->second.loadid;
        iter->second = next_part;
    } else {
        // The entry is new, "generate" a new int-id and link the new entry from the vector.
        next_part.loadid = vpart_id( vehicle_part_int_types.size() );
        vpart_info &new_entry = vehicle_part_types[next_part.id];
        new_entry = next_part;
        vehicle_part_int_types.push_back( &new_entry );
    }
}