text:
/******************************************************************************
 * Copyright (c) 2018 McAfee, LLC - All Rights Reserved.
 *****************************************************************************/

#include "include/BrokerHelpers.h"
#include "include/BrokerSettings.h"
#include "brokerregistry/include/brokerregistry.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace dxl::broker;

// GUID
string BrokerSettings::sm_guid;

// Tenant GUID
string BrokerSettings::sm_tenantGuid;

// Listen port
int BrokerSettings::sm_listenPort = 8883;

// Message size limit
int BrokerSettings::sm_messageSizeLimit = 1048576;

// User
string BrokerSettings::sm_user;

// Logging
string BrokerSettings::sm_logFilePath;
int BrokerSettings::sm_logFileMaxSize = 0;
int BrokerSettings::sm_logFileMaxCount = 0;
bool BrokerSettings::sm_logUseStdOut = false;
string BrokerSettings::sm_logLevel;
bool BrokerSettings::sm_noticeLoggingEnabled = false;

// Policy files
string BrokerSettings::sm_policyGeneralStateFile;
string BrokerSettings::sm_policyBrokerStateFile;
string BrokerSettings::sm_policyTopicAuthStateFile;

// The broker TTL
int BrokerSettings::sm_brokerTtl = 60;

// TTL Check interval
int BrokerSettings::sm_ttlInterval = 10;

// TTL grace period
int BrokerSettings::sm_ttlGracePeriod = 5;

// JSON pretty print
bool BrokerSettings::sm_jsonPrettyPrint = false;

// Certificates
bool BrokerSettings::sm_tlsEnabled = true;
bool BrokerSettings::sm_tlsBridgingInsecure = true;
bool BrokerSettings::sm_fipsEnabled = false;
string BrokerSettings::sm_certKeyStoreDir;
string BrokerSettings::sm_certBrokerCertChainFile;
string BrokerSettings::sm_certClientCertChainFile;
string BrokerSettings::sm_certBrokerCertFile;
string BrokerSettings::sm_certClientCertFile;
string BrokerSettings::sm_certBrokerCsrFile;
string BrokerSettings::sm_certClientCsrFile;
string BrokerSettings::sm_certBrokerPrivateKeyFile;
string BrokerSettings::sm_certClientPrivateKeyFile;
string BrokerSettings::sm_revokedCertsFile;
string BrokerSettings::sm_brokerCertsListFile;
int BrokerSettings::sm_certSignRetryMins = 5;

// Ciphers
string BrokerSettings::sm_ciphers;

// Message sampling
int BrokerSettings::sm_messageSampleSecs = 60;

// Whether to ignore the connection limit as received via policy (for testing)
bool BrokerSettings::sm_ignoreConnectionLimit = false;

// The maximum size of the packet buffer (per context)
uint64_t BrokerSettings::sm_maxPacketBufferSize = 500000;

// The approximate broker state topics batch size (in terms of character count).
int BrokerSettings::sm_brokerStateTopicsCharsBatchSize = 2048;

// Whether topic based routing is enabled
bool BrokerSettings::sm_topicRoutingEnabled = true;

// Whether the topic based routing cache is enabled
bool BrokerSettings::sm_topicRoutingCacheEnabled = true;

// The default delay to apply when the topic routing cache is cleared.
uint32_t BrokerSettings::sm_topicRoutingCacheClearDelay = 30;

// Whether to validate certificates against the connection identifier
bool BrokerSettings::sm_certIdentityValidationEnabled = false;

// Whether to to restrict the fabric to a single instance of each unique client identifier
bool BrokerSettings::sm_uniqueClientIdPerFabricEnabled = false;

// Whether test mode is enabled
bool BrokerSettings::sm_testModeEnabled = false;

// The default brokerLib thread pool size
uint32_t BrokerSettings::sm_brokerLibThreadPoolSize = 1;

// The default multi-tenant mode
bool BrokerSettings::sm_multiTenantModeEnabled = false;

// The tenant byte limit
uint32_t BrokerSettings::sm_tenantByteLimit = 0;

// The tenant connection limit
uint32_t BrokerSettings::sm_tenantConnectionLimit = 0;

// Whether to send events when clients connect/disconnect
bool BrokerSettings::sm_sendConnectEvents = false;

// WHether the broker has been initialized
bool BrokerSettings::sm_brokerInitialized = false;

/**
 * Normalizes slashes for the current platform
 *
 * @param    str The string to normalize
 */
static void normalizePath( string& str )
{
    boost::replace_all(str, "\\", "/");
}

/** {@inheritDoc} */
const char* BrokerSettings::getGuid( bool throwException )
{
    if( sm_guid.empty() )
    {
        if( throwException )
        {
            throw runtime_error( "Broker identifier has not been set" );
        }
        else
        {
            return NULL;
        }
    }

    return sm_guid.c_str();
}

/** {@inheritDoc} */
const char* BrokerSettings::getTenantGuid( bool throwException )
{
    if( sm_tenantGuid.empty() )
    {
        if( throwException )
        {
            throw runtime_error( "Broker tenant GUID not been set" );
        }
        else
        {
            return NULL;
        }
    }

    return sm_tenantGuid.c_str();
}

/** {@inheritDoc} */
string BrokerSettings::dumpSettings()
{
    stringstream out;
    out << endl;
    out << "BrokerSettings:" << endl;
    out << "\tbrokerVersion: " << BrokerRegistry::getInstance().getLocalBrokerVersion() << endl;
    out << "\tbrokerId: " << getGuid() << endl;
    out << "\tuser: " << getUser() << endl;
    out << "\tbrokerListenPort: " << getListenPort() << endl;
    out << "\tmessageSizeLimit: " << getMessageSizeLimit() << endl;
    out << "\tlogFilePath: " << getLogFilePath() << endl;
    out << "\tlogFileMaxSize: " << getLogFileMaxSize() << endl;
    out << "\tlogFileMaxCount: " << getLogFileMaxCount() << endl;
    out << "\tlogUseStdOut: " << ( isStdOutLoggingEnabled() ? "true" : "false" ) << endl;
    out << "\tlogLevel: " << getLogLevel() << endl;
    out << "\tlogNotices: " << ( isNoticeLoggingEnabled() ? "true" : "false" ) << endl;
    out << "\tpolicyGeneralStateFile: " << getPolicyGeneralStateFile() << endl;
    out << "\tpolicyBrokerStateFile: " << getPolicyBrokerStateFile() << endl;
    out << "\tpolicyTopicAuthStateFile: " << getPolicyTopicAuthStateFile() << endl;
    out << "\tbrokerTtl (Mins): " << getBrokerTtlMins() << endl;
    out << "\tttlCheckInterval (Mins): " << getTtlCheckIntervalMins() << endl;
    out << "\tttlGracePeriod (Mins): " << getTtlGracePeriodMins() << endl;
    out << "\tjsonPrettyPrint: " << ( isJsonPrettyPrintEnabled() ? "true" : "false" ) << endl;
    out << "\ttlsEnabled: " << ( isTlsEnabled() ? "true" : "false" ) << endl;
    out << "\ttlsBridgingInsecure: " << ( isTlsBridgingInsecure() ? "true" : "false" ) << endl;
    out << "\tfipsEnabled: " << ( isFipsEnabled() ? "true" : "false" ) << endl;
    out << "\tcertKeyStoreDir: " << getCertKeystoreDir() << endl;
    out << "\tbrokerCertChainFile: " << getBrokerCertChainFile() << endl;
    out << "\tbrokerCertFile: " << getBrokerCertFile() << endl;
    out << "\tbrokerCsrFile: " << getBrokerCsrFile() << endl;
    out << "\tbrokerPrivateKeyFile: " << getBrokerPrivateKeyFile() << endl;
    out << "\tclientCertChainFile: " << getClientCertChainFile() << endl;
    out << "\trevokedCertsFile: " << getRevokedCertsFile() << endl;
    out << "\tbrokerCertsListFile: " << getBrokerCertsListFile() << endl;
    out << "\tciphers: " << getCiphers() << endl;
    out << "\tmessageSample (Secs): " << getMessageSampleSecs() << endl;
    out << "\tmaximumPacketBufferSize: " << getMaxPacketBufferSize() << endl;
    out << "\tisConnectionLimitIgnored: " << ( isConnectionLimitIgnored() ? "true" : "false" ) << endl;
    out << "\tbrokerStateTopicsCharsBatchSize: " << getBrokerStateTopicsCharsBatchSize() << endl;
    out << "\ttopicRoutingEnabled: " << ( isTopicRoutingEnabled() ? "true" : "false" ) << endl;
    out << "\ttopicRoutingCacheEnabled: " << ( isTopicRoutingCacheEnabled() ? "true" : "false" ) << endl;
    out << "\ttopicRoutingCacheClearDelay: " << getTopicRoutingCacheClearDelay() << endl;
    out << "\ttestModeEnabled: " << ( isTestModeEnabled() ? "true" : "false" ) << endl;
    out << "\tcertIdentityValidationEnabled: " << ( isCertIdentityValidationEnabled() ? "true" : "false" ) << endl;
    out << "\tuniqueClientIdPerFabricEnabled: " << ( isUniqueClientIdPerFabricEnabled() ? "true" : "false" ) << endl;
    out << "\tbrokerLibThreadPoolSize: " << getBrokerLibThreadPoolSize() << endl;
    out << "\tmultiTenantModeEnabled: " << ( isMultiTenantModeEnabled() ? "true" : "false" ) << endl;
    out << "\tsendConnectEvents: " << ( isSendConnectEventsEnabled() ? "true" : "false" ) << endl;
    if( isMultiTenantModeEnabled() )
    {
        out << "\ttenantByteLimit: " << getTenantByteLimit() << endl;
        out << "\ttenantConnectionLimit: " << getTenantConnectionLimit() << endl;
    }
    out << endl;

    return out.str();
}

/** {@inheritDoc} */
void BrokerSettings::setValuesFromConfig( const Configuration& config )
{
    string strValue;

    // Broker identifier
    config.getProperty( "brokerId", sm_guid, "" );

    // Logging
    config.getProperty( "logFile", sm_logFilePath, "./dxlbroker.log" );
    normalizePath( sm_logFilePath );
    config.getProperty( "maxLogSize", strValue, "1000000" );
    sm_logFileMaxSize = atoi( strValue.c_str()) ;
    config.getProperty( "maxLogFiles", strValue, "10" );
    sm_logFileMaxCount = atoi( strValue.c_str() );
    config.getProperty("stdOutLogger", strValue, "false");
    sm_logUseStdOut = ( strValue == "true" );
    config.getProperty("logLevel", sm_logLevel, "warn");
    config.getProperty("logNotices", strValue, "false");
    sm_noticeLoggingEnabled = ( strValue == "true" );

    // Listener port
    config.getProperty("listenPort", strValue, "8883");
    sm_listenPort = atoi( strValue.c_str() );

    // Message size limit
    config.getProperty("messageSizeLimit", strValue, "1048576");
    sm_messageSizeLimit = atoi( strValue.c_str() );

    // User
    config.getProperty("user", sm_user, "");

    // Policy state files
    config.getProperty( "policyGeneralStateFile", sm_policyGeneralStateFile, POLICYGENERALSTATE_LOC );
    normalizePath( sm_policyGeneralStateFile );
    config.getProperty( "policyBrokerStateFile", sm_policyBrokerStateFile, POLICYBROKERSTATE_LOC );
    normalizePath( sm_policyBrokerStateFile );
    config.getProperty( "policyTopicAuthStateFile", sm_policyTopicAuthStateFile, TOPICAUTHSTATE_LOC );
    normalizePath( sm_policyTopicAuthStateFile );

    // Broker TTL
    config.getProperty( "brokerTtlMins", strValue, "60" );
    sm_brokerTtl = atoi( strValue.c_str() );

    // TTL check interval
    config.getProperty( "ttlCheckIntervalMins", strValue, "10" );
    sm_ttlInterval = atoi( strValue.c_str() );

    // TTL grace period
    config.getProperty( "ttlGraceMins", strValue, "5" );
    sm_ttlGracePeriod = atoi( strValue.c_str() );

    // JSON pretty print
    config.getProperty( "jsonPrettyPrint", strValue, "false" );
    sm_jsonPrettyPrint = ( strValue == "true" );

    // Certificates
    config.getProperty( "tlsEnabled", strValue, "true" );
    sm_tlsEnabled = ( strValue == "true" );
    config.getProperty( "tlsBridgingInsecure", strValue, "true" );
    sm_tlsBridgingInsecure = ( strValue == "true" );
    config.getProperty( "fipsEnabled", strValue, "false" );
    sm_fipsEnabled = ( strValue == "true" );
    config.getProperty( "certKeystoreDir", sm_certKeyStoreDir, "/var/McAfee/dxlbroker/keystore" );
    normalizePath( sm_certKeyStoreDir );
    sm_certBrokerCertChainFile = sm_certKeyStoreDir + "/ca-broker.crt";
    normalizePath( sm_certBrokerCertChainFile );
    sm_certClientCertChainFile = sm_certKeyStoreDir + "/ca-client.crt";
    normalizePath( sm_certClientCertChainFile );
    sm_certBrokerCertFile = sm_certKeyStoreDir + "/broker.crt";
    normalizePath( sm_certBrokerCertFile );
    sm_certClientCertFile = sm_certKeyStoreDir + "/client.crt";
    normalizePath( sm_certClientCertFile );
    sm_certBrokerCsrFile = sm_certKeyStoreDir + "/broker.csr";
    normalizePath( sm_certBrokerCsrFile );
    sm_certClientCsrFile = sm_certKeyStoreDir + "/client.csr";
    normalizePath( sm_certClientCsrFile );
    sm_certBrokerPrivateKeyFile = sm_certKeyStoreDir + "/broker.key";
    normalizePath( sm_certBrokerPrivateKeyFile );
    sm_certClientPrivateKeyFile = sm_certKeyStoreDir +  "/client.key";
    normalizePath( sm_certClientPrivateKeyFile );
    sm_revokedCertsFile = sm_certKeyStoreDir + "/revokedcerts.lst";
    normalizePath( sm_revokedCertsFile );
    sm_brokerCertsListFile = sm_certKeyStoreDir + "/ca-brokers.lst";
    normalizePath( sm_brokerCertsListFile );

    config.getProperty( "certSigningRetryIntervalMins", strValue, "5" );
    sm_certSignRetryMins = atoi( strValue.c_str() );

    // Ciphers
    config.getProperty( "ciphers", sm_ciphers, "" );

    // Message sample secs
    config.getProperty( "messageSampleSecs", strValue, "60" );
    sm_messageSampleSecs = atoi( strValue.c_str() );

    // Ignore connection limit
    config.getProperty( "ignoreConnectionLimit", strValue, "false" );
    sm_ignoreConnectionLimit = ( strValue == "true" );

    // The maximum size of the packet buffer in (per context)
    config.getProperty( "maximumPacketBufferSize", strValue, "500000" );
    sm_maxPacketBufferSize = std::stoull( strValue.c_str() );

    // The approximate broker state topics batch size (in terms of character count).
    config.getProperty( "brokerStateTopicsCharsBatchSize", strValue, "2048" );
    sm_brokerStateTopicsCharsBatchSize = atoi( strValue.c_str() );

    // Whether topic routing is enabled
    config.getProperty( "topicRoutingEnabled", strValue, "true" );
    sm_topicRoutingEnabled = ( strValue == "true" );

    // Whether the topic routing cache is enabled
    config.getProperty( "topicRoutingCacheEnabled", strValue, "true" );
    sm_topicRoutingCacheEnabled = ( strValue == "true" );

    // The topic routing cache clear delay
    config.getProperty( "topicRoutingCacheClearDelay", strValue, "30" );
    sm_topicRoutingCacheClearDelay = atoi( strValue.c_str() );

    // Whether to validate certificates against the connection identifier
    config.getProperty( "certIdentityValidationEnabled", strValue, "false" );
    sm_certIdentityValidationEnabled = ( strValue == "true" );

    // Whether to restrict the fabric to a single instance of each unique client identifier
    config.getProperty( "uniqueClientIdPerFabricEnabled", strValue, "false" );
    sm_uniqueClientIdPerFabricEnabled = ( strValue == "true" );

    // Whether test mode is enabled
    config.getProperty( "testModeEnabled", strValue, "true" );
    sm_testModeEnabled = ( strValue == "true" );

    // The brokerLib thread pool size
    config.getProperty( "brokerLibThreadPoolSize", strValue, "1" );
    sm_brokerLibThreadPoolSize = atoi( strValue.c_str() );

    // Whether multi-tenant mode is enabled
    config.getProperty( "multiTenantModeEnabled", strValue, "false" );
    sm_multiTenantModeEnabled = ( strValue == "true" );

    // Tenant identifier
    if ( sm_multiTenantModeEnabled )
    {
        config.getProperty( "tenantGuid", sm_tenantGuid, "" );
    }

    // Tenant byte limit
    config.getProperty( "tenantByteLimit", strValue, "0" );
    sm_tenantByteLimit = atol( strValue.c_str() );

    // Tenant connection limit
    config.getProperty( "tenantConnectionLimit", strValue, "0" );
    sm_tenantConnectionLimit = atol( strValue.c_str() );

    // Whether to send events when clients connect/disconnect
    config.getProperty( "sendConnectEvents", strValue, "false" );
    sm_sendConnectEvents = ( strValue == "true" );
}

max_stars_repo_name: ndcolter-mcafee/opendxl-broker

max_issues_repo_name: ndcolter-mcafee/opendxl-broker

max_forks_repo_name: ndcolter-mcafee/opendxl-broker


text:
#include <boost/python.hpp>

#include "../../src/chemist/molecule.h"
#include "../../src/algorithms/floydwarshall.h"

using Helium::Chemist::Molecule;
using namespace boost::python;

Helium::DistanceMatrix* floyd_warshall(const Molecule &mol)
{
  return new Helium::DistanceMatrix(Helium::floyd_warshall(mol));
}

void export_floyd_warshall()
{

  def("floyd_warshall", &floyd_warshall, return_value_policy<manage_new_object>());

}

ext: cpp

max_stars_repo_name: timvdm/Helium

max_issues_repo_name: timvdm/Helium

max_forks_repo_name: timvdm/Helium


text:
/*
 * Copyright (C) 2018 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#include <cassert>
#include <iostream>
#include <set>

#include "plugins/robot.hh"

#include <ignition/common/SystemPaths.hh>
#include <ignition/plugin/SpecializedPluginPtr.hh>
#include <ignition/plugin/Loader.hh>

#ifdef HAVE_BOOST_PROGRAM_OPTIONS
#include <boost/program_options.hpp>
namespace bpo = boost::program_options;
#endif

/////////////////////////////////////////////////
// The macro that this uses is provided as a compile definition in the
// examples/CMakeLists.txt file.
const std::string PluginLibDir = IGN_PLUGIN_EXAMPLES_LIBDIR;

/////////////////////////////////////////////////
using namespace ignition::plugin::examples;

/////////////////////////////////////////////////
using RobotPluginPtr = ignition::plugin::SpecializedPluginPtr<
    Drive, ProximitySensor, GPSSensor, Compass, MapDatabase>;

/////////////////////////////////////////////////
using EnvironmentPluginPtr =
    ignition::plugin::SpecializedPluginPtr<Environment>;

using PointPair = std::pair<ignition::math::Vector2d, ignition::math::Vector2d>;

/////////////////////////////////////////////////
using IntersectionResult = std::pair<bool, ignition::math::Vector2d>;

/////////////////////////////////////////////////
const IntersectionResult NoIntersection =
    std::make_pair(false, ignition::math::Vector2d());

/////////////////////////////////////////////////
IntersectionResult CheckIntersection(
    const PointPair &_points,
    const Wall &_wall)
{
  std::array<double,2> A;
  std::array<double,2> B;
  std::array<double,2> C;

  std::size_t i = 0;
  for (const PointPair &p : {_points, _wall})
  {
    A[i] = p.second.Y() - p.first.Y();
    B[i] = p.second.X() - p.first.X();
    C[i] = A[i]*p.first.X() + B[i]*p.first.Y();
    ++i;
  }

  const double det = A[0]*B[1] - A[1]*B[0];
  if (std::abs(det) < 1e-10)
  {
    // Lines are parallel
    return NoIntersection;
  }

  const double x = (B[1]*C[0] - B[0]*C[1])/det;
  const double y = (A[0]*C[1] - A[1]*C[0])/det;

  for (const PointPair &p : {_points, _wall})
  {
    if (x < std::min(p.first.X(), p.second.X()))
      return NoIntersection;

    if (std::max(p.first.X(), p.second.X() ) < x)
      return NoIntersection;
  }

  return std::make_pair(true, ignition::math::Vector2d(x,y));
}

/////////////////////////////////////////////////
IntersectionResult CheckCollisions(
    const ignition::math::Vector2d &_x1,
    const ignition::math::Vector2d &_x0,
    const Layout &_layout)
{
  PointPair points = std::make_pair(_x1, _x0);

  for (const Wall &wall : _layout)
  {
    const IntersectionResult result = CheckIntersection(points, wall);
    if (result.first)
      return result;
  }

  return NoIntersection;
}

/////////////////////////////////////////////////
void Simulate(const EnvironmentPluginPtr &_environment,
              const RobotPluginPtr &_robot,
              const double _duration,
              const bool _printState)
{
  Environment *env = _environment->QueryInterface<Environment>();
  assert(env && "Environment interface is missing!");

  const Drive *drive = _robot->QueryInterface<Drive>();
  assert(drive && "The robot cannot drive!");

  // Get the layout from the environment.
  const Layout &layout = env->GenerateLayout();

  // If the robot has a MapUplink interface, send it the layout of the
  // environment.
  if (MapDatabase *uplink = _robot->QueryInterface<MapDatabase>())
    uplink->ReadMap(layout);

  double time = 0.0;
  ignition::math::Vector2d x;
  double theta = 0.0;

  while (time < _duration)
  {
    // Update the proximity sensor.
    if (ProximitySensor *proximity = _robot->QueryInterface<ProximitySensor>())
    {
      const double range = proximity->MaxRange();
      const ignition::math::Vector2d x_far = x + ignition::math::Vector2d(
            range*cos(theta), range*sin(theta));
      IntersectionResult result = CheckCollisions(x, x_far, layout);

      if (result.first)
      {
        proximity->ReadProximity( (x-result.second).Length() );
      }
      else
      {
        proximity->ReadProximity(std::numeric_limits<double>::infinity());
      }
    }

    // Update the GPS sensor
    if (GPSSensor *gps = _robot->QueryInterface<GPSSensor>())
    {
      gps->ReadGPS(x);
    }

    // Update the compass sensor
    if (Compass *compass = _robot->QueryInterface<Compass>())
    {
      compass->ReadCompass(theta);
    }

    // Save the last state
    ignition::math::Vector2d x_last = x;

    // Get the driving information
    const double dt = 1.0/drive->Frequency();
    const ignition::math::Vector3d &vel = drive->Velocity();

    // We integrate the position components with a half-step taken in the angle,
    // which should smooth out the behavior of sharp turns.
    const double halfAngle = theta + 0.5*vel[2]*dt;
    const double dx = vel[0]*cos(halfAngle)*dt + vel[1]*sin(halfAngle)*dt;
    const double dy = - vel[0]*sin(halfAngle)*dt + vel[1]*cos(halfAngle)*dt;

    x[0] += dx;
    x[1] += dy;
    theta += vel[2]*dt;

    const IntersectionResult collision = CheckCollisions(x, x_last, layout);
    if (collision.first)
    {
      std::cout << "The robot has crashed at ("
                << collision.second.X() << "m, "
                << collision.second.Y() << "m)! Time: "
                << time << "s  |==|  Velocity output: "
                << vel << "\n" << std::endl;

      x[0] = collision.second.X();
      x[1] = collision.second.Y();

      break;
    }

    time += dt;

    if (_printState)
    {
      std::cout << "Location: (" << x[0] << "m, " << x[1] << "m) | Yaw: "
                << 180.0*theta/M_PI << "-degrees | Time: " << time
                << "s  |==|  Velocity output: " << vel << std::endl;
    }
  }

  std::cout << "The simulation has finished (time: " << time << "s).\n"
            << " -- Final robot location: (" << x[0] << "m, " << x[1] << "m)\n"
            << " -- Yaw: " << 180.0*theta/M_PI << "-degrees\n" << std::endl;
}

/////////////////////////////////////////////////
int main(int argc, char *argv[])
{
  // Create an object that can search the system paths for the plugin libraries.
  ignition::common::SystemPaths paths;

  // Create a plugin loader
  ignition::plugin::Loader loader;

  // Add the build directory path for the plugin libraries so the SystemPaths
  // object will know to search through it.
  paths.AddPluginPaths(PluginLibDir);

  std::vector<std::string> knownRobotPlugins = { "CrashBot", "CautiousBot" };
  std::vector<std::string> knownEnvPlugins = { "BoxEnvironment" };

  std::string robotLib = knownRobotPlugins.front();
  std::string envLib = knownEnvPlugins.front();
  double duration = 300;
  bool printState = false;

#ifdef HAVE_BOOST_PROGRAM_OPTIONS

  std::string knownRobotString;
  for (const std::string &r : knownRobotPlugins)
    knownRobotString += r + "  ";

  std::string knownEnvString;
  for (const std::string &e : knownEnvPlugins)
    knownEnvString += e + "  ";

  std::string usage;
  usage +=
      "The 'robot' example creates a very simple 2D kinematic simulation of a\n"
      "robot, provided by a plugin, within an environment, also provided by a\n"
      "plugin. The robot may have any combination of several sensors, defined\n"
      "in plugins/robot.hh.\n\n"

      "Known robot plugin libraries include:  " + knownRobotString + "\n\n"

      "Known environment plugin libraries include:  " + knownEnvString + "\n\n"

      "Custom plugins can be used by passing in the custom plugin library\n"
      "directory to the -I flag";

  bpo::options_description desc(usage);
  desc.add_options()

      ("help,h", "Print this usage message")

      ("robot,r", bpo::value<std::string>(&robotLib),
       std::string("Robot plugin library (default: "+robotLib+")").c_str())

      ("environment,e", bpo::value<std::string>(&envLib),
       std::string("Environment plugin library (default: "+envLib+")").c_str())

      ("include-dirs,I", bpo::value<std::vector<std::string>>()->multitoken(),
       "Additional directories that may contain plugin libraries")

      ("duration,t", bpo::value<double>(&duration),
       std::string("How many seconds of simulation time to run for (default: "
                   +std::to_string(duration)+")").c_str())

      ("print,p", "Print out the state during each iteration")
      ;

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

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

  if (vm.count("print") > 0)
  {
    printState = true;
  }

  if (vm.count("include-dirs"))
  {
    const std::vector<std::string> inputDirs =
        vm["include-dirs"].as<std::vector<std::string>>();

    for (const std::string &dir : inputDirs)
    {
      std::cout << "Including additional plugin directory: ["
                << dir << "]" << std::endl;
      paths.AddPluginPaths(dir);
    }
  }

#else

  std::cout << "boost::program_options was not found when this example was\n"
            << "compiled, so we will default to:\n"
            << " -- Robot:       " << robotLib <<"\n"
            << " -- Environment: " << envLib << "\n"
            << " -- Duration:    " << duration << "\n"
            << std::endl;

#endif

  std::unordered_set<std::string> robotPlugins = loader.LoadLib(
        paths.FindSharedLibrary(robotLib));

  std::unordered_set<std::string> drivePlugins =
      loader.PluginsImplementing("ignition::plugin::examples::Drive");

  RobotPluginPtr robot;
  // Get the first plugin from the robotLib library that provides a Drive
  // interface
  for (const std::string &plugin : robotPlugins)
  {
    if (drivePlugins.find(plugin) != drivePlugins.end())
    {
      robot = loader.Instantiate(plugin);
      break;
    }
  }

  if (robot.IsEmpty())
  {
    std::cerr << "The plugin library specified for the robot does not provide "
              << "a Drive interface, which is required for the robot to work.\n"
              << std::endl;
    return 2;
  }

  std::unordered_set<std::string> envPlugins = loader.LoadLib(
        paths.FindSharedLibrary(envLib));

  std::unordered_set<std::string> envInterfacePlugins =
      loader.PluginsImplementing("ignition::plugin::examples::Environment");

  EnvironmentPluginPtr environment;
  // Get the first plugin from the envLib library that provides an Environment
  // interface.
  for (const std::string &plugin : envPlugins)
  {
    if (envInterfacePlugins.find(plugin) != envInterfacePlugins.end())
    {
      environment = loader.Instantiate(plugin);
      break;
    }
  }

  if (environment.IsEmpty())
  {
    std::cerr << "The plugin library specified for the environment does not "
              << "provide an Environment interface, which is required for the "
              << "environment to be generated.\n" << std::endl;
    return 3;
  }

  Simulate(environment, robot, duration, printState);
}

ext: cc

max_stars_repo_name: scpeters-test/ign-plugin

max_issues_repo_name: scpeters-test/ign-plugin

max_forks_repo_name: scpeters-test/ign-plugin


text:
//头文件
#include <ros/ros.h>
#include <boost/format.hpp>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "swarm_control_utils.h"
#include "message_utils.h"

using namespace std;
//参数声明
int swarm_num;
const int max_swarm_num = 8; // indicate max num
string uav_name[max_swarm_num+1];
int uav_id[max_swarm_num+1];
prometheus_msgs::DroneState State_uav[max_swarm_num+1];
prometheus_msgs::SwarmCommand Command_uav[max_swarm_num+1];
geometry_msgs::PoseStamped ref_pose_uav[max_swarm_num+1];
ros::Subscriber command_sub[max_swarm_num+1];
ros::Subscriber drone_state_sub[max_swarm_num+1];
ros::Subscriber message_sub[max_swarm_num+1];
char *servInetAddr = "127.0.0.1"; //sever ip
string data;
char sendline[1024];
int socketfd;
struct sockaddr_in sockaddr;

//函数声明
void swarm_command_cb_1(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[1] = *msg; }
void swarm_command_cb_2(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[2] = *msg; }
void swarm_command_cb_3(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[3] = *msg; }
void swarm_command_cb_4(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[4] = *msg; }
void swarm_command_cb_5(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[5] = *msg; }
void swarm_command_cb_6(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[6] = *msg; }
void swarm_command_cb_7(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[7] = *msg; }
void swarm_command_cb_8(const prometheus_msgs::SwarmCommand::ConstPtr& msg) { Command_uav[8] = *msg; }
void (*swarm_command_cb[max_swarm_num+1])(const prometheus_msgs::SwarmCommand::ConstPtr&)={NULL,swarm_command_cb_1,
    swarm_command_cb_2,swarm_command_cb_3,swarm_command_cb_4,swarm_command_cb_5,swarm_command_cb_6,swarm_command_cb_7,swarm_command_cb_8};

void drone_state_cb1(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[1] = *msg; }
void drone_state_cb2(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[2] = *msg; }
void drone_state_cb3(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[3] = *msg; }
void drone_state_cb4(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[4] = *msg; }
void drone_state_cb5(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[5] = *msg; }
void drone_state_cb6(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[6] = *msg; }
void drone_state_cb7(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[7] = *msg; }
void drone_state_cb8(const prometheus_msgs::DroneState::ConstPtr& msg) { State_uav[8] = *msg; }
void (*drone_state_cb[max_swarm_num+1])(const prometheus_msgs::DroneState::ConstPtr&)={NULL,drone_state_cb1,drone_state_cb2,
    drone_state_cb3,drone_state_cb4,drone_state_cb5,drone_state_cb6,drone_state_cb7,drone_state_cb8};

void msg_cb(const prometheus_msgs::Message::ConstPtr& msg)
{
    prometheus_msgs::Message message = *msg;
    printf_message(message);
    sleep(0.2);
}

//主函数
int main(int argc, char **argv)
{
    ros::init(argc, argv, "swarm_ground_station");
    ros::NodeHandle nh("~");

    nh.param<int>("swarm_num", swarm_num, 1);
    for(int i = 1; i <= swarm_num; i++)
    {
        // 设置无人机名字，none代表无
        boost::format fmt1("uav%d_name");
        nh.param<string>((fmt1%(i)).str(), uav_name[i], "/none");
        boost::format fmt2("uav%d_id");
        nh.param<int>((fmt2%(i)).str(), uav_id[i], 0);
        // 订阅
        command_sub[i] = nh.subscribe<prometheus_msgs::SwarmCommand>(uav_name[i] + "/prometheus/swarm_command", 10, swarm_command_cb[i]);
        cout << uav_name[i] + "/prometheus/swarm_command" << endl;
        drone_state_sub[i] = nh.subscribe<prometheus_msgs::DroneState>(uav_name[i] + "/prometheus/drone_state", 10, drone_state_cb[i]);
        message_sub[i] = nh.subscribe<prometheus_msgs::Message>(uav_name[i] + "/prometheus/message/main", 100, msg_cb);
    }

    boost::format fmt3("uav%d,%f,%f,%f,%f,%f,%f,%f,%f,%f");
    while(ros::ok())
    {
        ros::spinOnce();
        cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>> Formation Flight Station <<<<<<<<<<<<<<<<<<<<<<<<< "<< endl;
        for(int i = 1; i <= swarm_num; i++)
        {
            if(uav_id[i] != 0)
            {
                swarm_control_utils::printf_swarm_state(swarm_num, uav_id[i], uav_name[i], State_uav[i], Command_uav[i]);
            }
            printf("send message to server: ");
            data = (fmt3%(i)%(State_uav[i].position[0])%(State_uav[i].position[1])%State_uav[i].position[2]%
                (State_uav[i].velocity[0])%(State_uav[i].velocity[1])%(State_uav[i].velocity[2])%
                (State_uav[i].attitude[0])%(State_uav[i].attitude[1])%(State_uav[i].attitude[2])).str();
            cout << data << endl;
            strcpy(sendline,data.c_str());
            //send by socket
            socketfd = socket(AF_INET,SOCK_STREAM,0);
            memset(&sockaddr,0,sizeof(sockaddr));
            sockaddr.sin_family = AF_INET;
            sockaddr.sin_port = htons(10004);
            inet_pton(AF_INET,servInetAddr,&sockaddr.sin_addr);
            if((connect(socketfd,(struct sockaddr*)&sockaddr,sizeof(sockaddr))) < 0 ) {
                printf("connect error %s errno: %d\n",strerror(errno),errno);
                printf("client connect failed!\n");
            }
            if((send(socketfd,sendline,strlen(sendline),0)) < 0)
            {
                printf("send mes error: %s errno : %d\n",strerror(errno),errno);
                printf("client send failed!\n");
            }
            close(socketfd);
        }
        sleep(2.0); // frequence
    }
    return 0;
}

max_stars_repo_name: SYSU-Unmaned-System-Team/Kongdijqun

max_issues_repo_name: SYSU-Unmaned-System-Team/Kongdijqun

max_forks_repo_name: SYSU-Unmaned-System-Team/Kongdijiqun


text:
#include "pso.h"

#include <Eigen/StdVector>

template <
  typename Scalar,
  typename DerivedX,
  typename DerivedLB,
  typename DerivedUB>
IGL_INLINE Scalar igl::pso(
  const std::function< Scalar (DerivedX &) > f,
  const Eigen::MatrixBase<DerivedLB> & LB,
  const Eigen::MatrixBase<DerivedUB> & UB,
  const int max_iters,
  const int population,
  DerivedX & X)
{
  const Eigen::Array<bool,Eigen::Dynamic,1> P =
    Eigen::Array<bool,Eigen::Dynamic,1>::Zero(LB.size(),1);
  return igl::pso(f,LB,UB,P,max_iters,population,X);
}

template <
  typename Scalar,
  typename DerivedX,
  typename DerivedLB,
  typename DerivedUB,
  typename DerivedP>
IGL_INLINE Scalar igl::pso(
  const std::function< Scalar (DerivedX &) > f,
  const Eigen::MatrixBase<DerivedLB> & LB,
  const Eigen::MatrixBase<DerivedUB> & UB,
  const Eigen::DenseBase<DerivedP> & P,
  const int max_iters,
  const int population,
  DerivedX & X)
{
  const int dim = LB.size();
  assert(UB.size() == dim && "UB should match LB size");
  assert(P.size() == dim && "P should match LB size");
  typedef std::vector<DerivedX,Eigen::aligned_allocator<DerivedX> > VectorList;
  VectorList position(population);
  VectorList best_position(population);
  VectorList velocity(population);
  Eigen::Matrix<Scalar,Eigen::Dynamic,1> best_f(population);
  // https://en.wikipedia.org/wiki/Particle_swarm_optimization#Algorithm
  //
  // g → X
  // p_i → best[i]
  // v_i → velocity[i]
  // x_i → position[i]
  Scalar min_f = std::numeric_limits<Scalar>::max();
  for(int p=0;p<population;p++)
  {
    {
      const DerivedX R = DerivedX::Random(dim).array()*0.5+0.5;
      position[p] = LB.array() + R.array()*(UB-LB).array();
    }
    best_f[p] = f(position[p]);
    best_position[p] = position[p];
    if(best_f[p] < min_f)
    {
      min_f = best_f[p];
      X = best_position[p];
    }
    {
      const DerivedX R = DerivedX::Random(dim);
      velocity[p] = (UB-LB).array() * R.array();
    }
  }

  int iter = 0;
  Scalar omega = 0.98;
  Scalar phi_p = 0.01;
  Scalar phi_g = 0.01;
  while(true)
  {
    //if(iter % 10 == 0)
    //{
    //  std::cout<<iter<<":"<<std::endl;
    //  for(int p=0;p<population;p++)
    //  {
    //    std::cout<<"  "<<best_f[p]<<", "<<best_position[p]<<std::endl;
    //  }
    //  std::cout<<std::endl;
    //}

    for(int p=0;p<population;p++)
    {
      const DerivedX R_p = DerivedX::Random(dim).array()*0.5+0.5;
      const DerivedX R_g = DerivedX::Random(dim).array()*0.5+0.5;
      velocity[p] =
        omega * velocity[p].array() +
        phi_p * R_p.array() *(best_position[p] - position[p]).array() +
        phi_g * R_g.array() *(               X - position[p]).array();
      position[p] += velocity[p];
      // Clamp to bounds
      for(int d = 0;d<dim;d++)
      {
//#define IGL_PSO_REFLECTION
#ifdef IGL_PSO_REFLECTION
        assert(!P(d));
        // Reflect velocities if exceeding bounds
        if(position[p](d) < LB(d))
        {
          position[p](d) = LB(d);
          if(velocity[p](d) < 0.0) velocity[p](d) *= -1.0;
        }
        if(position[p](d) > UB(d))
        {
          position[p](d) = UB(d);
          if(velocity[p](d) > 0.0) velocity[p](d) *= -1.0;
        }
#else
//#warning "trying no bounds on periodic"
//        // TODO: I'm not sure this is the right thing to do/enough. The
//        // velocities could be weird. Suppose the current "best" value is ε and
//        // the value is -ε and the "periodic bounds" [0,2π]. Moding will send
//        // the value to 2π-ε but the "velocity" term will now be huge pointing
//        // all the way from 2π-ε to ε.
//        //
//        // Q: Would it be enough to try (all combinations) of ±(UB-LB) before
//        // computing velocities to "best"s? In the example above, instead of
//        //
//        //     v += best - p = ε - (2π-ε) = -2π+2ε
//        //
//        // you'd use
//        //
//        //     v +=  / argmin  |b - p|            \  - p = (ε+2π)-(2π-ε) = 2ε
//        //          |                              |
//        //           \ b∈{best, best+2π, best-2π} /
//        //
//        // Though, for multivariate b,p,v this would seem to explode
//        // combinatorially.
//        //
//        // Maybe periodic things just shouldn't be bounded and we hope that the
//        // forces toward the current minima "regularize" them away from insane
//        // values.
//        if(P(d))
//        {
//          position[p](d) = std::fmod(position[p](d)-LB(d),UB(d)-LB(d))+LB(d);
//        }else
//        {
//          position[p](d) = std::max(LB(d),std::min(UB(d),position[p](d)));
//        }
        position[p](d) = std::max(LB(d),std::min(UB(d),position[p](d)));
#endif
      }
      const Scalar fp = f(position[p]);
      if(fp<best_f[p])
      {
        best_f[p] = fp;
        best_position[p] = position[p];
        if(best_f[p] < min_f)
        {
          min_f = best_f[p];
          X = best_position[p];
        }
      }
    }
    iter++;
    if(iter>=max_iters)
    {
      break;
    }
  }
  return min_f;
}

#ifdef IGL_STATIC_LIBRARY
template float igl::pso<float, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<float, 1, -1, 1, 1, -1> >(std::function<float (Eigen::Matrix<float, 1, -1, 1, 1, -1>&)>, Eigen::MatrixBase<Eigen::Matrix<float, 1, -1, 1, 1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<float, 1, -1, 1, 1, -1> > const&, int, int, Eigen::Matrix<float, 1, -1, 1, 1, -1>&);
#endif

max_stars_repo_name: RokKos/eol-cloth

max_issues_repo_name: RokKos/eol-cloth

max_forks_repo_name: RokKos/eol-cloth


text:
//=============================================================================================================
/**
* @file     fssurfacetreeitem.cpp
* @author   Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     November, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Lorenz Esch and Matti Hamalainen. All rights reserved.
*
* 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 MNE-CPP authors 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.
*
*
* @brief    FsSurfaceTreeItem class definition.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "fssurfacetreeitem.h"
#include "../common/metatreeitem.h"
#include "../../3dhelpers/renderable3Dentity.h"
#include "../../materials/pervertexphongalphamaterial.h"
#include "../../materials/shownormalsmaterial.h"

#include <fs/label.h>
#include <fs/surface.h>

//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================

#include <QList>
#include <QVariant>
#include <QStringList>
#include <QColor>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QUrl>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace DISP3DLIB;
using namespace Eigen;
using namespace FSLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

FsSurfaceTreeItem::FsSurfaceTreeItem(int iType, const QString& text)
: AbstractTreeItem(iType, text)
, m_sColorInfoOrigin("Color from curvature")
, m_pRenderable3DEntity(new Renderable3DEntity())
, m_pRenderable3DEntityNormals(new Renderable3DEntity())
, m_pItemSurfColGyri(new MetaTreeItem())
, m_pItemSurfColSulci(new MetaTreeItem())
{
    this->setEditable(false);
    this->setCheckable(true);
    this->setCheckState(Qt::Checked);
    this->setToolTip("Freesurfer Surface item");
}

//*************************************************************************************************************

FsSurfaceTreeItem::~FsSurfaceTreeItem()
{
    //Schedule deletion/Decouple of all entities so that the SceneGraph is NOT plotting them anymore.
    if(m_pRenderable3DEntity) {
        m_pRenderable3DEntity->deleteLater();
    }

    if(m_pRenderable3DEntityNormals) {
        m_pRenderable3DEntityNormals->deleteLater();
    }
}

//*************************************************************************************************************

QVariant FsSurfaceTreeItem::data(int role) const
{
    return AbstractTreeItem::data(role);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::setData(const QVariant& value, int role)
{
    AbstractTreeItem::setData(value, role);

    switch(role) {
        case Data3DTreeModelItemRoles::SurfaceCurrentColorVert:
            m_pRenderable3DEntity->getCustomMesh()->setColor(value.value<MatrixX3f>());
            break;

        default: // do nothing;
            break;
    }
}

//*************************************************************************************************************

void FsSurfaceTreeItem::addData(const Surface& tSurface, Qt3DCore::QEntity* parent)
{
    //Create renderable 3D entity
    m_pRenderable3DEntity->setParent(parent);

    //Initial transformation also regarding the surface offset
    m_pRenderable3DEntity->setPosition(QVector3D(-tSurface.offset()(0), -tSurface.offset()(1), -tSurface.offset()(2)));

    //Create color from curvature information with default gyri and sulcus colors
    MatrixX3f matCurvatureColor = createCurvatureVertColor(tSurface.curv());

    //Set renderable 3D entity mesh and color data
    m_pRenderable3DEntity->getCustomMesh()->setMeshData(tSurface.rr(), tSurface.nn(), tSurface.tris(), matCurvatureColor, Qt3DRender::QGeometryRenderer::Triangles);

    //Set shaders
    PerVertexPhongAlphaMaterial* pPerVertexPhongAlphaMaterial = new PerVertexPhongAlphaMaterial();
    m_pRenderable3DEntity->addComponent(pPerVertexPhongAlphaMaterial);

//    //Render normals
//    m_pRenderable3DEntityNormals = new Renderable3DEntity(parent);
//    m_pRenderable3DEntityNormals->setMeshData(tSurface.rr(), tSurface.nn(), tSurface.tris(), arrayCurvatureColor, Qt3DRender::QGeometryRenderer::Triangles);
//    m_pRenderable3DEntityNormals->setPosition(QVector3D(-tSurface.offset()(0), -tSurface.offset()(1), -tSurface.offset()(2)));
//    ShowNormalsMaterial* pShowNormalsMaterial = new ShowNormalsMaterial();
//    m_pRenderable3DEntityNormals->addComponent(pShowNormalsMaterial);

//    //Generate activation overlay surface
//    MatrixX3f overlayAdds = tSurface.rr();
//    for(int i = 0; i<tSurface.nn().rows(); i++) {
//        RowVector3f direction = tSurface.nn().row(i);
//        direction.normalize();

//        overlayAdds.row(i) = direction*0.0001;
//    }

//    m_pRenderable3DEntityNormals->setMeshData(tSurface.rr()+overlayAdds, tSurface.nn(), tSurface.tris(), arrayCurvatureColor);

    //Add data which is held by this FsSurfaceTreeItem
    QVariant data;

    data.setValue(matCurvatureColor);
    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert);
    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurvatureColorVert);

    data.setValue(tSurface.curv());
    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurv);

    //Add surface meta information as item children
    QList<QStandardItem*> list;

    m_pItemSurfColSulci = new MetaTreeItem(MetaTreeItemTypes::SurfaceColorSulci, "Sulci color");
    connect(m_pItemSurfColSulci, &MetaTreeItem::curvColorsChanged,
            this, &FsSurfaceTreeItem::onColorInfoOriginOrCurvColorChanged);
    list << m_pItemSurfColSulci;
    list << new QStandardItem(m_pItemSurfColSulci->toolTip());
    this->appendRow(list);
    data.setValue(QColor(50,50,50));
    m_pItemSurfColSulci->setData(data, MetaTreeItemRoles::SurfaceColorSulci);
    m_pItemSurfColSulci->setData(data, Qt::DecorationRole);

    m_pItemSurfColGyri = new MetaTreeItem(MetaTreeItemTypes::SurfaceColorGyri, "Gyri color");
    connect(m_pItemSurfColGyri, &MetaTreeItem::curvColorsChanged,
            this, &FsSurfaceTreeItem::onColorInfoOriginOrCurvColorChanged);
    list.clear();
    list << m_pItemSurfColGyri;
    list << new QStandardItem(m_pItemSurfColGyri->toolTip());
    this->appendRow(list);
    data.setValue(QColor(125,125,125));
    m_pItemSurfColGyri->setData(data, MetaTreeItemRoles::SurfaceColorGyri);
    m_pItemSurfColGyri->setData(data, Qt::DecorationRole);

    float fAlpha = 0.35f;
    MetaTreeItem *itemAlpha = new MetaTreeItem(MetaTreeItemTypes::SurfaceAlpha, QString("%1").arg(fAlpha));
    connect(itemAlpha, &MetaTreeItem::surfaceAlphaChanged,
            this, &FsSurfaceTreeItem::onSurfaceAlphaChanged);
    list.clear();
    list << itemAlpha;
    list << new QStandardItem(itemAlpha->toolTip());
    this->appendRow(list);
    data.setValue(fAlpha);
    itemAlpha->setData(data, MetaTreeItemRoles::SurfaceAlpha);

//    float fTessInner = 1.0;
//    MetaTreeItem *itemTessInner = new MetaTreeItem(MetaTreeItemTypes::SurfaceTessInner, QString("%1").arg(fTessInner));
//    connect(itemTessInner, &MetaTreeItem::surfaceTessInnerChanged,
//            this, &FsSurfaceTreeItem::onSurfaceTessInnerChanged);
//    list.clear();
//    list << itemTessInner;
//    list << new QStandardItem(itemTessInner->toolTip());
//    this->appendRow(list);
//    data.setValue(fTessInner);
//    itemTessInner->setData(data, MetaTreeItemRoles::SurfaceTessInner);

//    float fTessOuter = 1.0;
//    MetaTreeItem *itemTessOuter = new MetaTreeItem(MetaTreeItemTypes::SurfaceTessOuter, QString("%1").arg(fTessOuter));
//    connect(itemTessOuter, &MetaTreeItem::surfaceTessOuterChanged,
//            this, &FsSurfaceTreeItem::onSurfaceTessOuterChanged);
//    list.clear();
//    list << itemTessOuter;
//    list << new QStandardItem(itemTessOuter->toolTip());
//    this->appendRow(list);
//    data.setValue(fTessOuter);
//    itemTessOuter->setData(data, MetaTreeItemRoles::SurfaceTessOuter);

//    float fTriangleScale = 1.0;
//    MetaTreeItem *itemTriangleScale = new MetaTreeItem(MetaTreeItemTypes::SurfaceTriangleScale, QString("%1").arg(fTriangleScale));
//    connect(itemTriangleScale, &MetaTreeItem::surfaceTriangleScaleChanged,
//            this, &FsSurfaceTreeItem::onSurfaceTriangleScaleChanged);
//    list.clear();
//    list << itemTriangleScale;
//    list << new QStandardItem(itemTriangleScale->toolTip());
//    this->appendRow(list);
//    data.setValue(fTriangleScale);
//    itemTriangleScale->setData(data, MetaTreeItemRoles::SurfaceTriangleScale);

    MetaTreeItem *itemSurfFileName = new MetaTreeItem(MetaTreeItemTypes::FileName, tSurface.fileName());
    itemSurfFileName->setEditable(false);
    list.clear();
    list << itemSurfFileName;
    list << new QStandardItem(itemSurfFileName->toolTip());
    this->appendRow(list);
    data.setValue(tSurface.fileName());
    itemSurfFileName->setData(data, MetaTreeItemRoles::SurfaceFileName);

    MetaTreeItem *itemSurfType = new MetaTreeItem(MetaTreeItemTypes::SurfaceType, tSurface.surf());
    itemSurfType->setEditable(false);
    list.clear();
    list << itemSurfType;
    list << new QStandardItem(itemSurfType->toolTip());
    this->appendRow(list);
    data.setValue(tSurface.surf());
    itemSurfType->setData(data, MetaTreeItemRoles::SurfaceType);

    MetaTreeItem *itemSurfPath = new MetaTreeItem(MetaTreeItemTypes::FilePath, tSurface.filePath());
    itemSurfPath->setEditable(false);
    list.clear();
    list << itemSurfPath;
    list << new QStandardItem(itemSurfPath->toolTip());
    this->appendRow(list);
    data.setValue(tSurface.filePath());
    itemSurfPath->setData(data, MetaTreeItemRoles::SurfaceFilePath);

    MetaTreeItem *itemXTrans = new MetaTreeItem(MetaTreeItemTypes::SurfaceTranslateX, QString::number(tSurface.offset()(0)));
    itemXTrans->setEditable(true);
    connect(itemXTrans, &MetaTreeItem::surfaceTranslationXChanged,
            this, &FsSurfaceTreeItem::onSurfaceTranslationXChanged);
    list.clear();
    list << itemXTrans;
    list << new QStandardItem(itemXTrans->toolTip());
    this->appendRow(list);

    MetaTreeItem *itemYTrans = new MetaTreeItem(MetaTreeItemTypes::SurfaceTranslateY, QString::number(tSurface.offset()(1)));
    itemYTrans->setEditable(true);
    connect(itemYTrans, &MetaTreeItem::surfaceTranslationYChanged,
            this, &FsSurfaceTreeItem::onSurfaceTranslationYChanged);
    list.clear();
    list << itemYTrans;
    list << new QStandardItem(itemYTrans->toolTip());
    this->appendRow(list);

    MetaTreeItem *itemZTrans = new MetaTreeItem(MetaTreeItemTypes::SurfaceTranslateZ, QString::number(tSurface.offset()(2)));
    itemZTrans->setEditable(true);
    connect(itemZTrans, &MetaTreeItem::surfaceTranslationZChanged,
            this, &FsSurfaceTreeItem::onSurfaceTranslationZChanged);
    list.clear();
    list << itemZTrans;
    list << new QStandardItem(itemZTrans->toolTip());
    this->appendRow(list);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::setRtVertColor(const MatrixX3f& sourceColorSamples)
{
    //Set new data.
    //In setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert) we pass the new color values to the renderer (see setData function).
    QVariant data;
    data.setValue(sourceColorSamples);
    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onAnnotationVisibilityChanged(bool isVisible)
{
    if(isVisible) {
        m_sColorInfoOrigin = "Color from annotation";
    } else {
        m_sColorInfoOrigin = "Color from curvature";
    }

    onColorInfoOriginOrCurvColorChanged();
}

//*************************************************************************************************************

void FsSurfaceTreeItem::setVisible(bool state)
{
    m_pRenderable3DEntity->setEnabled(state);
    m_pRenderable3DEntityNormals->setEnabled(state);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onColorInfoOriginOrCurvColorChanged()
{
    if(this->hasChildren()) {
        QVariant data;
        MatrixX3f matNewVertColor;

        if(m_sColorInfoOrigin.contains("Color from curvature")) {
            //Create color from curvature information with default gyri and sulcus colors
            QColor colorSulci = m_pItemSurfColSulci->data(MetaTreeItemRoles::SurfaceColorSulci).value<QColor>();
            QColor colorGyri = m_pItemSurfColGyri->data(MetaTreeItemRoles::SurfaceColorGyri).value<QColor>();

            matNewVertColor = createCurvatureVertColor(this->data(Data3DTreeModelItemRoles::SurfaceCurv).value<VectorXf>(), colorSulci, colorGyri);

            data.setValue(matNewVertColor);
            this->setData(data, Data3DTreeModelItemRoles::SurfaceCurvatureColorVert);
            this->setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert);

            //Emit the new colors which are to be used during rt source loc plotting
            emit colorOriginChanged();

            //Return here because the new colors will be set to the renderable entity in the setData() function with the role Data3DTreeModelItemRoles::SurfaceCurrentColorVert
            return;
        }

        if(m_sColorInfoOrigin.contains("Color from annotation")) {
            //Find the FsAnnotationTreeItem
            for(int i = 0; i < this->QStandardItem::parent()->rowCount(); ++i) {
                if(this->QStandardItem::parent()->child(i,0)->type() == Data3DTreeModelItemTypes::AnnotationItem) {
                    matNewVertColor = this->QStandardItem::parent()->child(i,0)->data(Data3DTreeModelItemRoles::AnnotColors).value<MatrixX3f>();

                    //Set renderable 3D entity mesh and color data
                    data.setValue(matNewVertColor);
                    this->setData(data, Data3DTreeModelItemRoles::SurfaceAnnotationColorVert);
                    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert);

                    //Emit the new colors which are to be used during rt source loc plotting
                    emit colorOriginChanged();

                    //Return here because the new colors will be set to the renderable entity in the setData() function with the role Data3DTreeModelItemRoles::SurfaceCurrentColorVert
                    return;
                }
            }
        }
    }
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceAlphaChanged(float fAlpha)
{
    m_pRenderable3DEntity->setMaterialParameter(fAlpha, "alpha");
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceTessInnerChanged(float fTessInner)
{
    m_pRenderable3DEntity->setMaterialParameter(fTessInner, "innerTess");
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceTessOuterChanged(float fTessOuter)
{
    m_pRenderable3DEntity->setMaterialParameter(fTessOuter, "outerTess");
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceTriangleScaleChanged(float fTriangleScale)
{
    m_pRenderable3DEntity->setMaterialParameter(fTriangleScale, "triangleScale");
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onCheckStateChanged(const Qt::CheckState& checkState)
{
    m_pRenderable3DEntity->setEnabled(checkState == Qt::Unchecked ? false : true);
    m_pRenderable3DEntityNormals->setEnabled(checkState == Qt::Unchecked ? false : true);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceTranslationXChanged(float fTransX)
{
    QVector3D position = m_pRenderable3DEntity->position();
    position.setX(fTransX);
    m_pRenderable3DEntity->setPosition(position);
    m_pRenderable3DEntityNormals->setPosition(position);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceTranslationYChanged(float fTransY)
{
    QVector3D position = m_pRenderable3DEntity->position();
    position.setY(fTransY);
    m_pRenderable3DEntity->setPosition(position);
    m_pRenderable3DEntityNormals->setPosition(position);
}

//*************************************************************************************************************

void FsSurfaceTreeItem::onSurfaceTranslationZChanged(float fTransZ)
{
    QVector3D position = m_pRenderable3DEntity->position();
    position.setZ(fTransZ);
    m_pRenderable3DEntity->setPosition(position);
    m_pRenderable3DEntityNormals->setPosition(position);
}

//*************************************************************************************************************

MatrixX3f FsSurfaceTreeItem::createCurvatureVertColor(const VectorXf& curvature, const QColor& colSulci, const QColor& colGyri)
{
    MatrixX3f colors(curvature.rows(), 3);

    for(int i = 0; i < colors.rows(); ++i) {
        //Color (this is the default color and will be used until the updateVertColor function was called)
        if(curvature[i] >= 0) {
            colors(i,0) = colSulci.redF();
            colors(i,1) = colSulci.greenF();
            colors(i,2) = colSulci.blueF();
        } else {
            colors(i,0) = colGyri.redF();
            colors(i,1) = colGyri.greenF();
            colors(i,2) = colGyri.blueF();
        }
    }

    return colors;
}

max_stars_repo_name: LostSign/mne-cpp

max_issues_repo_name: LostSign/mne-cpp

max_forks_repo_name: LostSign/mne-cpp


text:
#include <boost/program_options.hpp>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <vector>

#include <includes/data_types.h>
#include <includes/transactions.h>
#include "benchmark_common.h"

/*
 * Client that measures latency of reactive transactions with and without client-side caching
 */

namespace po = boost::program_options;
using namespace diamond;

DString dstr;
std::mutex m;
std::condition_variable cv;
bool receivedNotification = false;

int main(int argc, char ** argv) {
    std::string configPrefix;
    int numSeconds = 10;
    bool caching = false;

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("config", po::value<std::string>(&configPrefix)->required(), "frontend config file prefix (required)")
        ("caching", po::bool_switch(&caching), "enable caching (disabled by default)")
        ("time", po::value<int>(&numSeconds), "number of seconds to run (default 10)")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    if (vm.count("help") || !vm.count("config")) {
        std::cout << desc << std::endl;
        return 1;
    }
    po::notify(vm);

    DiamondInit(configPrefix, 1, 0);
    StartTxnManager();
    initRand();
    DObject::SetCaching(caching);

    std::string key = getRandomKey();
    DObject::Map(dstr, key);

    uint64_t reactive_id = reactive_txn([] () {
        std::string temp = dstr.Value();
        std::unique_lock<std::mutex> lock(m);
        receivedNotification = true;
        cv.notify_all();
    });

    std::cout << "prev-end-time\tend-time\tcommitted" << std::endl;

    bool done = false;
    uint64_t globalStartTime = currentTimeMillis();
    uint64_t prevEndTime = globalStartTime;
    while (!done) {
        while (!receivedNotification) {
            // wait for notification to run next interactive transaction
            std::unique_lock<std::mutex> lock(m);
            cv.wait(lock);
        }
        receivedNotification = false;

        DObject::TransactionBegin();
        dstr.Set(std::to_string(prevEndTime));
        int committed = DObject::TransactionCommit();

        uint64_t endTime = currentTimeMillis();

        std::cout << prevEndTime << "\t" << endTime << "\t" << committed << std::endl;

        prevEndTime = endTime;

        if (endTime - globalStartTime > numSeconds * 1000) {
            done = true;
        }
    }

    // sleep to catch the last notification from the frontend (to prevent the frontend from segfaulting)
    sleep(5);
}

max_stars_repo_name: UWSysLab/diamond

max_issues_repo_name: UWSysLab/diamond

max_forks_repo_name: UWSysLab/diamond


text:
#pragma once

#include <logos/wallet_server/client/callback_manager.hpp>

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>

class WalletServerClient : public CallbackManager
{

    using Service  = boost::asio::io_service;
    using Endpoint = boost::asio::ip::tcp::endpoint;
    using Handle   = wallet_server::client::callback::Handle;

public:

    WalletServerClient(const Endpoint & callback_endpoint,
                       Service & service);

    void OnBatchBlock(const ApprovedRB & block);

private:

    Endpoint  _callback_endpoint;
    Service & _service;
    Handle    _next_handle = 0;
};

ext: hpp

max_stars_repo_name: LogosNetwork/logos-core

max_issues_repo_name: LogosNetwork/logos-core

max_forks_repo_name: LogosNetwork/logos-core


text:
#include <boost/test/unit_test.hpp>
#include "../../src/solvers/csp/propagators/IsPath.hpp"
#include <gecode/search.hh>
#include <gecode/minimodel.hh>

class TestSpace : public Gecode::Space
{
    uint32_t mNumberOfTimepoints;
    uint32_t mNumberOfFluents;

    uint32_t mNumberOfVertices;

    Gecode::SetVarArray mGraph;

public:
    TestSpace(size_t numberOfTimepoints, size_t numberOfFluents)
        : Gecode::Space()
        , mNumberOfTimepoints(numberOfTimepoints)
        , mNumberOfFluents(numberOfFluents)
        , mNumberOfVertices(numberOfTimepoints*numberOfFluents)
        , mGraph(*this, mNumberOfVertices, Gecode::IntSet::empty, Gecode::IntSet(0,mNumberOfVertices-1), 0u,1u )
    {
        // get full path length
        templ::solvers::csp::propagators::isPath(*this, mGraph, "test-path", numberOfTimepoints, numberOfFluents, numberOfTimepoints-1);
        branch(*this, mGraph, Gecode::SET_VAR_MAX_MAX(), Gecode::SET_VAL_MAX_EXC());
    }

    TestSpace(TestSpace& other)
        : Gecode::Space(other)
        , mNumberOfVertices(other.mNumberOfVertices)
        , mNumberOfFluents(other.mNumberOfFluents)
        , mNumberOfTimepoints(other.mNumberOfTimepoints)
    {
        mGraph.update(*this, other.mGraph);
    }

    virtual Gecode::Space* copy()
    {
        return new TestSpace(*this);
    }

    std::string toString() const
    {
        std::stringstream ss;
        ss << "Solution (" << mGraph.size() << ")" << std::endl;
        for(int r = 0; r < mGraph.size(); ++r)
        {
            ss << r << " --> " << mGraph[r] << std::endl;
        }
        return ss.str();
    }

    uint32_t getValue(uint32_t idx) const
    {
        Gecode::SetVar var = mGraph[idx];
        if(!var.assigned())
        {
            throw std::invalid_argument("Can only validate solutions that have been fully assigned");
        }

        Gecode::SetVarGlbValues v(var);
        return v.val();
    }

    void isValid() const
    {
    }

};

void run_test(uint32_t numberOfTimepoints, uint32_t numberOfFluents, const std::string& tag)
{
    TestSpace* testSpace = new TestSpace(numberOfTimepoints, numberOfFluents);
    Gecode::BAB<TestSpace> searchEngine(testSpace);
    TestSpace* best = NULL;
    TestSpace* current = NULL;
    bool foundSolution = false;

    BOOST_TEST_MESSAGE("Run search");
    while((current = searchEngine.next()))
    {
        delete best;
        best = current;

        try {
            best->isValid();
            BOOST_REQUIRE_MESSAGE(true, "Found solution for " << tag << " -- " << best->toString());
            break;
        } catch(const std::exception& e)
        {
            BOOST_REQUIRE_MESSAGE(false, "\n" << best->toString() << "\n" << tag << " Solution not valid: " << e.what());
        }
    }
    if(!current)
    {
        BOOST_REQUIRE_MESSAGE(false, "\n No solution found for " << tag );
    }
    if(best == NULL)
    {
        delete current;
    }

    std::cout << "Statistics: " << std::endl;
    std::cout << "    propagate " << searchEngine.statistics().propagate << std::endl;

    std::cout << "    fail " << searchEngine.statistics().fail << std::endl;
    std::cout << "    node " << searchEngine.statistics().node << std::endl;
    std::cout << "    depth" << searchEngine.statistics().depth << std::endl;
    std::cout << "    restart " << searchEngine.statistics().restart << std::endl;
    std::cout << "    nogoods " << searchEngine.statistics().nogood << std::endl;

}

BOOST_AUTO_TEST_SUITE(propagators_is_path)

BOOST_AUTO_TEST_CASE(check_valid_path)
{
    using namespace templ::solvers::csp::propagators;
    typedef std::pair<int, bool> wp;

    size_t start, end;

    std::vector< std::pair<int, bool> > path;
    path.push_back(wp(-1,true));
    BOOST_REQUIRE_MESSAGE( IsPath::isValidWaypointSequence(path, start, end), "Single unassigned row is an ok path: from: " << start << " to: " << end);
    path.push_back(wp(1,true));
    BOOST_REQUIRE_MESSAGE( IsPath::isValidWaypointSequence(path, start, end), "Single unassigned row and single assigned row is an ok path: from: " << start << " to: " << end );
    path.push_back(wp(1,true));
    BOOST_REQUIRE_MESSAGE( IsPath::isValidWaypointSequence(path, start, end), "Single unassigned row and 2 assigned rows is an ok path: from: " << start << " to: " << end);
    path.push_back(wp(-1,true));
    BOOST_REQUIRE_MESSAGE( IsPath::isValidWaypointSequence(path, start, end), "Single unassigned row and 2 assigned rows, and single unassigned is an ok path: from: " << start << " to: " << end );
    path.push_back(wp(1,true));
    BOOST_REQUIRE_MESSAGE(!IsPath::isValidWaypointSequence(path, start, end), "Path with gap is not a valid sequence" );

}

BOOST_AUTO_TEST_CASE(is_path)
{
    run_test(2,2, "2x2");
}

BOOST_AUTO_TEST_CASE(is_path_5_x_1)
{
    run_test(5,1,"5x1");
}

BOOST_AUTO_TEST_CASE(is_path_3_x_2)
{
    run_test(3,2,"3x2");
}

BOOST_AUTO_TEST_CASE(is_path_5_x_4)
{
    run_test(5,4,"5x4");
}

BOOST_AUTO_TEST_CASE(is_path_10_x_10)
{
    run_test(10,10,"10x10");
}

BOOST_AUTO_TEST_CASE(is_path_20_x_20)
{
    run_test(20,20,"20x20");
}

//BOOST_AUTO_TEST_CASE(is_path_100_x_100)
//{
//    run_test(100,100,"100x100");
//}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: tomcreutz/planning-templ

max_issues_repo_name: tomcreutz/planning-templ

max_forks_repo_name: tomcreutz/planning-templ


text:
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//   license.txt   (http://opensource.org/licenses/MIT)

#pragma once

#include <boost/thread.hpp>
#include <list>
#include <queue>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>
#include "conf/settings/DisableMPI.h"
#include "entities/PersonLoader.hpp"
#include "util/DebugFlags.hpp"
#include "util/FlexiBarrier.hpp"
#include "util/LangHelpers.hpp"

namespace sim_mob
{

class AuraManager; //TODO: to be removed
class Entity;
class PartitionManager;
class ProfileBuilder;
class RoadSegment;
class StartTimePriorityQueue;
class Worker;
class WorkGroupManager;

/**
 * A Worker wrapper which uses barriers to synchronize between all Workers of the same group.
 * WorkGroups are managed by the WorkGroupManager; this includes creation/destruction/advancement.
 * The only function you need to call at the WorkGroup level is assignAWorker().
 * A WorkGroup maintains one extra hold on the shared barrier.
 *
 * \author Seth N. Hetu
 * \author Harish Loganathan
 */
class WorkGroup
{
private:
    friend class WorkGroupManager;

    /** Private constructor: Use the static newWorkGroup function instead. */
    WorkGroup(unsigned int wgNum, unsigned int numWorkers, unsigned int numSimTicks, unsigned int tickStep, sim_mob::AuraManager* auraMgr,
            sim_mob::PartitionManager* partitionMgr, sim_mob::PeriodicPersonLoader* periodicLoader, uint32_t simulationStart);

    /**
     * Helper method; find the least loaded worker (least number of Agents). O(n), so be careful.
     *
     * @param workers input set of workers
     *
     * @return least loaded worker from workers
     */
    static sim_mob::Worker* getLeastLoadedWorker(const std::vector<sim_mob::Worker*>& workers);

public:
    /**
     * Type of Worker assignment strategy. Determines how a newly-dispatched Agent
     * will be distributed among the various Worker threads.
     */
    enum ASSIGNMENT_STRATEGY
    {
        ASSIGN_ROUNDROBIN,  ///< Assign an Agent to Worker 1, then Worker 2, etc.
        ASSIGN_SMALLEST,    ///< Assign an Agent to the Worker with the smallest number of Agents.
    //TODO: Something like "ASSIGN_TIMEBASED", based on actual time tick length.
    };

    /** Entity load/migration parameters */
    struct EntityLoadParams
    {
        StartTimePriorityQueue& pending_source;
        std::set<Entity*>& entity_dest;
        EntityLoadParams(StartTimePriorityQueue& pending_source, std::set<Entity*>& entity_dest) :
                pending_source(pending_source), entity_dest(entity_dest)
        {
        }
    };

    virtual ~WorkGroup();

    /**
     * returns the number of workers in workgroup
     *
     * @return number of workers
     */
    size_t size() const;

    /**
     * initialize workers in work group
     *
     * @param loader entity loaders for work group
     */
    void initWorkers(EntityLoadParams* loader);

    /**
     * assigns a suitable worker for entity
     *
     * @param ag the entity needing worker assignment
     */
    void assignAWorker(Entity* ag);

    /**
     * assigns specified worker for entitiy
     *
     * @param ag the entity needing worker assignment
     * @param workerId index of worker in workers list
     *
     * @return true if assignment was successful; false otherwise
     */
    bool assignWorker(Entity* ag, unsigned int workerId);

    /**
     * processes multi-update entities
     *
     * @param removedEntities input parameter to collect removed entities
     */
    void processMultiUpdateEntities(std::set<Entity*>& removedEntities);

    /**
     * adds a loader entity
     * @param loaderEntity a loader entity to be registered
     */
    void registerLoaderEntity(Entity* loaderEntity);

    /**
     * adds a person to a loader Entity for loading in subsequent tick
     * @param person Person to be loaded
     */
    void loadPerson(Entity* personEntity);

#ifndef SIMMOB_DISABLE_MPI
    void removeAgentFromWorker(Entity * ag);
    void addAgentInWorker(Entity * ag);
    int getTheMostFreeWorkerID() const;
#endif

private:
    /**
     * deletes all workers and non-shared barriers
     */
    void clear();

    /**
     * interrupts executing of worker
     * NOTE: not used anywhere at the moment
     */
    void interrupt();

    /**
     * gets requested worker
     *
     * @param id index of requested worker
     */
    Worker* getWorker(int id);

    /**
     * Schedule an entity for addition into the simulation. Only call this during the "update" phase.
     *
     * @param ag entity to be scheduled
     */
    void scheduleEntity(Entity* ag);

    /**
     * stages entities from pending source into the simulation
     */
    void stageEntities();

    /**
     * collects entities removed from simulation
     * TODO: the usage of this function is fuzzy at the moment. Check whether this is really required
     *
     * @param removedAgents input parameter to collect removed entities
     */
    void collectRemovedEntities(std::set<sim_mob::Entity*>* removedAgents);

    /**
     * container for entities removed from each worker
     * Each worker is given 1 mutually exclusive vector from this container
     */
    std::vector<std::vector<Entity*> > entToBeRemovedPerWorker;

    /**
     * container for entities bred into each worker
     * Each worker is given 1 mutually exclusive vector from this container
     */
    std::vector<std::vector<Entity*> > entToBeBredPerWorker;

    /**
     * Add to the list the name of each thread's output file.
     *
     * @param res input param to add file names to
     */
    void addOutputFileNames(std::list<std::string>& res) const;

    /**
     * starts all workers in group
     *
     * @param singleThreaded indicates whether the execution must be single threaded
     */
    void startAll(bool singleThreaded);

    //Various stages of "wait"-ing
    //These functions are designed so that you can simply call them one after the other. However,
    // make sure that you call all wait* functions for a given category before moving on.
    //E.g., call "waitFrameTick()" for all WorkGroups, THEN call "waitFlipBuffers()" for all
    // work groups, etc.
    //If "removedAgents" is non-null, any Agents which are removed this time tick are flagged.
    //NOTE: By passing in a non-null "removedAgents", you are taking ownership of these Agents (YOU must delete them).

    /**
     * wait on frame tick
     *
     * @param singleThreaded indicates whether the execution must be single threaded
     */
    void waitFrameTick(bool singleThreaded);

    /**
     * wait on flip buffers
     *
     * @param singleThreaded indicates whether the execution must be single threaded
     * @param removedAgents input parameter to collect removed entities
     */
    void waitFlipBuffers(bool singleThreaded, std::set<sim_mob::Entity*>* removedAgents);

    /**
     * wait on distribute messages barrier
     * TODO: this function must be renamed when AuraMAnager is moved out of WorkGroup
     *
     * @param removedAgents input parameter to collect removed entities
     */
    void waitAuraManager(const std::set<sim_mob::Entity*>& removedAgents);

    /**
     * wait on macro tick
     */
    void waitMacroTimeTick();

    /**
     * Initialize our shared (static) barriers. These barriers don't technically need to be copied
     * locally, but we'd rather avoid relying on static variables in case we ever make a WorkGroupGroup (or whatever) class.
     *
     * @param frame_tick frame tick barrier
     * @param buff_flip flip buffer barrier
     * @param msg_bus message bus barrier
     */
    void initializeBarriers(sim_mob::FlexiBarrier* frame_tick, sim_mob::FlexiBarrier* buff_flip, sim_mob::FlexiBarrier* msg_bus);

    /** The "number" of this WorkGroup. E.g., the first one created is 0, the second is 1, etc. Used ONLY for generating Log files; DON'T use this as an ID. */
    unsigned int wgNum;

    /** Number of workers we are handling. Should be equal to workers.size() once the workers vector has been initialized. */
    unsigned int numWorkers;

    /** Passed along to Workers */
    unsigned int numSimTicks;

    /** granularity of tick in w.r.t the base granularity */
    unsigned int tickStep;

    /** Maintain an offset. When it reaches zero, reset to tickStep and sync barriers */
    unsigned int tickOffset;

    /** Log files that we are managing for Workers in this group. */
    std::list<std::ostream*> managed_logs;

    /** names of Log files that we are managing for Workers in this group. */
    std::list<std::string> logFileNames;

    /**
     * Aura manager to update, if any (either may be null).
     * TODO: to be refactored out of work group
     */
    sim_mob::AuraManager* auraMgr;

    /**
     * partition manager to update, if any (either may be null).
     */
    sim_mob::PartitionManager* partitionMgr;

    /** started state indicator for work group */
    bool started;

    //Stays in sync with the Workers' time ticks; tells us which Workers to stage next.
    /** current time tick */
    uint32_t currTimeTick;

    /** next time tick. All entities are staged based on this. */
    uint32_t nextTimeTick;

    /** Container for information needed to migrate Entities */
    EntityLoadParams* loader;

    /**
     * List of all known workers, along with the ID of the next Worker to receive an agent.
     * Uses a round-robin approach to select the next Worker.
     */
    std::vector<Worker*> workers;

    /** worker index used for round-robin selection of worker for agent assignment */
    size_t nextWorkerID;

    /**
     * Container for any loader entities responsible for loading other entities in-turn.
     * In mid-term, workers manage conflux entities which in-turn manage person entities.
     * Each worker is assigned a loader conflux entity which are responsible for
     * dispatching new person entities to target conflux entities.
     * These loader confluxes are stored in the vector below.
     */
    std::vector<Entity*> loaderEntities;

    /**
     * index used for dispatching new persons to loader confluxes in round robin fashion
     */
    size_t nextLoaderIdx;

    /** Barrier for frame_tick stage */
    sim_mob::FlexiBarrier* frame_tick_barr;

    /** Barrier for flip buffers stage */
    sim_mob::FlexiBarrier* buff_flip_barr;

    /** Barrier for message distribution stage */
    sim_mob::FlexiBarrier* msg_bus_barr;

    /**
     * An optional barrier phase unique to each WorkGroup. If the timeStep is >1, then
     * one additional locking barrier is required to prevent Workers from rushing ahead
     * into the next time tick. Using a restricted boost::barrier helps to reinforce this.
     */
    boost::barrier* macro_tick_barr;

    /** Profiler */
    sim_mob::ProfileBuilder* profile;

    /** entity loader to load person entities periodically */
    PeriodicPersonLoader* periodicPersonLoader;

    uint32_t simulationStart;
};

} // namespace sim_mob


text: #include <boost/regex/v4/iterator_category.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_TUPLED_HPP
#define BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_TUPLED_HPP

#include <string>

#include <boost/tuple/tuple.hpp>
#include <boost/geometry/strategies/side_info.hpp>
#include <boost/geometry/util/select_calculation_type.hpp>
#include <boost/geometry/util/select_most_precise.hpp>

namespace boost { namespace geometry
{

namespace policies { namespace relate
{

// "tupled" to return intersection results together.
// Now with two, with some meta-programming and derivations it can also be three (or more)
template <typename Policy1, typename Policy2, typename CalculationType = void>
struct segments_tupled
{
    typedef boost::tuple
        <
            typename Policy1::return_type,
            typename Policy2::return_type
        > return_type;

    // Take segments of first policy, they should be equal
    typedef typename Policy1::segment_type1 segment_type1;
    typedef typename Policy1::segment_type2 segment_type2;

    typedef typename select_calculation_type
        <
            segment_type1,
            segment_type2,
            CalculationType
        >::type coordinate_type;

    // Get the same type, but at least a double
    typedef typename select_most_precise<coordinate_type, double>::type rtype;

	template <typename R>
    static inline return_type segments_intersect(side_info const& sides,
				    R const& r,
                    coordinate_type const& dx1, coordinate_type const& dy1,
                    coordinate_type const& dx2, coordinate_type const& dy2,
                    segment_type1 const& s1, segment_type2 const& s2)
    {
        return boost::make_tuple
            (
                Policy1::segments_intersect(sides, r,
                    dx1, dy1, dx2, dy2, s1, s2),
                Policy2::segments_intersect(sides, r,
                    dx1, dy1, dx2, dy2, s1, s2)
            );
    }

    static inline return_type collinear_touch(coordinate_type const& x,
                coordinate_type const& y, int arrival_a, int arrival_b)
    {
        return boost::make_tuple
            (
                Policy1::collinear_touch(x, y, arrival_a, arrival_b),
                Policy2::collinear_touch(x, y, arrival_a, arrival_b)
            );
    }

    template <typename S>
    static inline return_type collinear_interior_boundary_intersect(S const& segment,
                bool a_within_b,
                int arrival_a, int arrival_b, bool opposite)
    {
        return boost::make_tuple
            (
                Policy1::collinear_interior_boundary_intersect(segment, a_within_b, arrival_a, arrival_b, opposite),
                Policy2::collinear_interior_boundary_intersect(segment, a_within_b, arrival_a, arrival_b, opposite)
            );
    }

    static inline return_type collinear_a_in_b(segment_type1 const& segment,
                bool opposite)
    {
        return boost::make_tuple
            (
                Policy1::collinear_a_in_b(segment, opposite),
                Policy2::collinear_a_in_b(segment, opposite)
            );
    }
    static inline return_type collinear_b_in_a(segment_type2 const& segment,
                    bool opposite)
    {
        return boost::make_tuple
            (
                Policy1::collinear_b_in_a(segment, opposite),
                Policy2::collinear_b_in_a(segment, opposite)
            );
    }

    static inline return_type collinear_overlaps(
                    coordinate_type const& x1, coordinate_type const& y1,
                    coordinate_type const& x2, coordinate_type const& y2,
                    int arrival_a, int arrival_b, bool opposite)
    {
        return boost::make_tuple
            (
                Policy1::collinear_overlaps(x1, y1, x2, y2, arrival_a, arrival_b, opposite),
                Policy2::collinear_overlaps(x1, y1, x2, y2, arrival_a, arrival_b, opposite)
            );
    }

    static inline return_type segment_equal(segment_type1 const& s,
                bool opposite)
    {
        return boost::make_tuple
            (
                Policy1::segment_equal(s, opposite),
                Policy2::segment_equal(s, opposite)
            );
    }

    static inline return_type degenerate(segment_type1 const& segment,
                bool a_degenerate)
    {
        return boost::make_tuple
            (
                Policy1::degenerate(segment, a_degenerate),
                Policy2::degenerate(segment, a_degenerate)
            );
    }

    static inline return_type disjoint()
    {
        return boost::make_tuple
            (
                Policy1::disjoint(),
                Policy2::disjoint()
            );
    }

    static inline return_type error(std::string const& msg)
    {
        return boost::make_tuple
            (
                Policy1::error(msg),
                Policy2::error(msg)
            );
    }

    static inline return_type collinear_disjoint()
    {
        return boost::make_tuple
            (
                Policy1::collinear_disjoint(),
                Policy2::collinear_disjoint()
            );
    }

};

}} // namespace policies::relate

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_TUPLED_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/* Copyright 2016-2018 Joaquin M Lopez Munoz.
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org/libs/poly_collection for library home page.
 */

#ifndef BOOST_POLY_COLLECTION_DETAIL_ANY_MODEL_HPP
#define BOOST_POLY_COLLECTION_DETAIL_ANY_MODEL_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/core/addressof.hpp>
#include <boost/mpl/map/map10.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/vector/vector10.hpp>
#include <boost/poly_collection/detail/any_iterator.hpp>
#include <boost/poly_collection/detail/is_acceptable.hpp>
#include <boost/poly_collection/detail/segment_backend.hpp>
#include <boost/poly_collection/detail/split_segment.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/binding.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/type_erasure/concept_of.hpp>
#include <boost/type_erasure/is_subconcept.hpp>
#include <boost/type_erasure/relaxed.hpp>
#include <boost/type_erasure/static_binding.hpp>
#include <boost/type_erasure/typeid_of.hpp>
#include <memory>
#include <type_traits>
#include <typeinfo>
#include <utility>

namespace boost {

namespace poly_collection {

namespace detail {

/* model for any_collection */

template <typename Concept> struct any_model;

/* Refine is_acceptable to cover type_erasure::any classes whose assignment
 * operator won't compile.
 */

template <typename Concept, typename Concept2, typename T>
struct is_acceptable<type_erasure::any<Concept2, T>, any_model<Concept>,
                     typename std::enable_if<
                         !type_erasure::is_relaxed<Concept2>::value &&
                         !type_erasure::is_subconcept<
                             type_erasure::assignable<>, Concept2>::value &&
                         !type_erasure::is_subconcept<
                             type_erasure::assignable<type_erasure::_self,
                                                      type_erasure::_self &&>,
                             Concept2>::value>::type> : std::false_type {};

/* is_terminal defined out-class to allow for partial specialization */

template <typename Concept, typename T>
using any_model_enable_if_has_typeid_ =
    typename std::enable_if<type_erasure::is_subconcept<
        type_erasure::typeid_<typename std::decay<T>::type>,
        Concept>::value>::type *;

template <typename T, typename = void *>
struct any_model_is_terminal : std::true_type {};

template <typename Concept, typename T>
struct any_model_is_terminal<type_erasure::any<Concept, T>,
                             any_model_enable_if_has_typeid_<Concept, T>>
    : std::false_type {};

/* used for make_value_type */

template <typename T, typename Q> struct any_model_make_reference {
  static T &apply(Q &x) { return x; }
};

template <typename Concept> struct any_model {
  using value_type = type_erasure::any<
      typename std::conditional<
          type_erasure::is_subconcept<type_erasure::typeid_<>, Concept>::value,
          Concept, mpl::vector2<Concept, type_erasure::typeid_<>>>::type,
      type_erasure::_self &>;

  template <typename Concrete>
  using is_implementation = std::true_type; /* can't compile-time check concept
                                             * compliance */
  template <typename T> using is_terminal = any_model_is_terminal<T>;

  template <typename T> static const std::type_info &subtypeid(const T &) {
    return typeid(T);
  }

  template <typename Concept2, typename T,
            any_model_enable_if_has_typeid_<Concept2, T> = nullptr>
  static const std::type_info &
  subtypeid(const type_erasure::any<Concept2, T> &a) {
    return type_erasure::typeid_of(a);
  }

  template <typename T> static void *subaddress(T &x) {
    return boost::addressof(x);
  }

  template <typename T> static const void *subaddress(const T &x) {
    return boost::addressof(x);
  }

  template <typename Concept2, typename T,
            any_model_enable_if_has_typeid_<Concept2, T> = nullptr>
  static void *subaddress(type_erasure::any<Concept2, T> &a) {
    return type_erasure::any_cast<void *>(&a);
  }

  template <typename Concept2, typename T,
            any_model_enable_if_has_typeid_<Concept2, T> = nullptr>
  static const void *subaddress(const type_erasure::any<Concept2, T> &a) {
    return type_erasure::any_cast<const void *>(&a);
  }

  using base_iterator = any_iterator<value_type>;
  using const_base_iterator = any_iterator<const value_type>;
  using base_sentinel = value_type *;
  using const_base_sentinel = const value_type *;
  template <typename Concrete> using iterator = Concrete *;
  template <typename Concrete> using const_iterator = const Concrete *;
  template <typename Allocator>
  using segment_backend = detail::segment_backend<any_model, Allocator>;
  template <typename Concrete, typename Allocator>
  using segment_backend_implementation =
      split_segment<any_model, Concrete, Allocator>;

  static base_iterator nonconst_iterator(const_base_iterator it) {
    return base_iterator{
        const_cast<value_type *>(static_cast<const value_type *>(it))};
  }

  template <typename T>
  static iterator<T> nonconst_iterator(const_iterator<T> it) {
    return const_cast<iterator<T>>(it);
  }

private:
  template <typename, typename, typename> friend class split_segment;

  template <typename Concrete> static value_type make_value_type(Concrete &x) {
    return value_type{x};
  }

  template <typename Concept2, typename T>
  static value_type make_value_type(type_erasure::any<Concept2, T> &x) {
    /* I don't pretend to understand what's going on here, see
     * https://lists.boost.org/boost-users/2017/05/87556.php
     */

    using namespace boost::type_erasure;
    using ref_type = any<Concept2, T>;
    using make_ref = any_model_make_reference<_self, ref_type>;
    using concept_ = typename concept_of<value_type>::type;

    auto b = make_binding<mpl::map1<mpl::pair<_self, ref_type>>>();

    return {call(binding<make_ref>{b}, make_ref{}, x), binding<concept_>{b}};
  }
};

} // namespace detail

} /* namespace poly_collection */

} /* namespace boost */

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix