#include "supercontrol.h++"
#include <cstdlib>
#include <iostream>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
void  xftpclient::SuperControl::LList (Tokenizer &	 optns)
{

	using namespace std;
	using namespace boost::lambda;
	string path (".");
	int recurse=0;
	Tokenizer::iterator i =optns.begin ();
	if (i!=optns.end ())
	{
		path.assign (*i);
		if (++i!=optns.end ())
			recurse=atoi (i->c_str ());
	}
	xftp::server::MsgList list ;
	list.Fill (path, recurse);
	PrintNode (list.GetNode ());

}


text: #include <boost/mpl/map/aux_/has_key_impl.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// $Id: e57unpack.cpp 338 2013-09-03 12:36:09Z roland_schwarz $
#include <config.h>

#define PROGRAM_NAME "e57unpack"
#define PROGRAM_VERSION "1.0"
#ifndef SVN_VERSION
#  define SVN_VERSION unknown
#endif
#define STRING_HELPER2(a) #a
#define STRING_HELPER1(a) STRING_HELPER2(a)
#define BUILD_VERSION STRING_HELPER1(SVN_VERSION)

#include <openE57/openE57.h>
using e57::BlobNode;
using e57::CompressedVectorNode;
using e57::CompressedVectorReader;
using e57::E57Exception;
using e57::E57Utilities;
using e57::FloatNode;
using e57::ImageFile;
using e57::int64_t;
using e57::IntegerNode;
using e57::Node;
using e57::ScaledIntegerNode;
using e57::SourceDestBuffer;
using e57::StringNode;
using e57::StructureNode;
using e57::uint64_t;
using e57::uint8_t;
using e57::ustring;
using e57::VectorNode;

#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
using std::ios_base;
using std::ostream;
using std::streamsize;

#include <exception>
using std::exception;

#include <stdexcept>
using std::runtime_error;

#include <memory>

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <limits>
using std::numeric_limits;

#include <boost/config.hpp>

#include <boost/program_options.hpp>
using boost::program_options::command_line_parser;
using boost::program_options::options_description;
using boost::program_options::positional_options_description;
using boost::program_options::store;
using boost::program_options::value;
using boost::program_options::variables_map;

#include <boost/filesystem.hpp>
using boost::filesystem::create_directories;
using boost::filesystem::path;
using boost::filesystem::portable_directory_name;

#include <boost/filesystem/fstream.hpp>
using boost::filesystem::ofstream;

#include <boost/variant.hpp>
using boost::apply_visitor;
using boost::get;
using boost::static_visitor;
using boost::variant;

#include <boost/format.hpp>
using boost::format;
using boost::io::all_error_bits;
using boost::io::too_many_args_bit;

#include <boost/lexical_cast.hpp>
using boost::lexical_cast;

variables_map opt;

void print_version()
{
  cout << PROGRAM_NAME " (" << BOOST_PLATFORM << ") " << PROGRAM_VERSION << "." << '\n';

  int     astmMajor;
  int     astmMinor;
  ustring libraryId;
  E57Utilities().getVersions(astmMajor, astmMinor, libraryId);

  cout << "E57 API " << astmMajor << "." << astmMinor << endl;
  cout << libraryId << endl;
}

void print_help(const options_description& options)
{
  cout << "Usage:\n"
       << PROGRAM_NAME " [options] e57-file [unpack-directory]\n"
       << "  The purpose of this program is to break the e57 file into\n"
       << "  parts.\n"
       << endl
       << options;
}

class get_at : public static_visitor<variant<double, int64_t, ustring>>
{
  size_t at;

public:
  get_at(size_t at_) : at(at_) {}
  template <typename T>
  variant<double, int64_t, ustring> operator()(T& operand) const
  {
    return operand[at];
  }
};

int main(int argc, char* argv[])
{
  try
  {
    options_description options("options");
    options.add_options()("version,v", "show version")("help,h", "show help")("format,F", value<std::string>(),
                                                                              "a boost::format format string for\n"
                                                                              "the pointrecord data.\n")("src", value<string>(),
                                                                                "define e57 file\n"
                                                                                "  (--src may be omitted)\n")(
      "dst", value<string>(),
      "the destination directory\n"
      "  (--dst may be omitted)")("no-images", "supress image output")("no-points", "supress pointcloud output");

    positional_options_description positional;
    positional.add("src", 1);
    positional.add("dst", 2);

    store(command_line_parser(argc, argv).options(options).positional(positional).run(), opt);

    if (opt.count("version"))
    {
      print_version();
      return 0;
    }

    if (opt.count("help"))
    {
      print_help(options);
      return 0;
    }

    if (opt.count("src"))
    {
      string fmt;
      if (opt.count("format"))
        fmt = opt["format"].as<string>();

      ImageFile     imf(opt["src"].as<string>(), "r");
      StructureNode root = imf.root();

      path dst;
      if (opt.count("dst"))
        dst = path(opt["dst"].as<string>());
      else
      {
        dst = path(opt["src"].as<string>());
        dst.replace_extension();
      }

      create_directories(dst);

      ofstream root_inf(dst / "root.inf");
      root_inf << "formatName = " << StringNode(root.get("formatName")).value() << endl;
      root_inf << "guid = " << StringNode(root.get("guid")).value() << endl;
      root_inf << "versionMajor = " << IntegerNode(root.get("versionMajor")).value() << endl;
      root_inf << "versionMinor = " << IntegerNode(root.get("versionMinor")).value() << endl;
      if (root.isDefined("e57LibraryVersion"))
      {
        root_inf << "e57LibraryVersion = " << StringNode(root.get("e57LibraryVersion")).value() << endl;
      }
      if (root.isDefined("coordinateMetadata"))
      {
        root_inf << "coordinateMetadata = " << StringNode(root.get("coordinateMetadata")).value() << endl;
      }
      if (root.isDefined("creationDateTime"))
      {
        StructureNode t(root.get("creationDateTime"));
        root_inf << format("creationDateTime.dateTimeValue = %.15g\n") % FloatNode(t.get("dateTimeValue")).value();
        if (t.isDefined("isAtomicClockReferenced"))
        {
          root_inf << "creationDateTime.isAtomicClockReferenced = " << IntegerNode(t.get("isAtomicClockReferenced")).value() << endl;
        }
      }
      root_inf.close();

      if (root.isDefined("data3D") && !opt.count("no-points"))
      {
        VectorNode data3D(root.get("data3D"));
        for (int64_t child = 0; child < data3D.childCount(); ++child)
        {
          StructureNode                                                     scan(data3D.get(child));
          CompressedVectorNode                                              points(scan.get("points"));
          StructureNode                                                     prototype(points.prototype());
          vector<SourceDestBuffer>                                          sdb;
          const size_t                                                      buf_size = 1024;
          vector<variant<vector<double>, vector<int64_t>, vector<ustring>>> buf;
          string                                                            pointrecord;

          string comma;
          if (!opt.count("format"))
          {
            fmt.clear();
            for (int64_t i = 0; i < prototype.childCount(); ++i)
            {
              switch (prototype.get(i).type())
              {
              case e57::E57_FLOAT:
              case e57::E57_SCALED_INTEGER:
                buf.push_back(vector<double>(buf_size));
                if (!opt.count("format"))
                  fmt += comma + "%." + lexical_cast<string>(numeric_limits<double>::digits10) + "g";
                break;
              case e57::E57_INTEGER:
                buf.push_back(vector<int64_t>(buf_size));
                if (!opt.count("format"))
                  fmt += comma + "%d";
                break;
              case e57::E57_STRING:
                buf.push_back(vector<ustring>(buf_size));
                if (!opt.count("format"))
                  fmt += comma + "%s";
                break;
              case e57::E57_STRUCTURE:
              case e57::E57_VECTOR:
              case e57::E57_COMPRESSED_VECTOR:
              case e57::E57_BLOB:
              default:
                break;
              }
              if (comma.empty())
                comma = ",";
            }
          }
          comma.clear();
          for (int i = 0; i < prototype.childCount(); ++i)
          {
            Node n(prototype.get(i));
            pointrecord += comma + n.elementName();
            if (comma.empty())
              comma = ",";
            switch (n.type())
            {
            case e57::E57_FLOAT:
            case e57::E57_SCALED_INTEGER:
              sdb.push_back(SourceDestBuffer(imf, n.elementName(), &get<vector<double>>(buf[i])[0], buf_size, true, true));
              break;
            case e57::E57_INTEGER:
              sdb.push_back(SourceDestBuffer(imf, n.elementName(), &get<vector<int64_t>>(buf[i])[0], buf_size, true, true));
              break;
            case e57::E57_STRING:
              sdb.push_back(SourceDestBuffer(imf, n.elementName(), &get<vector<ustring>>(buf[i])));
              break;
            default:
              throw(runtime_error("prototype contains illegal type"));
            }
          }

          ofstream inf(dst / path(string("image3d-") + lexical_cast<string>(child) + ".inf"));
          inf << "pointrecord = " << pointrecord << endl; // can be used as a header line for the csv file
          inf << "pointrecord.format = " << fmt << endl;
          if (scan.isDefined("name"))
          {
            inf << "name = " << StringNode(scan.get("name")).value() << endl;
          }
          inf << "guid = " << StringNode(scan.get("guid")).value() << endl;
          if (scan.isDefined("description"))
          {
            inf << "description = " << StringNode(scan.get("description")).value() << endl;
          }
          if (scan.isDefined("pose"))
          {
            StructureNode pose(scan.get("pose"));
            StructureNode translation(pose.get("translation"));
            StructureNode rotation(pose.get("rotation"));
            inf << "pose.translation.x = " << FloatNode(translation.get("x")).value() << endl;
            inf << "pose.translation.y = " << FloatNode(translation.get("y")).value() << endl;
            inf << "pose.translation.z = " << FloatNode(translation.get("z")).value() << endl;
            inf << "pose.rotation.w = " << FloatNode(rotation.get("w")).value() << endl;
            inf << "pose.rotation.x = " << FloatNode(rotation.get("x")).value() << endl;
            inf << "pose.rotation.y = " << FloatNode(rotation.get("y")).value() << endl;
            inf << "pose.rotation.z = " << FloatNode(rotation.get("z")).value() << endl;
          }
          if (scan.isDefined("acquisitionStart"))
          {
            StructureNode t(scan.get("acquisitionStart"));
            inf << format("acquisitionStart.dateTimeValue = %.15g\n") % FloatNode(t.get("dateTimeValue")).value();
            if (t.isDefined("isAtomicClockReferenced"))
            {
              inf << "acquisitionStart.isAtomicClockReferenced = " << IntegerNode(t.get("isAtomicClockReferenced")).value() << endl;
            }
          }
          if (scan.isDefined("acquisitionEnd"))
          {
            StructureNode t(scan.get("acquisitionEnd"));
            inf << format("acquisitionEnd.dateTimeValue = %.15g\n") % FloatNode(t.get("dateTimeValue")).value();
            if (t.isDefined("isAtomicClockReferenced"))
            {
              inf << "acquisitionEnd.isAtomicClockReferenced = " << IntegerNode(t.get("isAtomicClockReferenced")).value() << endl;
            }
          }
          if (scan.isDefined("sensorVendor"))
          {
            inf << "sensorVendor = " << StringNode(scan.get("sensorVendor")).value() << endl;
          }
          if (scan.isDefined("sensorModel"))
          {
            inf << "sensorModel = " << StringNode(scan.get("sensorModel")).value() << endl;
          }
          if (scan.isDefined("sensorSerialNumber"))
          {
            inf << "sensorSerialNumber = " << StringNode(scan.get("sensorSerialNumber")).value() << endl;
          }
          if (scan.isDefined("HardwareVersion"))
          {
            inf << "HardwareVersion = " << StringNode(scan.get("HardwareVersion")).value() << endl;
          }
          if (scan.isDefined("SoftwareVersion"))
          {
            inf << "SoftwareVersion = " << StringNode(scan.get("SoftwareVersion")).value() << endl;
          }
          if (scan.isDefined("FirmwareVersion"))
          {
            inf << "FirmwareVersion = " << StringNode(scan.get("FirmwareVersion")).value() << endl;
          }
          if (scan.isDefined("temperature"))
          {
            inf << "temperature = " << FloatNode(scan.get("temperature")).value() << endl;
          }
          if (scan.isDefined("relativeHumidity"))
          {
            inf << "relativeHumidity = " << FloatNode(scan.get("relativeHumidity")).value() << endl;
          }
          if (scan.isDefined("atmosphericPressure"))
          {
            inf << "atmosphericPressure = " << FloatNode(scan.get("atmosphericPressure")).value() << endl;
          }
          inf.close();

          CompressedVectorReader rd(points.reader(sdb));
          path                   csvname(string("image3d-") + lexical_cast<string>(child) + ".csv");
          ofstream               ocsv(dst / csvname);
          ostream&               out(ocsv); // needed to fix ambiguity for << operator on msvc
          cout << "unpacking: " << dst / csvname << " ... ";
          unsigned count;
          uint64_t total_count(0);

          format tfmt(fmt);
          tfmt.exceptions(all_error_bits ^ too_many_args_bit);
          out << pointrecord << endl; // put the header line into csv
          while ((count = rd.read()))
          {
            total_count += count;
            for (size_t i = 0; i < count; ++i)
            {
              for (size_t j = 0; j < buf.size(); ++j)
                tfmt = tfmt % apply_visitor(get_at(i), buf.at(j));
              out << tfmt << endl;
            }
          }
          cout << " total points: " << total_count << endl;

          ocsv.close();
        }
      }

      if (root.isDefined("images2D") && !opt.count("no-images"))
      {
        VectorNode images2D(root.get("images2D"));
        for (int64_t child = 0; child < images2D.childCount(); ++child)
        {
          StructureNode image(images2D.get(child));
          path          inf_path = dst / path(string("image2d-") + lexical_cast<string>(child) + ".inf");
          ofstream      inf(inf_path);
          string        reptype;
          if (image.isDefined("visualReferenceRepresentation"))
            reptype = "visualReferenceRepresentation";
          else if (image.isDefined("pinholeRepresentation"))
            reptype = "pinholeRepresentation";
          else if (image.isDefined("sphericalRepresentation"))
            reptype = "sphericalRepresentation";
          else if (image.isDefined("cylindricalRepresentation"))
            reptype = "cylindricalRepresentation";
          StructureNode rep(image.get(reptype));
          string        imgtype;
          path          img_path(dst / path(string("image2d-") + lexical_cast<string>(child) + ".img"));
          if (rep.isDefined("jpegImage"))
          {
            img_path.replace_extension(".jpg");
            imgtype = "jpegImage";
          }
          else if (rep.isDefined("pngImage"))
          {
            img_path.replace_extension(".png");
            imgtype = "pngImage";
          }
          // extract image blob
          BlobNode         blob(rep.get(imgtype));
          ofstream         img(img_path, ios_base::out | ios_base::binary);
          const streamsize buffer_size = 1024 * 1024;
          vector<uint8_t>  buffer(buffer_size);
          int64_t          offset    = 0;
          int64_t          remaining = blob.byteCount();
          size_t           get;
          cout << "unpacking: " << img_path << " ... ";
          while (img && remaining > 0)
          {
            get = (remaining > buffer_size) ? buffer_size : remaining;
            blob.read(&buffer[0], offset, get);
            img.write(reinterpret_cast<char*>(&buffer[0]), get);
            offset += get;
            remaining -= get;
          }
          img.close();
          // extract meta data
          inf << "guid = " << StringNode(image.get("guid")).value() << endl;
          if (image.isDefined("name"))
          {
            inf << "name = " << StringNode(image.get("name")).value() << endl;
          }
          if (image.isDefined("description"))
          {
            inf << "description = " << StringNode(image.get("description")).value() << endl;
          }
          if (image.isDefined("sensorVendor"))
          {
            inf << "sensorVendor = " << StringNode(image.get("sensorVendor")).value() << endl;
          }
          if (image.isDefined("sensorModel"))
          {
            inf << "sensorModel = " << StringNode(image.get("sensorModel")).value() << endl;
          }
          if (image.isDefined("sensorSerialNumber"))
          {
            inf << "sensorSerialNumber = " << StringNode(image.get("sensorSerialNumber")).value() << endl;
          }
          if (image.isDefined("pose"))
          {
            StructureNode pose(image.get("pose"));
            StructureNode translation(pose.get("translation"));
            StructureNode rotation(pose.get("rotation"));
            inf << "pose.translation.x = " << FloatNode(translation.get("x")).value() << endl;
            inf << "pose.translation.y = " << FloatNode(translation.get("y")).value() << endl;
            inf << "pose.translation.z = " << FloatNode(translation.get("z")).value() << endl;
            inf << "pose.rotation.w = " << FloatNode(rotation.get("w")).value() << endl;
            inf << "pose.rotation.x = " << FloatNode(rotation.get("x")).value() << endl;
            inf << "pose.rotation.y = " << FloatNode(rotation.get("y")).value() << endl;
            inf << "pose.rotation.z = " << FloatNode(rotation.get("z")).value() << endl;
          }
          if (rep.isDefined("imageHeight"))
          {
            inf << reptype + ".imageHeight = " << IntegerNode(rep.get("imageHeight")).value() << endl;
            cout << IntegerNode(rep.get("imageHeight")).value() << " x ";
          }
          if (rep.isDefined("imageWidth"))
          {
            inf << reptype + ".imageWidth = " << IntegerNode(rep.get("imageWidth")).value() << endl;
            cout << IntegerNode(rep.get("imageWidth")).value() << " pixels" << endl;
          }
          if (rep.isDefined("focalLength"))
          {
            inf << reptype + ".focalLength = " << FloatNode(rep.get("focalLength")).value() << endl;
          }
          if (rep.isDefined("pixelWidth"))
          {
            inf << reptype + ".pixelWidth = " << FloatNode(rep.get("pixelWidth")).value() << endl;
          }
          if (rep.isDefined("pixelHeight"))
          {
            inf << reptype + ".pixelHeight = " << FloatNode(rep.get("pixelHeight")).value() << endl;
          }
          if (rep.isDefined("principalPointX"))
          {
            inf << reptype + ".principalPointX = " << FloatNode(rep.get("principalPointX")).value() << endl;
          }
          if (rep.isDefined("principalPointY"))
          {
            inf << reptype + ".principalPointY = " << FloatNode(rep.get("principalPointY")).value() << endl;
          }
          if (rep.isDefined("radius"))
          {
            inf << reptype + ".radius = " << FloatNode(rep.get("radius")).value() << endl;
          }

          inf.close();
        }
      }

      return 0;
    }
    else
    {
      print_help(options);
      return -1;
    }
  }
  catch (E57Exception& e)
  {
    e.report(__FILE__, __LINE__, __FUNCTION__);
    return -1;
  }
  catch (exception& e)
  {
    cerr << e.what() << endl;
    return -1;
  }
  catch (...)
  {
    cerr << "unknown exception" << endl;
    return -1;
  }
  return 0;
}

ext: cpp


text:
/*
 * Copyright (c) 2018 Ryan Berryhill, University of Toronto
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "pme/util/cardinality_constraint.h"
#include "pme/engine/sat_adaptor.h"
#include "pme/engine/variable_manager.h"

#define BOOST_TEST_MODULE CardinalityConstraintTest
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

using namespace PME;

template<typename T>
struct CardinalityFixture
{
    VariableManager v;
    std::unique_ptr<CardinalityConstraint> cardinality;
    std::vector<ID> ids;
    SATAdaptor sat;

    CardinalityFixture(unsigned n) : cardinality(new T(v))
    {
        for (unsigned i = 0; i < n; ++i)
        {
            ids.push_back(v.getNewID());
        }

        for (ID id : ids) { cardinality->addInput(id); }
    }

    unsigned countAssignedTo(ModelValue value)
    {
        unsigned count = 0;
        for (unsigned id : ids)
        {
            if (sat.getAssignment(id) == value) { count++; }
        }
        return count;
    }

    Cube assumeTrue(unsigned n)
    {
        Clause assumps;
        for (unsigned j = 0; j < ids.size(); ++j)
        {
            ID id = ids[j];
            if (j >= n) { id = negate(id); }
            assumps.push_back(id);
        }
        return assumps;
    }
};

template<typename T>
void testGetCardinality()
{
    VariableManager v;
    std::unique_ptr<CardinalityConstraint> cardinality(new T(v));

    ID a = v.getNewID("a");
    ID b = v.getNewID("b");
    ID c = v.getNewID("c");

    BOOST_CHECK_EQUAL(cardinality->getCardinality(), 0);
    BOOST_CHECK_EQUAL(cardinality->getOutputCardinality(), 0);

    cardinality->setCardinality(1);

    BOOST_CHECK_EQUAL(cardinality->getCardinality(), 1);
    BOOST_CHECK_EQUAL(cardinality->getOutputCardinality(), 0);

    cardinality->addInput(a);

    BOOST_CHECK_EQUAL(cardinality->getCardinality(), 1);
    BOOST_CHECK_EQUAL(cardinality->getOutputCardinality(), 1);
    cardinality->CNFize();
    BOOST_CHECK_EQUAL(cardinality->outputs().size(), 1);

    cardinality->addInput(b);

    BOOST_CHECK_EQUAL(cardinality->getCardinality(), 1);
    BOOST_CHECK_EQUAL(cardinality->getOutputCardinality(), 1);
    cardinality->CNFize();
    BOOST_CHECK_EQUAL(cardinality->outputs().size(), 1);

    cardinality->setCardinality(3);

    BOOST_CHECK_EQUAL(cardinality->getCardinality(), 3);
    BOOST_CHECK_EQUAL(cardinality->getOutputCardinality(), 2);
    cardinality->CNFize();
    BOOST_CHECK_EQUAL(cardinality->outputs().size(), 2);

    cardinality->addInput(c);

    BOOST_CHECK_EQUAL(cardinality->getCardinality(), 3);
    BOOST_CHECK_EQUAL(cardinality->getOutputCardinality(), 3);
    cardinality->CNFize();
    BOOST_CHECK_EQUAL(cardinality->outputs().size(), 3);
}

BOOST_AUTO_TEST_CASE(totalizer_get_cardinality)
{
    testGetCardinality<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_get_cardinality)
{
    testGetCardinality<SortingCardinalityConstraint>();
}

template<typename T>
void testCardinality1CNFization()
{
    CardinalityFixture<T> f(8);
    f.cardinality->setCardinality(1);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    BOOST_CHECK_EQUAL(f.cardinality->outputs().size(), 1);
    ID output = f.cardinality->outputs().at(0);

    // Cardinality should be SAT on its own
    BOOST_CHECK(f.sat.solve());

    // Should be SAT with output = 1
    BOOST_CHECK(f.sat.solve({output}));
    // And exactly one variable should be assigned to 1
    BOOST_CHECK_EQUAL(f.countAssignedTo(SAT::TRUE), 1);

    // Should be SAT with output = 0
    BOOST_CHECK(f.sat.solve({negate(output)}));
    // And none should be assigned to 1
    BOOST_CHECK_EQUAL(f.countAssignedTo(SAT::TRUE), 0);
}

BOOST_AUTO_TEST_CASE(totalizer_cnfization_cardinality_1)
{
    testCardinality1CNFization<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_cnfization_cardinality_1)
{
    testCardinality1CNFization<SortingCardinalityConstraint>();
}

template<typename T>
void testAssumeEq()
{
    CardinalityFixture<T> f(8);
    f.cardinality->setCardinality(8);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    for (unsigned i = 0; i <= 8; ++i)
    {
        for (unsigned j = 0; j <= 8; ++j)
        {
            Cube assumps = f.assumeTrue(i);
            Cube cassumps = f.cardinality->assumeEq(j);
            assumps.insert(assumps.end(), cassumps.begin(), cassumps.end());
            if (i == j)
            {
                BOOST_REQUIRE(f.sat.solve(assumps));
                BOOST_CHECK(f.countAssignedTo(SAT::TRUE) == j);
            }
            else
            {
                BOOST_CHECK(!f.sat.solve(assumps));
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(totalizer_assume_eq)
{
    testAssumeEq<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_assume_eq)
{
    testAssumeEq<SortingCardinalityConstraint>();
}

template<typename T>
void testAssumeLEq()
{
    CardinalityFixture<T> f(8);
    f.cardinality->setCardinality(8);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    for (unsigned i = 0; i <= 8; ++i)
    {
        for (unsigned j = 0; j <= 8; ++j)
        {
            Cube assumps = f.assumeTrue(i);
            Cube cassumps = f.cardinality->assumeLEq(j);
            assumps.insert(assumps.end(), cassumps.begin(), cassumps.end());
            if (i <= j)
            {
                BOOST_REQUIRE(f.sat.solve(assumps));
                BOOST_CHECK(f.countAssignedTo(SAT::TRUE) <= j);
            }
            else
            {
                BOOST_CHECK(!f.sat.solve(assumps));
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(totalizer_assume_leq)
{
    testAssumeLEq<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_assume_leq)
{
    testAssumeLEq<SortingCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(half_sn_assume_leq)
{
    testAssumeLEq<SortingLEqConstraint>();
}

template<typename T>
void testAssumeLT()
{
    CardinalityFixture<T> f(8);
    f.cardinality->setCardinality(8);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    for (unsigned i = 0; i <= 8; ++i)
    {
        for (unsigned j = 1; j < 8; ++j)
        {
            Cube assumps = f.assumeTrue(i);
            Cube cassumps = f.cardinality->assumeLT(j);
            assumps.insert(assumps.end(), cassumps.begin(), cassumps.end());
            if (i < j)
            {
                BOOST_REQUIRE(f.sat.solve(assumps));
                BOOST_CHECK(f.countAssignedTo(SAT::TRUE) < j);
            }
            else
            {
                BOOST_CHECK(!f.sat.solve(assumps));
            }
        }
    }

    BOOST_CHECK_THROW(f.cardinality->assumeLT(0), std::invalid_argument);
}

BOOST_AUTO_TEST_CASE(totalizer_assume_lt)
{
    testAssumeLT<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_assume_lt)
{
    testAssumeLT<SortingCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(half_sn_assume_lt)
{
    testAssumeLT<SortingLEqConstraint>();
}

template<typename T>
void testAssumeGEq()
{
    CardinalityFixture<TotalizerCardinalityConstraint> f(8);
    f.cardinality->setCardinality(8);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    for (unsigned i = 0; i <= 8; ++i)
    {
        for (unsigned j = 0; j <= 8; ++j)
        {
            Cube assumps = f.assumeTrue(i);
            Cube cassumps = f.cardinality->assumeGEq(j);
            assumps.insert(assumps.end(), cassumps.begin(), cassumps.end());
            if (i >= j)
            {
                BOOST_REQUIRE(f.sat.solve(assumps));
                BOOST_CHECK(f.countAssignedTo(SAT::TRUE) >= j);
            }
            else
            {
                BOOST_CHECK(!f.sat.solve(assumps));
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(totalizer_assume_geq)
{
    testAssumeGEq<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_assume_geq)
{
    testAssumeGEq<SortingCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(half_sn_assume_geq)
{
    testAssumeGEq<SortingGEqConstraint>();
}

template<typename T>
void testAssumeGT()
{
    CardinalityFixture<T> f(8);
    f.cardinality->setCardinality(8);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    for (unsigned i = 0; i <= 8; ++i)
    {
        for (unsigned j = 0; j < 8; ++j)
        {
            Cube assumps = f.assumeTrue(i);
            Cube cassumps = f.cardinality->assumeGT(j);
            assumps.insert(assumps.end(), cassumps.begin(), cassumps.end());
            if (i > j)
            {
                BOOST_REQUIRE(f.sat.solve(assumps));
                BOOST_CHECK(f.countAssignedTo(SAT::TRUE) > j);
            }
            else
            {
                BOOST_CHECK(!f.sat.solve(assumps));
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(totalizer_assume_gt)
{
    testAssumeGT<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_assume_gt)
{
    testAssumeGT<SortingCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(half_sn_assume_gt)
{
    testAssumeGT<SortingGEqConstraint>();
}

template<typename T>
void testLargeCardinality()
{
    CardinalityFixture<T> f(100);
    f.cardinality->setCardinality(50);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    BOOST_CHECK_EQUAL(f.cardinality->outputs().size(), 50);

    // Cardinality should be SAT on its own
    BOOST_CHECK(f.sat.solve());

    // Should count correctly
    for (unsigned i = 0; i <= 50; ++i)
    {
        Clause assumps = f.assumeTrue(i);

        BOOST_CHECK(f.sat.solve(assumps));

        const std::vector<ID> & outputs = f.cardinality->outputs();
        for (unsigned j = 0; j < outputs.size(); ++j)
        {
            ID lit = outputs[j];
            ModelValue expected = j < i ? SAT::TRUE : SAT::FALSE;
            BOOST_CHECK_EQUAL(f.sat.getAssignment(lit), expected);
        }
    }

    // Should be SAT for all values
    for (unsigned i = 0; i < 50; ++i)
    {
        BOOST_REQUIRE(f.sat.solve(f.cardinality->assumeEq(i)));
        BOOST_CHECK_EQUAL(f.countAssignedTo(SAT::TRUE), i);
    }

    // Should throw for values that are too high
    BOOST_CHECK_THROW(f.cardinality->assumeEq(50), std::invalid_argument);
    BOOST_CHECK_THROW(f.cardinality->assumeEq(51), std::invalid_argument);
}

BOOST_AUTO_TEST_CASE(totalizer_large_cardinality)
{
    testLargeCardinality<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_large_cardinality)
{
    testLargeCardinality<SortingCardinalityConstraint>();
}

template<typename T>
void testFullCardinality()
{
    CardinalityFixture<T> f(50);
    f.cardinality->setCardinality(50);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    f.sat.addClauses(cnf);

    BOOST_CHECK_EQUAL(f.cardinality->outputs().size(), 50);

    // Cardinality should be SAT on its own
    BOOST_CHECK(f.sat.solve());

    // Should count correctly
    for (unsigned i = 0; i <= 50; ++i)
    {
        Clause assumps;
        for (unsigned j = 0; j < f.ids.size(); ++j)
        {
            ID id = f.ids[j];
            if (j >= i) { id = negate(id); }
            assumps.push_back(id);
        }

        BOOST_CHECK(f.sat.solve(assumps));

        const std::vector<ID> & outputs = f.cardinality->outputs();
        for (unsigned j = 0; j < outputs.size(); ++j)
        {
            ID lit = outputs[j];
            ModelValue expected = j < i ? SAT::TRUE : SAT::FALSE;
            BOOST_CHECK_EQUAL(f.sat.getAssignment(lit), expected);
        }
    }

    // Should be SAT for all values
    for (unsigned i = 0; i <= 50; ++i)
    {
        BOOST_REQUIRE(f.sat.solve(f.cardinality->assumeEq(i)));
        BOOST_CHECK_EQUAL(f.countAssignedTo(SAT::TRUE), i);
    }

    // Should throw for values that are too high
    BOOST_CHECK_THROW(f.cardinality->assumeEq(51), std::invalid_argument);
}

BOOST_AUTO_TEST_CASE(totalizer_full_cardinality)
{
    testFullCardinality<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_full_cardinality)
{
    testFullCardinality<SortingCardinalityConstraint>();
}

template<typename T>
void testDecreasingCardinality()
{
    CardinalityFixture<TotalizerCardinalityConstraint> f(3);
    f.cardinality->setCardinality(4);

    ClauseVec cnf = f.cardinality->CNFize();

    BOOST_REQUIRE(!cnf.empty());

    ID a = f.ids[0];
    ID b = f.ids[1];
    ID c = f.ids[2];

    f.sat.addClause({negate(a), negate(b), negate(c)});
    f.sat.addClauses(cnf);

    BOOST_REQUIRE(f.sat.solve());

    Cube assumps = f.cardinality->assumeGEq(3);
    BOOST_CHECK(!f.sat.solve(assumps));

    assumps = f.cardinality->assumeGEq(2);
    BOOST_CHECK(f.sat.solve(assumps));
    f.sat.addClause({negate(a), negate(c)});
    BOOST_CHECK(f.sat.solve(assumps));
    f.sat.addClause({negate(a), negate(b)});
    BOOST_CHECK(f.sat.solve(assumps));
    f.sat.addClause({negate(b), negate(c)});
    BOOST_CHECK(!f.sat.solve(assumps));

    assumps = f.cardinality->assumeGEq(1);
    BOOST_CHECK(f.sat.solve(assumps));
    f.sat.addClause({negate(a)});
    BOOST_CHECK(f.sat.solve(assumps));
    f.sat.addClause({negate(b)});
    BOOST_CHECK(f.sat.solve(assumps));
    f.sat.addClause({negate(c)});
    BOOST_CHECK(!f.sat.solve(assumps));

    assumps = f.cardinality->assumeGEq(0);
    BOOST_CHECK(f.sat.solve(assumps));
    BOOST_CHECK(f.sat.solve());
}

BOOST_AUTO_TEST_CASE(totalizer_decreasing_cardinality)
{
    testDecreasingCardinality<TotalizerCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(sn_decreasing_cardinality)
{
    testDecreasingCardinality<SortingCardinalityConstraint>();
}

BOOST_AUTO_TEST_CASE(incremental_cardinality)
{
    CardinalityFixture<TotalizerCardinalityConstraint> f(32);

    TotalizerCardinalityConstraint & cardinality =
        dynamic_cast<TotalizerCardinalityConstraint&>(*f.cardinality);

    std::set<Clause> knownClauses;

    for (unsigned current = 1; current < 32; ++current)
    {
        cardinality.setCardinality(current);
        ClauseVec cnf = cardinality.incrementalCNFize();

        // It should not generate duplicate clauses
        for (Clause cls : cnf)
        {
            std::sort(cls.begin(), cls.end());
            BOOST_CHECK(knownClauses.count(cls) == 0);
            knownClauses.insert(cls);
        }

        BOOST_REQUIRE(!cnf.empty());

        f.sat.addClauses(cnf);

        BOOST_CHECK_EQUAL(cardinality.outputs().size(), current);

        // Cardinality should be SAT on its own
        BOOST_CHECK(f.sat.solve());

        // Should count correctly
        for (unsigned i = 0; i <= current; ++i)
        {
            Clause assumps;
            for (unsigned j = 0; j < f.ids.size(); ++j)
            {
                ID id = f.ids[j];
                if (j >= i) { id = negate(id); }
                assumps.push_back(id);
            }

            BOOST_CHECK(f.sat.solve(assumps));

            const std::vector<ID> & outputs = cardinality.outputs();
            for (unsigned j = 0; j < outputs.size(); ++j)
            {
                ID lit = outputs[j];
                ModelValue expected = j < i ? SAT::TRUE : SAT::FALSE;
                BOOST_CHECK_EQUAL(f.sat.getAssignment(lit), expected);
            }
        }

        // Should be SAT for all values
        for (unsigned i = 0; i < current; ++i)
        {
            BOOST_REQUIRE(f.sat.solve(cardinality.assumeEq(i)));
            BOOST_CHECK_EQUAL(f.countAssignedTo(SAT::TRUE), i);
        }

        // Should throw for values that are too high
        if (current < 32)
        {
            BOOST_CHECK_THROW(cardinality.assumeEq(current), std::invalid_argument);
        }
        else
        {
            // But if we're assuming all variables it's okay to assume Eq
            BOOST_REQUIRE(f.sat.solve(cardinality.assumeEq(32)));
            BOOST_CHECK_EQUAL(f.countAssignedTo(SAT::TRUE), 32);
        }

        if (current + 1 < 32)
        {
            BOOST_CHECK_THROW(cardinality.assumeEq(current + 1), std::invalid_argument);
        }
    }
}

BOOST_AUTO_TEST_CASE(mixed_incremental)
{
    CardinalityFixture<TotalizerCardinalityConstraint> f(20);

    TotalizerCardinalityConstraint & cardinality =
        dynamic_cast<TotalizerCardinalityConstraint&>(*f.cardinality);
    cardinality.setCardinality(16);

    ClauseVec cnf_orig = cardinality.CNFize();
    ClauseVec should_be_empty = cardinality.incrementalCNFize();

    BOOST_CHECK(!cnf_orig.empty());
    BOOST_CHECK(should_be_empty.empty());

    ClauseVec cnf_again = cardinality.CNFize();

    std::sort(cnf_orig.begin(), cnf_orig.end());
    std::sort(cnf_again.begin(), cnf_again.end());

    BOOST_CHECK(cnf_again == cnf_orig);
}

max_stars_repo_name: ryanberryhill/pme

max_issues_repo_name: ryanberryhill/pme

max_forks_repo_name: ryanberryhill/pme


text:
#pragma once

#include <Eigen/StdVector>
#include <sophus/se2.hpp>
#include <sophus/so2.hpp>

EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Vector2d)

using Scalar = double;
using so2    = Sophus::SO2<Scalar>;
using se2    = Sophus::SE2<Scalar>;

template <int rows, int cols>
using Mat = Eigen::Matrix<double, rows, cols>;

template <int cols>
using Vec = Eigen::Matrix<double, 1, cols>;

ext: hh

max_stars_repo_name: jpanikulam/experiments


text:
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.

#include "Carla.h"
#include "Carla/Walker/WalkerController.h"
#include "Carla/Walker/WalkerAnim.h"

#include "Components/PoseableMeshComponent.h"
#include "Components/PrimitiveComponent.h"
#include "Containers/Map.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Pawn.h"

#include <boost/variant/apply_visitor.hpp>

AWalkerController::AWalkerController(const FObjectInitializer &ObjectInitializer)
  : Super(ObjectInitializer)
{
  PrimaryActorTick.bCanEverTick = true;
}

void AWalkerController::OnPossess(APawn *InPawn)
{
  Super::OnPossess(InPawn);

  auto *Character = Cast<ACharacter>(InPawn);
  if (Character == nullptr)
  {
    UE_LOG(LogCarla, Error, TEXT("Walker is not a character!"));
    return;
  }

  auto *MovementComponent = Character->GetCharacterMovement();
  if (MovementComponent == nullptr)
  {
    UE_LOG(LogCarla, Error, TEXT("Walker missing character movement component!"));
    return;
  }

  MovementComponent->MaxWalkSpeed = GetMaximumWalkSpeed();
  MovementComponent->JumpZVelocity = 500.0f;
  Character->JumpMaxCount = 2;
}

void AWalkerController::ApplyWalkerControl(const FWalkerControl &InControl)
{
  Control = InControl;
}

void AWalkerController::GetBonesTransform(FWalkerBoneControlOut &WalkerBones)
{
  auto *Character = GetCharacter();
  if (!Character) return;

  TArray<USkeletalMeshComponent *> SkeletalMeshes;
  Character->GetComponents<USkeletalMeshComponent>(SkeletalMeshes, false);
  USkeletalMeshComponent *SkeletalMesh = SkeletalMeshes.IsValidIndex(0) ? SkeletalMeshes[0] : nullptr;
  if (!SkeletalMesh) return;

  // get the walker animation class
  auto *AnimInst = SkeletalMesh->GetAnimInstance();
  if (!AnimInst) return;
  UWalkerAnim *WalkerAnim = Cast<UWalkerAnim>(AnimInst);
  if (!WalkerAnim) return;

  // get current pose
  FPoseSnapshot TempSnapshot;
  SkeletalMesh->SnapshotPose(TempSnapshot);

  // copy pose
  // WalkerAnim->Snap = TempSnapshot;

  for (int i=0; i<TempSnapshot.BoneNames.Num(); ++i)
  {
    FWalkerBoneControlOutData Transforms;
    Transforms.World = SkeletalMesh->GetSocketTransform(TempSnapshot.BoneNames[i], ERelativeTransformSpace::RTS_World);
    Transforms.Component = SkeletalMesh->GetSocketTransform(TempSnapshot.BoneNames[i], ERelativeTransformSpace::RTS_Actor);
    Transforms.Relative = SkeletalMesh->GetSocketTransform(TempSnapshot.BoneNames[i], ERelativeTransformSpace::RTS_ParentBoneSpace);
    // Transforms.Relative = TempSnapshot.LocalTransforms[i];

    WalkerBones.BoneTransforms.Add(TempSnapshot.BoneNames[i].ToString(), Transforms);
  }
}

void AWalkerController::SetBonesTransform(const FWalkerBoneControlIn &WalkerBones)
{
  auto *Character = GetCharacter();
  if (!Character) return;

  TArray<USkeletalMeshComponent *> SkeletalMeshes;
  Character->GetComponents<USkeletalMeshComponent>(SkeletalMeshes, false);
  USkeletalMeshComponent *SkeletalMesh = SkeletalMeshes.IsValidIndex(0) ? SkeletalMeshes[0] : nullptr;
  if (!SkeletalMesh) return;

  // get the walker animation class
  auto *AnimInst = SkeletalMesh->GetAnimInstance();
  if (!AnimInst) return;
  UWalkerAnim *WalkerAnim = Cast<UWalkerAnim>(AnimInst);
  if (!WalkerAnim) return;

  // if pose is empty, then get a first version
  if (WalkerAnim->Snap.BoneNames.Num() == 0)
  {
    // get current pose
    SkeletalMesh->SnapshotPose(WalkerAnim->Snap);
  }

  TMap<FName, FTransform> BonesMap;
  for (const TPair<FString, FTransform> &pair : WalkerBones.BoneTransforms)
  {
    FName BoneName = FName(*pair.Key);
    BonesMap.Add(BoneName, pair.Value);
  }

  // assign common bones
  for (int i=0; i<WalkerAnim->Snap.BoneNames.Num(); ++i)
  {
    FTransform *Trans = BonesMap.Find(WalkerAnim->Snap.BoneNames[i]);
    if (Trans)
    {
      WalkerAnim->Snap.LocalTransforms[i] = *Trans;
    }
  }
}

void AWalkerController::BlendPose(float Blend)
{
  auto *Character = GetCharacter();
  if (!Character) return;

  TArray<USkeletalMeshComponent *> SkeletalMeshes;
  Character->GetComponents<USkeletalMeshComponent>(SkeletalMeshes, false);
  USkeletalMeshComponent *SkeletalMesh = SkeletalMeshes.IsValidIndex(0) ? SkeletalMeshes[0] : nullptr;
  if (!SkeletalMesh) return;

  // get the walker animation class
  auto *AnimInst = SkeletalMesh->GetAnimInstance();
  if (!AnimInst) return;
  UWalkerAnim *WalkerAnim = Cast<UWalkerAnim>(AnimInst);
  if (!WalkerAnim) return;

  // set current pose
  WalkerAnim->Blend = Blend;
}

void AWalkerController::GetPoseFromAnimation()
{
  auto *Character = GetCharacter();
  if (!Character) return;

  TArray<USkeletalMeshComponent *> SkeletalMeshes;
  Character->GetComponents<USkeletalMeshComponent>(SkeletalMeshes, false);
  USkeletalMeshComponent *SkeletalMesh = SkeletalMeshes.IsValidIndex(0) ? SkeletalMeshes[0] : nullptr;
  if (!SkeletalMesh) return;

  // get the walker animation class
  auto *AnimInst = SkeletalMesh->GetAnimInstance();
  if (!AnimInst) return;
  UWalkerAnim *WalkerAnim = Cast<UWalkerAnim>(AnimInst);
  if (!WalkerAnim) return;

  // get current pose
  SkeletalMesh->SnapshotPose(WalkerAnim->Snap);
}

void AWalkerController::ControlTickVisitor::operator()(const FWalkerControl &WalkerControl)
{
  auto *Character = Controller->GetCharacter();
  if (!Character) return;

  Character->AddMovementInput(WalkerControl.Direction,
        WalkerControl.Speed / Controller->GetMaximumWalkSpeed());
  if (WalkerControl.Jump)
  {
    Character->Jump();
  }
}

void AWalkerController::Tick(float DeltaSeconds)
{
  TRACE_CPUPROFILER_EVENT_SCOPE(AWalkerController::Tick);
  Super::Tick(DeltaSeconds);
  AWalkerController::ControlTickVisitor ControlTickVisitor(this);
  boost::apply_visitor(ControlTickVisitor, Control);
}


text:
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//

#ifndef BEAST_HANDLER_HELPERS_HPP
#define BEAST_HANDLER_HELPERS_HPP

#include <boost/asio/handler_alloc_hook.hpp>
#include <boost/asio/handler_continuation_hook.hpp>
#include <boost/asio/handler_invoke_hook.hpp>
#include <memory>

/*  Calls to:

    * asio_handler_allocate
    * asio_handler_deallocate
    * asio_handler_invoke
    * asio_handler_is_continuation

    must be made from a namespace that does not
    contain overloads of this function. The beast_asio_helpers
    namespace is defined here for that purpose.
*/

namespace beast_asio_helpers {

/// Allocation function for handlers.
template <class Handler>
inline
void*
allocate(std::size_t s, Handler& handler)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
    return ::operator new(s);
#else
    using boost::asio::asio_handler_allocate;
    return asio_handler_allocate(s, std::addressof(handler));
#endif
}

/// Deallocation function for handlers.
template<class Handler>
inline
void
deallocate(void* p, std::size_t s, Handler& handler)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
    ::operator delete(p);
#else
    using boost::asio::asio_handler_deallocate;
    asio_handler_deallocate(p, s, std::addressof(handler));
#endif
}

/// Invoke function for handlers.
template<class Function, class Handler>
inline
void
invoke(Function& function, Handler& handler)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
    Function tmp(function);
    tmp();
#else
    using boost::asio::asio_handler_invoke;
    asio_handler_invoke(function, std::addressof(handler));
#endif
}

/// Invoke function for handlers.
template<class Function, class Handler>
inline
void
invoke(Function const& function, Handler& handler)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
    Function tmp(function);
    tmp();
#else
    using boost::asio::asio_handler_invoke;
    asio_handler_invoke(function, std::addressof(handler));
#endif
}

/// Returns true if handler represents a continuation of the asynchronous operation
template<class Handler>
inline
bool
is_continuation(Handler& handler)
{
#if !defined(BOOST_ASIO_HAS_HANDLER_HOOKS)
    return false;
#else
    using boost::asio::asio_handler_is_continuation;
    return asio_handler_is_continuation(std::addressof(handler));
#endif
}

} // beast_asio_helpers

#endif

max_stars_repo_name: AgreeTechnology/ABC

max_issues_repo_name: AgreeTechnology/ABC

max_forks_repo_name: AgreeTechnology/ABC


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"
#include "Generic/common/ParamReader.h"
#include "Generic/common/UnrecoverableException.h"
#include "Generic/common/UTF8InputStream.h"
#include "Generic/common/UTF8Token.h"
#include "Arabic/BuckWalter/ar_BWRuleDictionary.h"
#include <boost/scoped_ptr.hpp>

BWRuleDictionary * BWRuleDictionary::instance = 0;

BWRuleDictionary * BWRuleDictionary::getInstance() {
	if (instance == 0) {
		instance = _new BWRuleDictionary();
		instance->initialize();
	}
	return instance;
}

void BWRuleDictionary::destroy() {
	delete instance;
	instance = 0;
}

BWRuleDictionary::BWRuleDictionary(){
	_n_rules = 0;

	_A_map = _new SingleHashMap(MAX_CATEGORIES, singleHasher, singleEqTester);
	_B_map = _new SingleHashMap(MAX_CATEGORIES, singleHasher, singleEqTester);
	_C_map = _new SingleHashMap(MAX_CATEGORIES, singleHasher, singleEqTester);

	_BC_map = _new DoubleHashMap(MAX_RULES, doubleHasher, doubleEqTester);
	_AB_map = _new DoubleHashMap(MAX_RULES, doubleHasher, doubleEqTester);
	_AC_map = _new DoubleHashMap(MAX_RULES, doubleHasher, doubleEqTester);

}

BWRuleDictionary::~BWRuleDictionary(){
	delete _A_map;
	delete _B_map;
	delete _C_map;
	delete _BC_map;
	delete _AB_map;
	delete _AC_map;
}

void BWRuleDictionary::initialize() {
	std::string buffer = ParamReader::getRequiredParam("BWRuleDict");

	//read rule dictionary
	readBWRuleDictionaryFile(buffer.c_str());

	SessionLogger::logger->reportInfoMessage()<<"Read BW Rule Dictionary: "<<buffer<<
		" "<<(int)getNRules()<<" rules\n";
}

void BWRuleDictionary::readBWRuleDictionaryFile(const char *rule_dict_file) {
	boost::scoped_ptr<UTF8InputStream> stream_scoped_ptr(UTF8InputStream::build(rule_dict_file));
	UTF8InputStream& stream(*stream_scoped_ptr);

	size_t numEntries;
	UTF8Token position1;
	UTF8Token position2;
	UTF8Token category1;
	UTF8Token category2;

	stream >> numEntries;

	for (size_t line = 0; line < numEntries; line++) {

		stream >> position1;
		stream >> position2;
		stream >> category1;
		stream >> category2;
		addRule(position1.symValue(), category1.symValue(),
			    position2.symValue(), category2.symValue());

	}
	stream.close();
}

void BWRuleDictionary::addRule(const Symbol& position1, const Symbol& category1, const Symbol& position2, const Symbol& category2) {

	DoubleHashMap* dhm = getAppropriateDoubleMap(position1, position2);
	SingleHashMap* shm1 = getAppropriateSingleMap(position1);
	//SingleHashMap* shm2 = getAppropriateSingleMap(position1);  //is this incorrect? marjorie
	SingleHashMap* shm2 = getAppropriateSingleMap(position2);

	std::pair<Symbol, Symbol> combinedRule(category1, category2);
	if(dhm->get(combinedRule) != NULL){
		(*dhm)[combinedRule].n_exists++;
	}else{
		if(_n_rules >= MAX_RULES){
			sprintf(_message, "%s%d", "Attempted to add more rules than allowed", MAX_RULES);
			throw UnrecoverableException("BWRuleDictionary::addRule", _message);
		}
		_n_rules++;
		(*dhm)[combinedRule].n_exists = 1;
		(*dhm)[combinedRule].first_category = category1;
		(*dhm)[combinedRule].second_category = category2;
	}

	//update the following list
	if(shm1->get(category1) != NULL){
	//	std::cout <<"shm1: "<<category1.to_debug_string()
	//		<<" nfollowing "<< (*shm1)[category1].n_following
	//		<<" npreceding "<< (*shm1)[category1].n_preceding<<std::endl;
		if ((*shm1)[category1].n_following < MAX_RULES_PER_CATEGORY){
			(*shm1)[category1].following[(*shm1)[category1].n_following] = category2;
			(*shm1)[category1].n_following++;
		}else{
			sprintf(_message, "%s%d%s%s", "Tried to add too many left hand sides, ", (*shm1)[category1].n_following ," to category ", category1.to_debug_string());
			throw UnrecoverableException("BWRuleDictionary::addRule", _message);
		}
	}else{
		(*shm1)[category1].n_following = 0;
		(*shm1)[category1].n_preceding = 0;
	//	std::cout <<"shm1: "<<category1.to_debug_string()
	//		<<" nfollowing "<< (*shm1)[category1].n_following
	//		<<" npreceding "<< (*shm1)[category1].n_preceding <<std::endl;;
		(*shm1)[category1].following[(*shm1)[category1].n_following] = category2;
		(*shm1)[category1].n_following++;
	}

	//update the preceding list
	if(shm2->get(category2) != NULL){
	//	std::cout <<"shm2: "<<category2.to_debug_string()
	//		<<" nfollowing "<< (*shm2)[category2].n_following
	//		<<" npreceding "<< (*shm2)[category2].n_preceding<<std::endl;
		if ((*shm2)[category2].n_preceding < MAX_RULES_PER_CATEGORY){
			//(*shm2)[category2].preceding[(*shm1)[category1].n_preceding] = category1;
			(*shm2)[category2].preceding[(*shm2)[category2].n_preceding] = category1;
			(*shm2)[category2].n_preceding++;
		}else{

			sprintf(_message, "%s%d%s%s", "Tried to add too many right hand sides, ", (*shm1)[category1].n_following ," to category ", category1.to_debug_string());
			throw UnrecoverableException("BWRuleDictionary::addRule", _message);
		}
	}else{
		(*shm2)[category2].n_preceding = 0;
		(*shm2)[category2].n_following = 0;
		//std::cout <<"shm2: "<<category2.to_debug_string()
		//	<<" nfollowing "<< (*shm2)[category2].n_following
		//	<<" npreceding "<< (*shm2)[category2].n_preceding<<std::endl;
		//(*shm2)[category2].preceding[(*shm1)[category2].n_preceding] = category 1;
		(*shm2)[category2].preceding[(*shm2)[category2].n_preceding] = category1;
		(*shm2)[category2].n_preceding++;
	}
}

int BWRuleDictionary::getFollowingPossibilities(const Symbol& position, const Symbol& category, Symbol *results){
	if (getAppropriateSingleMap(position)->get(category) != NULL){
		int n_following = (*getAppropriateSingleMap(position))[category].n_following;
		for(int n =0; n < n_following; n++){
			results[n] = (*getAppropriateSingleMap(position))[category].following[n];
		}
		return n_following;
	}else{
		return 0;
	}
}
/*
size_t BWRuleDictionary::getPrecedingPossibilities(const Symbol& position, const Symbol& category, Symbol *results){
	if (getAppropriateSingleMap(position)->get(category) != NULL){
		size_t n_following = (*getAppropriateSingleMap(position))[category].n_preceding;
		for(size_t n =0; n < n_following; n++){
			results[n] = (*getAppropriateSingleMap(position))[category].preceding[n];
		}
	}else{
		return 0;
	}
}
*/
bool BWRuleDictionary::isABPermitted(const Symbol& A,  const Symbol& B){
	return (_AB_map->get(std::make_pair(A,B)) != NULL);
}
bool BWRuleDictionary::isBCPermitted(const Symbol& B,  const Symbol& C){
	return (_BC_map->get(std::make_pair(B,C)) != NULL);
}
bool BWRuleDictionary::isACPermitted(const Symbol& A,  const Symbol& C){
	return (_AC_map->get(std::make_pair(A,C)) != NULL);
}

void BWRuleDictionary::dump(UTF8OutputStream &uos){
	DoubleHashMap::iterator curr;

	for(curr =_AB_map->begin(); curr !=_AB_map->end(); ++curr){
		DoubleHashEntry entry = (*curr).second;
		uos <<  L"A B " << entry.first_category.to_string() << L" " << entry.second_category.to_string() << L"\n";
	}
	for(curr =_BC_map->begin(); curr !=_BC_map->end(); ++curr){
		DoubleHashEntry entry = (*curr).second;
		uos <<  L"B C "  << entry.first_category.to_string() << L" " << entry.second_category.to_string() << L"\n";
	}
	for(curr =_AC_map->begin(); curr !=_AC_map->end(); ++curr){
		DoubleHashEntry entry = (*curr).second;
		uos <<  L"A C "<< entry.first_category.to_string() << L" " << entry.second_category.to_string() << L"\n";
	}
}

BWRuleDictionary::SingleHashMap* BWRuleDictionary::getAppropriateSingleMap(const Symbol& position) {
	if (position == Symbol(L"A")){
		return _A_map;
	}else if (position == Symbol(L"B")){
		return _B_map;
	}else if (position == Symbol(L"C")){
		return _C_map;
	}
	else{
		sprintf(_message, "%s%s", "InvalidPosition ", position.to_debug_string());
		throw UnrecoverableException("BWRuleDictionary::getAppropriateSingleMap", _message);
	}
}
BWRuleDictionary::DoubleHashMap* BWRuleDictionary::getAppropriateDoubleMap(const Symbol& position1, const Symbol& position2) {
	if ((position1 == Symbol(L"A")) && (position2 == Symbol(L"B"))){
		return _AB_map;
	}else if ((position1 == Symbol(L"B")) && (position2 == Symbol(L"C"))){
		return _BC_map;
	}else if ((position1 == Symbol(L"A")) && (position2 == Symbol(L"C"))){
		return _AC_map;
	}else{
		sprintf(_message, "%s%s%s", "Impossible rule postion combination ", position1.to_debug_string(), position2.to_debug_string());
		throw UnrecoverableException("BWRuleDictionary::getAppropriateDoubleMap", _message);
	}
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
#pragma once

#include <mtlog/badbotlogger.hpp>
#include <sharedstorage/sharedstrings.hpp>
#include <atomic>
#include <thread>
#include <boost/signals2.hpp>

using namespace std;
using namespace boost;

class ControllerBase : protected BadBotLogger
{
    public:
        typedef boost::signals2::signal<void (std::string source, unsigned char vLeft, unsigned char vRight)> signalDrivelineCmd;
        typedef signalDrivelineCmd::slot_type slot_signalDrivelineCmd;

    protected:
        //how many frames to keep the motor on once drive command is issued
        atomic<int> _driveline_on_counter; //decremented with every read frame

        //read from config
        //how much person can deviate before we take corrective action
        int _DEADZONE_MIN;
        int _DEADZONE_MAX;

        //how many ms to repeat the last action
        int _MS_TO_REPEAT_LAST_CMD;
        int _CMD_CALCULATION_FREQUENCY;
        int _MAX_NO_UPDATE_DURATION;

        std::thread _thread_cmd_generator;
        bool _keep_running = true;

        //flagged by the orchestrator
        //if true signals will be raised an calcualtions will be done
        bool _active_controller = false;

        signalDrivelineCmd _signalDrivelineCmd;

        //safety feature, how long since we last got a sensor update?
        //if we do not get updated in _MAX_NO_UPDATE_DURATION we stop issuing commands
        std::chrono::time_point<std::chrono::system_clock> _last_updated_inputs_at;

    protected:

        bool init(std::string ymlNodeName);
        /**
         * Utility function that takes returns true if
         *  current time - _last_updated_inputs_at < _MAX_NO_UPDATE_DURATION
         * or false otherwise
         */
        bool isInputStillValid();

        /**
         * updates the member field _last_updated_inputs_at with current system clock timepoint
         */
        void updateLastInputRxTime();

    public:
        ControllerBase(std::string name);
        bool cleanup();
        virtual void calculateNextFrame() = 0;
        void connectToSignalDrivelineCmd(const slot_signalDrivelineCmd &slot);
        virtual void setActive(bool state);
        void raiseDrivelineSignal(std::string source, unsigned char vLeft, unsigned char vRight);
};


text:
/*
    Copyright 2020 php42

   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 "diffgen.h"
#include "ziparchive.h"
#include "legacy.h"
#include "../common/filesystem.h"
#include "../common/textconvert.h"
#include "../common/console.h"
#include "../common/endian.h"
#include "../common/thread_pool.h"
#include <boost/algorithm/string.hpp>
#include <libtpdp.h>
#include <iostream>
#include <tuple>
#include <thread>
#include <future>
#include <regex>
#include <unordered_map>
#include <algorithm>

namespace algo = boost::algorithm;
namespace fs = std::filesystem;

typedef std::pair<Path, Path> DiffPair;
typedef std::tuple<int, Path, Path> DiffTuple;
typedef std::vector<DiffTuple> DiffVec;
typedef std::unordered_map<int, std::vector<DiffPair>> DiffMap;

std::mutex g_mtx;

static std::wostream& operator<<(std::wostream& os, const fs::path& p)
{
    os << p.wstring();
    return os;
}

/* async task for diff generation */
static void diff_task(Path path, Path rel_path, const libtpdp::Archive& arc, int arc_num, DiffVec& out)
{
    try
    {
        auto it = arc.find(utf_to_sjis(rel_path.wstring()));
        if(it >= arc.end())
        {
            {
                ScopedConsoleColorMT color(COLOR_OK);
                std::wcout << L"Adding new file: " << rel_path << std::endl;
            }

            std::lock_guard lock(g_mtx);
            out.push_back({ arc_num, std::move(rel_path), std::move(path) });
            return;
        }

        auto src_file = arc.get_file(it);
        if(!src_file)
            throw DiffgenException("Error extracting file from archive.");

        std::size_t sz;
        auto dst_file = read_file(path.wstring(), sz);
        if(!dst_file)
            throw DiffgenException("Failed to read file.");

        if((src_file.size() == sz) && (memcmp(src_file.data(), dst_file.get(), sz) == 0))
            return;

        std::lock_guard lock(g_mtx);
        out.push_back({ arc_num, std::move(rel_path), std::move(path) });
    }
    catch(const std::exception& ex)
    {
        ScopedConsoleColorMT color(COLOR_CRITICAL);
        std::wcerr << L"Error processing file: " << path << std::endl;
        std::wcerr << utf_widen(ex.what()) << std::endl;
    }
}

/* async task for file extraction */
static void extract_task(const libtpdp::Archive& arc, const libtpdp::Archive::iterator& it, const Path& path)
{
    try
    {
        auto file = arc.get_file(it);
        if(!file)
        {
            ScopedConsoleColorMT color(COLOR_CRITICAL);
            std::wcerr << L"Error extracting file: " << path << std::endl;
            return;
        }

        auto dir = path.parent_path();

        try
        {
            fs::create_directories(dir);
        }
        catch(const fs::filesystem_error& ex)
        {
            ScopedConsoleColorMT color(COLOR_CRITICAL);
            std::wcerr << L"Failed to create directory: " << dir << std::endl;
            std::wcerr << utf_widen(ex.what()) << std::endl;
            return;
        }

        if(!write_file(path.wstring(), file.data(), file.size()))
        {
            ScopedConsoleColorMT color(COLOR_WARN);
            std::wcerr << L"Failed to write to file: " << path << std::endl;
        }
    }
    catch(const std::exception& ex)
    {
        ScopedConsoleColorMT color(COLOR_CRITICAL);
        std::wcerr << L"Error extracting file: " << path << std::endl;
        std::wcerr << utf_widen(ex.what()) << std::endl;
    }
}

static DiffVec get_diffs(const Path& in_dir, const Path& output, int threads)
{
    DiffVec diffs;
    libtpdp::Archive arc;
    ThreadPool pool(threads);
    bool suppress_json_warning = false;

    for(int i = 1; i < 7; ++i)
    {
        auto arc_name = (L"gn_dat" + std::to_wstring(i) + L".arc");
        auto arc_path = in_dir / arc_name;
        auto out_dir = output / arc_name;

        if(!fs::exists(arc_path) || !fs::is_regular_file(arc_path))
        {
            std::wcerr << L"File not found: " << arc_path << std::endl;
            continue;
        }

        if(!fs::exists(out_dir) || !fs::is_directory(out_dir))
        {
            std::wcerr << L"Missing directory: " << out_dir << std::endl;
            continue;
        }

        try
        {
            std::wcout << L">> " << arc_path << std::endl;
            arc.open(arc_path.wstring());
        }
        catch(const libtpdp::ArcError&)
        {
            ScopedConsoleColorMT color(COLOR_CRITICAL);
            std::wcerr << L"Failed to open file: " << arc_path << std::endl;
            throw;
        }

        for(auto& entry : fs::recursive_directory_iterator(out_dir))
        {
            if(!entry.is_regular_file())
                continue;

            auto path = entry.path();
            auto rel = path.lexically_relative(out_dir);
            if(rel.empty())
                continue;

            if(algo::iequals(entry.path().extension().wstring(), L".json"))
            {
                if(!suppress_json_warning)
                {
                    ScopedConsoleColorMT color(COLOR_WARN);
                    std::wcerr << L"Skipping json files..." << std::endl;
                    suppress_json_warning = true;
                }
                continue;
            }

            pool.queue_task([=, &arc, &diffs]() mutable { diff_task(std::move(path), std::move(rel), arc, i, diffs); });
        }

        pool.wait();
    }

    return diffs;
}

bool diff(const Path& input, const Path& output, const Path& diff_path, int threads)
{
    std::wcout << L"Using up to " << threads << L" concurrent threads" << std::endl;

    Path in_dir(input / L"dat");
    auto diffs = get_diffs(in_dir, output, threads);

    if(diffs.empty())
    {
        ScopedConsoleColorChanger color(COLOR_WARN);
        std::wcerr << L"Source and target are identical, no diffs to output!" << std::endl;
        return false;
    }

    ZipArchive zip;

    try
    {
        zip.open(diff_path, ZIP_CREATE | ZIP_TRUNCATE);

        for(auto& i : diffs)
        {
            auto&[arc_num, rel_path, data_path] = i;
            auto arc_name = "gn_dat" + std::to_string(arc_num) + ".arc";
            auto path = utf_narrow((arc_name / rel_path).wstring());
            [[maybe_unused]] auto entry = zip.add_file(path, data_path);
        }

        zip.close();
    }
    catch(const std::exception& ex)
    {
        ScopedConsoleColorMT color(COLOR_CRITICAL);
        std::wcerr << L"Error writing to file: " << diff_path << std::endl;
        std::wcerr << utf_widen(ex.what()) << std::endl;
        return false;
    }

    return true;
}

bool extract(const Path& input, const Path& output, int threads)
{
    std::wcout << L"Using up to " << threads << L" concurrent threads" << std::endl;
    ThreadPool pool(threads);

    libtpdp::Archive arc;
    Path in_dir(input / L"dat");
    for(int i = 1; i < 7; ++i)
    {
        auto arc_name = (L"gn_dat" + std::to_wstring(i) + L".arc");
        auto arc_path = in_dir / arc_name;

        if(!fs::exists(arc_path) || !fs::is_regular_file(arc_path))
        {
            std::wcerr << L"File not found: " << arc_path << std::endl;
            continue;
        }

        try
        {
            std::wcout << L"Extracting: " << arc_path << std::endl;
            arc.open(arc_path.wstring());
        }
        catch(const libtpdp::ArcError& ex)
        {
            ScopedConsoleColorChanger color(COLOR_CRITICAL);
            std::wcerr << L"Failed to open file: " << arc_path << std::endl;
            std::wcerr << utf_widen(ex.what()) << std::endl;
            return false;
        }

        Path out_dir(output / arc_name);

        for(auto it = arc.begin(); it != arc.end(); ++it)
        {
            if(arc.is_dir(it) || it->data_size == 0)
                continue;

            auto fp = sjis_to_utf(arc.get_path(it));
            if(fp.empty())
            {
                ScopedConsoleColorChanger color(COLOR_WARN);
                std::wcerr << L"Skipping unknown object at index: " << it.index() << std::endl;
                continue;
            }

            auto out_path = out_dir / fp;
            pool.queue_task([=, &arc]() { extract_task(arc, it, out_path); });
        }

        pool.wait();
    }

    return true;
}

bool patch(const Path& input, const Path& output)
{
    ZipArchive zip;
    std::unordered_map<int, std::vector<std::pair<ZipEntry,std::string>>> patches;
    Path in_dir = input / L"dat";

    try
    {
        try
        {
            zip.open(output);
        }
        catch(const ZipWrongFmt&)
        {
            return legacy_patch(input, output);
        }

        auto files = zip.get_file_table();

        std::regex regex("^gn_dat(\\d)\\.arc(?:\\\\|/)+(.+)", std::regex::icase);
        for(auto& entry : files)
        {
            std::smatch matches;
            if(std::regex_search(entry.name, matches, regex))
            {
                auto num = std::stol(matches.str(1));
                auto relpath = matches.str(2);
                if(num >= 1 && num <= 6)
                    patches[num].emplace_back(entry, std::move(relpath));
            }
        }

        if(patches.empty())
            throw DiffgenException("No patches found.");

        std::size_t count = 0;
        for(auto& it : patches)
        {
            auto arcname = L"gn_dat" + std::to_wstring(it.first) + L".arc";
            auto arcpath = in_dir / arcname;
            if(!fs::exists(arcpath) || !fs::is_regular_file(arcpath))
            {
                ScopedConsoleColorChanger color(COLOR_CRITICAL);
                std::wcerr << L"Missing file: " << arcpath << std::endl;
                continue;
            }

            try
            {
                libtpdp::Archive arc;
                arc.open(arcpath.wstring());

                for(auto& i : it.second)
                {
                    auto file = zip.get_file(i.first);
                    auto pos = arc.find(utf8_to_sjis(i.second));
                    if(pos < arc.end())
                    {
                        pos = arc.repack_file(pos, file.data(), file.size());
                        if(pos >= arc.end())
                            throw DiffgenException("Failed to repack file: " + i.second);
                    }
                    else
                    {
                        pos = arc.insert(file.data(), file.size(), utf8_to_sjis(i.second));
                        if(pos >= arc.end())
                            throw DiffgenException("Failed to insert file: " + i.second);
                    }

                    ++count;
                }

                arc.save(arcpath.wstring());
            }
            catch(const libtpdp::ArcError& ex)
            {
                ScopedConsoleColorChanger color(COLOR_CRITICAL);
                std::wcerr << L"Error writing to file: " << arcpath << std::endl;
                std::wcerr << utf_widen(ex.what()) << std::endl;
                return false;
            }
        }

        std::wcout << L"Patched " << count << L" files." << std::endl;
        if(count == 0)
        {
            ScopedConsoleColorChanger color(COLOR_CRITICAL);
            std::wcerr << L"Could not apply any patches." << std::endl;
            return false;
        }
    }
    catch(const ZipError& ex)
    {
        ScopedConsoleColorChanger color(COLOR_CRITICAL);
        std::wcerr << L"Error reading from file: " << output << std::endl;
        std::wcerr << utf_widen(ex.what()) << std::endl;
        return false;
    }

    return true;
}

bool repack(const Path& input, const Path& output, int threads)
{
    std::unordered_map<int, std::vector<DiffPair>> patches;

    std::wcout << L"Using up to " << threads << L" concurrent threads" << std::endl;

    Path in_dir(input / L"dat");

    {
        auto diffs = get_diffs(in_dir, output, threads);

        if(diffs.empty())
            throw DiffgenException("Source and target are identical, no files to repack!");

        for(auto& i : diffs)
        {
            auto&[arc_num, rel_path, data_path] = i;
            patches[arc_num].push_back({ std::move(rel_path), std::move(data_path) });
        }
    }

    Path arc_path;
    try
    {
        for(const auto& i : patches)
        {
            auto arc_num = i.first;
            arc_path = in_dir / (L"gn_dat" + std::to_wstring(arc_num) + L".arc");

            libtpdp::Archive arc;
            arc.open(arc_path.wstring());

            for(const auto& j : i.second)
            {
                const auto&[rel_path, data_path] = j;

                std::size_t sz;
                auto file = read_file(data_path.wstring(), sz);
                if(!file)
                    throw DiffgenException("Failed to read file: " + utf_narrow(data_path.wstring()));

                auto filename = utf_to_sjis(rel_path.wstring());
                auto it = arc.find(filename);
                if(it >= arc.end())
                {
                    auto pos = arc.insert(file.get(), sz, filename);
                    if(pos >= arc.end())
                        throw DiffgenException("Failed to insert file: " + utf_narrow(data_path.wstring()));
                }
                else
                {
                    auto pos = arc.repack_file(it, file.get(), sz);
                    if(pos >= arc.end())
                        throw DiffgenException("Failed to repack file: " + utf_narrow(data_path.wstring()));
                }
            }

            arc.save(arc_path.wstring());
        }
    }
    catch(const libtpdp::ArcError& ex)
    {
        ScopedConsoleColorChanger color(COLOR_CRITICAL);
        std::wcerr << L"Error writing to file: " << arc_path << std::endl;
        std::wcerr << utf_widen(ex.what()) << std::endl;
        return false;
    }

    return true;
}


text:
#ifndef _planeseg_PlaneSegmenter_hpp_
#define _planeseg_PlaneSegmenter_hpp_

#include <vector>
#include <unordered_map>
#include <Eigen/Dense>

#include "Types.hpp"

namespace planeseg {

class PlaneSegmenter {
public:
  struct Result {
    std::vector<int> mLabels;
    std::unordered_map<int,Eigen::Vector4f> mPlanes;
  };

public:
  PlaneSegmenter();

  void setData(const LabeledCloud::Ptr& iCloud,
               const NormalCloud::Ptr& iNormals);

  void setMaxError(const float iError);
  void setMaxAngle(const float iAngle);
  void setSearchRadius(const float iRadius);
  void setMinPoints(const int iMin);

  Result go();

protected:
  LabeledCloud::Ptr mCloud;
  NormalCloud::Ptr mNormals;
  float mMaxError;
  float mMaxAngle;
  float mSearchRadius;
  int mMinPoints;
};

}

#endif


text:
#include <boost/thread.hpp>

int main(int argc, char** argv){
	boost::thread th;
	return 0;
}


text:
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Implementation for SocketStore class.
 *
 * Copyright (c) 2009 Webroot Software, Inc.
 *
 * 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 "SocketStore.h"
#include "ConnectionPool.h"
#include "voldemort/UnreachableStoreException.h"

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

namespace Voldemort {

using namespace boost;
using asio::ip::tcp;

SocketStore::SocketStore(const std::string& storeName,
                         const std::string& storeHost,
                         int storePort,
                         shared_ptr<ClientConfig>& conf,
                         shared_ptr<ConnectionPool>& pool,
                         RequestFormat::RequestFormatType requestFormatType,
                         bool shouldReroute)
    : name(storeName), host(storeHost), port(storePort), reroute(shouldReroute),
      config(conf), connPool(pool),
      request(RequestFormat::newRequestFormat(requestFormatType)) {

}

SocketStore::~SocketStore() {
    close();
}

std::list<VersionedValue>* SocketStore::get(const std::string& key) const {
    try {
        ConnectionPoolSentinel
            conn(connPool->checkout(host, port,
                                    request->getNegotiationString()),
                 connPool);
        std::iostream& sstream = conn->get_io_stream();

        request->writeGetRequest(&sstream,
                                 &name,
                                 &key,
                                 reroute);
        sstream.flush();
        return request->readGetResponse(&sstream);
    } catch (UnreachableStoreException& e) {
        throw UnreachableStoreException(std::string("Failure to get ") + host +
                                        std::string(": ") + e.what());
    }
}

void SocketStore::put(const std::string& key, const VersionedValue& value) {
    try {
        ConnectionPoolSentinel
            conn(connPool->checkout(host, port,
                                    request->getNegotiationString()),
                 connPool);
        std::iostream& sstream = conn->get_io_stream();

        request->writePutRequest(&sstream,
                                 &name,
                                 &key,
                                 value.getValue(),
                                 dynamic_cast<const VectorClock*>(value.getVersion()),
                                 reroute);
        sstream.flush();
        request->readPutResponse(&sstream);
    } catch (UnreachableStoreException& e) {
        throw UnreachableStoreException(std::string("Failure to put ") + host +
                                        std::string(": ") + e.what());
    }
}

bool SocketStore::deleteKey(const std::string& key, const Version& version) {
    try {
        ConnectionPoolSentinel
            conn(connPool->checkout(host, port,
                                    request->getNegotiationString()),
                 connPool);
        std::iostream& sstream = conn->get_io_stream();

        request->writeDeleteRequest(&sstream,
                                    &name,
                                    &key,
                                    dynamic_cast<const VectorClock*>(&version),
                                    reroute);
        sstream.flush();
        return request->readDeleteResponse(&sstream);
    } catch (UnreachableStoreException& e) {
        throw UnreachableStoreException(std::string("Failure to delete ") + host +
                                        std::string(": ") + e.what());
    }
}

const std::string* SocketStore::getName() const {
    return &name;
}

void SocketStore::close() {
    /* noop */
}

} /* namespace Voldemort */

max_stars_repo_name: ramiyer/voldemort

max_issues_repo_name: ramiyer/voldemort

max_forks_repo_name: ramiyer/voldemort


text:
namespace boost { namespace logging {

/**
@page defining_your_logger_filter Declaring/Defining your logger/filter class(es)

- @ref defining_prerequisites
    - @ref defining_prerequisites_typedef
    - @ref defining_prerequisites_dd

- @ref typedefing_your_filter
    - @ref typedefing_your_filter_scenario
    - @ref typedefing_your_filter_manually
- @ref typedefing_your_logger
    - @ref typedefing_your_logger_scenario
    - @ref typedefing_your_logger_format_write
    - @ref typedefing_your_logger_use_logger

- @ref declare_define
    - @ref declare_define_use_macros
        - @ref declare_define_use_macros_under_the_hood
        - @ref declare_define_use_macros_as_functions
        - @ref declare_define_use_macros_fast_compile
        - @ref declare_define_use_macros_before_main
        - @ref declare_define_use_macros_no_after_destroyed
    - @ref declare_define_manually
        - @ref declare_define_manually_f_vs_v
        - @ref declare_define_manually_logger_holder
        - @ref declare_define_manually_before_main

@section defining_prerequisites Prerequisites

When using the Boost Logging Lib, you need 2 things (see @ref workflow "Workflow"):
- a filter : which tells you if a logger is enabled or not. Note that you can use the same filter for multiple loggers - if you want.
- a logger : which does the actual logging, once it's enabled

In order to declare/define filters and loggers:
- you have to choose the filter and logger based on your needs (@ref defining_prerequisites_typedef "typedefing")
- you have to declare and define your fiter and logger (@ref defining_prerequisites_dd "declare and define")

\n\n
@subsection defining_prerequisites_typedef Prerequisites - Typedefing

Typedefing your filter/logger is the process where you find the @c type of your filter/logger.

Example 1:
@code
using namespace boost::logging::scenario::usage;
typedef use< filter_::change::often<10> > finder;
// now, finder::logger contains the logger type and finder::filter contains the filter type
@endcode

Example 2:
@code
namespace bl = boost::logging;
typedef bl::logger_format_write< > logger_type;
typedef bl::filter::no_ts filter_type;
@endcode

\n\n
@subsection defining_prerequisites_dd Prerequisites - Declare and define

Now that you know the types of your logger(s) and filter(s), you have to declare and define them.
The easiest way is to use the @c BOOST_DECLARE_LOG* and @c BOOST_DEFINE_LOG* macros:

In a header file
@code
BOOST_DECLARE_LOG_FILTER(g_log_filter, filter_type )
BOOST_DECLARE_LOG(g_l, logger_type)
@endcode

In a source file
@code
BOOST_DEFINE_LOG_FILTER(g_log_filter, filter_type )
BOOST_DEFINE_LOG(g_l, logger_type)

// ... manipulating the logger/filter in the code
g_l()->writer().add_formatter( formatter::idx(), "[%] "  );
g_log_filter()->set_enabled(false);
@endcode

However, there are other ways to declare/define your loggers/filters. We'll explore them @ref declare_define "later".

\n\n
@section typedefing_your_filter Typedefing your filter class

@subsection typedefing_your_filter_scenario Typedefing your filter using scenarios (the easy way)

You can declare/define both your logger and filter based on how you'll use them (scenario::usage).
Thus, you'll deal with the filter like this:

@code
#include <boost/logging/format_fwd.hpp>
using namespace boost::logging::scenario::usage;
typedef use<
        // how often does the filter change?
        filter_::change::often<10>,
        // does the filter use levels?
        filter_::level::no_levels,
        // logger info
        ...
        > finder;

// declare filter
BOOST_DECLARE_LOG_FILTER(g_log_filter, finder::filter )

// define filter
BOOST_DEFINE_LOG_FILTER(g_log_filter, finder::filter )
@endcode

@subsection typedefing_your_filter_manually Typedefing your filter manually

This is where you manually specify the filter class you want. There are multiple filter implementations:
- not using levels - the classes from the filter namespace
- using levels - the classes from the level namespace

Choose any you wish:

@code
#include <boost/logging/format_fwd.hpp>

// declare filter
BOOST_DECLARE_LOG_FILTER(g_log_filter, filter::no_ts )

BOOST_DEFINE_LOG_FILTER(g_log_filter, filter::no_ts )
@endcode

@section typedefing_your_logger Typedefing your logger class(es)

@subsection typedefing_your_logger_scenario Typedefing your logger using scenarios (the very easy way)

When you use formatters and destinations, you can declare/define both your logger and filter based on how you'll use them (scenario::usage).
Thus, you'll deal with the logger like this:

@code
#include <boost/logging/format_fwd.hpp>

using namespace boost::logging::scenario::usage;
typedef use<
        // filter info
        ...,
        // how often does the logger change?
        logger_::change::often<10>,
        // what does the logger favor?
        logger_::favor::speed> finder;

// declare
BOOST_DECLARE_LOG(g_log_err, finder::logger )

// define
BOOST_DEFINE_LOG(g_log_err, finder::logger )

@endcode

@subsection typedefing_your_logger_format_write Typedefing your logger using logger_format_write (the easy way)

When you use formatters and destinations, you can use the logger_format_write class. The template params you don't want to set,
just leave them @c default_.

@code
#include <boost/logging/format_fwd.hpp>

namespace bl = boost::logging;
typedef bl::logger_format_write< bl::default_, bl::default_, bl::writer::threading::on_dedicated_thread > logger_type;

// declare
BOOST_DECLARE_LOG(g_l, logger_type)

// define
BOOST_DEFINE_LOG(g_l, logger_type)
@endcode

@subsection typedefing_your_logger_use_logger Typedefing your logger using the logger class

In case you don't use formatters and destinations, or have custom needs that the above methods can't satisfy, or
just like to do things very manually, you can use the logger class directly:

@code
#include <boost/logging/logging.hpp>

typedef logger< gather::ostream_like::return_str<>, destination::cout> logger_type;

// declare
BOOST_DECLARE_LOG(g_l, logger_type)

// define
BOOST_DEFINE_LOG(g_l, logger_type)
@endcode

\n\n
@section declare_define Declaring and defining your logger and filter

At this point, you @em have your logger class and your filter class. Lets assume they are @c logger_type and @c filter_type.
You could have obtained them like this:

@code
namespace bl = boost::logging;
typedef bl::logger_format_write< > logger_type;
typedef bl::filter::no_ts filter_type;
@endcode

\n\n
@subsection declare_define_use_macros Declaring and defining your logger/filter using macros

This is the simplest way to declare/define your filters.

Declaring:

@code
// in a header file

#include <boost/logging/format_fwd.hpp>
// if you don't use formatters/destinations, you can include only <boost/logging/logging.hpp>

// declare a filter, called g_log_filter
BOOST_DECLARE_LOG_FILTER(g_log_filter, filter_type)

// declare a logger, called g_log
BOOST_DECLARE_LOG(g_log, logger_type)
@endcode

Defining:

@code
// in a source file
#include <boost/logging/format.hpp>

// define a filter, called g_log_filter
BOOST_DEFINE_LOG_FILTER(g_log_filter, filter_type)

// define a logger, called g_log
BOOST_DEFINE_LOG(g_log, logger_type)
@endcode

Specifying some arguments when defining the logger/filter:
@code
// in a source file
#include <boost/logging/format.hpp>

// define a filter, called g_log_filter - assuming it needs an 2 arguments at construction
BOOST_DEFINE_LOG_FILTER_WITH_ARGS(g_log_filter, filter_type, (level::debug, true) )

// define a logger, called g_log - assuming it needs an extra argument at construction
BOOST_DEFINE_LOG_WITH_ARGS(g_log, logger_type, ("log.txt") )
@endcode

\n\n
@subsection declare_define_use_macros_under_the_hood Declaring and defining your logger/filter using macros - what happens under the hood?

When using the @c BOOST_DECLARE_LOG* and @c BOOST_DEFINE_LOG* macros, this is what the lib takes care for you:
-# it declares and defines a logger/filter name, as a @b function (which internally contains a static variable)
-# cares about @ref BOOST_LOG_COMPILE_FAST_ON "Fast Compile" (default) or @ref BOOST_LOG_COMPILE_FAST_OFF "not"
-# ensures the logger/filter object is instantiated before @c main(), even if not used before main(). This is very useful,
   since we can assume that before main() there won't be more than 1 threads, thus no problems at initializing the static variable.
-# ensures we don't @ref after_destruction "use a logger and/or filter after it's been destroyed"

\n\n
@subsubsection declare_define_use_macros_as_functions logger/filter as functions

We declare/define the logger/filter as a function, in order to avoid being used before it's initialized. Example:

@code
// Translation unit 1:
logger<...> g_l;

// Translation unit 2:
struct widget {
    widget() {
        // use g_l
        g_l.writer() ....
    }
} g_global_widget;

@endcode

In the above code we have 2 global variables (g_l and g_global_widget) in 2 different translation units. In this case, it's unspecified
which will be constructed first - thus, we could end up having g_global_widget constructed first, and using g_l before g_l is initialized.

To avoid this, g_l should be a function, like this:

@code
// Translation unit 1:
logger<...> & g_l() { static logger<...> l; return l; }

// Translation unit 2:
struct widget {
    widget() {
        // use g_l
        g_l().writer() ....
    }
} g_global_widget;

@endcode

In the above case, when g_l() is used for the first time, it constructs the local @c l, and it all works.
The @c BOOST_DECLARE_LOG* and @c BOOST_DEFINE_LOG* macros take care of this automatically.

\n\n
@subsubsection declare_define_use_macros_fast_compile Fast compiling : On/Off

The @c BOOST_DECLARE_LOG* and @c BOOST_DEFINE_LOG* macros also automatically take care of fast compiling or not.

Fast compiling (on by default) applies only to loggers. It means that you can use the loggers in code, even without knowing their definition.
More to the point, you can log messages throughout your application, even if you don't know the full type of the logger
(a @em typedef is enough).
This avoids inclusion of a lot of header files, speeding the compile process.

If fast compile is on, you only need this when using logs:

@code
// usually in a header file
#include <boost/logging/format_fwd.hpp>
typedef logger_format_write< > logger_type;

BOOST_DECLARE_LOG(g_l, logger_type)

// macro used for logging
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() )

// in your code, only by #including boost/logging/format_fwd.hpp, you can log messages
L_ << "this is so cool " << i++;
std::string hello = "hello", world = "world";
L_ << hello << ", " << world;
@endcode

If fast compile is off, when using the logs, you'll need to know the full type of the logger (the definition of the logger class). \n
When using formatters/destinations, this means <tt>\#include <boost/logging/format.hpp></tt>. Also, when logging a message,
the code for doing the actual logging will be generated inline, this taking a bit of compilation time.

@ref macros_compile_time "More details here".

In short,

When fast compile is off, BOOST_DEFINE_LOG will generate code similar to this:

@code
logger_type * g_l() { static logger_type l; return &l; }
@endcode

When fast compile is on, BOOST_DEFINE_LOG will generate code similar to this:

@code
logger_holder<logger_type> & g_l() { static logger_holder_by_value<logger_type> l; return l; }
@endcode

In the latter case, logger_holder<> holds a pointer to the original log, and when a message is logged,
it forwards it to the real logger (implemented in logger_holder_by_value).

\n\n
@subsubsection declare_define_use_macros_before_main Ensuring instantiation before main()

The @c BOOST_DECLARE_LOG* and @c BOOST_DEFINE_LOG* macros also automatically ensure that the logger/filter is instantiated before main().
This is very useful, since we can assume that before main() there won't be more than 1 threads, thus no problems at initializing the static variable.

For this, it uses the @c ensure_early_log_creation class, like this:

@code
// this will ensure g_l() is called before main(), even if not used anywhere else before main()
ensure_early_log_creation ensure( g_l() );
@endcode

\n\n
@subsubsection declare_define_use_macros_no_after_destroyed Ensuring you don't use a logger and/or filter after it's been destroyed

See @ref after_destruction "this" for more details.

\n\n
@subsection declare_define_manually Declaring and defining your logger/filter manually

As explained @ref declare_define_use_macros "above", you can use macros to declare/define your loggers/filters.

Of course, you can declare/define them manually. If you decide to do it, please read the @ref declare_define_use_macros "Define/declare ... macros" section
throughly, so that you know what you should watch for.

For example, declaring/defining your logger can be as easy as:

In a header file
@code
logger_type * g_l();

// example of macro used for logging
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() )
@endcode

In a source file
@code
logger_type * g_l() { static logger_type l; return &l; }

// example of usage
L_ << "this is so cool " << i++;
std::string hello = "hello", world = "world";
L_ << hello << ", " << world;
@endcode

\n\n
@subsubsection declare_define_manually_f_vs_v Functions versus variables

As I said, you should prefer @ref declare_define_use_macros_as_functions "functions instead of variables" for the obvious reasons.

Thus (when using functions), your code should look like:

In a header file
@code
logger_type * g_l();

// example of macro used for logging
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() )
@endcode

In a source file
@code
logger_type * g_l() { static logger_type l; return &l; }

// example of usage
L_ << "this is so cool " << i++;
std::string hello = "hello", world = "world";
L_ << hello << ", " << world;
@endcode

\n
You can use variables, provided that @ref declare_define_use_macros_as_functions "you know the risks".

In a header file
@code
extern logger_type g_l;

// example of macro used for logging
#define L_ BOOST_LOG_USE_LOG_IF_FILTER((*g_l), g_log_filter()->is_enabled() )
@endcode

In a source file
@code
logger_type g_l;

// example of usage
L_ << "this is so cool " << i++;
std::string hello = "hello", world = "world";
L_ << hello << ", " << world;
@endcode

\n\n
@subsubsection declare_define_manually_logger_holder Using logger_holder class

You should use @c logger_holder<> when you want to be able to use the logger without knowing its definition (in other words, you only have a typedef).
Thus, you'll only need to #include <boost/logging/format_fwd.hpp> throughout the application.

In case you're using formatters and destinations, you'll need to #include <boost/logging/format.hpp> :
- when defining the logger
- when initializing it

Note that this will involve a virtual function call for each logged message - when performing the actual logging.

<tt>logger_holder<logger></tt> is the base class - the one that will be used in code/presented to clients.
The possible implementations are :
- logger_holder_by_value<logger> - holds the original logger by value
  - in case you think the logger could be used after it's been destroyed, you should use this
- logger_holder_by_ptr<logger> - holds the original logger as a pointer (allocates it constructor, deallocates it in destructor)

Example of using logger_holder<> :

In a header file
@code
logger_holder<logger_type> & g_l();

// example of macro used for logging
#define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() )
@endcode

In a source file
@code
logger_holder<logger_type> & g_l() {
  static logger_holder_by_value<logger_type> l;
  return l;
}

// example of usage
L_ << "this is so cool " << i++;
std::string hello = "hello", world = "world";
L_ << hello << ", " << world;
@endcode

\n\n
@subsubsection declare_define_manually_before_main  Ensure initialized before main()

If you use loggers/filters as global variables, you don't need to worry about this.

If you use loggers/filters as functions with static variables, they will be initialized on first usage.

This could be problematic, in case the variable is initialized when more than one thread is running.
In some current implementations , if 2 threads are calling the function at the same time (and when each function enters, needs to construct the variable),
you might end up  with 2 different instances of the same static variable. Thus, trouble.

The easy solution is to use @c ensure_early_log_creation class, like this:

@code
// in the source file
logger_holder<logger_type> & g_l() {
  static logger_holder_by_value<logger_type> l;
  return l;
}
ensure_early_log_creation ensure( g_l() );

@endcode

This will ensure the logger is initialized before main(), thus the above problem does not happen.

*/

}}

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp