text:
/**********************************************************************
*  Copyright (c) 2008-2013, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#include <analysis/SequentialSearch.hpp>
#include <analysis/SequentialSearch_Impl.hpp>

#include <analysis/SequentialSearchOptions.hpp>
#include <analysis/SequentialSearchOptions_Impl.hpp>

#include <analysis/Analysis.hpp>
#include <analysis/DataPoint.hpp>
#include <analysis/OptimizationProblem.hpp>
#include <analysis/OptimizationProblem_Impl.hpp>
#include <analysis/OptimizationDataPoint.hpp>
#include <analysis/OptimizationDataPoint_Impl.hpp>
#include <analysis/DiscreteVariable.hpp>
#include <analysis/DiscreteVariable_Impl.hpp>

#include <utilities/document/Table.hpp>
#include <utilities/math/FloatCompare.hpp>
#include <utilities/core/Assert.hpp>
#include <utilities/core/Containers.hpp>

#include <boost/foreach.hpp>
#include <boost/bind.hpp>

namespace openstudio {
namespace analysis {

namespace detail {

  SequentialSearch_Impl::SequentialSearch_Impl(const SequentialSearchOptions& options)
    : OpenStudioAlgorithm_Impl(SequentialSearch::standardName(),options)
  {}

  SequentialSearch_Impl::SequentialSearch_Impl(const UUID& uuid,
                                               const UUID& versionUUID,
                                               const std::string& displayName,
                                               const std::string& description,
                                               bool complete,
                                               bool failed,
                                               int iter,
                                               const SequentialSearchOptions& options)
    : OpenStudioAlgorithm_Impl(uuid,
                               versionUUID,
                               SequentialSearch::standardName(),
                               displayName,
                               description,
                               complete,
                               failed,
                               iter,
                               options)
  {}

  SequentialSearch_Impl::SequentialSearch_Impl(const SequentialSearch_Impl& other)
    : OpenStudioAlgorithm_Impl(other)
  {}

  AnalysisObject SequentialSearch_Impl::clone() const {
    boost::shared_ptr<SequentialSearch_Impl> impl(new SequentialSearch_Impl(*this));
    return SequentialSearch(impl);
  }

  bool SequentialSearch_Impl::isCompatibleProblemType(const Problem& problem) const {
    OptionalOptimizationProblem optimizationProblem = problem.optionalCast<OptimizationProblem>();
    if (!optimizationProblem) {
      return false;
    }
    if (!optimizationProblem->allVariablesAreDiscrete()) {
      return false;
    }
    if (optimizationProblem->numObjectives() != 2) {
      return false;
    }
    return true;
  }

  int SequentialSearch_Impl::createNextIteration(Analysis& analysis) {
    OS_ASSERT(analysis.algorithm().get() == getPublicObject<SequentialSearch>());

    int numAdded(0);
    if (isComplete()) {
      LOG(Info,"Algorithm is already marked as complete. Returning without creating new points.");
      return numAdded;
    }

    SequentialSearchOptions options = sequentialSearchOptions();
    OptionalInt maxIter = options.maxIter();
    OptionalInt maxSims = options.maxSims();
    DataPointVector ssDataPoints = analysis.getDataPoints("ss");
    // return without doing anything if any ssDataPoints are incomplete
    DataPointVector incompletePoints = analysis.dataPointsToQueue();
    DataPointVector::const_iterator it = std::find_if(incompletePoints.begin(),
                                                      incompletePoints.end(),
                                                      boost::bind(&DataPoint::isTag,_1,"ss"));
    if (it != incompletePoints.end()) {
      LOG(Info,"Returning because the last iteration has not yet been run.");
      return numAdded;
    }
    // last iteration appears complete
    int nSims = ssDataPoints.size();
    if (maxSims && (nSims >= *maxSims)) {
      LOG(Info,"Returning because maxSims " << *maxSims << " reached. No DataPoints will be added "
          << "to Analysis '"<< analysis.name() << "', and the Algorithm will be marked complete.");
      markComplete();
      return numAdded;
    }
    if (maxIter && (m_iter+1 == *maxIter)) {
      LOG(Info,"Returning because maxIter " << *maxIter << " reached. No DataPoints will be added "
          << "to Analysis '"<< analysis.name() << "', and the Algorithm will be marked complete.");
      markComplete();
      return numAdded;
    }
    onChange(AnalysisObject_Impl::Benign);
    ++m_iter;

    if (m_iter == 0) {
      // run baseline point, which is just the 0th perturbation of each variable.
      OptimizationProblem problem = analysis.problem().cast<OptimizationProblem>();
      std::vector<QVariant> baselineValues(problem.numVariables(),0);
      // see if already in analysis
      DataPointVector baselines = analysis.getDataPoints(baselineValues);
      if (!baselines.empty()) {
        OS_ASSERT(baselines.size() == 1u);
        DataPoint baseline = baselines[0];
        OS_ASSERT(baseline.optionalCast<OptimizationDataPoint>());
        OS_ASSERT(baseline.problem() == problem);
        if (!baseline.isTag("ss")) {
          baseline.addTag("ss");
        }
        if (!baseline.isTag("iter0")) {
          baseline.addTag("iter0");
        }
        if (!baseline.isTag("current")) {
          baseline.addTag("current");
        }
        if (!baseline.isComplete()) {
          ++numAdded;
        }
      }
      else {
        OptimizationDataPoint dataPoint = problem.createDataPoint(baselineValues).get().cast<OptimizationDataPoint>();
        dataPoint.addTag("ss");
        dataPoint.addTag("iter0");
        dataPoint.addTag("current");
        analysis.addDataPoint(dataPoint);
        ++numAdded;
      }
    }
    else {
      OptimizationDataPointVector minimumCurve =
          getMinimumCurve(options.objectiveToMinimizeFirst(),analysis);
      OS_ASSERT(!minimumCurve.empty());
      OS_ASSERT(minimumCurve.back().isTag("current"));
      if (!minimumCurve.back().isTag("explored")) {
        std::vector< std::vector<QVariant> > candidateVariableValues = getCandidateCombinations(minimumCurve.back());
        std::stringstream ss;
        ss << "iter" << m_iter;
        std::string iterTag(ss.str()); ss.str("");
        BOOST_FOREACH(const std::vector<QVariant>& candidate, candidateVariableValues) {
          DataPoint newDataPoint = analysis.problem().createDataPoint(candidate).get();
          OS_ASSERT(newDataPoint.optionalCast<OptimizationDataPoint>());
          newDataPoint.addTag("ss");
          newDataPoint.addTag(iterTag);
          bool added = analysis.addDataPoint(newDataPoint);
          if (added) {
            ++numAdded;
            if (maxSims && (nSims + numAdded == *maxSims)) {
              break;
            }
          }
        }
        minimumCurve.back().addTag("explored");
      }
    }

    if (numAdded == 0) {
      LOG(Trace,"No new points were added, so marking this SequentialSearch complete.");
      markComplete();
    }

    return numAdded;
  }

  SequentialSearchOptions SequentialSearch_Impl::sequentialSearchOptions() const {
    return options().cast<SequentialSearchOptions>();
  }

  std::vector<OptimizationDataPoint> SequentialSearch_Impl::getMinimumCurve(
      unsigned i, Analysis& analysis) const
  {
    std::stringstream ss;
    ss << "curve" << i;
    std::string curveTag(ss.str()); ss.str("");

    OptimizationDataPointVector lastCurve = castVector<OptimizationDataPoint>(
        analysis.getDataPoints(curveTag));
    OptimizationDataPointVector lastCurrent = castVector<OptimizationDataPoint>(
        analysis.getDataPoints("current"));
    OptimizationDataPointVector result = castVector<OptimizationDataPoint>(
        analysis.getDataPoints("iter0")); // baseline point
    OS_ASSERT(result.size() < 2);
    OptimizationDataPointVector successfulPoints = castVector<OptimizationDataPoint>(
        analysis.successfulDataPoints());

    // construct curve
    OptionalOptimizationDataPoint current;
    if (!result.empty()) {
      current = result.back();
      if (!current->isTag(curveTag)) {
        current->addTag(curveTag);
      }
      OptimizationDataPointVector::iterator it = std::find(successfulPoints.begin(),
                                                           successfulPoints.end(),
                                                           result.back());
      successfulPoints.erase(it);
    }
    int otherIndex(0);
    if (i == 0) {
      otherIndex = 1;
    }
    else {
      OS_ASSERT(i == 1);
    }
    while (current) {
      OptionalOptimizationDataPoint candidate;
      if (current->isTag("explored") && current->isComplete() && !current->failed()) {
        // candidates have objective function at otherIndex < current's
        DoubleVector currentValues = current->objectiveValues();
        OptionalDouble candidateSlope;
        DoubleVector candidateValues;
        for (OptimizationDataPointVector::iterator it = successfulPoints.begin();
             it != successfulPoints.end(); )
        {
          DoubleVector values = it->objectiveValues();
          if (lessThanOrEqual(values[otherIndex],currentValues[otherIndex])) {
            // take maximum slope as calculated on graph i vs. otherIndex
            double slope = (values[i] - currentValues[i])/
                           (values[otherIndex] - currentValues[otherIndex]);
            // infinite slope exception for start of algorithm
            bool infiniteSlopeException =
                current->isTag("iter0") &&
                equal(values[otherIndex],currentValues[otherIndex]) &&
                (values[i] < currentValues[i]);
            if (infiniteSlopeException && candidateSlope) {
              infiniteSlopeException = infiniteSlopeException &&
                  ((candidateValues[otherIndex] < values[otherIndex]) ||
                   (values[i] < candidateValues[i]));
            }
            if (infiniteSlopeException ||
                (!equal(values[otherIndex],currentValues[otherIndex]) &&
                 ((!candidateSlope) || (slope > *candidateSlope) ||
                  (equal(slope,*candidateSlope) && (values[i] < candidateValues[i])))))
            {
              candidate = *it;
              candidateSlope = slope;
              candidateValues = values;
              if (infiniteSlopeException) {
                candidateSlope = std::numeric_limits<double>::max();
              }
            }
            ++it;
          }
          else {
            // erase it from consideration--with other objective function > current,
            // will never be candidate.
            it = successfulPoints.erase(it);
          }
        }
      }
      if (candidate) {
        result.push_back(*candidate);
        if (!result.back().isTag(curveTag)) {
          result.back().addTag(curveTag);
        }
        OptimizationDataPointVector::iterator it = std::find(successfulPoints.begin(),
                                                             successfulPoints.end(),
                                                             result.back());
        successfulPoints.erase(it);
      }
      current = candidate;
    }

    // remove outdated tags
    BOOST_FOREACH(OptimizationDataPoint& point,lastCurve) {
      OptimizationDataPointVector::const_iterator it = std::find(result.begin(),result.end(),point);
      if (it == result.end()) {
        point.deleteTag(curveTag);
      }
    }
    if (!lastCurrent.empty()) {
      OS_ASSERT(lastCurrent.size() == 1u);
      if (lastCurrent[0] != result.back()) {
        lastCurrent[0].deleteTag("current");
      }
    }

    // add current tag
    if (!result.empty() && !result.back().isTag("current")) {
      result.back().addTag("current");
    }

    return result;
  }

  std::vector<OptimizationDataPoint> SequentialSearch_Impl::getParetoFront(
      Analysis& analysis) const
  {
    DataPointVector temp = analysis.getDataPoints("pareto");
    OptimizationDataPointVector lastParetoFront = castVector<OptimizationDataPoint>(temp);
    OptimizationDataPointVector result;
    temp = analysis.successfulDataPoints();
    OptimizationDataPointVector successfulPoints = castVector<OptimizationDataPoint>(temp);

    // sort by objective function options().objectiveToMinimizeFirst()
    int i = sequentialSearchOptions().objectiveToMinimizeFirst();
    int otherIndex(0);
    if (i == 0) {
      otherIndex = 1;
    }
    else {
      OS_ASSERT(i == 1);
    }
    OptimizationDataPointObjectiveFunctionLess predicate(i);
    std::sort(successfulPoints.begin(),successfulPoints.end(),predicate);

    // non-dominated means that you cannot improve one objective without harming the other
    OptimizationDataPointVector::iterator it = successfulPoints.begin();
    DoubleVector currentValues;
    while (it != successfulPoints.end()) {
      // it has next-worst objective i
      DoubleVector candidateValues = it->objectiveValues();
      if (!currentValues.empty()) {
        OS_ASSERT(greaterThanOrEqual(candidateValues[i],currentValues[i]));
      }
      // is Pareto if improves objective otherIndex, and
      if (!currentValues.empty() &&
          greaterThanOrEqual(candidateValues[otherIndex],currentValues[otherIndex]))
      {
        it = successfulPoints.erase(it);
        continue;
      }
      // is Pareto if there is no other point with same objective i and better objective otherIndex
      OptimizationDataPointVector::const_iterator jt = it; ++jt;
      bool erasedIt(false);
      while (jt != successfulPoints.end()) {
        DoubleVector nextValues = jt->objectiveValues();
        if (equal(candidateValues[i],nextValues[i])) {
          if (nextValues[otherIndex] < candidateValues[otherIndex]) {
            it = successfulPoints.erase(it);
            erasedIt = true;
            break;
          }
          ++jt;
        }
        else {
          break;
        }
      }
      if (erasedIt) {
        continue;
      }
      result.push_back(*it);
      it = successfulPoints.erase(it);
      currentValues = result.back().objectiveValues();
      if (!result.back().isTag("pareto")) {
        result.back().addTag("pareto");
      }
    }

    // remove outdated tags
    BOOST_FOREACH(OptimizationDataPoint& point,lastParetoFront) {
      OptimizationDataPointVector::const_iterator it = std::find(result.begin(),result.end(),point);
      if (it == result.end()) {
        point.deleteTag("pareto");
      }
    }

    return result;
  }

  Table SequentialSearch_Impl::getSummaryTable(Analysis& analysis) const {
    Table result;

    TableElementVector row;
    std::stringstream ss;
    row.push_back(TableElement(std::string("iter")));
    row.push_back(TableElement(std::string("current")));
    row.push_back(TableElement(std::string("curve0")));
    row.push_back(TableElement(std::string("curve1")));
    row.push_back(TableElement(std::string("pareto")));
    row.push_back(TableElement(std::string("explored")));
    InputVariableVector variables = analysis.problem().variables();
    for (int i = 0, n = analysis.problem().numVariables(); i < n; ++i) {
      ss << "v" << i << ", " << variables[i].name();
      row.push_back(TableElement(ss.str())); ss.str("");
    }
    FunctionVector objectiveFunctions = analysis.problem().cast<OptimizationProblem>().objectives();
    ss << "f0, " << objectiveFunctions[0].name();
    row.push_back(TableElement(ss.str())); ss.str("");
    ss << "f1, " << objectiveFunctions[1].name();
    row.push_back(TableElement(ss.str())); ss.str("");
    row.push_back(TableElement(std::string("incomplete")));
    row.push_back(TableElement(std::string("failed")));
    result.appendRow(row); row.clear();
    result.setNHead(1);
    int nCols = result.nCols();

    // populate curves
    int i =  sequentialSearchOptions().objectiveToMinimizeFirst();
    int otherIndex(0);
    if (i == 0) {
      otherIndex = 1;
    }
    else {
      OS_ASSERT(i == 1);
    }

    getMinimumCurve(otherIndex,analysis);
    getMinimumCurve(i,analysis);
    getParetoFront(analysis);

    // construct table row for each data point
    struct TagInfo {
      TagInfo()
        : current(false), curve0(false), curve1(false), pareto(false), explored(false)
      {}
      boost::optional<int> iter;
      bool current;
      bool curve0;
      bool curve1;
      bool pareto;
      bool explored;
    };

    boost::regex re("iter([0-9]+)");
    boost::smatch m;

    OptimizationDataPointVector dataPoints = castVector<OptimizationDataPoint>(analysis.dataPoints());
    BOOST_FOREACH(const OptimizationDataPoint& dataPoint,dataPoints) {
      TagVector tags = dataPoint.tags();
      TagInfo tagInfo;
      BOOST_FOREACH(const Tag& tag,tags) {
        std::string tagName = tag.name();
        if (tagName == "current") {
          tagInfo.current = true;
        }
        else if (tagName == "curve0") {
          tagInfo.curve0 = true;
        }
        else if (tagName == "curve1") {
          tagInfo.curve1 = true;
        }
        else if (tagName == "pareto") {
          tagInfo.pareto = true;
        }
        else if (tagName == "explored") {
          tagInfo.explored = true;
        }
        else if (boost::regex_match(tagName,m,re)) {
          std::string iterNumber(m[1].first,m[1].second);
          tagInfo.iter = boost::lexical_cast<int>(iterNumber);
        }
      }
      if (tagInfo.iter) {
        row.push_back(TableElement(tagInfo.iter.get()));
      }
      else {
        row.push_back(TableElement(std::string("custom")));
      }
      if (tagInfo.current) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      if (tagInfo.curve0) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      if (tagInfo.curve1) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      if (tagInfo.pareto) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      if (tagInfo.explored) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      BOOST_FOREACH(const QVariant& value, dataPoint.variableValues()) {
        row.push_back(TableElement(value.toInt()));
      }
      DoubleVector values = dataPoint.objectiveValues();
      if (values.size() == 2u) {
        row.push_back(TableElement(values[0]));
        row.push_back(TableElement(values[1]));
      }
      else {
        row.push_back(TableElement(std::string("")));
        row.push_back(TableElement(std::string("")));
      }
      if (!dataPoint.isComplete()) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      if (dataPoint.failed()) {
        row.push_back(TableElement(std::string("x")));
      }
      else {
        row.push_back(TableElement(std::string("")));
      }
      OS_ASSERT(row.size() == static_cast<size_t>(nCols));
      result.appendRow(row); row.clear();
    }

    return result;
  }

  std::vector< std::vector<QVariant> > SequentialSearch_Impl::getCandidateCombinations(
      const DataPoint& dataPoint) const
  {
    Problem problem = dataPoint.problem();
    std::vector<QVariant> currentValues = dataPoint.variableValues();
    std::vector< std::vector<QVariant> > result;
    for (int i = 0, n = problem.numVariables(); i < n; ++i) {
      DiscreteVariable variable = problem.getVariable(i).cast<DiscreteVariable>();
      // only use selected items
      int currentValue = currentValues[i].toInt();
      BOOST_FOREACH(int j, variable.validValues(true)) {
        if (currentValue != j) {
          std::vector<QVariant> newValues = currentValues;
          newValues[i] = j;
          result.push_back(newValues);
        }
      }
    }
    return result;
  }

  QVariant SequentialSearch_Impl::toVariant() const {
    QVariantMap map = Algorithm_Impl::toVariant().toMap();

    map["algorithm_type"] = QString("SequentialSearch");

    return QVariant(map);
  }

  SequentialSearch SequentialSearch_Impl::fromVariant(const QVariant& variant, const VersionString& version) {
    QVariantMap map = variant.toMap();
    SequentialSearchOptions options = SequentialSearchOptions_Impl::fromVariant(map["options"],version);
    return SequentialSearch(toUUID(map["uuid"].toString().toStdString()),
                            toUUID(map["version_uuid"].toString().toStdString()),
                            map.contains("display_name") ? map["display_name"].toString().toStdString() : std::string(),
                            map.contains("description") ? map["description"].toString().toStdString() : std::string(),
                            map["complete"].toBool(),
                            map["failed"].toBool(),
                            map["iter"].toInt(),
                            options);
  }

} // detail

SequentialSearch::SequentialSearch(const SequentialSearchOptions& options)
  : OpenStudioAlgorithm(boost::shared_ptr<detail::SequentialSearch_Impl>(
        new detail::SequentialSearch_Impl(options)))
{
  createCallbackForOptions();
}

SequentialSearch::SequentialSearch(const UUID& uuid,
                                   const UUID& versionUUID,
                                   const std::string& displayName,
                                   const std::string& description,
                                   bool complete,
                                   bool failed,
                                   int iter,
                                   const SequentialSearchOptions& options)
  : OpenStudioAlgorithm(boost::shared_ptr<detail::SequentialSearch_Impl>(
        new detail::SequentialSearch_Impl(uuid,
                                          versionUUID,
                                          displayName,
                                          description,
                                          complete,
                                          failed,
                                          iter,
                                          options)))
{
  createCallbackForOptions();
}

std::string SequentialSearch::standardName() {
  return std::string("Sequential Search");
}

SequentialSearchOptions SequentialSearch::sequentialSearchOptions() const {
  return getImpl<detail::SequentialSearch_Impl>()->sequentialSearchOptions();
}

std::vector<OptimizationDataPoint> SequentialSearch::getMinimumCurve(
    unsigned i, Analysis& analysis) const
{
  return getImpl<detail::SequentialSearch_Impl>()->getMinimumCurve(i,analysis);
}

std::vector<OptimizationDataPoint> SequentialSearch::getParetoFront(
    Analysis& analysis) const
{
  return getImpl<detail::SequentialSearch_Impl>()->getParetoFront(analysis);
}

Table SequentialSearch::getSummaryTable(Analysis& analysis) const {
  return getImpl<detail::SequentialSearch_Impl>()->getSummaryTable(analysis);
}

std::vector< std::vector<QVariant> > SequentialSearch::getCandidateCombinations(
    const DataPoint& dataPoint) const
{
  return getImpl<detail::SequentialSearch_Impl>()->getCandidateCombinations(dataPoint);
}

/// @cond
SequentialSearch::SequentialSearch(boost::shared_ptr<detail::SequentialSearch_Impl> impl)
  : OpenStudioAlgorithm(impl)
{}
/// @endcond

} // analysis
} // openstudio

max_stars_repo_name: bobzabcik/OpenStudio

max_issues_repo_name: bobzabcik/OpenStudio

max_forks_repo_name: bobzabcik/OpenStudio


text:
#include <nano/lib/config.hpp>

#include <boost/filesystem/path.hpp>

#include <valgrind/valgrind.h>

namespace nano
{
const char * network_constants::active_network_err_msg = "Invalid network. Valid values are live, beta and test.";

void force_nano_test_network ()
{
	nano::network_constants::set_active_network (nano::nano_networks::nano_test_network);
}

bool running_within_valgrind ()
{
	return (RUNNING_ON_VALGRIND > 0);
}

std::string get_config_path (boost::filesystem::path const & data_path)
{
	return (data_path / "config.json").string ();
}

std::string get_rpc_config_path (boost::filesystem::path const & data_path)
{
	return (data_path / "rpc_config.json").string ();
}

std::string get_node_toml_config_path (boost::filesystem::path const & data_path)
{
	return (data_path / "config-node.toml").string ();
}

std::string get_rpc_toml_config_path (boost::filesystem::path const & data_path)
{
	return (data_path / "config-rpc.toml").string ();
}

std::string get_qtwallet_toml_config_path (boost::filesystem::path const & data_path)
{
	return (data_path / "config-qtwallet.toml").string ();
}
}

ext: cpp

max_stars_repo_name: ArdeshirV/nano-node

max_issues_repo_name: ArdeshirV/nano-node

max_forks_repo_name: ArdeshirV/nano-node


text:
/*
Example taken from https://www.youtube.com/watch?v=Apm2KNj8GW4
*/

#include <iostream>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>

using namespace std;

namespace sc=boost::statechart;

struct lostMoney : sc::event<lostMoney> {};
struct gotMoney : sc::event<gotMoney> {};

struct HappyState;
struct SadState;
struct Person: sc::state_machine<Person,HappyState> {};

struct HappyState: sc::simple_state<HappyState,Person>
{
	HappyState()
	{
		cout << "Happy !\n";
	}
	typedef sc::transition<lostMoney,SadState> reactions;
};

struct SadState: sc::simple_state<SadState,Person>
{
	SadState()
	{
		cout << "Sad !\n";
	}
	typedef sc::transition<gotMoney,HappyState> reactions;
};

int main()
{
	cout << "start\n";
	Person sm;
	sm.initiate();
	sm.process_event( lostMoney() );
	sm.process_event( gotMoney() );
}

max_stars_repo_name: deodates-dev/FSM-CPP-spaghetti

max_issues_repo_name: deodates-dev/FSM-CPP-spaghetti

max_forks_repo_name: deodates-dev/FSM-CPP-spaghetti


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#include <arpa/inet.h>
#include <boost/chrono.hpp>
#include <boost/optional.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <yaml-cpp/yaml.h>

#include <common.h>
#include <latency.h>

#define FILL_CHAR 'a'

namespace po = boost::program_options;

int main(int argc, char *argv[])
{
    parse_args(argc, argv, false);

    struct sockaddr_in saddr = {};
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);
    if (inet_pton(AF_INET, server_ip_addr->c_str(), &saddr.sin_addr) != 1)
    {
        std::cerr << "Unable to parse IP address." << std::endl;
        return -1;
    }

    dmtr_latency_t *latency = NULL;
    assert(dmtr_new_latency(&latency, "end-to-end") == 0);

    int fd = socket(AF_INET, SOCK_STREAM, 0);
    // Set TCP_NODELAY
    int n = 1;
    if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&n, sizeof(n)) < 0)
    {
        exit(-1);
    }

    printf("client fd:\t%d\n", fd);
    std::cerr << "Attempting to connect to `" << boost::get(server_ip_addr) << ":" << port << "`..." << std::endl;
    assert(connect(fd, reinterpret_cast<struct sockaddr *>(&saddr), sizeof(saddr)) == 0);
    std::cerr << "Connected." << std::endl;

    char buf[packet_size];
    memset(&buf, FILL_CHAR, packet_size);
    buf[packet_size - 1] = '\0';

    for (size_t i = 0; i < iterations; i++)
    {
        auto t0 = boost::chrono::steady_clock::now();
        for (uint32_t i = 0; i < clients; i++)
        {
            int bytes_written = 0, ret;
            while (bytes_written < (int)packet_size)
            {
                ret = write(fd, (void *)&(buf[bytes_written]), packet_size - bytes_written);
                if (ret < 0)
                {
                    fprintf(stderr, "write says bye\n");
                    exit(-1);
                }
                bytes_written += ret;
            }
        }

        for (uint32_t i = 0; i < clients; i++)
        {
            int bytes_read = 0;
            while (bytes_read < (int)packet_size)
            {
                int ret = read(fd, (void *)&(buf[bytes_read]), packet_size - bytes_read);
                if (ret < 0)
                {
                    fprintf(stderr, "read says bye\n");
                    exit(-1);
                }
                bytes_read += ret;
            }
        }
        auto dt = boost::chrono::steady_clock::now() - t0;
        assert(dmtr_record_latency(latency, dt.count()) == 0);
        buf[packet_size - 1] = '\0';
    }
    close(fd);
    assert(dmtr_dump_latency(stderr, latency) == 0);
    return 0;
}

max_stars_repo_name: demikernel/echo

max_issues_repo_name: demikernel/echo

max_forks_repo_name: demikernel/echo


text:
#include <ros/ros.h>

#include <vector>
#include <boost/algorithm/string.hpp>

#include <pulson_ros/P4xx/RCM/rcmIf.h>
#include <pulson_ros/P4xx/RCM/rcm.h>
#include <pulson_ros/RangeArray.h>
#include <pulson_ros/RangeMeasurement.h>

void init(std::string dev_path);
void print_status(rcmMsg_GetStatusInfoConfirm *statusInfo);
void print_configuration(rcmConfiguration *config);
void error_check(int r, const char *msg);

int main(int argc, char **argv)
{

    ros::init(argc, argv, "rcm_node");
    ros::NodeHandle nh("~");

    // parameters
    int rate;
    std::string dev_path;
    std::string network_nodes;

    nh.param("rate", rate, 30);
    nh.param("dev_path", dev_path, std::string("/dev/ttyACM0"));
    nh.param("network_nodes", network_nodes, std::string(""));

    // publisher
    ros::Publisher range_pub = nh.advertise<pulson_ros::RangeArray>("/ranges", 100);

    // initialization
    init(dev_path);

    // extract node IDs from parameter
    std::vector<std::string> node_ids;
    boost::split(node_ids, network_nodes, boost::is_any_of("\t "));

    // variables to store the data
    int r;
    rcmMsg_FullRangeInfo rangeInfo;
    rcmMsg_DataInfo dataInfo;
    rcmMsg_ScanInfo scanInfo;
    rcmMsg_FullScanInfo fullScanInfo;

    // publish range data
    ros::Rate loop_rate(rate);
    while (ros::ok())
    {
        // message to be built
        pulson_ros::RangeArray range_array;

        // loop through all the nodes in the network
        for (int i = 0; i < node_ids.size(); i++)
        {

            // get next id
            int id = atoi(node_ids[i].c_str());
            if (id == 0)
            {
                break;
            }

            // compute range measurement
            r = rcmRangeTo(id, RCM_ANTENNAMODE_TXA_RXA, 0, NULL,
                    &rangeInfo, &dataInfo, &scanInfo, &fullScanInfo);
            if (r != 0)
            {
                continue;
            }

            // create message
            pulson_ros::RangeMeasurement range_measurement;
            range_measurement.message_id = rangeInfo.msgId;
            range_measurement.responder_id = rangeInfo.responderId;
            range_measurement.range_status = rangeInfo.rangeStatus;
            range_measurement.antenna_mode = rangeInfo.antennaMode;
            range_measurement.stopwatch_time = rangeInfo.stopwatchTime;
            range_measurement.precision_range = rangeInfo.precisionRangeMm;
            range_measurement.coarse_range = rangeInfo.coarseRangeMm;
            range_measurement.filtered_range = rangeInfo.filteredRangeMm;
            range_measurement.precision_range_error = rangeInfo.precisionRangeErrEst;
            range_measurement.coarse_range_error = rangeInfo.coarseRangeErrEst;
            range_measurement.filtered_range_error = rangeInfo.filteredRangeErrEst;
            range_measurement.filtered_velocity = rangeInfo.filteredRangeVel;
            range_measurement.filtered_velocity_error = rangeInfo.filteredRangeVelErrEst;
            range_measurement.timestamp = rangeInfo.timestamp;

            // save
            range_array.ranges.push_back(range_measurement);
        }

        // publish
        range_pub.publish(range_array);

        // block
        loop_rate.sleep();
    }

    // cleanup
    rcmIfClose();

}

