text:
#include "Component.h"
#include "File.h"
#include "PendingCommand.h"
#include "Project.h"
#include "Toolset.h"
#include "fw/dotted.h"

#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <stack>

ClangToolset::ClangToolset()
{
    parameters["name"] = "clang";
    parameters["compiler"] = "clang++";
    parameters["linker"] = "clang++";
    parameters["archiver"] = "ar";
    parameters["cross"] = "false";
}

std::string ClangToolset::getBmiNameFor(const File &file)
{
    return file.moduleName + ".pcm";
    //return file.path.generic_string() + ".bmi";
}

std::string ClangToolset::getObjNameFor(const File &file)
{
    return file.path.generic_string() + ".o";
}

std::string ClangToolset::getLibNameFor(const Component &component)
{
    return "lib" + getNameFor(component) + ".a";
}

std::string ClangToolset::getExeNameFor(const Component &component)
{
    return getNameFor(component);
}

std::string ClangToolset::getUnityCommand(const std::string &program, const std::string &outputFile, const File *inputFile, const std::set<std::string> &includes, std::vector<std::vector<Component *>> linkDeps)
{
    std::string command = program + " -c -o " + outputFile + " " + inputFile->path.generic_string();
    for(auto &i : includes)
        command += " -I" + i;
    for(auto d : linkDeps)
    {
        for(auto &c : d)
        {
            command += " -l" + c->GetName();
        }
    }
    return command;
}

std::string ClangToolset::getPrecompileCommand(const std::string &program, const std::string &outputFile, const File *inputFile, const std::set<std::string> &includes, bool hasModules)
{
    std::string command = program + " -fmodules-ts --precompile -x c++-module -o " + outputFile + " " + inputFile->path.generic_string();
    if(hasModules)
        command += " -fprebuilt-module-path=modules";
    for(auto &i : includes)
        command += " -I" + i;
    return command;
}

std::string ClangToolset::getCompileCommand(const std::string &program, const std::string &outputFile, const File *inputFile, const std::set<std::string> &includes, bool hasModules)
{
    std::string command = program + " -c -o " + outputFile + " " + inputFile->path.generic_string();
    if(hasModules)
        command += " -fmodules-ts -fprebuilt-module-path=modules";
    for(auto &i : includes)
        command += " -I" + i;
    return command;
}

std::string ClangToolset::getArchiverCommand(const std::string &program, const std::string &outputFile, const std::vector<File *> inputs)
{
    std::string command = program + " rcs " + outputFile;
    for(auto &file : inputs)
    {
        command += " " + file->path.generic_string();
    }
    return command;
}

std::string ClangToolset::getLinkerCommand(const std::string &program, const std::string &outputFile, const std::vector<File *> objects, std::vector<std::vector<Component *>> linkDeps)
{
    std::string command = program + " -o " + outputFile;
    for(auto &file : objects)
    {
        command += " " + file->path.string();
    }
    command += " -Lbuild/" + parameters["name"] + "/lib";
    for(auto d : linkDeps)
    {
        for(auto &c : d)
        {
            command += " -l" + c->GetName();
        }
    }
    return command;
}

std::string ClangToolset::getUnittestCommand(const std::string &program)
{
    return program;
}

max_stars_repo_name: PenguinLemma/evoke

max_issues_repo_name: PenguinLemma/evoke

max_forks_repo_name: PenguinLemma/evoke


text:
/**
* Copyright 2014 Social Robotics Lab, University of Freiburg
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
*    # Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*    # Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*    # Neither the name of the University of Freiburg nor the names of its
*       contributors may be used to endorse or promote products derived from
*       this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \author Billy Okal <okal@cs.uni-freiburg.de>
* \author Sven Wehner <mail@svenwehner.de>
*/

#include <pedsim_simulator/config.h>
#include <pedsim_simulator/scene.h>

#include <pedsim/ped_tree.h>
#include <pedsim_simulator/element/agent.h>
#include <pedsim_simulator/element/agentcluster.h>
#include <pedsim_simulator/element/areawaypoint.h>
#include <pedsim_simulator/element/attractionarea.h>
#include <pedsim_simulator/element/obstacle.h>
#include <pedsim_simulator/element/waitingqueue.h>
#include <pedsim_simulator/force/alongwallforce.h>
#include <pedsim_simulator/force/groupcoherenceforce.h>
#include <pedsim_simulator/force/groupgazeforce.h>
#include <pedsim_simulator/force/grouprepulsionforce.h>
#include <pedsim_simulator/force/randomforce.h>
#include <pedsim_simulator/rng.h>
#include <QGraphicsScene>

#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
#include <fstream>

#include <ros/ros.h>
#include <ros/console.h>

// initialize static value
Scene* Scene::Scene::instance = nullptr;

Scene::Scene(QObject* parent)
{
  // initialize values
  sceneTime = 0;

  // TODO: create this dynamically according to scenario
  QRect area(-500, -500, 1000, 1000);

  // we need to add a tree to the scene to be able to search for neighbours
  //ONLY USEFUL WITH MORE THAN 1000 AGENTS
  // tree = new Ped::Ttree(this, 0, area.x(), area.y(), area.width(), area.height());

  obstacle_cells_.clear();

  minDist = INT_MAX;
}

Scene::~Scene()
{
  // clean up
  clear();
}

Scene& Scene::getInstance()
{
  // create an instance if there hasn't been one yet
  if (instance == nullptr)
    instance = new Scene();
  return *instance;
}

void Scene::clear()
{
  // remove all elements from the scene
  Ped::Tscene::clear();

  // remove all agents
  // note: we don't need to delete them, because Ped::Tscene did so already
  agents.clear();

  // remove all waypoints
  // note: we don't need to delete them, because Ped::Tscene did so already
  waypoints.clear();

  // remove all obstacles
  // note: we don't need to delete them, because Ped::Tscene did so already
  obstacles.clear();

  // remove all agents groups
  foreach (AttractionArea* attraction, attractions)
    delete attraction;
  attractions.clear();

  // remove all agents clusters
  foreach (AgentCluster* agentCluster, agentClusters)
    delete agentCluster;
  agentClusters.clear();

  // remove all agents groups
  foreach (AgentGroup* group, agentGroups)
    delete group;
  agentGroups.clear();

  // don't clear the grid, because we can reuse it

  // reset time
  sceneTime = 0;
  emit sceneTimeChanged(sceneTime);
}

QRectF Scene::itemsBoundingRect() const
{
  QRectF boundingRect(QPointF(-50, -50), QSizeF(100, 100));

  // iterate over all elements
  // → agents
  foreach (Agent* agent, agents)
  {
    if (!boundingRect.contains(agent->getVisiblePosition()))
    {
      // resize rectangle to include point
      boundingRect |= QRectF(agent->getVisiblePosition() - QPointF(0.5, 0.5), QSizeF(1, 1));
    }
  }
  // → obstacles
  foreach (Obstacle* obstacle, obstacles)
  {
    QPointF startPoint = obstacle->getVisiblePosition();
    QPointF endPoint(obstacle->getbx(), obstacle->getby());

    if (!boundingRect.contains(startPoint) || !boundingRect.contains(endPoint))
    {
      // resize rectangle to include point
      boundingRect |= QRectF(startPoint, endPoint);
    }
  }
  // → waypoints
  foreach (Waypoint* waypoint, waypoints)
  {
    AreaWaypoint* areaWaypoint = dynamic_cast<AreaWaypoint*>(waypoint);
    WaitingQueue* waitingQueue = dynamic_cast<WaitingQueue*>(waypoint);

    // → area waypoints
    if (areaWaypoint != nullptr)
    {
      if (!boundingRect.contains(areaWaypoint->getVisiblePosition()))
      {
        // resize rectangle to include point
        boundingRect |=
            QRectF(areaWaypoint->getVisiblePosition(), QSizeF(areaWaypoint->getRadius(), areaWaypoint->getRadius()));
      }
    }
    // → waiting queues
    else if (waitingQueue != nullptr)
    {
      if (!boundingRect.contains(waitingQueue->getVisiblePosition()))
      {
        // resize rectangle to include point
        boundingRect |= QRectF(waitingQueue->getVisiblePosition() - QPointF(0.5, 0.5), QSizeF(1, 1));
      }
    }
  }
  // → agent clusters
  foreach (AgentCluster* agentCluster, agentClusters)
  {
    if (!boundingRect.contains(agentCluster->getVisiblePosition()))
    {
      // resize rectangle to include point
      boundingRect |= QRectF(agentCluster->getVisiblePosition() - QPointF(0.5, 0.5), QSizeF(1, 1));
    }
  }

  return boundingRect;
}

const QList<Agent*>& Scene::getAgents() const
{
  return agents;
}

QList<AgentGroup*> Scene::getGroups()
{
  return agentGroups;
}

QMap<QString, AttractionArea*> Scene::getAttractions()
{
  return attractions;
}

Agent* Scene::getAgentById(int idIn) const
{
  foreach (Agent* currentAgent, agents)
  {
    if (idIn == currentAgent->getId())
      return currentAgent;
  }

  return nullptr;
}

const QList<Obstacle*>& Scene::getObstacles() const
{
  return obstacles;
}

const QMap<QString, Waypoint*>& Scene::getWaypoints() const
{
  return waypoints;
}

const QMap<QString, AttractionArea*>& Scene::getAttractions() const
{
  return attractions;
}

Waypoint* Scene::getWaypointById(int idIn) const
{
  foreach (Waypoint* currentWaypoint, waypoints)
  {
    if (idIn == currentWaypoint->getId())
      return currentWaypoint;
  }

  return nullptr;
}

Waypoint* Scene::getWaypointByName(const QString& nameIn) const
{
  return waypoints.value(nameIn);
}

WaitingQueue* Scene::getWaitingQueueByName(const QString& nameIn) const
{
  Waypoint* waypoint = waypoints.value(nameIn);
  return dynamic_cast<WaitingQueue*>(waypoint);
}

const QList<AgentCluster*>& Scene::getAgentClusters() const
{
  return agentClusters;
}

AttractionArea* Scene::getAttractionByName(const QString& nameIn) const
{
  return attractions.value(nameIn);
}

AttractionArea* Scene::getClosestAttraction(const Agent* agentIn, double* distanceOut) const
{
  double minDistance = INFINITY;
  AttractionArea* minArg = nullptr;

  QList<AttractionArea*> perceived = agentIn->getPerceivedAttractions();

  // find the attraction with minimal distance
  foreach (AttractionArea* attraction, perceived)
  {

    double distance = (attraction->getPosition() - agentIn->getPosition()).length();
    if (distance < minDistance)
    {
      minDistance = distance;
      minArg = attraction;
    }
  }

  // additionally return distance
  if (distanceOut != nullptr)
    *distanceOut = minDistance;

  return minArg;
}

double Scene::getTime() const
{
  return sceneTime;
}

bool Scene::hasStarted() const
{
  return (sceneTime == 0);
}

void Scene::dissolveClusters()
{
  foreach (AgentCluster* cluster, agentClusters)
  {
    QList<Agent*> newAgents = cluster->dissolve();

    // divide agents into groups
    QList<AgentGroup*> newGroups = AgentGroup::divideAgents(newAgents);

    // apply group forces
    foreach (AgentGroup* currentGroup, newGroups)
    {
      if (currentGroup->memberCount() == 1)
      {
        // we don't need one agent groups
        delete currentGroup;
      }
      else if (currentGroup->memberCount() > 1)
      {
        // keep track of groups
        agentGroups.append(currentGroup);

         // add group's agents to the scene
         foreach (Agent* currentAgent, currentGroup->getMembers())
         {
            // Regroup agents in groups if too sparse
            if((currentAgent->getPosition() - currentGroup->getMembers().at(0)->getPosition()).length() > 2.0){
               std::uniform_real_distribution<double> random(-2.0, 2.0);
               currentAgent->setPosition(currentGroup->getMembers().at(0)->getPosition().x+random(RNG()),currentGroup->getMembers().at(0)->getPosition().y+random(RNG()));
            }

           currentAgent->setWaypoints(cluster->getWaypoints());

           if (currentGroup->memberCount() > 1)
           {
             currentAgent->setGroup(currentGroup);
             // → Gaze Force
             GroupGazeForce* gazeForce = new GroupGazeForce(currentAgent);
             gazeForce->setGroup(currentGroup);
             currentAgent->addForce(gazeForce);

             // → Coherence Force
             GroupCoherenceForce* coherenceForce = new GroupCoherenceForce(currentAgent);
             coherenceForce->setGroup(currentGroup);
             currentAgent->addForce(coherenceForce);

             // → Repulsion Force
             GroupRepulsionForce* repulsionForce = new GroupRepulsionForce(currentAgent);
             repulsionForce->setGroup(currentGroup);
             currentAgent->addForce(repulsionForce);
           }
         }
      }
    }
    // finally remove cluster
    delete cluster;
  }

  agentClusters.clear();
}

void Scene::addAgent(Agent* agent)
{
  // keep track of the agent
  agents.append(agent);

  // add the agent to the PedSim scene
  Ped::Tscene::addAgent(agent);

  // add additional forces
  // → Random Force
  RandomForce* randomForce = new RandomForce(agent);
  agent->addForce(randomForce);
  // → Along Wall Force
  AlongWallForce* alongWallForce = new AlongWallForce(agent);
  agent->addForce(alongWallForce);

  // inform users
  emit agentAdded(agent->getId());
}

void Scene::addObstacle(Obstacle* obstacle)
{
  // keep track of the obstacle
  obstacles.append(obstacle);

  // add the obstacle to the PedSim scene
  Ped::Tscene::addObstacle(obstacle);

  // inform users
  emit obstacleAdded(obstacle->getid());
}

void Scene::addWaypoint(Waypoint* waypoint)
{
  // keep track of the waypoints
  waypoints.insert(waypoint->getName(), waypoint);

  // add the obstacle to the PedSim scene
  Ped::Tscene::addWaypoint(waypoint);

  // inform users
  emit waypointAdded(waypoint->getId());
}

void Scene::addAgentCluster(AgentCluster* clusterIn)
{
  // keep track of agent clusters
  agentClusters.append(clusterIn);

  // inform users
  emit agentClusterAdded(clusterIn->getId());
}

void Scene::addWaitingQueue(WaitingQueue* queueIn)
{
  // sanity checks
  if (queueIn == nullptr)
  {
    ROS_DEBUG("Cannot add null to the list of waiting queues!");
    return;
  }

  // add waiting queue as waypoint to the scene
  addWaypoint(dynamic_cast<Waypoint*>(queueIn));

  // inform users
  emit waitingQueueAdded(queueIn->getName());
}

void Scene::addAttraction(AttractionArea* attractionIn)
{
  // sanity checks
  if (attractionIn == nullptr)
  {
    ROS_DEBUG("Cannot add null to the list of attractions!");
    return;
  }

  // add attraction to the scene
  attractions.insert(attractionIn->getName(), attractionIn);

  // inform users
  emit attractionAdded(attractionIn->getName());
}

bool Scene::removeAgent(Agent* agent)
{
  // don't keep track of agent anymore
  agents.removeAll(agent);

  // remove agent from all groups
  QList<AgentGroup*> groupsToRemove;
  foreach (AgentGroup* currentGroup, agentGroups)
  {
    currentGroup->removeMember(agent);

    // check whether the group is empty and can be removed
    if (currentGroup->isEmpty())
      groupsToRemove.append(currentGroup);
  }

  // remove unnecessary groups
  // note: use QObject::deleteLater() to keep the group valid till after the
  // agent's destructor
  foreach (AgentGroup* currentGroup, groupsToRemove)
  {
    agentGroups.removeAll(currentGroup);
    currentGroup->deleteLater();
  }

  // inform users
  emit agentRemoved(agent->getId());

  // actually remove it
  return Ped::Tscene::removeAgent(agent);
}

bool Scene::removeObstacle(Obstacle* obstacle)
{
  // don't keep track of obstacle anymore
  obstacles.removeAll(obstacle);

  // inform users
  emit obstacleRemoved(obstacle->getid());

  // actually remove it
  return Ped::Tscene::removeObstacle(obstacle);
}

bool Scene::removeWaypoint(Waypoint* waypoint)
{
  // don't keep track of waypoint anymore
  waypoints.remove(waypoint->getName());

  // remove waypoint from all agent clusters
  // (it is also removed from all agents in Ped::Tscene::removeWaypoint())
  foreach (AgentCluster* cluster, agentClusters)
    cluster->removeWaypoint(waypoint);

  // inform users
  emit waypointRemoved(waypoint->getId());

  // actually remove it
  return Ped::Tscene::removeWaypoint(waypoint);
}

bool Scene::removeAgentCluster(AgentCluster* clusterIn)
{
  // don't keep track of agent cluster anymore
  int removedClusters = agentClusters.removeAll(clusterIn);

  // report when the cluster wasn't part of the scene
  if (removedClusters == 0)
    return false;

  // inform users
  emit agentClusterRemoved(clusterIn->getId());

  // free memory
  delete clusterIn;

  // report successful removal
  return true;
}

bool Scene::removeWaitingQueue(WaitingQueue* queueIn)
{
  // sanity checks
  if (queueIn == nullptr)
  {
    ROS_DEBUG("Cannot remove null from the list of waiting queues!");
    return false;
  }

  // don't keep track of waiting queue anymore
  int removedCount = waypoints.remove(queueIn->getName());

  // check whether the queue was removed
  if (removedCount == 0)
    return false;

  // inform users
  emit waitingQueueRemoved(queueIn->getName());

  // delete object
  delete queueIn;

  // report successful removal
  return true;
}

bool Scene::removeAttraction(AttractionArea* attractionInIn)
{
  // sanity checks
  if (attractionInIn == nullptr)
  {
    ROS_DEBUG("Cannot remove null from the list of attractions!");
    return false;
  }

  // don't keep track of attraction anymore
  int removedCount = attractions.remove(attractionInIn->getName());

  // check whether the queue was removed
  if (removedCount == 0)
    return false;

  // inform users
  emit attractionRemoved(attractionInIn->getName());

  // delete object
  delete attractionInIn;

  // report successful removal
  return true;
}

std::set<const Ped::Tagent*> Scene::getNeighbors(double x, double y, double maxDist)
{
  std::set<const Ped::Tagent*> potentialNeighbours = Ped::Tscene::getNeighbors(x, y, maxDist);
  Ped::Tvector position(x, y);

  // filter according to euclidean distance
  auto agentIter = potentialNeighbours.begin();
  while (agentIter != potentialNeighbours.end())
  {
    const Ped::Tagent& candidate = **agentIter;
    Ped::Tvector candidatePos = candidate.getPosition();
    double distance = (candidatePos - position).length();

    // remove distant neighbors
    if (distance > maxDist)
    {
      potentialNeighbours.erase(agentIter++);
    }
    else
    {
      ++agentIter;
    }
  }

  return potentialNeighbours;
}

void Scene::moveAgent(const Ped::Tagent* a)
{
   Ped::Tscene::moveAgent(a);
}

void Scene::moveAllAgents()
{
  // inform users when there is going to be the first update
  if (sceneTime == 0)
    emit aboutToStart();

  // clean up scene if necessary
  double cleanupInterval = 2.0;
  if (fmod(sceneTime, cleanupInterval) < CONFIG.getTimeStepSize())
    cleanupScene();

  // inform users that there will be an update
  emit aboutToMoveAgents();

  // dissolve agent clusters
  if (!agentClusters.isEmpty()){
    dissolveClusters();
    // overwriteGroups();
   }

  // update scene time
  sceneTime += CONFIG.getTimeStepSize();
  emit sceneTimeChanged(sceneTime);

  // move the agents
  updatePerceptions();

   // move the agents
   Ped::Tscene::moveAgents(CONFIG.getTimeStepSize());

   //computeMinDist();

  auto Dist = [](const double ax, const double ay, const double bx, const double by) -> double {
    return std::hypot(ax - bx, ay - by);
  };

  // For every agents, if next WP is sink and 'close', call removeAgent.
  for (auto agent : getAgents())
  {
     if (agent->getType() == Ped::Tagent::ROBOT)
     {
       continue;
     }
    const auto agent_next_wp = agent->getCurrentWaypoint();
    if(agent_next_wp){
       if (agent_next_wp->getBehavior() != Ped::Twaypoint::Behavior::SINK)
       {
         continue;
       }

       const double d = Dist(agent_next_wp->getx(), agent_next_wp->gety(), agent->getx(), agent->gety());
       if (d < agent_next_wp->getRadius())
       {
         // At sink waypoint.
         ROS_DEBUG_STREAM("Killing agent: " << agent->getId());
         removeAgent(agent);
       }
    }
  }

  // inform users
  emit movedAgents();
}

//
void Scene::updatePerceptions(){
   // update distraction every 3s
   if (abs(fmod(roundf(sceneTime*100)/100, 3.0))< 0.01){
      for (Agent* agent : agents)
         agent->varyDistraction();
   }

   // then update perceived neighbours
   for (Agent* agent : agents)
      agent->updatePerceivedNeighbors();

   // finally update perceived obstacles
   for (Agent* agent : agents)
      agent->updatePerceivedObstacles();
}

void Scene::cleanupScene()
{
  Ped::Tscene::cleanup();
}

/**
 * @brief Simulator::loadTrajectoriesFromFile
 * read file with trajectories
 * time (in frame number), id (starting from 1), x, y (in cm)
 */
void Scene::loadTrajectoriesFromFile(std::string file_path)
{
  string line;
  std::vector<std::string> words;
  std::ifstream file (file_path);
  if (file.is_open())
  {
    while ( getline (file,line) )
    {
      words.clear();
      boost::split(words, line, boost::is_any_of(","), boost::token_compress_on);

      boost::algorithm::trim(words[0]);
      int time =  boost::lexical_cast<int> (words[0]);

      boost::algorithm::trim(words[1]);
      int id =  boost::lexical_cast<int> (words[1]);

      boost::algorithm::trim(words[2]);
      boost::algorithm::trim(words[3]);
      double x = boost::lexical_cast<double> (words[2])/100;
      double y = boost::lexical_cast<double> (words[3])/100;

      Ped::Tvector position(x, y);
      SCENE.realTrajectories[time][id] = position;
    }
    file.close();
  }

  else cout << "Unable to open file";
}

//Calcule la distance minimum d'approche entre deux piétons
void Scene::computeMinDist(){
   for (Agent* agent : agents)
   {
      QList<const Agent*> neighbors = agent->updatePerceivedNeighbors();
      for (auto neighbor : neighbors)
      {
         double distance = sqrt(pow(agent->getx()-neighbor->getx(), 2)+pow(agent->gety() - neighbor->gety(), 2));
         if(distance < minDist && distance > 0){
            minDist = distance;
         }
      }
   }

  for (auto agent : agents)
  {
     double distance = sqrt(pow(agent->getCurrentDestination()->getPosition().x-agent->getx(), 2)+pow(agent->getCurrentDestination()->getPosition().y - agent->gety(), 2));
     // Si agent en 1000,1000 ou arrivé à destination -> à supprimer
     if((abs(agent->getx()-1000) < 0.01 && abs(agent->gety()-1000) < 0.01) || distance < 0.01)
     {
         removeAgent(agent);
         ROS_INFO("Min dist %f", minDist);
         if(abs(minDist-INT_MAX) > 0.01)
         {
            minDistList.push_back(minDist);

            double mean = std::accumulate(minDistList.begin(), minDistList.end(), 0.0)/minDistList.size();
            double var = 0;
            for( int n = 0; n < minDistList.size(); n++ )
            {
              var += (minDistList[n] - mean) * (minDistList[n] - mean);
            }
            var /= minDistList.size();

            ROS_INFO("Average min dist: %f", mean );
            ROS_INFO("Ecart type min dist: %f", sqrt(var));
            minDist = INT_MAX;
         }
     }
   }
}

void Scene::overwriteGroups(){
    QList<AgentGroup*> newGroups;

    //create groups
    list<list<int>> groupsMembers = {{1, 2, 0, 3}, {4,5,6}};
    list<list<int> >::iterator nested_list_itr;
    for (nested_list_itr = groupsMembers.begin();
            nested_list_itr != groupsMembers.end();
            ++nested_list_itr) {

       AgentGroup* newGroup = new AgentGroup();
       newGroup->setType(AgentGroup::AgentGroupType::FRIENDS);

       list<int>::iterator single_list_itr;
       list<int>& single_list_pointer = *nested_list_itr;

        for (single_list_itr = single_list_pointer.begin();
             single_list_itr != single_list_pointer.end();
             single_list_itr++) {
           newGroup->addMember(agents.at(*single_list_itr));
           agents.at(*single_list_itr)->setGroup(newGroup);
        }
        newGroups.append(newGroup);
    }

     //apply group forces
    foreach (AgentGroup* currentGroup, newGroups)
    {
        agentGroups.append(currentGroup);

      // add group's agents to the scene
      foreach (Agent* currentAgent, currentGroup->getMembers())
      {
        if (currentGroup->memberCount() > 1)
        {
          currentAgent->setGroup(currentGroup);
          // → Gaze Force
          GroupGazeForce* gazeForce = new GroupGazeForce(currentAgent);
          gazeForce->setGroup(currentGroup);
          currentAgent->addForce(gazeForce);

          // → Coherence Force
          GroupCoherenceForce* coherenceForce = new GroupCoherenceForce(currentAgent);
          coherenceForce->setGroup(currentGroup);
          currentAgent->addForce(coherenceForce);

          // → Repulsion Force
          GroupRepulsionForce* repulsionForce = new GroupRepulsionForce(currentAgent);
          repulsionForce->setGroup(currentGroup);
          currentAgent->addForce(repulsionForce);
        }
      }
    }
}

ext: cpp

max_stars_repo_name: maprdhm/Spaciss


text:
/* ---------------------------------------------------------------------
 *
 * Copyright (C) 1999 - 2020 by the deal.II authors
 *
 * This file is part of the deal.II library.
 *
 * The deal.II library is free software; you can use it, redistribute
 * it, and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * The full text of the license can be found in the file LICENSE.md at
 * the top level directory of deal.II.
 *
 * ---------------------------------------------------------------------
 *
 * Authors: Wolfgang Bangerth, 1999,
 *          Guido Kanschat, 2011
 *          Luca Heltai, 2021
 */
#include "base_block_problem.h"

#include <deal.II/dofs/dof_renumbering.h>

using namespace dealii;

template <int dim>
BaseBlockProblem<dim>::BaseBlockProblem(
  const std::vector<std::string> component_names,
  const std::string &            problem_name)
  : BaseProblem<dim>(component_names.size(), problem_name)
  , component_names(component_names)
{}

template <int dim>
void
BaseBlockProblem<dim>::setup_system()
{
  TimerOutput::Scope timer_section(this->timer, "setup_system");
  if (!this->fe) // this 其作用就是指向成员函数所作用的对象
    {
      this->fe = FETools::get_fe_by_name<dim>(this->fe_name);
      this->mapping =
        std::make_unique<MappingQGeneric<dim>>(this->mapping_degree);
      const auto vars = dim == 1 ? "x" : dim == 2 ? "x,y" : "x,y,z";
      this->forcing_term.initialize(vars,
                                    this->forcing_term_expression,
                                    this->constants);
      this->exact_solution.initialize(vars,
                                      this->exact_solution_expression,
                                      this->constants);

      this->dirichlet_boundary_condition.initialize(
        vars, this->dirichlet_boundary_conditions_expression, this->constants);

      this->neumann_boundary_condition.initialize(
        vars, this->neumann_boundary_conditions_expression, this->constants);
    }

  this->dof_handler.distribute_dofs(*this->fe);

  // 以顺时针的方式重新编号Dofs。
  std::vector<unsigned int> blocks(this->n_components);
  unsigned int              i = 0;
  Assert(component_names.size() > 0, ExcInternalError());
  AssertDimension(this->n_components, component_names.size());
  blocks[0] = i;
  for (unsigned int j = 1; j < this->n_components; ++j)
    {
      if (component_names[j] == component_names[j - 1])
        blocks[j] = i;
      else
        blocks[j] = ++i;
    }
  DoFRenumbering::component_wise(this->dof_handler, blocks);

  dofs_per_block = DoFTools::count_dofs_per_fe_block(this->dof_handler, blocks);

  locally_owned_dofs =
    this->dof_handler.locally_owned_dofs().split_by_block(dofs_per_block);

  IndexSet non_blocked_locally_relevant_dofs;
  DoFTools::extract_locally_relevant_dofs(this->dof_handler,
                                          non_blocked_locally_relevant_dofs);
  locally_relevant_dofs =
    non_blocked_locally_relevant_dofs.split_by_block(dofs_per_block);

  this->pcout << "Number of degrees of freedom: " << this->dof_handler.n_dofs()
              << " (" << Patterns::Tools::to_string(dofs_per_block) << ")"
              << std::endl;

  this->constraints.clear();
  this->constraints.reinit(non_blocked_locally_relevant_dofs);
  DoFTools::make_hanging_node_constraints(this->dof_handler, this->constraints);

  for (const auto &id : this->dirichlet_ids)
    VectorTools::interpolate_boundary_values(*this->mapping,
                                             this->dof_handler,
                                             id,
                                             this->dirichlet_boundary_condition,
                                             this->constraints);
  this->constraints.close();

  TrilinosWrappers::BlockSparsityPattern dsp(locally_owned_dofs,
                                             locally_owned_dofs,
                                             locally_relevant_dofs,
                                             this->mpi_communicator);

  DoFTools::make_sparsity_pattern(this->dof_handler,
                                  dsp,
                                  this->constraints,
                                  false);
  // SparsityTools::distribute_sparsity_pattern(dsp,
  //                                            locally_owned_dofs,
  //                                            mpi_communicator,
  //                                            locally_relevant_dofs);

  dsp.compress();
  system_block_matrix.reinit(dsp);

  block_solution.reinit(locally_owned_dofs, this->mpi_communicator);
  system_block_rhs.reinit(locally_owned_dofs, this->mpi_communicator);

  locally_relevant_block_solution.reinit(locally_owned_dofs,
                                         locally_relevant_dofs,
                                         this->mpi_communicator);

  this->error_per_cell.reinit(this->triangulation.n_active_cells());

  // 现在调用任何可能需要的东西
  this->setup_system_call_back();
}

template <int dim>
void
BaseBlockProblem<dim>::assemble_system_one_cell(
  const typename DoFHandler<dim>::active_cell_iterator &,
  ScratchData &,
  CopyData &)
{
  Assert(false, ExcPureFunctionCalled());
}

template <int dim>
void
BaseBlockProblem<dim>::copy_one_cell(const CopyData &copy)
{
  this->constraints.distribute_local_to_global(copy.matrices[0],
                                               copy.vectors[0],
                                               copy.local_dof_indices[0],
                                               system_block_matrix,
                                               system_block_rhs);
}

template <int dim>
void
BaseBlockProblem<dim>::assemble_system()
{
  TimerOutput::Scope timer_section(this->timer, "assemble_system");
  QGauss<dim>        quadrature_formula(this->fe->degree + 1);
  QGauss<dim - 1>    face_quadrature_formula(this->fe->degree + 1);

  ScratchData scratch(*this->mapping,
                      *this->fe,
                      quadrature_formula,
                      update_values | update_gradients |
                        update_quadrature_points | update_JxW_values,
                      face_quadrature_formula,
                      update_values | update_quadrature_points |
                        update_JxW_values);

  CopyData copy(this->fe->n_dofs_per_cell());

  auto worker = [&](const auto &cell, auto &scratch, auto &copy) {
    assemble_system_one_cell(cell, scratch, copy);
  };

  auto copier = [&](const auto &copy) { copy_one_cell(copy); };

  using CellFilter =
    FilteredIterator<typename DoFHandler<dim>::active_cell_iterator>;

  WorkStream::run(CellFilter(IteratorFilters::LocallyOwnedCell(),
                             this->dof_handler.begin_active()),
                  CellFilter(IteratorFilters::LocallyOwnedCell(),
                             this->dof_handler.end()),
                  worker,
                  copier,
                  scratch,
                  copy);

  system_block_matrix.compress(VectorOperation::add);
  system_block_rhs.compress(VectorOperation::add);
}

template <int dim>
void
BaseBlockProblem<dim>::solve()
{
  TimerOutput::Scope timer_section(this->timer, "solve");
  // SolverCG<LA::MPI::BlockVector> solver(solver_control);
  // LA::MPI::PreconditionAMG  amg;
  // amg.initialize(system_matrix);
  // solver.solve(system_matrix, solution, system_rhs, amg);
  // constraints.distribute(solution);
  // locally_relevant_solution = solution;
}

template class BaseBlockProblem<1>;
template class BaseBlockProblem<2>;
template class BaseBlockProblem<3>;

ext: cc


text:
/**
 *    \file include/geombd/CRTP/JointDerived/Visitors.hxx
 *    \author Alvaro Paz, Gustavo Arechavaleta
 *    \version 1.0
 *    \date 2021
 *
 *    Classes for visitors
 *    Copyright (c) 2021 Cinvestav
 *    This library is distributed under the MIT License.
 */

#ifndef GEOMBD_VISITORS_HXX
#define GEOMBD_VISITORS_HXX

#define EIGEN_NO_DEBUG
#include "Eigen/Core"

//#include <boost/foreach.hpp>
//#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>

namespace geoCRTP{

  //! Forward Kinematics Visitor
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Vector3Type, typename Matrix3Type>
  class FwdKin_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    FwdKin_visitor( ) : R(nullptr), S(nullptr) {}

    ScalarType qi;
    Vector3Type* S;
    Matrix3Type* R;

    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
        BaseType.FwdKin(qi, (*S).derived(), (*R).derived());
      return 0;
    }

  };

  //! Visitor for Twist and bias elements at root
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Vector3Type, typename Vector6Type, typename Matrix6Type>
  class TCP_root_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    TCP_root_visitor( ) : S(nullptr), S_i(nullptr), p_(nullptr), M_(nullptr) {}

    //! Members
    ScalarType vi;  Vector3Type* S;  Vector6Type* S_i;  Vector6Type* p_;  Matrix6Type* M_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
        BaseType.TCP_root(vi, (*S).derived(), (*S_i).derived(), (*p_).derived(), (*M_).derived());
      return 0;
    }

  };

  //! Visitor for Twist and bias elements.
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Matrix3Type, typename Matrix6Type,
           typename Vector3Type, typename Vector6Type>
  class TwCbPb_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    TwCbPb_visitor( ) : S(nullptr), R_(nullptr), P_(nullptr), S_j(nullptr),
                        M_(nullptr), S_i(nullptr), c_(nullptr), p_(nullptr) {}

    //! Members
    bool zeroFlag;
    ScalarType vi;    Vector3Type* S;    Matrix3Type* R_;   Vector3Type* P_;  Vector6Type* S_j;
    Matrix6Type* M_;  Vector6Type* S_i;  Vector6Type* c_;   Vector6Type* p_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
      BaseType.TwCbPb(zeroFlag, vi, (*S).derived(), (*R_).derived(),  (*P_).derived(), (*S_j).derived(), (*M_).derived(),
                      (*S_i).derived(), (*c_).derived(), (*p_).derived());
      return 0;
    }

  };

  //! Visitor for U, u & invD expressions
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Vector3Type, typename Vector6Type, typename Matrix6Type>
  class UuiD_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    UuiD_visitor( ) : u(nullptr), iD(nullptr), S(nullptr), U_(nullptr), P_A_(nullptr), M_A_(nullptr) {}

    //! Members
    ScalarType* u;    ScalarType* iD;     ScalarType tau;     Vector3Type* S;
    Vector6Type* U_;  Vector6Type* P_A_;  Matrix6Type* M_A_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
      ScalarType & u_ = (*u);  ScalarType & iD_ = (*iD);
      BaseType.UuiD(u_, iD_, tau, (*S).derived(), (*U_).derived(), (*P_A_).derived(), (*M_A_).derived());
      return 0;
    }

  };

  //! Visitor for preparing inertial expressions
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Vector3Type, typename Vector6Type, typename Matrix6Type>
  class PreIner_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    PreIner_visitor( ) : S(nullptr), U_(nullptr), c_(nullptr), P_a_(nullptr),
                         M_a_(nullptr), P_A_(nullptr), M_A_(nullptr) {}

    //! Members
    ScalarType u, iD;   Vector3Type* S;
    Vector6Type* U_;    Vector6Type* c_;    Vector6Type* P_a_;
    Matrix6Type* M_a_;  Vector6Type* P_A_;  Matrix6Type* M_A_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
      BaseType.PreIner(u, iD, (*S).derived(), (*U_).derived(), (*c_).derived(), (*P_a_).derived(),
                       (*M_a_).derived(), (*P_A_).derived(), (*M_A_).derived());
      return 0;
    }

  };

  //! Visitor for inertial back projection
  //!------------------------------------------------------------------------------!//
  template<typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename Matrix6Type>
  class InerProj_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    InerProj_visitor( ) : S(nullptr), P_(nullptr), R_(nullptr), P_a_(nullptr), P_A_(nullptr), M_a_(nullptr), M_A_(nullptr) {}

    //! Members
    bool P_z;           Vector3Type* S;
    Vector3Type* P_;    Matrix3Type* R_;
    Vector6Type* P_a_;  Vector6Type* P_A_;
    Matrix6Type* M_a_;  Matrix6Type* M_A_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
      BaseType.InerProj(P_z, (*S).derived(), (*P_).derived(), (*R_).derived(), (*P_a_).derived(), (*P_A_).derived(),
                        (*M_a_).derived(), (*M_A_).derived());
      return 0;
    }

  };

  //! Visitor for computing the acceleration
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type>
  class Accel_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    Accel_visitor( ) : ddq(nullptr), S_(nullptr), P_(nullptr), R_(nullptr), c_(nullptr),
                       U_(nullptr), Acc_i_(nullptr), Acc_j_(nullptr) {}

    //! Members
    bool zeroFlag;
    ScalarType u, iD;
    ScalarType* ddq;

    Vector3Type* S_;  Vector3Type* P_;  Matrix3Type* R_;  Vector6Type* c_;
    Vector6Type* U_;  Vector6Type* Acc_i_;  Vector6Type* Acc_j_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
      BaseType.Accel(zeroFlag, u, iD, ddq, (*S_).derived(), (*P_).derived(), (*R_).derived(), (*c_).derived(),
                     (*U_).derived(), (*Acc_i_).derived(), (*Acc_j_).derived());
      return 0;
    }

  };

  //! Visitor for computing the acceleration at root
  //!------------------------------------------------------------------------------!//
  template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type>
  class Accel_root_visitor : public boost::static_visitor<int> {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    //! Constructor
    Accel_root_visitor( ) : ddq(nullptr), S_(nullptr), P_(nullptr), R_(nullptr), U_(nullptr), Acc_i_(nullptr) {}

    //! Members
    ScalarType u, iD;
    ScalarType* ddq;

    Vector3Type* S_;  Vector3Type* P_;  Matrix3Type* R_;  Vector6Type* U_;  Vector6Type* Acc_i_;

    //! Method -> member function
    template<typename Derived>
    int operator()(CRTPInterface<Derived> & BaseType) const {
      BaseType.AccelRoot(u, iD, ddq, (*S_).derived(), (*P_).derived(), (*R_).derived(), (*U_).derived(), (*Acc_i_).derived());
      return 0;
    }

  };

}

#endif // GEOMBD_VISITORS_HXX

ext: hxx


text:
/**
 * Copyright (C) 2015 Dato, Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
#include <stdint.h>
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <zookeeper_util/key_value.hpp>
#include <fault/query_object_server_master.hpp>
#include <fault/query_object_server_replica.hpp>
#include <fault/query_object_server_process.hpp>
#include <fault/query_object_create_flags.hpp>
namespace libfault {

int query_main(int argc, char** argv,
               const query_object_factory_type& factory) {

  void* zmq_ctx = zmq_ctx_new();

  if (argc < 4) {
    std::cout << "Usage: " << argv[0]
              << " [comma-seperated Zookeeper machines] [prefix] [objectkey:replicaid]\n";
    return 0;
  }
  // parse zkhosts
  std::vector<std::string> zkhosts;
  boost::split(zkhosts, argv[1],
               boost::is_any_of(", "), boost::token_compress_on);
  // prefix
  std::string prefix = argv[2];

  // object and key
  std::vector<std::string> object_and_key_split;
  boost::split(object_and_key_split, argv[3],
               boost::is_any_of(": "), boost::token_compress_on);
  if (object_and_key_split.size() != 2) {
    std::cout << "Invalid object key name. Expected objectkey:replicaid\n";
    return 0;
  }
  std::string objectkey = object_and_key_split[0];
  size_t replicaid = atoi(object_and_key_split[1].c_str());

  // create the zookeeper instance
  graphlab::zookeeper_util::key_value keyval(zkhosts, prefix, "");

  if (replicaid == 0) {
    std::cout << "Creating Master : " << objectkey << "\n";
    // if we fail the master election, fail immediately
    if (master_election(&keyval, objectkey) == false) return false;

    // create object
    uint64_t flags = 0;
    if (replicaid == 0) flags |= QUERY_OBJECT_CREATE_MASTER;
    else flags |= QUERY_OBJECT_CREATE_REPLICA;
    query_object* qobj = factory(objectkey, zkhosts, prefix, flags);

    query_object_server_master master(zmq_ctx, &keyval, objectkey, qobj);
    master.start();
  } else {
    std::cout << "Creating Replica: " << objectkey << ":" << replicaid << "\n";
    // replica
    if (replica_election(&keyval, objectkey, replicaid) == false) return false;

    // create object
    uint64_t flags = 0;
    if (replicaid == 0) flags |= QUERY_OBJECT_CREATE_MASTER;
    else flags |= QUERY_OBJECT_CREATE_REPLICA;
    query_object* qobj = factory(objectkey, zkhosts, prefix, flags);

    int ret = 0;
    {
      query_object_server_replica replica(zmq_ctx, &keyval, objectkey,
                                        qobj, replicaid);
      ret = replica.start();
    }
    if (ret > 0) {
      std::cout << "Master lost. Promoting... ";
      // promote
      query_object_server_master master(zmq_ctx, &keyval, objectkey, qobj);
      master.start();
    }
  }
  return 0;
}

} // namespace

max_stars_repo_name: parquette/ParFrame

max_issues_repo_name: parquette/ParFrame

max_forks_repo_name: parquette/ParFrame


text:
/*****************************************************************************
*
* NXP Confidential Proprietary
*
* Copyright 2017 NXP
* All Rights Reserved
*
******************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/

#ifndef WEBSOCKETAPPLICATIONSCHATSERVER_HPP
#define WEBSOCKETAPPLICATIONSCHATSERVER_HPP

#include <string>
#include <vector>
#include <boost/asio.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include "room.hpp"
#include "session.hpp"
#include "request_handler.hpp"

namespace websocket {
    namespace applications {
		namespace auditorium {

        /// The top-level class of the chat server.
        class server
            : private boost::noncopyable
        {
		public:
            /// get instance of server
            static server* getInstance();

            /// Run the server's io_service loop.
            void run();

            /// The chat room.
            room room_;

            /// Setup server
            static void server_setup(const char *address, const char *port);

            /// Server status
            bool isRunning;

        private:

            /// Singleton instance
            static server* instance;

            /// Construct the server to listen on the specified TCP address and port, and
            /// serve up files from the given directory.
            explicit server(const std::string& address, const std::string& port);

            /// Server address
            static const char *address_;

            /// Server port
            static const char *port_;

            /// Initiate an asynchronous accept operation.
            void start_accept();

            /// Handle completion of an asynchronous accept operation.
            void handle_accept(const boost::system::error_code& e);

            /// Handle a request to stop the server.
            void handle_stop();

            /// The io_service used to perform asynchronous operations.
            boost::asio::io_service io_service_;

            /// The signal_set is used to register for process termination notifications.
            boost::asio::signal_set signals_;

            /// Acceptor used to listen for incoming connections.
            boost::asio::ip::tcp::acceptor acceptor_;

            /// The next connection to be accepted.
            session_ptr new_session_;

            /// The handler for all incoming requests.
            http::request_handler request_handler_;

			/// Running Thread
			boost::thread run_t_;

			/// Function for run thread
			void run_thread();
        };

        } // namespace chat
    } // namespace applications
} // namespace websocket

#endif /* WEBSOCKETAPPLICATIONSCHATSERVER_HPP */

ext: hpp


text:
// (C) Copyright Tobias Schwinger
//
// Use modification and distribution are subject to the boost Software License,
// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt).

//------------------------------------------------------------------------------

#ifndef BOOST_FT_FUNCTION_POINTER_HPP_INCLUDED
#define BOOST_FT_FUNCTION_POINTER_HPP_INCLUDED

#include <boost/mpl/aux_/lambda_support.hpp>

#include <boost/function_types/function_type.hpp>

namespace boost
{
  namespace function_types
  {
    template<typename Types, typename Tag = null_tag> struct function_pointer
    {
      typedef typename function_types::function_type<Types,Tag>::type * type;

      BOOST_MPL_AUX_LAMBDA_SUPPORT(2,function_pointer,(Types,Tag))
    };
  }
}

#endif


text:
#pragma once
#include <sstream>

#include <boost/lexical_cast.hpp>

#include "simple_match/simple_match.hpp"
namespace simple_match
{
namespace detail
{
template<class Type, class Matcher>
struct lexical_cast_t
{
  Type t;
  Matcher m;

  template<class U>
  auto check(U&& u) -> bool
  {
    return boost::conversion::try_lexical_convert(std::forward<U>(u), t);
  }

  template<class T>
  auto get(T&& /*unused*/)
  {
    return match_get(t, m);
  }

  lexical_cast_t(Matcher m)
      : m {std::move(m)}
  {
  }
};
template<class Type>
struct lexical_cast_t<Type, void>
{
  Type t;

  template<class U>
  auto check(U&& u) -> bool
  {
    return boost::conversion::try_lexical_convert(std::forward<U>(u), t);
  }

  template<class T>
  auto get(T&& /*unused*/)
  {
    return std::tie();
  }
};

}  // namespace detail

namespace customization
{
template<class Type, class Type2, class M>
struct matcher<Type, detail::lexical_cast_t<Type2, M>>
{
  template<class T, class U>
  static auto check(T&& t, U&& u) -> bool
  {
    return u.check(std::forward<T>(t));
  }

  template<class T, class U>
  static auto get(T&& t, U&& u)
  {
    return u.get(std::forward<T>(t));
  }
};
}  // namespace customization

template<class T>
auto lexical_cast() -> detail::lexical_cast_t<T, void>
{
  return {};
}

template<class T, class Matcher>
auto lexical_cast(Matcher&& m) -> detail::lexical_cast_t<T, Matcher>
{
  return {std::forward<Matcher>(m)};
}
}  // namespace simple_match


text:
#pragma once

#include <ysu/lib/rpcconfig.hpp>

#include <boost/property_tree/ptree_fwd.hpp>

#include <string>

namespace boost
{
namespace filesystem
{
	class path;
}
}

namespace ysu
{
class tomlconfig;
class rpc_child_process_config final
{
public:
	bool enable{ false };
	std::string rpc_path{ get_default_rpc_filepath () };
};

class node_rpc_config final
{
public:
	ysu::error serialize_json (ysu::jsonconfig &) const;
	ysu::error deserialize_json (bool & upgraded_a, ysu::jsonconfig &, boost::filesystem::path const & data_path);
	ysu::error serialize_toml (ysu::tomlconfig & toml) const;
	ysu::error deserialize_toml (ysu::tomlconfig & toml);

	bool enable_sign_hash{ false };
	ysu::rpc_child_process_config child_process;
	static unsigned json_version ()
	{
		return 1;
	}

	// Used in tests to ensure requests are modified in specific cases
	void set_request_callback (std::function<void(boost::property_tree::ptree const &)>);
	std::function<void(boost::property_tree::ptree const &)> request_callback;
};
}


text:
#include "../../include/component/opt_streaming_component.hpp"
#include <boost/filesystem.hpp>
namespace fs = ::boost::filesystem;

// return the filenames of all files that have the specified extension
// in the specified directory and all subdirectories
void get_all(const fs::path& root, const std::string& ext, std::vector<fs::path>& ret)
{
    if(!fs::exists(root) || !fs::is_directory(root)) return;

    fs::recursive_directory_iterator it(root);
    fs::recursive_directory_iterator endit;

    while(it != endit)
    {
        if(fs::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename());
        ++it;

    }

}

OPT_Streaming_Component::OPT_Streaming_Component(QQuickItem * parent) :
  nh(),
  QQuickPaintedItem(parent),
  current_image(NULL),
  current_buffer(NULL),
  topic_value("Click_on_one_of_the_camera_views_on_the_left_to_start"),
  ros_ready(false),
  img_trans(NULL),number_of_rois(0) {
  all_rois_dir_path_value=QString::fromStdString("file:"+ros::package::getPath("opt_gui")+"/data/");
}

//set up the subscriber(image msg from sensor) and advertiser(roi msg)
void OPT_Streaming_Component::setup() {
  img_trans = new image_transport::ImageTransport(nh);

  image_sub = img_trans->subscribe(
        topic_value.toStdString(),
        1,
        &OPT_Streaming_Component::receive_image,
        this,
        image_transport::TransportHints("raw")
        );

  std::string sensor_name=topic_value.toStdString().substr(1, (topic_value.toStdString().size()-17));
  std::string image2D_rois_from_gui_pub_name = "/"+sensor_name + "/image2D_rois_from_gui";
  image2D_rois_from_gui_pub=nh.advertise<opt_msgs::Image2D_roi_array>(image2D_rois_from_gui_pub_name,3);

  std::string image2D_rois_from_file_pub_name = "/"+sensor_name + "/image2D_rois_from_file/image";
//  image2D_rois_from_file_pub=nh.advertise<sensor_msgs::Image>(image2D_rois_from_file_pub_name,3);
   image2D_rois_from_file_pub=nh.advertise<opt_msgs::Image2D_roi_file>(image2D_rois_from_file_pub_name,3);

  ros_ready = true;
  ROS_INFO("Setup of video component complete");
}

//call back function to recieve images from sensor
void OPT_Streaming_Component::receive_image(const sensor_msgs::Image::ConstPtr &msg) {
  image2D_rois_msg.header=msg->header;

  //-----------------------------This part comes from rtq_image_view----------------------------------
  try
  {
    // First let cv_bridge do its magic
    cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::RGB8);
    conversion_mat_ = cv_ptr->image;
  }
  catch (cv_bridge::Exception& e)
  {
    try
    {
      // If we're here, there is no conversion that makes sense, but let's try to imagine a few first
      cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvShare(msg);
      if (msg->encoding == "CV_8UC3")
      {
        // assuming it is rgb
        conversion_mat_ = cv_ptr->image;
      } else if (msg->encoding == "8UC1") {
        // convert gray to rgb
        cv::cvtColor(cv_ptr->image, conversion_mat_, CV_GRAY2RGB);
      } else if (msg->encoding == "16UC1" || msg->encoding == "32FC1") {
        // scale / quantify
        double min = 0;
        double max = 10;
        if (msg->encoding == "16UC1") max *= 1000;
        // dynamically adjust range based on min/max in image
        cv::minMaxLoc(cv_ptr->image, &min, &max);
        if (min == max) {
          // completely homogeneous images are displayed in gray
          min = 0;
          max = 2;
        }
        cv::Mat img_scaled_8u;
        cv::Mat(cv_ptr->image-min).convertTo(img_scaled_8u, CV_8UC1, 255. / (max - min));
        cv::cvtColor(img_scaled_8u, conversion_mat_, CV_GRAY2RGB);
      } else {
        qWarning("ImageView.callback_image() could not convert image from '%s' to 'rgb8' (%s)", msg->encoding.c_str(), e.what());
        return;
      }
    }
    catch (cv_bridge::Exception& e)
    {
      qWarning("ImageView.callback_image() while trying to convert image from '%s' to 'rgb8' an exception was thrown (%s)", msg->encoding.c_str(), e.what());
      return;
    }
  }
  //-----------------------------This part comes from rtq_image_view----------------------------------

  // Only Qimage can be painted
  current_image=QImage(conversion_mat_.data,conversion_mat_.cols,conversion_mat_.rows,QImage::Format_RGB888);

  // finally we need to re-render the component to display the new image
  update();
}

//This function will run  after "update();" is called
void OPT_Streaming_Component::paint(QPainter * painter) {
  painter->drawImage(boundingRect().adjusted(1, 1, -1, -1), current_image);//paint the image to fit the size of the Rectangle
}

//When the sensor name is modified in the camera view, change the topics with the new sensor name in the subscriber and advertiser
void OPT_Streaming_Component::set_topic(const QString & new_value) {
  if(topic_value != new_value) {
    topic_value = new_value;
    if(ros_ready) {
      image_sub.shutdown();
      image_sub = img_trans->subscribe(
            topic_value.toStdString(),
            1,
            &OPT_Streaming_Component::receive_image,
            this,
            image_transport::TransportHints("raw")
            );

      image2D_rois_msg.Rois.clear();

      std::string sensor_name=topic_value.toStdString().substr(1, (topic_value.toStdString().size()-17));
      std::string image2D_rois_from_gui_pub_name = "/"+sensor_name + "/image2D_rois_from_gui";
      image2D_rois_from_gui_pub=nh.advertise<opt_msgs::Image2D_roi_array>(image2D_rois_from_gui_pub_name,3);

      std::string image2D_rois_from_file_pub_name = "/"+sensor_name + "/image2D_rois_from_file/image";
      image2D_rois_from_file_pub=nh.advertise<opt_msgs::Image2D_roi_file>(image2D_rois_from_file_pub_name,3);

    }
    emit topic_changed();
  }
}

QString OPT_Streaming_Component::get_topic() const {
  return topic_value;
}

void OPT_Streaming_Component::set_rois_dir_path(const QString rois_dir_path_)
{
  rois_dir_path_value=rois_dir_path_;
  emit rois_dir_path_changed();
}

QString OPT_Streaming_Component::get_rois_dir_path() const {
  return rois_dir_path_value;
}
QString OPT_Streaming_Component::get_all_rois_dir_path() const {
  return all_rois_dir_path_value;
}

//save the selected rois in the gui as images to their folder named with the corresponding sensor names
void OPT_Streaming_Component::save_ROI(QString sensor_name,int no_ROI, int rect_X,int rect_Y, int rect_width, int rect_height )
{
  //get the roi with the bouding box you created in qml main_view, save it as a file
  cv::Rect roi_rec=cv::Rect(rect_X,rect_Y,rect_width,rect_height) & cv::Rect(0,0,conversion_mat_.size().width,conversion_mat_.size().height);
  cv::Mat roi(conversion_mat_,roi_rec);
  cv::cvtColor(roi, roi, CV_BGR2RGB);
//  std::string roi_file_name=ros::package::getPath("opt_gui")+"/data/"+sensor_name.toStdString()+"_roi_"+ QString::number(no_ROI).toStdString()+".png";
  std::string roi_file_name=ros::package::getPath("opt_gui")+"/data/"+"{"+sensor_name.toStdString()+"}-"
                                                                     +"{default_name}-"
                                                                     +QString::number(no_ROI).toStdString()+".png";
  cv::imwrite(roi_file_name,roi);
}

void OPT_Streaming_Component::rename_ROI_files(int no_ROI, QString roi_name )
{
  std::string sensor_name=topic_value.toStdString().substr(1, (topic_value.toStdString().size()-18));
  std::string old_roi_file_name=ros::package::getPath("opt_gui")+"/data/"+"{"+sensor_name+"}-"
                                                                     +"{default_name}-"
                                                                     +QString::number(no_ROI).toStdString()+".png";
  std::string new_roi_file_name=ros::package::getPath("opt_gui")+"/data/"+"{"+sensor_name+"}-"
                                                                     +"{"+roi_name.toStdString()+"}-"
                                                                     +QString::number(no_ROI).toStdString()+".png";
  rename(old_roi_file_name.c_str(),new_roi_file_name.c_str());
}

// Add rois one by one to the msg in the qml after push the button named "publish_rois_from_gui"
void OPT_Streaming_Component::add_roi(int no_ROI,QString roi_name, int rect_X,int rect_Y, int rect_width, int rect_height)
{
  current_image2D_roi_msg.no=no_ROI;
  current_image2D_roi_msg.name=roi_name.toStdString();
  current_image2D_roi_msg.x=rect_X;
  current_image2D_roi_msg.y=rect_Y;
  current_image2D_roi_msg.width=rect_width;
  current_image2D_roi_msg.height=rect_height;
  image2D_rois_msg.Rois.push_back(current_image2D_roi_msg);
}

//After Add all the rois , publish the msg, this is also excuted in qml as the "add_roi" function
void OPT_Streaming_Component::publish_rois_from_gui()
{
  image2D_rois_from_gui_pub.publish(image2D_rois_msg);
  std::cout<<image2D_rois_msg.Rois.size()<<" image2D_rois are published"<<std::endl;
  image2D_rois_msg.Rois.clear();//use clear so that we can create new rois after starting detection
}

/*
//read the rois from previous save image files in the folder correspong to the sensor name, and publish them one by one
void OPT_Streaming_Component::publish_rois_from_file()
{
  std::string sensor_name=topic_value.toStdString().substr(1, (topic_value.toStdString().size()-17));
  cv::Directory dir;
  std::string rois_dir_path=ros::package::getPath("opt_gui")+"/data/"+sensor_name;
  std::vector<std::string> roi_filenames = dir.GetListFiles(rois_dir_path, ".png");

  //publish roi iamge one by one
  for(std::vector<std::string>::iterator it =roi_filenames.begin(); it!=roi_filenames.end();it++)
  {
    cv::Mat image = cv::imread(rois_dir_path+*it);
    sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();
    image2D_rois_from_file_pub.publish(msg);
    std::cout<<"image msg for file has published"<<std::endl;
    ros::Duration(0.3).sleep(); // sleep for half a second
  }

  //create a empty image to publish so that the reciever can know all the rois images have been published
  cv::Mat image_;
  sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image_).toImageMsg();
  image2D_rois_from_file_pub.publish(msg);
  std::cout<<"Finish publishing roi msg from file"<<std::endl;
}
*/

//read the rois from previous save image files in the folder correspong to the sensor name, and publish them one by one
void OPT_Streaming_Component::publish_rois_from_file()
{
  std::string sensor_name=topic_value.toStdString().substr(1, (topic_value.toStdString().size()-17));
//  cv::Directory dir;
  std::string rois_dir_path=ros::package::getPath("opt_gui")+"/data/"+sensor_name;
  std::vector<fs::path> roi_filenames;
  get_all(rois_dir_path, ".png", roi_filenames);

  //publish roi iamge one by one
  for(const auto& name : roi_filenames)
  {
    cv::Mat image = cv::imread(rois_dir_path+fs::basename(name) + ".png");
    sensor_msgs::ImagePtr image_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();
    opt_msgs::Image2D_roi_file current_image2D_roi_file_msg;
    current_image2D_roi_file_msg.image_roi=*image_msg;

    std::string tmp_str=fs::basename(name);
    std::size_t p2 = tmp_str.find_last_of("{");
    std::size_t q2 = tmp_str.find_last_of("}");
    std::string object_name_from_file=tmp_str.substr(p2+1,q2-p2-1);

    current_image2D_roi_file_msg.name=object_name_from_file;

    image2D_rois_from_file_pub.publish(current_image2D_roi_file_msg);
    std::cout<<"image msg for file has published"<<std::endl;
    ros::Duration(0.3).sleep(); // sleep for half a second
  }

  opt_msgs::Image2D_roi_file current_image2D_roi_file_msg;
  current_image2D_roi_file_msg.name="end_flag";
  image2D_rois_from_file_pub.publish(current_image2D_roi_file_msg);
  std::cout<<"Finish publishing roi msg from file"<<std::endl;
}


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

#include "pxr/pxr.h"
#include "pxr/usd/sdf/cleanupEnabler.h"
#include <boost/python.hpp>
#include <memory>

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE

namespace {

// This class and its wrapping allow a client to do this:
//
//    with Sdf.CleanupEnabler() :
//        // some code
//
// Any specs modified in the with block will be removed if they are inert when
// leaving the 'with' block.
//
class Sdf_PyCleanupEnabler
{
public:
    // We don't create and destory the SdfCleanupEnabler object
    // on construction and destruction, but rather in the Enter/Exit methods.
    // This ties the lifetime of that object to the python 'with' block rather
    // than to the lifetime of this object, which may be garbage collected.
    Sdf_PyCleanupEnabler()
    {
        // Do nothing
    }

    // Called by python when entering the 'with' block
    void Enter()
    {
        _state.reset(new SdfCleanupEnabler());
    }

    // Called by python when exiting the 'with' block.
    //
    // The three extra arguments are required by the __enter__/__exit__
    // protocol, and can contain the python exception state if the
    // with-statement is exited by an exception.  We ignore them here.
    void Exit(object const &, object const &, object const &)
    {
        _state.reset();
    }

private :
    std::unique_ptr<SdfCleanupEnabler> _state;
};

} // anonymous namespace

void wrapCleanupEnabler()
{
    typedef Sdf_PyCleanupEnabler This;

    class_<This,boost::noncopyable>("CleanupEnabler",
        init<>())

        // Callbacks for the python 'with' statement
        .def("__enter__", &This::Enter)
        .def("__exit__", &This::Exit)

        ;
}

max_stars_repo_name: DougRogers-DigitalFish/USD

max_issues_repo_name: DougRogers-DigitalFish/USD

max_forks_repo_name: DougRogers-DigitalFish/USD