void init(std::string dev_path)
{
    int r;

    // initialize interface
    r = rcmIfInit(rcmIfUsb, (char*) dev_path.c_str());
    error_check(r, "Initialization Failed");

    // make sure RCM is awake
    r = rcmSleepModeSet(RCM_SLEEP_MODE_ACTIVE);
    error_check(r, "Timeout waiting for sleep mode set");

    // make sure correct internal opmode is set
    r = rcmOpModeSet(RCM_OPMODE_RCM);
    error_check(r, "Timeout waiting for opmode set");

    // execute Built-In Test
    int status;
    r = rcmBit(&status);
    error_check(r, "Timeout waiting for test");
    error_check(status, "Built-In Test Failed");

    // get configuration from RCM
    rcmConfiguration config;
    r = rcmConfigGet(&config);
    error_check(r, "Timeout watiing for configuration");
    print_configuration(&config);

    // get status information
    rcmMsg_GetStatusInfoConfirm statusInfo;
    r = rcmStatusInfoGet(&statusInfo);
    error_check(r, "Timeout waiting for status information");
    print_status(&statusInfo);
}

void print_status(rcmMsg_GetStatusInfoConfirm *statusInfo)
{
    char buf[1024];
    sprintf(buf, "\n\tStatus Information:\n");
    sprintf(buf, "%s\t\tPackage Version: %s\n", buf, statusInfo->packageVersionStr);
    sprintf(buf, "%s\t\tRCM Version: %d.%d Build %d\n", buf,
            statusInfo->appVersionMajor,
            statusInfo->appVersionMinor,
            statusInfo->appVersionBuild);
    sprintf(buf, "%s\t\tUWB Kernel Version: %d.%d Build %d\n", buf,
            statusInfo->uwbKernelVersionMajor,
            statusInfo->uwbKernelVersionMinor,
            statusInfo->uwbKernelVersionBuild);
    sprintf(buf, "%s\t\tFirmware Version: %x/%x/%x Ver. %X\n", buf,
            statusInfo->firmwareMonth,
            statusInfo->firmwareDay,
            statusInfo->firmwareYear,
            statusInfo->firmwareVersion);
    sprintf(buf, "%s\t\tSerial Number: %08X\n", buf, statusInfo->serialNum);
    sprintf(buf, "%s\t\tBoard Revision: %c\n", buf, statusInfo->boardRev);
    sprintf(buf, "%s\t\tTemperature: %.2f degC\n", buf, statusInfo->temperature/4.0);

    ROS_INFO("[rcm_node] %s", buf);

}

void print_configuration(rcmConfiguration *config)
{
    char buf[1024];
    sprintf(buf, "\n\tConfiguration:\n");
    sprintf(buf, "%s\t\tNode ID: %d\n", buf, config->nodeId);
    sprintf(buf, "%s\t\tIntegration Index: %d\n", buf, config->integrationIndex);
    sprintf(buf, "%s\t\tAntenna Mode: %d\n", buf, config->antennaMode);
    sprintf(buf, "%s\t\tCode Channel: %d\n", buf, config->codeChannel);
    sprintf(buf, "%s\t\tElectrical Delay PsA: %d\n", buf, config->electricalDelayPsA);
    sprintf(buf, "%s\t\tElectrical Delay PsB: %d\n", buf, config->electricalDelayPsB);
    sprintf(buf, "%s\t\tFlags: 0x%X\n", buf, config->flags);
    sprintf(buf, "%s\t\ttxGain: %d\n", buf, config->txGain);

    ROS_INFO("[rcm_node] %s", buf);
}

void error_check(int r, char const *msg)
{
    if (r != 0)
    {
        ROS_ERROR("[rcm_node] %s\n", msg);
        ros::requestShutdown();
    }

}


text:
// This file is auto-generated, don't edit it. Thanks.

#include <alibabacloud/waf_openapi_20180117.hpp>
#include <alibabacloud/endpoint_util.hpp>
#include <alibabacloud/open_api.hpp>
#include <boost/any.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>
#include <vector>

using namespace std;

using namespace Alibabacloud_Waf-openapi20180117;

Alibabacloud_Waf-openapi20180117::Client::Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config) : Alibabacloud_OpenApi::Client(config) {
  _endpointRule = make_shared<string>("regional");
  _endpointMap = make_shared<map<string, string>>(map<string, string>({
    {"cn-qingdao", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-beijing", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-chengdu", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-zhangjiakou", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-huhehaote", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-hangzhou", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-shanghai", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-shenzhen", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-heyuan", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-wulanchabu", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-hongkong", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"ap-southeast-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"ap-southeast-2", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"ap-southeast-3", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"ap-southeast-5", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"eu-west-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"us-west-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"us-east-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"eu-central-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"me-east-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"ap-south-1", "wafopenapi.ap-southeast-1.aliyuncs.com"},
    {"cn-shanghai-finance-1", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-shenzhen-finance-1", "wafopenapi.cn-hangzhou.aliyuncs.com"},
    {"cn-north-2-gov-1", "wafopenapi.cn-hangzhou.aliyuncs.com"}
  })
);
  checkConfig(config);
  _endpoint = make_shared<string>(getEndpoint(make_shared<string>("waf-openapi"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint));
};

string Alibabacloud_Waf-openapi20180117::Client::getEndpoint(shared_ptr<string> productId,
                                                             shared_ptr<string> regionId,
                                                             shared_ptr<string> endpointRule,
                                                             shared_ptr<string> network,
                                                             shared_ptr<string> suffix,
                                                             shared_ptr<map<string, string>> endpointMap,
                                                             shared_ptr<string> endpoint) {
  if (!Darabonba_Util::Client::empty(endpoint)) {
    return *endpoint;
  }
  if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)["[object Object]"]))) {
    return (*endpointMap)["[object Object]"];
  }
  return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix);
}

CreateAclRuleResponse Alibabacloud_Waf-openapi20180117::Client::createAclRuleWithOptions(shared_ptr<CreateAclRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return CreateAclRuleResponse(doRPCRequest(make_shared<string>("CreateAclRule"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

CreateAclRuleResponse Alibabacloud_Waf-openapi20180117::Client::createAclRule(shared_ptr<CreateAclRuleRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return createAclRuleWithOptions(request, runtime);
}

CreateCertAndKeyResponse Alibabacloud_Waf-openapi20180117::Client::createCertAndKeyWithOptions(shared_ptr<CreateCertAndKeyRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return CreateCertAndKeyResponse(doRPCRequest(make_shared<string>("CreateCertAndKey"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

CreateCertAndKeyResponse Alibabacloud_Waf-openapi20180117::Client::createCertAndKey(shared_ptr<CreateCertAndKeyRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return createCertAndKeyWithOptions(request, runtime);
}

CreateDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::createDomainConfigWithOptions(shared_ptr<CreateDomainConfigRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return CreateDomainConfigResponse(doRPCRequest(make_shared<string>("CreateDomainConfig"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

CreateDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::createDomainConfig(shared_ptr<CreateDomainConfigRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return createDomainConfigWithOptions(request, runtime);
}

CreateProtectionModuleRuleResponse Alibabacloud_Waf-openapi20180117::Client::createProtectionModuleRuleWithOptions(shared_ptr<CreateProtectionModuleRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return CreateProtectionModuleRuleResponse(doRPCRequest(make_shared<string>("CreateProtectionModuleRule"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

CreateProtectionModuleRuleResponse Alibabacloud_Waf-openapi20180117::Client::createProtectionModuleRule(shared_ptr<CreateProtectionModuleRuleRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return createProtectionModuleRuleWithOptions(request, runtime);
}

DeleteAclRuleResponse Alibabacloud_Waf-openapi20180117::Client::deleteAclRuleWithOptions(shared_ptr<DeleteAclRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DeleteAclRuleResponse(doRPCRequest(make_shared<string>("DeleteAclRule"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DeleteAclRuleResponse Alibabacloud_Waf-openapi20180117::Client::deleteAclRule(shared_ptr<DeleteAclRuleRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return deleteAclRuleWithOptions(request, runtime);
}

DeleteDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::deleteDomainConfigWithOptions(shared_ptr<DeleteDomainConfigRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DeleteDomainConfigResponse(doRPCRequest(make_shared<string>("DeleteDomainConfig"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DeleteDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::deleteDomainConfig(shared_ptr<DeleteDomainConfigRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return deleteDomainConfigWithOptions(request, runtime);
}

DescribeAclRulesResponse Alibabacloud_Waf-openapi20180117::Client::describeAclRulesWithOptions(shared_ptr<DescribeAclRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeAclRulesResponse(doRPCRequest(make_shared<string>("DescribeAclRules"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeAclRulesResponse Alibabacloud_Waf-openapi20180117::Client::describeAclRules(shared_ptr<DescribeAclRulesRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeAclRulesWithOptions(request, runtime);
}

DescribeAsyncTaskStatusResponse Alibabacloud_Waf-openapi20180117::Client::describeAsyncTaskStatusWithOptions(shared_ptr<DescribeAsyncTaskStatusRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeAsyncTaskStatusResponse(doRPCRequest(make_shared<string>("DescribeAsyncTaskStatus"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeAsyncTaskStatusResponse Alibabacloud_Waf-openapi20180117::Client::describeAsyncTaskStatus(shared_ptr<DescribeAsyncTaskStatusRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeAsyncTaskStatusWithOptions(request, runtime);
}

DescribeDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::describeDomainConfigWithOptions(shared_ptr<DescribeDomainConfigRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeDomainConfigResponse(doRPCRequest(make_shared<string>("DescribeDomainConfig"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::describeDomainConfig(shared_ptr<DescribeDomainConfigRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeDomainConfigWithOptions(request, runtime);
}

DescribeDomainConfigStatusResponse Alibabacloud_Waf-openapi20180117::Client::describeDomainConfigStatusWithOptions(shared_ptr<DescribeDomainConfigStatusRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeDomainConfigStatusResponse(doRPCRequest(make_shared<string>("DescribeDomainConfigStatus"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeDomainConfigStatusResponse Alibabacloud_Waf-openapi20180117::Client::describeDomainConfigStatus(shared_ptr<DescribeDomainConfigStatusRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeDomainConfigStatusWithOptions(request, runtime);
}

DescribeDomainNamesResponse Alibabacloud_Waf-openapi20180117::Client::describeDomainNamesWithOptions(shared_ptr<DescribeDomainNamesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeDomainNamesResponse(doRPCRequest(make_shared<string>("DescribeDomainNames"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeDomainNamesResponse Alibabacloud_Waf-openapi20180117::Client::describeDomainNames(shared_ptr<DescribeDomainNamesRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeDomainNamesWithOptions(request, runtime);
}

DescribePayInfoResponse Alibabacloud_Waf-openapi20180117::Client::describePayInfoWithOptions(shared_ptr<DescribePayInfoRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribePayInfoResponse(doRPCRequest(make_shared<string>("DescribePayInfo"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribePayInfoResponse Alibabacloud_Waf-openapi20180117::Client::describePayInfo(shared_ptr<DescribePayInfoRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describePayInfoWithOptions(request, runtime);
}

DescribeProtectionModuleRulesResponse Alibabacloud_Waf-openapi20180117::Client::describeProtectionModuleRulesWithOptions(shared_ptr<DescribeProtectionModuleRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeProtectionModuleRulesResponse(doRPCRequest(make_shared<string>("DescribeProtectionModuleRules"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeProtectionModuleRulesResponse Alibabacloud_Waf-openapi20180117::Client::describeProtectionModuleRules(shared_ptr<DescribeProtectionModuleRulesRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeProtectionModuleRulesWithOptions(request, runtime);
}

DescribeRegionsResponse Alibabacloud_Waf-openapi20180117::Client::describeRegionsWithOptions(shared_ptr<DescribeRegionsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeRegionsResponse(doRPCRequest(make_shared<string>("DescribeRegions"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeRegionsResponse Alibabacloud_Waf-openapi20180117::Client::describeRegions(shared_ptr<DescribeRegionsRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeRegionsWithOptions(request, runtime);
}

DescribeWafSourceIpSegmentResponse Alibabacloud_Waf-openapi20180117::Client::describeWafSourceIpSegmentWithOptions(shared_ptr<DescribeWafSourceIpSegmentRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return DescribeWafSourceIpSegmentResponse(doRPCRequest(make_shared<string>("DescribeWafSourceIpSegment"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

DescribeWafSourceIpSegmentResponse Alibabacloud_Waf-openapi20180117::Client::describeWafSourceIpSegment(shared_ptr<DescribeWafSourceIpSegmentRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return describeWafSourceIpSegmentWithOptions(request, runtime);
}

ModifyAclRuleResponse Alibabacloud_Waf-openapi20180117::Client::modifyAclRuleWithOptions(shared_ptr<ModifyAclRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return ModifyAclRuleResponse(doRPCRequest(make_shared<string>("ModifyAclRule"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

ModifyAclRuleResponse Alibabacloud_Waf-openapi20180117::Client::modifyAclRule(shared_ptr<ModifyAclRuleRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return modifyAclRuleWithOptions(request, runtime);
}

ModifyDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::modifyDomainConfigWithOptions(shared_ptr<ModifyDomainConfigRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return ModifyDomainConfigResponse(doRPCRequest(make_shared<string>("ModifyDomainConfig"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

ModifyDomainConfigResponse Alibabacloud_Waf-openapi20180117::Client::modifyDomainConfig(shared_ptr<ModifyDomainConfigRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return modifyDomainConfigWithOptions(request, runtime);
}

ModifyProtectionRuleCacheStatusResponse Alibabacloud_Waf-openapi20180117::Client::modifyProtectionRuleCacheStatusWithOptions(shared_ptr<ModifyProtectionRuleCacheStatusRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return ModifyProtectionRuleCacheStatusResponse(doRPCRequest(make_shared<string>("ModifyProtectionRuleCacheStatus"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

ModifyProtectionRuleCacheStatusResponse Alibabacloud_Waf-openapi20180117::Client::modifyProtectionRuleCacheStatus(shared_ptr<ModifyProtectionRuleCacheStatusRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return modifyProtectionRuleCacheStatusWithOptions(request, runtime);
}

ModifyProtectionRuleStatusResponse Alibabacloud_Waf-openapi20180117::Client::modifyProtectionRuleStatusWithOptions(shared_ptr<ModifyProtectionRuleStatusRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return ModifyProtectionRuleStatusResponse(doRPCRequest(make_shared<string>("ModifyProtectionRuleStatus"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

ModifyProtectionRuleStatusResponse Alibabacloud_Waf-openapi20180117::Client::modifyProtectionRuleStatus(shared_ptr<ModifyProtectionRuleStatusRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return modifyProtectionRuleStatusWithOptions(request, runtime);
}

ModifyWafSwitchResponse Alibabacloud_Waf-openapi20180117::Client::modifyWafSwitchWithOptions(shared_ptr<ModifyWafSwitchRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return ModifyWafSwitchResponse(doRPCRequest(make_shared<string>("ModifyWafSwitch"), make_shared<string>("2018-01-17"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

ModifyWafSwitchResponse Alibabacloud_Waf-openapi20180117::Client::modifyWafSwitch(shared_ptr<ModifyWafSwitchRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return modifyWafSwitchWithOptions(request, runtime);
}

max_stars_repo_name: aliyun/alibabacloud-cpp-sdk

max_issues_repo_name: aliyun/alibabacloud-cpp-sdk

max_forks_repo_name: aliyun/alibabacloud-cpp-sdk


text:
#include "examples/cuttingstock.hpp"
#include "examples/multipleknapsack.hpp"
#include "examples/binpackingwithconflicts.hpp"
#include "examples/capacitatedvehiclerouting.hpp"
#include "examples/vehicleroutingwithtimewindows.hpp"
#include "examples/capacitatedopenvehiclerouting.hpp"
#include "examples/parallelschedulingwithfamilysetuptimestwct.hpp"
#include "examples/starobservationscheduling.hpp"

#include "columngenerationsolver/read_args.hpp"

#include <boost/program_options.hpp>

using namespace columngenerationsolver;

namespace po = boost::program_options;

void run(
        std::string algorithm,
        std::string columngeneration_args_string,
        const optimizationtools::Info& info,
        Parameters& p)
{
    std::vector<std::string> algorithm_args
        = boost::program_options::split_unix(algorithm);
    std::vector<char*> algorithm_argv;
    for (Counter i = 0; i < (Counter)algorithm_args.size(); ++i)
        algorithm_argv.push_back(const_cast<char*>(algorithm_args[i].c_str()));

    ColumnGenerationOptionalParameters columngeneration_parameters
        = read_columngeneration_args(columngeneration_args_string);

    if (algorithm_args[0] == "columngeneration") {
        columngeneration_parameters.info = info;
        columngeneration(p, columngeneration_parameters);
    } else if (algorithm_args[0] == "greedy") {
        GreedyOptionalParameters op;
        op.info = info;
        op.columngeneration_parameters = columngeneration_parameters;
        greedy(p, op);
    } else if (algorithm_args[0] == "limiteddiscrepancysearch") {
        auto op = read_limiteddiscrepancysearch_args(algorithm_argv);
        op.info = info;
        op.columngeneration_parameters = columngeneration_parameters;
        limiteddiscrepancysearch(p, op);
    } else if (algorithm_args[0] == "heuristictreesearch") {
        auto op = read_heuristictreesearch_args(algorithm_argv);
        op.info = info;
        op.columngeneration_parameters = columngeneration_parameters;
        heuristictreesearch(p, op);
    } else {
        std::cerr << "\033[31m" << "ERROR, unknown algorithm: '" << algorithm_args[0] << "'.\033[0m" << std::endl;
    }
}

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

    // Parse program options

    std::string problem = "cuttingstock";
    std::string instance_path = "";
    std::string output_path = "";
    std::string certificate_path = "";
    std::string format = "";
    std::string algorithm = "heuristictreesearch";
    std::string columngeneration_args_string = "";
    double time_limit = std::numeric_limits<double>::infinity();

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "produce help message")
        ("problem,p", po::value<std::string>(&problem)->required(), "set problem (required)")
        ("input,i", po::value<std::string>(&instance_path)->required(), "set input path (required)")
        ("output,o", po::value<std::string>(&output_path), "set JSON output path")
        ("certificate,c", po::value<std::string>(&certificate_path), "set certificate path")
        ("format,f", po::value<std::string>(&format), "set input file format (default: orlibrary)")
        ("algorithm,a", po::value<std::string>(&algorithm), "set algorithm")
        ("column-generation-parameters,g", po::value<std::string>(&columngeneration_args_string), "set column generation parameters")
        ("time-limit,t", po::value<double>(&time_limit), "Time limit in seconds\n  ex: 3600")
        ("verbose,v", "")
        ("print-instance", "")
        ("print-solution", "")
        ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    if (vm.count("help")) {
        std::cout << desc << std::endl;;
        return 1;
    }
    try {
        po::notify(vm);
    } catch (const po::required_option& e) {
        std::cout << desc << std::endl;;
        return 1;
    }

    optimizationtools::Info info = optimizationtools::Info()
        .set_verbose(vm.count("verbose"))
        .set_time_limit(time_limit)
        .set_json_output_path(output_path)
        .set_sigint_handler()
        ;

    // Run algorithm

    if (problem == "cuttingstock") {
        cuttingstock::Instance instance(instance_path, format);
        //if (vm.count("print-instance")) TODO
        //    std::cout << instance << std::endl;
        Parameters p = cuttingstock::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "multipleknapsack") {
        multipleknapsack::Instance instance(instance_path, format);
        //if (vm.count("print-instance")) TODO
        //    std::cout << instance << std::endl;
        Parameters p = multipleknapsack::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "binpackingwithconflicts") {
        binpackingwithconflicts::Instance instance(instance_path, format);
        //if (vm.count("print-instance")) TODO
        //    std::cout << instance << std::endl;
        Parameters p = binpackingwithconflicts::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "capacitatedvehiclerouting") {
        capacitatedvehiclerouting::Instance instance(instance_path, format);
        //if (vm.count("print-instance")) TODO
        //    std::cout << instance << std::endl;
        Parameters p = capacitatedvehiclerouting::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "vehicleroutingwithtimewindows") {
        vehicleroutingwithtimewindows::Instance instance(instance_path, format);
        //if (vm.count("print-instance")) TODO
        //    std::cout << instance << std::endl;
        Parameters p = vehicleroutingwithtimewindows::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "capacitatedopenvehiclerouting") {
        capacitatedopenvehiclerouting::Instance instance(instance_path, format);
        if (vm.count("print-instance"))
            std::cout << instance << std::endl;
        Parameters p = capacitatedopenvehiclerouting::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "parallelschedulingwithfamilysetuptimestwct") {
        parallelschedulingwithfamilysetuptimestwct::Instance instance(instance_path, format);
        if (vm.count("print-instance"))
            std::cout << instance << std::endl;
        Parameters p = parallelschedulingwithfamilysetuptimestwct::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else if (problem == "starobservationscheduling") {
        starobservationscheduling::Instance instance(instance_path, format);
        //if (vm.count("print-instance")) TODO
        //    std::cout << instance << std::endl;
        Parameters p = starobservationscheduling::get_parameters(instance);
        run(algorithm, columngeneration_args_string, info, p);

    } else {
        std::cerr << "\033[31m" << "ERROR, unknown problem: '" << problem << "'.\033[0m" << std::endl;
        return 1;
    }

    return 0;
}

max_stars_repo_name: fontanf/columngenerationsolver

max_issues_repo_name: fontanf/columngenerationsolver

max_forks_repo_name: fontanf/columngenerationsolver


text:
//
//  Meshrectangular.hpp
//  hybrid_fem_bie
//
//  Created by Max on 2/5/18.
//
//

#ifndef Meshrectangular_hpp
#define Meshrectangular_hpp

#include <stdio.h>
#include <Eigen/Eigen>
#include "share_header.hpp"
using namespace Eigen;

void Meshrectangular(double x_min, double x_max, double y_min, double y_max, double dx ,double dy ,int nx, int ny , MatrixXd &Node, MatrixXi_rm &Element);

#endif /* Meshrectangular_hpp */

ext: hpp


text:
/*=============================================================================
    Copyright (c) 1999-2003 Jaakko Jarvi
    Copyright (c) 2001-2011 Joel de Guzman

    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)
==============================================================================*/
#if !defined(FUSION_LESS_05052005_0432)
#define FUSION_LESS_05052005_0432

#include <boost/fusion/sequence/comparison/detail/less.hpp>
#include <boost/fusion/sequence/comparison/enable_comparison.hpp>
#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/fusion/sequence/intrinsic/size.hpp>
#include <boost/fusion/support/config.hpp>

namespace boost {
namespace fusion {
template <typename Seq1, typename Seq2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline bool less(Seq1 const &a,
                                                          Seq2 const &b) {
  return detail::sequence_less<Seq1 const, Seq2 const>::call(fusion::begin(a),
                                                             fusion::begin(b));
}

namespace operators {
template <typename Seq1, typename Seq2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline
    typename boost::enable_if<traits::enable_comparison<Seq1, Seq2>, bool>::type
    operator<(Seq1 const &a, Seq2 const &b) {
  return fusion::less(a, b);
}
} // namespace operators
using operators::operator<;
} // namespace fusion
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix