text:
#include <iostream>
#include <sstream>
#include <vector>
#include <atomic>
#include <csignal>

#include <boost/program_options.hpp>

#include "../src/Client/DSMClient.h"

namespace po = boost::program_options;

std::atomic<bool> isRunning;

void signalHandler(int signum) {
    isRunning = false;
}

void processInput(dsm::Client* client) {
    std::cout << "> ";

    std::string input;
    std::getline(std::cin, input);
    std::stringstream ss(input);
    std::string token;
    std::vector<std::string> tokens;
    while (std::getline(ss, token, ' ')) {
        tokens.push_back(token);
    }
    dsm::LocalBufferKey lKey;
    dsm::RemoteBufferKey rKey;
    uint16_t size;
    switch (tokens.size()-1) {
        case 0:
            if (tokens[0] == "kill" || tokens[0] == "exit") {
                std::cout << "exiting" << std:: endl;
                isRunning = false;
                return;
            }
            break;
        case 1:
            lKey = dsm::Client::createLocalKey(tokens[1]);
            if (tokens[0] == "dcl") {
                if (client->disconnectFromLocalBuffer(lKey)) {
                    std::cout << "Disconnected from local buffer";
                } else {
                    std::cout << "Invalid operands";
                }
            } else if (tokens[0] == "checkl") {
                size = client->doesLocalExist(lKey);
                if (size) {
                    std::cout << "Local buffer exists with size " << size;
                } else {
                    std::cout << "Local buffer does not exist";
                }
            } else if (tokens[0] == "getl") {
                char data[MAX_BUFFER_SIZE];
                if (client->getLocalBufferContents(lKey, data)) {
                    std::cout << std::string(data, client->doesLocalExist(lKey));
                } else {
                    std::cout << "Invalid operands";
                }
            }
            break;
        case 2:
            lKey = dsm::Client::createLocalKey(tokens[1]);
            if (tokens[0] == "regl") {
                if (client->registerLocalBuffer(lKey, stoi(tokens[2]), false)) {
                    std::cout << "Registered new local buffer";
                } else {
                    std::cout << "Invalid operands";
                }
            } else if (tokens[0] == "reglo") {
                if (client->registerLocalBuffer(lKey, stoi(tokens[2]), true)) {
                    std::cout << "Registered new local only buffer";
                } else {
                    std::cout << "Invalid operands";
                }
            } else if (tokens[0] == "setl") {
                if (client->setLocalBufferContents(lKey, tokens[2].data())) {
                    std::cout << "Set local buffer contents";
                } else {
                    std::cout << "Invalid operands";
                }
            }
            break;
        case 3:
            rKey = dsm::Client::createRemoteKey(tokens[1], tokens[2], stoi(tokens[3]));
            if (tokens[0] == "regr") {
                if (client->registerRemoteBuffer(rKey)) {
                    std::cout << "Registered new remote buffer";
                } else {
                    std::cout << "Invalid operands";
                }
            } else if (tokens[0] == "dcr") {
                if (client->disconnectFromRemoteBuffer(rKey)) {
                    std::cout << "Disconnect from remote buffer";
                } else {
                    std::cout << "Invalid operands";
                }
            } else if (tokens[0] == "checkr") {
                size = client->doesRemoteExist(rKey);
                if (size) {
                    if (client->isRemoteActive(rKey)) {
                        std::cout << "Remote buffer is active and has size " << size;
                    } else {
                        std::cout << "Remote buffer is inactive and has size " << size;
                    }
                } else {
                    std::cout << "Remote buffer does not exist";
                }
            } else if (tokens[0] == "getr") {
                char data[MAX_BUFFER_SIZE];
                switch (client->getRemoteBufferContents(rKey, data)) {
                    case 0:
                        std::cout << "Active: " << std::string(data, client->doesRemoteExist(rKey));
                        break;
                    case 1:
                        std::cout << "Inactive: " << std::string(data, client->doesRemoteExist(rKey));
                        break;
                    default:
                        std::cout << "Invalid operands";
                        break;
                }
            }
            break;
        default:
            std::cout << "unknown";
            break;
    }
    std::cout << std::endl;
}

int main(int argc, char** argv) {
    try {
        int serverID;
        int clientID;
        po::options_description generalOptions("Options");
        generalOptions.add_options()
            ("help,h", "print help message")
            ("serverID,s", po::value<int>(&serverID), "the serverID of the server")
            ("clientID,c", po::value<int>(&clientID), "the clientID to connect with")
            ;
        po::positional_options_description positionalOptions;
        positionalOptions
            .add("serverID", 1)
            .add("clientID", 1)
            ;

        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).
                  options(generalOptions).
                  positional(positionalOptions).
                  run(), vm);
        po::notify(vm);

        if (vm.count("help") || !vm.count("serverID") || !vm.count("clientID")) {
            std::cout << "Usage: clientTester serverID clientID" << std::endl;
            std::cout << generalOptions;
            return 0;
        }

        if (serverID < 0 || serverID >= MAX_SERVERS) {
            std::cout << "Server ID must be between 0 and " << MAX_SERVERS-1 << std::endl;
            return 0;
        }

        if (clientID < 0 || clientID >= MAX_CLIENTS) {
            std::cout << "Client ID must be between 0 and " << MAX_CLIENTS-1 << std::endl;
            return 0;
        }

        std::signal(SIGINT, signalHandler);

        dsm::Client client(serverID, clientID);

        isRunning = true;
        while(isRunning.load()) {
            processInput(&client);
        }

        return 0;
    } catch (std::exception& e) {
        std::cout << "Error: ";
        std::cout << e.what() << std::endl;
        return 1;
    }

}

max_stars_repo_name: rahulsalvi/DistributedSharedMemory

max_issues_repo_name: rahulsalvi/DistributedSharedMemory

max_forks_repo_name: rahulsalvi/DistributedSharedMemory


text:
#ifndef OPENGM_PYTHON_INTERFACE
#define OPENGM_PYTHON_INTERFACE 1
#endif

#include <stdexcept>
#include <stddef.h>
#include <string>
#include <boost/python.hpp>
#include "nifty_iterator.hxx"
#include "inferencehelpers.hxx"
#include "export_typedes.hxx"

#include <opengm/inference/lpcplex.hxx>

// to print parameter as string
template< class PARAM>
std::string cplexParamAsString(const PARAM & param) {
   std::string p=" ";
   return p;
}
// export function
template<class GM, class ACC>
void export_cplex() {
   using namespace boost::python;
   // import numpy c-api
   import_array();
   // Inference typedefs
   typedef opengm::LPCplex<GM, ACC> PyLPCplex;
   typedef typename PyLPCplex::Parameter PyLPCplexParameter;
   typedef typename PyLPCplex::VerboseVisitorType PyLPCplexVerboseVisitor;

   // export inference parameter
   class_<PyLPCplexParameter > ("LPCplexParameter", init< typename PyLPCplex::MoveType > (args("moveType")))
      .def(init<>())
      .def_readwrite("numberOfThreads", &PyLPCplexParameter::numberOfThreads_)
      .def_readwrite("cutUp", &PyLPCplexParameter::cutUp_)
      .def_readwrite("epGap", &PyLPCplexParameter::epGap_)
      .def("__str__", &cplexParamAsString<PyLPCplexParameter>)
      ;
   // export inference verbose visitor via macro
   OPENGM_PYTHON_VERBOSE_VISITOR_EXPORTER(PyLPCplexVerboseVisitor, "LPCplexVerboseVisitor");
   // export inference via macro
   OPENGM_PYTHON_INFERENCE_EXPORTER(PyLPCplex, "LPCplex");
}
// explicit template instantiation for the supported semi-rings
template void export_LPCplex<GmAdder, opengm::Minimizer>();

ext: cxx

max_stars_repo_name: amueller/opengm

max_issues_repo_name: amueller/opengm

max_forks_repo_name: amueller/opengm


text:
#include <pel/database/database_creator.h>
#include <pel/database/database_io.h>
#include <pel/database/database.h>
#include <pcl/console/parse.h>
#include <string>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem/path.hpp>

using namespace pcl::console;

bool load(false), overwrite(false);
boost::filesystem::path in_path, out_path;
boost::filesystem::path p_path;

void
show_help(char* prog_name)
{
  //trim and split program name string
  std::string pn = prog_name;
  boost::trim(pn);
  std::vector<std::string> vst;
  boost::split (vst, pn, boost::is_any_of("/\\.."), boost::token_compress_on);
  pn = vst.at( vst.size() -1);
  print_highlight ("%s takes a path containing pcd files of objects viewes to assemble a PEL Database from them, using default or specified parameters.\n", pn.c_str());
  print_highlight ("Usage:\t%s [SourceDir] [OutputDir] [Options]\n", pn.c_str());
  print_highlight ("Options are:\n");
  print_value ("\t-h, --help");
  print_info (":\t\tShow this help screen and quit.\n");
  print_value ("\t--load <path>");
  print_info (":\t\tLoad a set of configuration parameters from a yaml file in <path>\n");
  print_value ("\t-w");
  print_info (":\t\t\tOverwrite <OutputDir> even if it already exists.\n");
}

void
parse_command_line(int argc, char* argv[])
{
  if (find_switch (argc, argv, "-h") || find_switch (argc, argv, "--help"))
  {
    show_help(argv[0]);
    exit(0);
  }
  if (find_switch (argc, argv, "-w"))
    overwrite = true;
  std::string param_path;
  parse_argument (argc, argv, "--load", param_path);
  p_path = param_path;
  if (!boost::filesystem::exists(p_path) || !boost::filesystem::is_regular_file(p_path))
  {
    print_warn("Invalid path for parameters loading! Ignoring...\n");
    load = false;
  }
  else
    load=true;
  in_path = argv[1];
  out_path = argv[2];
  if (!boost::filesystem::exists(in_path) || !boost::filesystem::is_directory(in_path))
  {
    print_error("Invalid path for source clouds. Cannot continue...\n");
    exit(0);
  }
}

////////////////////////////////////////////////////
//////////////////  Main  //////////////////////////
////////////////////////////////////////////////////
int
main (int argc, char *argv[])
{
  //take care of command line...
  if (argc <3)
  {
    print_error("Need at least 2 parameters: [SourceDir] and [OutputDir], in this order.\n");
    show_help(argv[0]);
    return(0);
  }
  parse_command_line(argc, argv);

  //to business!
  //Create an empty database and
  pel::Database db;
  //a creator
  pel::DatabaseCreator creator;
  if (load)
  {
    //load provided parameters instead of default ones
    creator.loadParamsFromFile(p_path);
  }
  //be verbose
  creator.setParam("verbosity", 2);
  //inform user what parameters we are going to use
  creator.printAllParams();

  //ok, start Database creation
  db = creator.create(in_path);
  //go get coffee...

  if (!db.isEmpty())
  {
    //Everything went fine, lets save the database where the user told us
    //Writer object
    pel::DatabaseWriter writer;
    //write it!
    writer.save(out_path, db, overwrite);
  }
  else
  {
    print_error("Something went wrong with Database creation, not saving it...\n");
    return (0);
  }
  //bye
  return (1);
}

ext: cpp

max_stars_repo_name: catree/Pose-Estimation-Library

max_issues_repo_name: Tabjones/Pose-Estimation-Library

max_forks_repo_name: Tabjones/Pose-Estimation-Library


text:
//  Copyright (c)      2012 Daniel Kogler
//
//  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)

/*The server file for the pingpong component, this contains the bulk of the
pingpong component's code*/
#ifndef _PINGPONG_SERVER
#define _PINGPONG_SERVER
#include <hpx/hpx.hpp>
#include <hpx/hpx_fwd.hpp>
#include <boost/thread/mutex.hpp>
#include <hpx/runtime/applier/applier.hpp>
#include <hpx/runtime/actions/component_action.hpp>
#include <hpx/runtime/components/component_type.hpp>
#include <hpx/runtime/components/server/simple_component_base.hpp>

#include <vector>
#include <string>
#include "../../statstd.hpp"

namespace hpx { namespace components { namespace server
{

using hpx::parcelset::parcel;
using hpx::applier::get_applier;
using hpx::naming::id_type;
using boost::mutex;
using boost::timed_mutex;

//export the component to hpx
class HPX_COMPONENT_EXPORT pingpong :
    public simple_component_base<pingpong>
{
public:
    pingpong(){}

    //initialize the component.  We don't do this in the constructor because
    //it's easier than dealing with multiple constructor arguments when calling
    //the create() function (which is used for creating components)
    int init(uint64_t num, double ot_, id_type des){
        number = num;
        ot = ot_;
        destiny = des;
        return 0;
    }

    typedef hpx::actions::result_action3<pingpong, int, 0, uint64_t, double,
        id_type, &pingpong::init> init_action;

    //get the elapsed time since t and divide it by 2 since we must send parcels
    //twice in order to ensure clock consistency (once from source to destination
    //and again from destination to source)
    double set_time(double t){
        double tim = (timer.elapsed()-t)*.5;
        return tim;
    }

    typedef hpx::actions::result_action1<pingpong, double, 1, double,
        &pingpong::set_time> set_action;

    //this sends a parcel from the destination back to the source so that we use
    //the same timer that started timing to get the total latency.  when this
    //function returns, we will have sent two parcels for certain and perhaps three,
    //but only the first two latencies are measured so we do not need to worry
    //about accounting for any additional overhead
    double pong(double t){
        hpx::lcos::packaged_action<server::pingpong::set_action> future(destiny, t);
        return future.get_future().get();
    }

    typedef hpx::actions::result_action1<pingpong, double, 2, double,
        &pingpong::pong> pong_action;

    //send the parcels from the sender to the receiver
    int ping(){
        uint64_t i = 0;
        double mean;
        string message = "Measuring intra-nodal latency by sending parcels:\n"
            "NOTE - time creating and applying packages is included, please\n"
            "compare with general_pa_analysis.";
        time.reserve(number);

        //obtain the statistical sampling of the timings
        for(i = 0; i < number; i++){
            hpx::lcos::packaged_action<server::pingpong::pong_action>
                future(destiny,timer.elapsed());
            time.push_back(future.get_future().get());
        }

        //unlike most of the statistical benchmarks, we cannot easily obtain
        //a highly accurate mean time.  the best we can do is simply take the
        //mean as determined by the statistical sampling
        double sum = 0;
        for(i=0;i<number;i++){
            sum+=time[i];
        }
        mean = sum/number;

        printout(time, ot, mean, message);
        return 0;
    }

    typedef hpx::actions::result_action0<pingpong, int, 3, &pingpong::ping> ping_action;

private:

    id_type destiny;
    uint64_t number;
    double ot;
    vector<double> time;
    high_resolution_timer timer;
};

}}}

HPX_REGISTER_ACTION_DECLARATION_EX(
    hpx::components::server::pingpong::wrapped_type::init_action, hpx_init_action)
HPX_REGISTER_ACTION_DECLARATION_EX(
    hpx::components::server::pingpong::wrapped_type::set_action, hpx_set_action)
HPX_REGISTER_ACTION_DECLARATION_EX(
    hpx::components::server::pingpong::wrapped_type::pong_action, hpx_pong_action)
HPX_REGISTER_ACTION_DECLARATION_EX(
    hpx::components::server::pingpong::wrapped_type::ping_action, hpx_ping_action)

#endif

ext: hpp

max_stars_repo_name: vamatya/benchmarks

max_issues_repo_name: vamatya/benchmarks

max_forks_repo_name: vamatya/benchmarks


text:
//
// Copyright 2013 Christian Henning
//
// 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
//
#include <boost/gil.hpp>
#include <boost/gil/extension/io/targa.hpp>

#include <boost/core/lightweight_test.hpp>

#include "paths.hpp"
#include "scanline_read_test.hpp"

namespace gil = boost::gil;

#ifdef BOOST_GIL_IO_USE_TARGA_FILEFORMAT_TEST_SUITE_IMAGES

template <typename Image>
void test_targa_scanline_reader(std::string filename)
{
    test_scanline_reader<Image, gil::targa_tag>(std::string(targa_in + filename).c_str());
}

template <typename Image>
void write(Image& img, std::string const& file_name)
{
#ifdef BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
    gil::write_view(targa_out + file_name, gil::view(img), gil::targa_tag());
#endif  // BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
}

void test_read_header()
{
    using backend_t   = gil::get_reader_backend<std::string const, gil::targa_tag>::type;
    backend_t backend = gil::read_image_info(targa_filename, gil::targa_tag());

    BOOST_TEST_EQ(backend._info._header_size, 18);
    BOOST_TEST_EQ(backend._info._offset, 18);
    BOOST_TEST_EQ(backend._info._color_map_type, 0);
    BOOST_TEST_EQ(backend._info._image_type, 10);
    BOOST_TEST_EQ(backend._info._color_map_start, 0);
    BOOST_TEST_EQ(backend._info._color_map_length, 0);
    BOOST_TEST_EQ(backend._info._color_map_depth, 0);
    BOOST_TEST_EQ(backend._info._x_origin, 0);
    BOOST_TEST_EQ(backend._info._y_origin, 0);
    BOOST_TEST_EQ(backend._info._width, 124);
    BOOST_TEST_EQ(backend._info._height, 124);
    BOOST_TEST_EQ(backend._info._bits_per_pixel, 24);
    BOOST_TEST_EQ(backend._info._descriptor, 0);
}

void test_read_reference_images()
{
    // 24BPP_compressed.tga
    {
        gil::rgb8_image_t img;
        gil::read_image(targa_in + "24BPP_compressed.tga", img, gil::targa_tag());

        typename gil::rgb8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgb8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgb8_pixel_t(248, 0, 248));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgb8_pixel_t(0, 0, 248));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgb8_pixel_t(248, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgb8_pixel_t(248, 0, 248));

        write(img, "24BPP_compressed_out.tga");
    }
    // 24BPP_uncompressed.tga
    {
        gil::rgb8_image_t img;
        gil::read_image(targa_in + "24BPP_uncompressed.tga", img, gil::targa_tag());

        typename gil::rgb8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgb8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgb8_pixel_t(248, 0, 248));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgb8_pixel_t(0, 0, 248));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgb8_pixel_t(248, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgb8_pixel_t(248, 0, 248));

        write(img, "24BPP_uncompressed_out.tga");

        test_targa_scanline_reader<bgr8_image_t>("24BPP_uncompressed.tga");
    }
    // 32BPP_compressed.tga
    {
        gil::rgba8_image_t img;
        gil::read_image(targa_in + "32BPP_compressed.tga", img, gil::targa_tag());

        typename gil::rgba8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgba8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgba8_pixel_t(248, 0, 248, 255));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgba8_pixel_t(0, 0, 248, 255));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgba8_pixel_t(0, 0, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgba8_pixel_t(248, 0, 248, 255));

        write(img, "32BPP_compressed_out.tga");
    }
    // 32BPP_uncompressed.tga
    {
        gil::rgba8_image_t img;
        gil::read_image(targa_in + "32BPP_uncompressed.tga", img, gil::targa_tag());

        typename gil::rgba8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgba8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgba8_pixel_t(248, 0, 248, 255));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgba8_pixel_t(0, 0, 248, 255));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgba8_pixel_t(0, 0, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgba8_pixel_t(248, 0, 248, 255));

        write(img, "32BPP_uncompressed_out.tga");

        test_targa_scanline_reader<bgra8_image_t>("32BPP_uncompressed.tga");
    }
    // 24BPP_compressed_ul_origin.tga
    {
        gil::rgb8_image_t img;
        gil::read_image(targa_in + "24BPP_compressed_ul_origin.tga", img, gil::targa_tag());

        typename gil::rgb8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgb8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgb8_pixel_t(248, 0, 248));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgb8_pixel_t(0, 0, 248));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgb8_pixel_t(248, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgb8_pixel_t(248, 0, 248));

        write(img, "24BPP_compressed_ul_origin_out.tga");
    }
    // 24BPP_uncompressed_ul_origin.tga
    {
        gil::rgb8_image_t img;
        gil::read_image(targa_in + "24BPP_uncompressed_ul_origin.tga", img, gil::targa_tag());

        typename gil::rgb8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgb8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgb8_pixel_t(248, 0, 248));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgb8_pixel_t(0, 0, 248));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgb8_pixel_t(248, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgb8_pixel_t(248, 0, 248));

        write(img, "24BPP_uncompressed_ul_origin_out.tga");
    }
    // 32BPP_compressed_ul_origin.tga
    {
        gil::rgba8_image_t img;
        gil::read_image(targa_in + "32BPP_compressed_ul_origin.tga", img, gil::targa_tag());

        typename gil::rgba8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgba8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgba8_pixel_t(248, 0, 248, 255));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgba8_pixel_t(0, 0, 248, 255));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgba8_pixel_t(0, 0, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgba8_pixel_t(248, 0, 248, 255));

        write(img, "32BPP_compressed_ul_origin_out.tga");
    }
    // 32BPP_uncompressed_ul_origin.tga
    {
        gil::rgba8_image_t img;
        gil::read_image(targa_in + "32BPP_uncompressed_ul_origin.tga", img, gil::targa_tag());

        typename gil::rgba8_image_t::x_coord_t width  = gil::view(img).width();
        typename gil::rgba8_image_t::y_coord_t height = gil::view(img).height();

        BOOST_TEST_EQ(width, 124);
        BOOST_TEST_EQ(height, 124);
        BOOST_TEST(gil::view(img)(0, 0) == gil::rgba8_pixel_t(248, 0, 248, 255));
        BOOST_TEST(gil::view(img)(width - 1, 0) == gil::rgba8_pixel_t(0, 0, 248, 255));
        BOOST_TEST(gil::view(img)(0, height - 1) == gil::rgba8_pixel_t(0, 0, 0, 0));
        BOOST_TEST(gil::view(img)(width - 1, height - 1) == gil::rgba8_pixel_t(248, 0, 248, 255));

        write(img, "32BPP_uncompressed_ul_origin_out.tga");
    }
}

void test_partial_image()
{
    std::string const filename(targa_in + "24BPP_compressed.tga");

    gil::rgb8_image_t img;
    gil::read_image(
        filename, img,
        gil::image_read_settings<gil::targa_tag>(gil::point_t(0, 0), gil::point_t(50, 50)));

#ifdef BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
    gil::write_view(targa_out + "targa_partial.tga", gil::view(img), gil::targa_tag());
#endif  // BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
}

int main()
{
    test_read_header();
    test_read_reference_images();

    return boost::report_errors();
}
#else
int main() {}
#endif // BOOST_GIL_IO_USE_PNM_TEST_SUITE_IMAGES

max_stars_repo_name: martin-carrasco/gil

max_issues_repo_name: martin-carrasco/gil

max_forks_repo_name: martin-carrasco/gil


text:
// Copyright (c) 2012-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcserver.h"
#include "rpcclient.h"

#include "base58.h"
#include "netbase.h"

#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>

using namespace std;
using namespace json_spirit;

Array
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
    Array result;
    result.push_back(nRequired);
    Array addresses;
    if (address1) addresses.push_back(address1);
    if (address2) addresses.push_back(address2);
    result.push_back(addresses);
    return result;
}

Value CallRPC(string args)
{
    vector<string> vArgs;
    boost::split(vArgs, args, boost::is_any_of(" \t"));
    string strMethod = vArgs[0];
    vArgs.erase(vArgs.begin());
    Array params = RPCConvertValues(strMethod, vArgs);

    rpcfn_type method = tableRPC[strMethod]->actor;
    try {
        Value result = (*method)(params, false);
        return result;
    }
    catch (Object& objError)
    {
        throw runtime_error(find_value(objError, "message").get_str());
    }
}

BOOST_AUTO_TEST_SUITE(rpc_tests)

BOOST_AUTO_TEST_CASE(rpc_rawparams)
{
    // Test raw transaction API argument handling
}

BOOST_AUTO_TEST_CASE(rpc_rawsign)
{
}

BOOST_AUTO_TEST_CASE(rpc_format_monetary_values)
{
}

static Value ValueFromString(const std::string &str)
{
    Value value;
    BOOST_CHECK(read_string(str, value));
    return value;
}

BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)
{
}

BOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)
{
    // Check IPv4 addresses
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("1.2.3.4")).ToString(), "1.2.3.4");
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("127.0.0.1")).ToString(), "127.0.0.1");
    // Check IPv6 addresses
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::1")).ToString(), "::1");
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("123:4567:89ab:cdef:123:4567:89ab:cdef")).ToString(),
                                         "123:4567:89ab:cdef:123:4567:89ab:cdef");
    // v4 compatible must be interpreted as IPv4
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::0:127.0.0.1")).ToString(), "127.0.0.1");
    // v4 mapped must be interpreted as IPv4
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::ffff:127.0.0.1")).ToString(), "127.0.0.1");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ConneXdev/tester

max_issues_repo_name: ConneXdev/tester

max_forks_repo_name: ConneXdev/tester


text:
// Copyright (c) 2014-2016 The Bitcoin Core developers
// Original code was distributed under the MIT software license.
// Copyright (c) 2014-2017 Coin Sciences Ltd
// MultiChain code distributed under the GPLv3 license, see COPYING file.

#include "structs/base58.h"
#include "rpc/rpcserver.h"
#include "core/init.h"
#include "core/main.h"
#include "script/script.h"
#include "script/standard.h"
#include "utils/sync.h"
#include "utils/util.h"
#include "utils/utiltime.h"
#include "wallet/wallet.h"
/* MCHN START */
#include "wallet/wallettxs.h"
#include "rpc/rpcutils.h"
/* MCHN END */

#include <fstream>
#include <stdint.h>

#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "json/json_spirit_value.h"

using namespace json_spirit;
using namespace std;

void EnsureWalletIsUnlocked();
/* MCHN START */
vector<string> ParseStringList(Value param);
char * __US_FullPath(const char* path, char *full_path, int len);
/* MCHN END */

std::string static EncodeDumpTime(int64_t nTime) {
    return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}

int64_t static DecodeDumpTime(const std::string &str) {
    static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
    static const std::locale loc(std::locale::classic(),
        new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
    std::istringstream iss(str);
    iss.imbue(loc);
    boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
    iss >> ptime;
    if (ptime.is_not_a_date_time())
        return 0;
    return (ptime - epoch).total_seconds();
}

std::string static EncodeDumpString(const std::string &str) {
    std::stringstream ret;
    BOOST_FOREACH(unsigned char c, str) {
        if (c <= 32 || c >= 128 || c == '%') {
            ret << '%' << HexStr(&c, &c + 1);
        } else {
            ret << c;
        }
    }
    return ret.str();
}

std::string DecodeDumpString(const std::string &str) {
    std::stringstream ret;
    for (unsigned int pos = 0; pos < str.length(); pos++) {
        unsigned char c = str[pos];
        if (c == '%' && pos+2 < str.length()) {
            c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
                ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
            pos += 2;
        }
        ret << c;
    }
    return ret.str();
}

Value importprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 3)
        throw runtime_error("Help message not found\n");

    EnsureWalletIsUnlocked();

    string strLabel = "";
    if (params.size() > 1)
        strLabel = params[1].get_str();

    // Whether to perform rescan after import
    bool fRescan = true;
    int start_block=0;
    if (params.size() > 2)
    {
        start_block=ParseRescanParameter(params[2],&fRescan);
    }

    bool fNewFound=false;
    vector<string> inputStrings=ParseStringList(params[0]);
    vector<CKey> inputKeys;
    vector<CPubKey> inputPubKeys;
    vector<CKeyID> inputKeyIDs;

    for(int is=0;is<(int)inputStrings.size();is++)
    {
        string strSecret=inputStrings[is];

        CBitcoinSecret vchSecret;
        bool fGood = vchSecret.SetString(strSecret);

        if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");

        CKey key = vchSecret.GetKey();
        if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");

        CPubKey pubkey = key.GetPubKey();
        assert(key.VerifyPubKey(pubkey));
        CKeyID vchAddress = pubkey.GetID();

        inputKeys.push_back(key);
        inputPubKeys.push_back(pubkey);
        inputKeyIDs.push_back(vchAddress);

        if (!pwalletMain->HaveKey(vchAddress))
        {
            fNewFound=true;
        }
    }

    if(!fNewFound)
    {
        return Value::null;
    }

    pwalletMain->MarkDirty();

    for(int is=0;is<(int)inputStrings.size();is++)
    {
        CKey key = inputKeys[is];
        CPubKey pubkey = inputPubKeys[is];
        CKeyID vchAddress = inputKeyIDs[is];

        pwalletMain->SetAddressBook(vchAddress, strLabel, "receive");

        // Don't throw error in case a key is already there
        if (!pwalletMain->HaveKey(vchAddress))
        {
            pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;

            if (!pwalletMain->AddKeyPubKey(key, pubkey))
                throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");

            // whenever a key is imported, we need to scan the whole chain
            pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'

            if(mc_gState->m_WalletMode & MC_WMD_ADDRESS_TXS)
            {
                mc_TxEntity entity;
                const CKeyID& KeyID=pubkey.GetID();

                memcpy(entity.m_EntityID,&KeyID,MC_TDB_ENTITY_ID_SIZE);
                entity.m_EntityType=MC_TET_PUBKEY_ADDRESS | MC_TET_CHAINPOS;
                pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
                entity.m_EntityType=MC_TET_PUBKEY_ADDRESS | MC_TET_TIMERECEIVED;
                pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
            }
        }
    }

    if (fRescan) {
        pwalletMain->ScanForWalletTransactions(chainActive[start_block], true, true);
    }

    return Value::null;
}

Value importaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 3)
        throw runtime_error("Help message not found\n");

    CScript script;

    string strLabel = "";
    if (params.size() > 1)
        strLabel = params[1].get_str();

    // Whether to perform rescan after import
    bool fRescan = true;
    int start_block=0;
    if (params.size() > 2)
    {
        start_block=ParseRescanParameter(params[2],&fRescan);
    }

    bool fNewFound=false;
    vector<string> inputStrings=ParseStringList(params[0]);
    vector<CBitcoinAddress> inputAddresses;
    vector<CScript> inputScripts;

    for(int is=0;is<(int)inputStrings.size();is++)
    {
        string param=inputStrings[is];

        CBitcoinAddress address(param);
        if (address.IsValid()) {
            script = GetScriptForDestination(address.Get());
        } else if (IsHex(param)) {
            std::vector<unsigned char> data(ParseHex(param));
            script = CScript(data.begin(), data.end());
        } else {
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid MultiChain address or script");
        }

        inputAddresses.push_back(address);
        inputScripts.push_back(script);

        if( (mc_gState->m_WalletMode & MC_WMD_ADDRESS_TXS) == 0 )
        {
            if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE)
            {
    //            throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
                return Value::null;
            }
        }

        if (!pwalletMain->HaveWatchOnly(script))
        {
            fNewFound=true;
        }
    }

    if( (mc_gState->m_WalletMode & MC_WMD_ADDRESS_TXS) == 0 )
    {
        if(!fNewFound)
        {
            return Value::null;
        }
    }

    pwalletMain->MarkDirty();

    for(int is=0;is<(int)inputStrings.size();is++)
    {
        CBitcoinAddress address=inputAddresses[is];
        script=inputScripts[is];

        // add to address book or update label
        if (address.IsValid())
        {
            pwalletMain->SetAddressBook(address.Get(), strLabel, "receive");
        }
        else
        {
            CScriptID innerID(script);
            address=CBitcoinAddress(innerID);
        }

        // Don't throw error in case an address is already there
        if (!pwalletMain->HaveWatchOnly(script))
        {
            if (!pwalletMain->AddWatchOnly(script))
                throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");

            if(mc_gState->m_WalletMode & MC_WMD_ADDRESS_TXS)
            {
                mc_TxEntity entity;
                CTxDestination addressRet=address.Get();
                const CKeyID *lpKeyID=boost::get<CKeyID> (&addressRet);
                const CScriptID *lpScriptID=boost::get<CScriptID> (&addressRet);

                if(lpKeyID)
                {
                    memcpy(entity.m_EntityID,lpKeyID,MC_TDB_ENTITY_ID_SIZE);
                    entity.m_EntityType=MC_TET_PUBKEY_ADDRESS | MC_TET_CHAINPOS;
                    pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
                    entity.m_EntityType=MC_TET_PUBKEY_ADDRESS | MC_TET_TIMERECEIVED;
                    pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
                }
                if(lpScriptID)
                {
                    memcpy(entity.m_EntityID,lpScriptID,MC_TDB_ENTITY_ID_SIZE);
                    entity.m_EntityType=MC_TET_SCRIPT_ADDRESS | MC_TET_CHAINPOS;
                    pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
                    entity.m_EntityType=MC_TET_SCRIPT_ADDRESS | MC_TET_TIMERECEIVED;
                    pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
                }
            }
        }
    }

    {
        if (fRescan)
        {
            pwalletMain->ScanForWalletTransactions(chainActive[start_block], true, true);
            pwalletMain->ReacceptWalletTransactions();
        }
    }

    return Value::null;
}

Value importwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error("Help message not found\n");

    EnsureWalletIsUnlocked();

    bool fRescan = true;
    int start_block=0;
    if (params.size() > 1)
    {
        start_block=ParseRescanParameter(params[1],&fRescan);
    }

    ifstream file;
    file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate);
    if (!file.is_open())
        throw JSONRPCError(RPC_GENERAL_FILE_ERROR, "Cannot open wallet dump file");

    int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();

    bool fGood = true;

    int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
    file.seekg(0, file.beg);

    pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
    while (file.good()) {
        pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
        std::string line;
        std::getline(file, line);
        if (line.empty() || line[0] == '#')
            continue;

        std::vector<std::string> vstr;
        boost::split(vstr, line, boost::is_any_of(" "));
        if (vstr.size() < 2)
            continue;
        CBitcoinSecret vchSecret;
        if (!vchSecret.SetString(vstr[0]))
            continue;
        CKey key = vchSecret.GetKey();
        CPubKey pubkey = key.GetPubKey();
        assert(key.VerifyPubKey(pubkey));
        CKeyID keyid = pubkey.GetID();
        bool fAlreadyHave=false;
        if (pwalletMain->HaveKey(keyid)) {
            LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
//                continue;
            fAlreadyHave=true;
        }
        int64_t nTime = DecodeDumpTime(vstr[1]);
        std::string strLabel;
        bool fLabel = true;
        for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
            if (boost::algorithm::starts_with(vstr[nStr], "#"))
                break;
            if (vstr[nStr] == "change=1")
                fLabel = false;
            if (vstr[nStr] == "reserve=1")
                fLabel = false;
            if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
                strLabel = DecodeDumpString(vstr[nStr].substr(6));
                fLabel = true;
            }
        }
        LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
        if(!fAlreadyHave)
        {
            if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
                fGood = false;
                continue;
            }
            pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
        }
        if (fLabel)
            pwalletMain->SetAddressBook(keyid, strLabel, "receive");

/* MCHN START */
        if(mc_gState->m_WalletMode & MC_WMD_ADDRESS_TXS)
        {
            mc_TxEntity entity;
            const CKeyID& KeyID=pubkey.GetID();

            memcpy(entity.m_EntityID,&KeyID,MC_TDB_ENTITY_ID_SIZE);
            entity.m_EntityType=MC_TET_PUBKEY_ADDRESS | MC_TET_CHAINPOS;
            pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
            entity.m_EntityType=MC_TET_PUBKEY_ADDRESS | MC_TET_TIMERECEIVED;
            pwalletTxsMain->AddEntity(&entity,MC_EFL_NOT_IN_SYNC);
        }
/* MCHN END */

        nTimeBegin = std::min(nTimeBegin, nTime);
    }
    file.close();
    pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI

    CBlockIndex *pindex = chainActive.Tip();
    while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 12 * Params().TargetSpacing()) // MCHN
        pindex = pindex->pprev;

    if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
        pwalletMain->nTimeFirstKey = nTimeBegin;

/* MCHN START */
    if(mc_gState->m_WalletMode & MC_WMD_ADDRESS_TXS)
    {
        if(start_block)
        {
            LogPrintf("Rescanning last %i blocks\n", chainActive.Height()-start_block+1);
        }
        else
        {
            LogPrintf("Rescanning all %i blocks\n", chainActive.Height());
        }
        pwalletMain->ScanForWalletTransactions(chainActive[start_block],false,true);
        pwalletMain->MarkDirty();
    }
    else
    {
        LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1);
        pwalletMain->ScanForWalletTransactions(pindex,false,true);
        pwalletMain->MarkDirty();
    }

    if (!fGood)
        throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");

    return Value::null;
}

Value dumpprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error("Help message not found\n");

    EnsureWalletIsUnlocked();

    string strAddress = params[0].get_str();
    CBitcoinAddress address;
    if (!address.SetString(strAddress))
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid MultiChain address");
    CKeyID keyID;
    if (!address.GetKeyID(keyID))
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Address does not refer to a key");
    CKey vchSecret;
    if (!pwalletMain->GetKey(keyID, vchSecret))
        throw JSONRPCError(RPC_WALLET_ADDRESS_NOT_FOUND, "Private key for address " + strAddress + " is not known");
    return CBitcoinSecret(vchSecret).ToString();
}

Value dumpwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error("Help message not found\n");

    char bufOutput[MC_DCT_DB_MAX_PATH+1];
    char *full_path=__US_FullPath(params[0].get_str().c_str(),bufOutput,MC_DCT_DB_MAX_PATH+1);

    if(full_path)
    {
        char bufWallet[MC_DCT_DB_MAX_PATH+1];
        mc_GetFullFileName(mc_gState->m_NetworkParams->Name(),"wallet",".dat",MC_FOM_RELATIVE_TO_DATADIR,bufWallet);

        if(strcmp(full_path,bufWallet) == 0)
        {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot dump wallet file to itself");
        }
    }

    EnsureWalletIsUnlocked();

    ofstream file;
    file.open(params[0].get_str().c_str());
    if (!file.is_open())
        throw JSONRPCError(RPC_GENERAL_FILE_ERROR, "Cannot open wallet dump file");

    std::map<CKeyID, int64_t> mapKeyBirth;
    std::set<CKeyID> setKeyPool;
    pwalletMain->GetKeyBirthTimes(mapKeyBirth);
    pwalletMain->GetAllReserveKeys(setKeyPool);

    // sort time/key pairs
    std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
    for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
        vKeyBirth.push_back(std::make_pair(it->second, it->first));
    }
    mapKeyBirth.clear();
    std::sort(vKeyBirth.begin(), vKeyBirth.end());

    // produce output
    file << strprintf("# Wallet dump created by MultiChain %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
    file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
    file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
    file << strprintf("#   mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
    file << "\n";
    for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
        const CKeyID &keyid = it->second;
        std::string strTime = EncodeDumpTime(it->first);
        std::string strAddr = CBitcoinAddress(keyid).ToString();
        CKey key;
        if (pwalletMain->GetKey(keyid, key)) {
            if (pwalletMain->mapAddressBook.count(keyid)) {
                file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr);
            } else if (setKeyPool.count(keyid)) {
                file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
            } else {
                file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
            }
        }
    }
    file << "\n";
    file << "# End of dump\n";
    file.close();
    return Value::null;
}

max_stars_repo_name: VersumDEX/VersumClient

max_issues_repo_name: VersumDEX/VersumClient

max_forks_repo_name: VersumDEX/VersumClient


text:
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "InferenceTestImage.hpp"

#include <boost/core/ignore_unused.hpp>
#include <boost/format.hpp>
#include <boost/core/ignore_unused.hpp>
#include <boost/numeric/conversion/cast.hpp>

#include <array>

#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>

#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb/stb_image_resize.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb/stb_image_write.h>

namespace
{

unsigned int GetImageChannelIndex(ImageChannelLayout channelLayout, ImageChannel channel)
{
    switch (channelLayout)
    {
    case ImageChannelLayout::Rgb:
        return static_cast<unsigned int>(channel);
    case ImageChannelLayout::Bgr:
        return 2u - static_cast<unsigned int>(channel);
    default:
        throw UnknownImageChannelLayout(boost::str(boost::format("Unknown layout %1%")
            % static_cast<int>(channelLayout)));
    }
}

inline float Lerp(float a, float b, float w)
{
    return w * b + (1.f - w) * a;
}

inline void PutData(std::vector<float> & data,
                    const unsigned int width,
                    const unsigned int x,
                    const unsigned int y,
                    const unsigned int c,
                    float value)
{
    data[(3*((y*width)+x)) + c] = value;
}

std::vector<float> ResizeBilinearAndNormalize(const InferenceTestImage & image,
                                              const unsigned int outputWidth,
                                              const unsigned int outputHeight,
                                              const float scale,
                                              const std::array<float, 3>& mean,
                                              const std::array<float, 3>& stddev)
{
    std::vector<float> out;
    out.resize(outputWidth * outputHeight * 3);

    // We follow the definition of TensorFlow and AndroidNN: the top-left corner of a texel in the output
    // image is projected into the input image to figure out the interpolants and weights. Note that this
    // will yield different results than if projecting the centre of output texels.

    const unsigned int inputWidth = image.GetWidth();
    const unsigned int inputHeight = image.GetHeight();

    // How much to scale pixel coordinates in the output image to get the corresponding pixel coordinates
    // in the input image.
    const float scaleY = boost::numeric_cast<float>(inputHeight) / boost::numeric_cast<float>(outputHeight);
    const float scaleX = boost::numeric_cast<float>(inputWidth) / boost::numeric_cast<float>(outputWidth);

    uint8_t rgb_x0y0[3];
    uint8_t rgb_x1y0[3];
    uint8_t rgb_x0y1[3];
    uint8_t rgb_x1y1[3];

    for (unsigned int y = 0; y < outputHeight; ++y)
    {
        // Corresponding real-valued height coordinate in input image.
        const float iy = boost::numeric_cast<float>(y) * scaleY;

        // Discrete height coordinate of top-left texel (in the 2x2 texel area used for interpolation).
        const float fiy = floorf(iy);
        const unsigned int y0 = boost::numeric_cast<unsigned int>(fiy);

        // Interpolation weight (range [0,1])
        const float yw = iy - fiy;

        for (unsigned int x = 0; x < outputWidth; ++x)
        {
            // Real-valued and discrete width coordinates in input image.
            const float ix = boost::numeric_cast<float>(x) * scaleX;
            const float fix = floorf(ix);
            const unsigned int x0 = boost::numeric_cast<unsigned int>(fix);

            // Interpolation weight (range [0,1]).
            const float xw = ix - fix;

            // Discrete width/height coordinates of texels below and to the right of (x0, y0).
            const unsigned int x1 = std::min(x0 + 1, inputWidth - 1u);
            const unsigned int y1 = std::min(y0 + 1, inputHeight - 1u);

            std::tie(rgb_x0y0[0], rgb_x0y0[1], rgb_x0y0[2]) = image.GetPixelAs3Channels(x0, y0);
            std::tie(rgb_x1y0[0], rgb_x1y0[1], rgb_x1y0[2]) = image.GetPixelAs3Channels(x1, y0);
            std::tie(rgb_x0y1[0], rgb_x0y1[1], rgb_x0y1[2]) = image.GetPixelAs3Channels(x0, y1);
            std::tie(rgb_x1y1[0], rgb_x1y1[1], rgb_x1y1[2]) = image.GetPixelAs3Channels(x1, y1);

            for (unsigned c=0; c<3; ++c)
            {
                const float ly0 = Lerp(float(rgb_x0y0[c]), float(rgb_x1y0[c]), xw);
                const float ly1 = Lerp(float(rgb_x0y1[c]), float(rgb_x1y1[c]), xw);
                const float l = Lerp(ly0, ly1, yw);
                PutData(out, outputWidth, x, y, c, ((l / scale) - mean[c]) / stddev[c]);
            }
        }
    }
    return out;
}

} // namespace

InferenceTestImage::InferenceTestImage(char const* filePath)
 : m_Width(0u)
 , m_Height(0u)
 , m_NumChannels(0u)
{
    int width;
    int height;
    int channels;

    using StbImageDataPtr = std::unique_ptr<unsigned char, decltype(&stbi_image_free)>;
    StbImageDataPtr stbData(stbi_load(filePath, &width, &height, &channels, 0), &stbi_image_free);

    if (stbData == nullptr)
    {
        throw InferenceTestImageLoadFailed(boost::str(boost::format("Could not load the image at %1%") % filePath));
    }

    if (width == 0 || height == 0)
    {
        throw InferenceTestImageLoadFailed(boost::str(boost::format("Could not load empty image at %1%") % filePath));
    }

    m_Width = boost::numeric_cast<unsigned int>(width);
    m_Height = boost::numeric_cast<unsigned int>(height);
    m_NumChannels = boost::numeric_cast<unsigned int>(channels);

    const unsigned int sizeInBytes = GetSizeInBytes();
    m_Data.resize(sizeInBytes);
    memcpy(m_Data.data(), stbData.get(), sizeInBytes);
}

std::tuple<uint8_t, uint8_t, uint8_t> InferenceTestImage::GetPixelAs3Channels(unsigned int x, unsigned int y) const
{
    if (x >= m_Width || y >= m_Height)
    {
        throw InferenceTestImageOutOfBoundsAccess(boost::str(boost::format("Attempted out of bounds image access. "
            "Requested (%1%, %2%). Maximum valid coordinates (%3%, %4%).") % x % y % (m_Width - 1) % (m_Height - 1)));
    }

    const unsigned int pixelOffset = x * GetNumChannels() + y * GetWidth() * GetNumChannels();
    const uint8_t* const pixelData = m_Data.data() + pixelOffset;
    BOOST_ASSERT(pixelData <= (m_Data.data() + GetSizeInBytes()));

    std::array<uint8_t, 3> outPixelData;
    outPixelData.fill(0);

    const unsigned int maxChannelsInPixel = std::min(GetNumChannels(), static_cast<unsigned int>(outPixelData.size()));
    for (unsigned int c = 0; c < maxChannelsInPixel; ++c)
    {
        outPixelData[c] = pixelData[c];
    }

    return std::make_tuple(outPixelData[0], outPixelData[1], outPixelData[2]);
}

void InferenceTestImage::StbResize(InferenceTestImage& im, const unsigned int newWidth, const unsigned int newHeight)
{
    std::vector<uint8_t> newData;
    newData.resize(newWidth * newHeight * im.GetNumChannels() * im.GetSingleElementSizeInBytes());

    // boost::numeric_cast<>() is used for user-provided data (protecting about overflows).
    // static_cast<> is ok for internal data (assumes that, when internal data was originally provided by a user,
    // a boost::numeric_cast<>() handled the conversion).
    const int nW = boost::numeric_cast<int>(newWidth);
    const int nH = boost::numeric_cast<int>(newHeight);

    const int w = static_cast<int>(im.GetWidth());
    const int h = static_cast<int>(im.GetHeight());
    const int numChannels = static_cast<int>(im.GetNumChannels());

    const int res = stbir_resize_uint8(im.m_Data.data(), w, h, 0, newData.data(), nW, nH, 0, numChannels);
    if (res == 0)
    {
        throw InferenceTestImageResizeFailed("The resizing operation failed");
    }

    im.m_Data.swap(newData);
    im.m_Width = newWidth;
    im.m_Height = newHeight;
}

std::vector<float> InferenceTestImage::Resize(unsigned int newWidth,
                                              unsigned int newHeight,
                                              const armnn::CheckLocation& location,
                                              const ResizingMethods meth,
                                              const std::array<float, 3>& mean,
                                              const std::array<float, 3>& stddev,
                                              const float scale)
{
    std::vector<float> out;
    if (newWidth == 0 || newHeight == 0)
    {
        throw InferenceTestImageResizeFailed(boost::str(boost::format("None of the dimensions passed to a resize "
            "operation can be zero. Requested width: %1%. Requested height: %2%.") % newWidth % newHeight));
    }

    switch (meth) {
        case ResizingMethods::STB:
        {
            StbResize(*this, newWidth, newHeight);
            break;
        }
        case ResizingMethods::BilinearAndNormalized:
        {
            out = ResizeBilinearAndNormalize(*this, newWidth, newHeight, scale, mean, stddev);
            break;
        }
        default:
            throw InferenceTestImageResizeFailed(boost::str(
                boost::format("Unknown resizing method asked ArmNN only supports {STB, BilinearAndNormalized} %1%")
                              % location.AsString()));
    }
    return out;
}

void InferenceTestImage::Write(WriteFormat format, const char* filePath) const
{
    const int w = static_cast<int>(GetWidth());
    const int h = static_cast<int>(GetHeight());
    const int numChannels = static_cast<int>(GetNumChannels());
    int res = 0;

    switch (format)
    {
    case WriteFormat::Png:
        {
            res = stbi_write_png(filePath, w, h, numChannels, m_Data.data(), 0);
            break;
        }
    case WriteFormat::Bmp:
        {
            res = stbi_write_bmp(filePath, w, h, numChannels, m_Data.data());
            break;
        }
    case WriteFormat::Tga:
        {
            res = stbi_write_tga(filePath, w, h, numChannels, m_Data.data());
            break;
        }
    default:
        throw InferenceTestImageWriteFailed(boost::str(boost::format("Unknown format %1%")
            % static_cast<int>(format)));
    }

    if (res == 0)
    {
        throw InferenceTestImageWriteFailed(boost::str(boost::format("An error occurred when writing to file %1%")
            % filePath));
    }
}

template <typename TProcessValueCallable>
std::vector<float> GetImageDataInArmNnLayoutAsFloats(ImageChannelLayout channelLayout,
    const InferenceTestImage& image,
    TProcessValueCallable processValue)
{
    const unsigned int h = image.GetHeight();
    const unsigned int w = image.GetWidth();

    std::vector<float> imageData;
    imageData.resize(h * w * 3);

    for (unsigned int j = 0; j < h; ++j)
    {
        for (unsigned int i = 0; i < w; ++i)
        {
            uint8_t r, g, b;
            std::tie(r, g, b) = image.GetPixelAs3Channels(i, j);

            // ArmNN order: C, H, W
            const unsigned int rDstIndex = GetImageChannelIndex(channelLayout, ImageChannel::R) * h * w + j * w + i;
            const unsigned int gDstIndex = GetImageChannelIndex(channelLayout, ImageChannel::G) * h * w + j * w + i;
            const unsigned int bDstIndex = GetImageChannelIndex(channelLayout, ImageChannel::B) * h * w + j * w + i;

            imageData[rDstIndex] = processValue(ImageChannel::R, float(r));
            imageData[gDstIndex] = processValue(ImageChannel::G, float(g));
            imageData[bDstIndex] = processValue(ImageChannel::B, float(b));
        }
    }

    return imageData;
}

std::vector<float> GetImageDataInArmNnLayoutAsNormalizedFloats(ImageChannelLayout layout,
    const InferenceTestImage& image)
{
    return GetImageDataInArmNnLayoutAsFloats(layout, image,
        [](ImageChannel channel, float value)
        {
            boost::ignore_unused(channel);
            return value / 255.f;
        });
}

std::vector<float> GetImageDataInArmNnLayoutAsFloatsSubtractingMean(ImageChannelLayout layout,
    const InferenceTestImage& image,
    const std::array<float, 3>& mean)
{
    return GetImageDataInArmNnLayoutAsFloats(layout, image,
        [layout, &mean](ImageChannel channel, float value)
        {
            const unsigned int channelIndex = GetImageChannelIndex(layout, channel);
            return value - mean[channelIndex];
        });
}

std::vector<float> GetImageDataAsNormalizedFloats(ImageChannelLayout layout,
                                                  const InferenceTestImage& image)
{
    std::vector<float> imageData;
    const unsigned int h = image.GetHeight();
    const unsigned int w = image.GetWidth();

    const unsigned int rDstIndex = GetImageChannelIndex(layout, ImageChannel::R);
    const unsigned int gDstIndex = GetImageChannelIndex(layout, ImageChannel::G);
    const unsigned int bDstIndex = GetImageChannelIndex(layout, ImageChannel::B);

    imageData.resize(h * w * 3);
    unsigned int offset = 0;

    for (unsigned int j = 0; j < h; ++j)
    {
        for (unsigned int i = 0; i < w; ++i)
        {
            uint8_t r, g, b;
            std::tie(r, g, b) = image.GetPixelAs3Channels(i, j);

            imageData[offset+rDstIndex] = float(r) / 255.0f;
            imageData[offset+gDstIndex] = float(g) / 255.0f;
            imageData[offset+bDstIndex] = float(b) / 255.0f;
            offset += 3;
        }
    }

    return imageData;
}

max_stars_repo_name: VinayKarnam/armnn

max_issues_repo_name: VinayKarnam/armnn

max_forks_repo_name: VinayKarnam/armnn


text:
//  overlapped.hpp  --------------------------------------------------------------//

//  Copyright 2016 Klemens D. Morgenstern

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

#ifndef BOOST_DETAIL_WINAPI_OVERLAPPED_HPP_
#define BOOST_DETAIL_WINAPI_OVERLAPPED_HPP_

#include <boost/detail/winapi/basic_types.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {
struct _OVERLAPPED;
}
#endif

namespace boost {
namespace detail {
namespace winapi {

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union
#endif

typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _OVERLAPPED {
    ULONG_PTR_ Internal;
    ULONG_PTR_ InternalHigh;
    union {
        struct {
            DWORD_ Offset;
            DWORD_ OffsetHigh;
        };
        PVOID_  Pointer;
    };
    HANDLE_    hEvent;
} OVERLAPPED_, *LPOVERLAPPED_;

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

}}}

#endif // BOOST_DETAIL_WINAPI_OVERLAPPED_HPP_


text:
#include "../agg.hpp"
#include <boost/accumulators/statistics/mean.hpp>

ARRAY_AGGREGATE_FNC(amean, tag::mean);
SQL_AGGREGATE_FNC(v_mean, tag::mean);

max_stars_repo_name: tarkmeper/numpgsql

max_issues_repo_name: tarkmeper/numpgsql

max_forks_repo_name: tarkmeper/numpgsql


text:
/*
 [auto_generated]
 boost/numeric/odeint/iterator/const_step_ode_iterator.hpp

 [begin_description]
 Iterator for iterating through the solution of an ODE with constant step size.
 [end_description]

 Copyright 2009-2011 Karsten Ahnert
 Copyright 2009-2011 Mario Mulansky

 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 BOOST_NUMERIC_ODEINT_ITERATOR_CONST_STEP_ODE_ITERATOR_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_ITERATOR_CONST_STEP_ODE_ITERATOR_HPP_INCLUDED

#include <boost/numeric/odeint/util/stepper_traits.hpp>
#include <boost/numeric/odeint/stepper/stepper_categories.hpp>

namespace boost {
namespace numeric {
namespace odeint {

    template< class Stepper , class System ,
              class StepperTag = typename base_tag< typename traits::stepper_category< Stepper >::type >::type >
    class const_step_iterator;

    template< class Stepper , class System >
    const_step_iterator< Stepper , System > make_const_step_iterator_begin(
        Stepper stepper ,
        System system ,
        typename traits::state_type< Stepper >::type &x ,
        typename traits::time_type< Stepper >::type t ,
        typename traits::time_type< Stepper >::type t_end ,
        typename traits::time_type< Stepper >::type dt )
    {
        return const_step_iterator< Stepper , System >( stepper , system , x , t , t_end , dt );
    }

    template< class Stepper , class System >
    const_step_iterator< Stepper , System > make_const_step_iterator_end(
        Stepper stepper ,
        System system ,
        typename traits::state_type< Stepper >::type &x )
    {
        return const_step_iterator< Stepper , System >( stepper , system , x );
    }

    template< class Stepper , class System >
    std::pair< const_step_iterator< Stepper , System > , const_step_iterator< Stepper , System > >
    make_const_step_range(
        Stepper stepper ,
        System system ,
        typename traits::state_type< Stepper >::type &x ,
        typename traits::time_type< Stepper >::type t_start ,
        typename traits::time_type< Stepper >::type t_end ,
        typename traits::time_type< Stepper >::type dt )
    {
        return std::make_pair(
            const_step_iterator< Stepper , System >( stepper , system , x , t_start , t_end , dt ) ,
            const_step_iterator< Stepper , System >( stepper , system , x )
            );
    }

    /**
     * \fn make_const_step_iterator_begin( Stepper stepper , System system , typename Stepper::state_type &x , typename Stepper::time_type t , typename Stepper::time_type t_end , typename Stepper::time_type dt )
     *
     * \brief Factory function for const_step_iterator. Constructs a begin iterator.
     *
     * \param stepper The stepper to use during the iteration.
     * \param system The system function (ODE) to solve.
     * \param x The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
     * \param t The initial time.
     * \param t_end The end time, at which the iteration should stop.
     * \param dt The initial time step.
     * \returns The const step iterator.
     */

    /**
     * \fn make_const_step_iterator_end( Stepper stepper , System system , typename Stepper::state_type &x )
     * \brief Factory function for const_step_iterator. Constructs a end iterator.
     *
     * \param stepper The stepper to use during the iteration.
     * \param system The system function (ODE) to solve.
     * \param x The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
     * \returns The const_step_iterator.
     */

    /**
     * \fn make_const_step_range( Stepper stepper , System system , typename Stepper::state_type &x , typename Stepper::time_type t_start , typename Stepper::time_type t_end , typename Stepper::time_type dt )
     *
     * \brief Factory function to construct a single pass range of const step iterators. A range is here a pair
     * of const_step_iterator.
     *
     * \param stepper The stepper to use during the iteration.
     * \param system The system function (ODE) to solve.
     * \param x The initial state. const_step_iterator store a reference of s and changes its value during the iteration.
     * \param t The initial time.
     * \param t_end The end time, at which the iteration should stop.
     * \param dt The initial time step.
     * \returns The const step range.
     */

} // namespace odeint
} // namespace numeric
} // namespace boost

#include <boost/numeric/odeint/iterator/impl/const_step_iterator_impl.hpp>
#include <boost/numeric/odeint/iterator/impl/const_step_iterator_dense_output_impl.hpp>

#endif // BOOST_NUMERIC_ODEINT_ITERATOR_CONST_STEP_ODE_ITERATOR_HPP_INCLUDED

max_stars_repo_name: MINATILO/packing-generation

max_issues_repo_name: MINATILO/packing-generation

max_forks_repo_name: MINATILO/packing-generation


text:
#pragma once

#include "../common.hpp"

#include <boost/dynamic_bitset.hpp>

#include <numbers>
#include <span>

namespace ugsdr {
	struct Ephemeris {
	protected:
		template <typename T>
		static auto bin2dec(std::span<T> full_span, std::size_t offset, std::size_t length) {
			auto data = std::span(full_span.begin() + static_cast<std::ptrdiff_t>(offset), length);
			auto bit_value = boost::dynamic_bitset(data.size(), 0);
			for (std::size_t i = 0; i < data.size(); ++i)
				bit_value[i] = data[data.size() - i - 1];

			return bit_value.to_ulong();
		}

		template <typename T>
		static auto bin2dec(std::span<T> full_span, std::size_t offset, std::size_t length, std::size_t offset_second, std::size_t length_second) {
			auto first = bin2dec(full_span, offset, length);
			auto second = bin2dec(full_span, offset_second, length_second);

			return (first << length_second) | second;
		}

		template <typename T>
		static double twocomp2dec(std::span<T> full_span, std::size_t offset, std::size_t length) {
			auto raw = bin2dec(full_span, offset, length);
			if (full_span[offset] == static_cast<T>(1))
				return raw - std::pow(2, length);

			return raw;
		}

		template <typename T>
		static double twocomp2dec(std::span<T> full_span, std::size_t offset, std::size_t length, std::size_t offset_second, std::size_t length_second) {
			auto raw = bin2dec(full_span, offset, length, offset_second, length_second);
			if (full_span[offset] == static_cast<T>(1))
				return raw - std::pow(2, length + length_second);

			return raw;
		}

		template <typename T>
		static double signmagndec(std::span<T> full_span, std::size_t offset, std::size_t length) {
			auto raw = bin2dec(full_span, offset, length);
			if (full_span[offset] == static_cast<T>(1))
				return -static_cast<double>(bin2dec(full_span, offset + 1, length - 1));

			return raw;
		}
	};
}

max_stars_repo_name: mfkiwl/ugsdr

max_issues_repo_name: mfkiwl/ugsdr

max_forks_repo_name: mfkiwl/ugsdr


text:
#pragma once

#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
#include <boost/stacktrace.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception/get_error_info.hpp>
#include <boost/exception/enable_error_info.hpp>
#include <boost/exception/exception.hpp>
#include <boost/exception/info.hpp>
#include <boost/current_function.hpp>

#include "utility.h"

typedef boost::error_info<struct StackTraceErrorInfoTag, boost::stacktrace::stacktrace> StackTraceErrorInfo;

template<typename T>
class ExceptionThrower
{
public:
    ExceptionThrower(
        const char* functionName,
        const char* fileName,
        int lineNumber,
        boost::stacktrace::stacktrace && st)
        : oss()
        , functionName(functionName)
        , fileName(fileName)
        , lineNumber(lineNumber)
        , stacktrace(st)
    {}
    ExceptionThrower(const ExceptionThrower&) = delete;
    ExceptionThrower& operator=(const ExceptionThrower&) = delete;
    ~ExceptionThrower()noexcept(false)
    {
        throw boost::enable_error_info(T(this->oss.str()))
            << boost::throw_function(this->functionName)
            << boost::throw_file(this->fileName)
            << boost::throw_line(this->lineNumber)
            << StackTraceErrorInfo(std::move(this->stacktrace));
    }

    template<typename U>
    std::ostream& operator<<(U &&x)
    {
        return this->oss << std::forward<U>(x);
    }

    template<typename U>
    std::ostream& operator<<(const U& x)
    {
        return this->oss << x;
    }

private:
    std::ostringstream oss;
    const char* functionName;
    const char* fileName;
    int lineNumber;
    boost::stacktrace::stacktrace stacktrace;
};

#define AWESOME_THROW(...)             \
::ExceptionThrower<__VA_ARGS__>(    \
    BOOST_CURRENT_FUNCTION,            \
    __FILE__,                                \
    __LINE__,                                \
    ::boost::stacktrace::stacktrace())

class ExceptionHandlerSetter
{
public:
    ExceptionHandlerSetter()noexcept
    {
        std::set_terminate(&terminate);
    }
public:
    [[noreturn]] static void terminate() noexcept
    {
        std::exception_ptr const pException = std::current_exception();
        if(!pException) {
            std::abort();
        }
        try {
            std::rethrow_exception(pException);
        } catch(boost::exception const& e) {
            handleBoostException(e);
        }catch(std::exception const& e) {
            std::cerr << "A unhandling exception occurred.\n";
            std::cerr << e.what() << std::endl;
        }catch(...) {
            std::cerr << "A unhandling exception occurred." << std::endl;
        }
        std::abort();
    }

    static void handleBoostException(boost::exception const& e)
    {
        {
            std::cerr << "terminate called after throwing an instance of '";
            auto const& ti = typeid(e);
            auto demangleName = demangle(ti);
            std::cerr << (demangleName.empty() ? ti.name() : demangleName) << "\n";
        }
        if (char const *const* p = boost::get_error_info<boost::throw_file>(e)) {
            std::cerr << *p << ':';
        }
        if (int const * p = boost::get_error_info<boost::throw_line>(e)) {
            std::cerr << *p << ":";
        }
        if (char const* const* p = boost::get_error_info<boost::throw_function>(e)) {
            std::cerr << *p << ": ";
        }
        if (std::exception const* p = dynamic_cast<std::exception const *>(&e)) {
            std::cerr << p->what();
        }
        std::cerr << "\n";
        if (boost::stacktrace::stacktrace const* p = boost::get_error_info<StackTraceErrorInfo>(e)) {
            std::cerr << "Backtrace:\n";
            std::cerr << *p << "\n";
        }
        std::cerr << std::flush;
    }
};

max_stars_repo_name: tositeru/watagashi

max_issues_repo_name: tositeru/watagashi

max_forks_repo_name: tositeru/watagashi


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * 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 <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>

#include <limits>

#include <boost/thread.hpp>

#include "../../include/moost/thread/xtime_util.hpp"
#include "../../include/moost/timer.h"

using namespace moost;
using namespace moost::thread;

BOOST_AUTO_TEST_SUITE( timer_test )

struct Fixture
{
   Fixture()
   : timer_(48)
   {
   }

   ~Fixture()
   {
   }

   timer timer_;
};

struct FixtureThreshold
{
   FixtureThreshold()
      : timer_(48, 10, 5)
   {
   }

   ~FixtureThreshold()
   {
   }

   timer timer_;
};

BOOST_FIXTURE_TEST_CASE( test_timer_empty, Fixture )
{
  // test preconditions of timer
  BOOST_CHECK_EQUAL(timer_.avg_time(), -1);
  BOOST_CHECK_EQUAL(timer_.min_time(), -1);
  BOOST_CHECK_EQUAL(timer_.max_time(), -1);
  BOOST_CHECK_EQUAL(timer_.count_per_second(), 0);
}

BOOST_FIXTURE_TEST_CASE( test_timer_time, Fixture )
{
  {
    timer::scoped_time lock(timer_);
    boost::thread::sleep(xtime_util::add_ms(xtime_util::now(), 100));
  }
  double time = timer_.avg_time();
  double eps = 0.0000001;
  BOOST_CHECK( fabs(timer_.avg_time() - time) < eps );
  BOOST_CHECK( fabs(timer_.min_time() - time) < eps );
  BOOST_CHECK( fabs(timer_.max_time() - time) < eps );
  //BOOST_CHECK(timer_.count_per_second() > 1);
}

BOOST_FIXTURE_TEST_CASE( test_past_threshold, FixtureThreshold )
{
   std::vector< std::pair<int, boost::posix_time::ptime> > past_thresholds = timer_.past_threshold_times(2);
   BOOST_REQUIRE( past_thresholds.empty() );

   {
      timer::scoped_time lock(timer_);
      boost::thread::sleep(xtime_util::add_ms(xtime_util::now(), 1));
   }

   int longTimeMs = 25;
   {
      timer::scoped_time lock(timer_);
      boost::thread::sleep(xtime_util::add_ms(xtime_util::now(), longTimeMs));
   }

   past_thresholds = timer_.past_threshold_times(2);
   BOOST_REQUIRE( past_thresholds.size() == 1 );
   int tolerance = 1; //ms
   BOOST_CHECK( abs( past_thresholds[0].first - longTimeMs ) < tolerance );
}

BOOST_FIXTURE_TEST_CASE( test_past_threshold_rollover, FixtureThreshold )
{
   {
      timer::scoped_time lock(timer_);
      boost::thread::sleep(xtime_util::add_ms(xtime_util::now(), 1));
   }

   int longTimeMs = 25;
   for ( int i = 0; i < 6; ++i ) // 6 times, but the size of the threshold vector is 5!
   {
      timer::scoped_time lock(timer_);
      boost::thread::sleep(xtime_util::add_ms(xtime_util::now(), longTimeMs+i));
   }

   std::vector< std::pair<int, boost::posix_time::ptime> > past_thresholds = timer_.past_threshold_times(10);
   BOOST_REQUIRE( past_thresholds.size() == 5 ); // the size of the threshold vector is 5!

   boost::posix_time::time_duration dur;
   int totMs;
   int tolerance = 1; //ms

   for ( int i = 0; i < 4; ++i )
   {
      dur = past_thresholds[i].second - past_thresholds[i+1].second;
      totMs = static_cast<int>(dur.total_milliseconds());
      BOOST_CHECK( abs(totMs - (longTimeMs + 5 - i)) < tolerance );
   }

}

/*BOOST_FIXTURE_TEST_CASE( test_timer_rollover, Fixture )
{
  for (int i = 0; i != 49; ++i)
  {
    timer::scoped_time lock(timer_);
    boost::thread::sleep(xtime_util::add_ms(xtime_util::now(), 10));
  }
  int cps = timer_.count_per_second();
  int time = timer_.avg_time();
  BOOST_CHECK_PREDICATE( std::greater_equal<int>(), (time) (8) );
  BOOST_CHECK_PREDICATE( std::less_equal<int>(), (time) (12) );
  BOOST_CHECK_PREDICATE( std::greater<int>(), (timer_.min_time()) (5) );
  BOOST_CHECK_PREDICATE( std::less<int>(), (timer_.max_time()) (15) );
  BOOST_CHECK_PREDICATE( std::greater<int>(), (cps) (95) );
  BOOST_CHECK_PREDICATE( std::less<int>(), (cps) (105) );
}*/

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.

#include "Viewer.h"

//#include <chrono>
#include <thread>

#include <Eigen/LU>

#include <cmath>
#include <cstdio>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <limits>
#include <cassert>

#include <igl/project.h>
//#include <igl/get_seconds.h>
#include <igl/readOBJ.h>
#include <igl/readOFF.h>
#include <igl/adjacency_list.h>
#include <igl/writeOBJ.h>
#include <igl/writeOFF.h>
#include <igl/massmatrix.h>
#include <igl/file_dialog_open.h>
#include <igl/file_dialog_save.h>
#include <igl/quat_mult.h>
#include <igl/axis_angle_to_quat.h>
#include <igl/trackball.h>
#include <igl/two_axis_valuator_fixed_up.h>
#include <igl/snap_to_canonical_view_quat.h>
#include <igl/unproject.h>
#include <igl/serialize.h>
#include <igl/jet.h>

#include <Windows.h>
#include <mmsystem.h>

// Internal global variables used for glfw event handling
//static igl::opengl::glfw::Viewer * __viewer;
static double highdpi = 1;
static double scroll_x = 0;
static double scroll_y = 0;

namespace igl
{
namespace opengl
{
namespace glfw
{

  using namespace Eigen;
  void Viewer::Init(const std::string config)
  {

  }

  IGL_INLINE Viewer::Viewer():
    data_list(1),
    selected_data_index(0),
    next_data_id(1),
	isPicked(false),
	isActive(false)
  {
    data_list.front().id = 0;
    level = 0;
    isDuringLevel = false;
    isWonLevel = false;

    // Temporary variables initialization
   // down = false;
  //  hack_never_moved = true;
    scroll_position = 0.0f;

    // Per face
    data().set_face_based(false);

#ifndef IGL_VIEWER_VIEWER_QUIET
    const std::string usage(R"(igl::opengl::glfw::Viewer usage:
  [drag]  Rotate scene
  A,a     Toggle animation (tight draw loop)
  F,f     Toggle face based
  I,i     Toggle invert normals
  L,l     Toggle wireframe
  O,o     Toggle orthographic/perspective projection
  T,t     Toggle filled faces
  [,]     Toggle between cameras
  1,2     Toggle between models
  ;       Toggle vertex labels
  :       Toggle face labels)"
);
    std::cout<<usage<<std::endl;
#endif
  }

  IGL_INLINE Viewer::~Viewer()
  {
  }

  IGL_INLINE bool Viewer::load_mesh_from_file(
      const std::string & mesh_file_name_string)
  {

    // Create new data slot and set to selected
    if(!(data().F.rows() == 0  && data().V.rows() == 0))
    {
      append_mesh();
    }
    data().clear();

    size_t last_dot = mesh_file_name_string.rfind('.');
    if (last_dot == std::string::npos)
    {
      std::cerr<<"Error: No file extension found in "<<
        mesh_file_name_string<<std::endl;
      return false;
    }

    std::string extension = mesh_file_name_string.substr(last_dot+1);

    if (extension == "off" || extension =="OFF")
    {
      Eigen::MatrixXd V;
      Eigen::MatrixXi F;
      if (!igl::readOFF(mesh_file_name_string, V, F))
        return false;

      data().set_mesh(V,F);
    }
    else if (extension == "obj" || extension =="OBJ")
    {
      Eigen::MatrixXd corner_normals;
      Eigen::MatrixXi fNormIndices;

      Eigen::MatrixXd UV_V;
      Eigen::MatrixXi UV_F;
      Eigen::MatrixXd V;
      Eigen::MatrixXi F;

      if (!(
            igl::readOBJ(
              mesh_file_name_string,
              V, UV_V, corner_normals, F, UV_F, fNormIndices)))
      {
        return false;
      }

      data().set_mesh(V,F);
      if (UV_V.rows() > 0)
      {
          data().set_uv(UV_V, UV_F);
      }

    }
    else
    {
      // unrecognized file type
      printf("Error: %s is not a recognized file type.\n",extension.c_str());
      return false;
    }

    data().compute_normals();
    data().uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
                   Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
                   Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));

    // Alec: why?
    if (data().V_uv.rows() == 0)
    {
      data().grid_texture();
    }

    //for (unsigned int i = 0; i<plugins.size(); ++i)
    //  if (plugins[i]->post_load())
    //    return true;
    return true;
  }

  IGL_INLINE bool Viewer::save_mesh_to_file(
      const std::string & mesh_file_name_string)
  {
    // first try to load it with a plugin
    //for (unsigned int i = 0; i<plugins.size(); ++i)
    //  if (plugins[i]->save(mesh_file_name_string))
    //    return true;

    size_t last_dot = mesh_file_name_string.rfind('.');
    if (last_dot == std::string::npos)
    {
      // No file type determined
      std::cerr<<"Error: No file extension found in "<<
        mesh_file_name_string<<std::endl;
      return false;
    }
    std::string extension = mesh_file_name_string.substr(last_dot+1);
    if (extension == "off" || extension =="OFF")
    {
      return igl::writeOFF(
        mesh_file_name_string,data().V,data().F);
    }
    else if (extension == "obj" || extension =="OBJ")
    {
      Eigen::MatrixXd corner_normals;
      Eigen::MatrixXi fNormIndices;

      Eigen::MatrixXd UV_V;
      Eigen::MatrixXi UV_F;

      return igl::writeOBJ(mesh_file_name_string,
          data().V,
          data().F,
          corner_normals, fNormIndices, UV_V, UV_F);
    }
    else
    {
      // unrecognized file type
      printf("Error: %s is not a recognized file type.\n",extension.c_str());
      return false;
    }
    return true;
  }

  IGL_INLINE bool Viewer::load_scene()
  {
    std::string fname = igl::file_dialog_open();
    if(fname.length() == 0)
      return false;
    return load_scene(fname);
  }

  IGL_INLINE bool Viewer::load_scene(std::string fname)
  {
   // igl::deserialize(core(),"Core",fname.c_str());
    igl::deserialize(data(),"Data",fname.c_str());
    return true;
  }

  IGL_INLINE bool Viewer::save_scene()
  {
    std::string fname = igl::file_dialog_save();
    if (fname.length() == 0)
      return false;
    return save_scene(fname);
  }

  IGL_INLINE bool Viewer::save_scene(std::string fname)
  {
    //igl::serialize(core(),"Core",fname.c_str(),true);
    igl::serialize(data(),"Data",fname.c_str());

    return true;
  }

  IGL_INLINE void Viewer::open_dialog_load_mesh()
  {
    std::string fname = igl::file_dialog_open();

    if (fname.length() == 0)
      return;

    this->load_mesh_from_file(fname.c_str());

  }

  IGL_INLINE void Viewer::open_dialog_save_mesh()
  {
    std::string fname = igl::file_dialog_save();

    if(fname.length() == 0)
      return;

    this->save_mesh_to_file(fname.c_str());
  }

  IGL_INLINE ViewerData& Viewer::data(int mesh_id /*= -1*/)
  {
    assert(!data_list.empty() && "data_list should never be empty");
    int index;
    if (mesh_id == -1)
      index = selected_data_index;
    else
      index = mesh_index(mesh_id);

    assert((index >= 0 && index < data_list.size()) &&
      "selected_data_index or mesh_id should be in bounds");
    return data_list[index];
  }

  IGL_INLINE const ViewerData& Viewer::data(int mesh_id /*= -1*/) const
  {
    assert(!data_list.empty() && "data_list should never be empty");
    int index;
    if (mesh_id == -1)
      index = selected_data_index;
    else
      index = mesh_index(mesh_id);

    assert((index >= 0 && index < data_list.size()) &&
      "selected_data_index or mesh_id should be in bounds");
    return data_list[index];
  }

  IGL_INLINE int Viewer::append_mesh(bool visible /*= true*/)
  {
    assert(data_list.size() >= 1);

    data_list.emplace_back();
    selected_data_index = data_list.size()-1;
    data_list.back().id = next_data_id++;
    //if (visible)
    //    for (int i = 0; i < core_list.size(); i++)
    //        data_list.back().set_visible(true, core_list[i].id);
    //else
    //    data_list.back().is_visible = 0;
    return data_list.back().id;
  }

  IGL_INLINE bool Viewer::erase_mesh(const size_t index)
  {
    assert((index >= 0 && index < data_list.size()) && "index should be in bounds");
    assert(data_list.size() >= 1);
    if(data_list.size() == 1)
    {
      // Cannot remove last mesh
      return false;
    }
    data_list[index].meshgl.free();
    data_list.erase(data_list.begin() + index);
    if(selected_data_index >= index && selected_data_index > 0)
    {
      selected_data_index--;
    }

    return true;
  }

  IGL_INLINE size_t Viewer::mesh_index(const int id) const {
    for (size_t i = 0; i < data_list.size(); ++i)
    {
      if (data_list[i].id == id)
        return i;
    }
    return 0;
  }

  Eigen::Matrix4d Viewer::CalcParentsTrans(int indx)
  {
	  Eigen::Matrix4d prevTrans = Eigen::Matrix4d::Identity();

	  for (int i = indx; parents[i] >= 0; i = parents[i])
	  {
		  //std::cout << "parent matrix:\n" << scn->data_list[scn->parents[i]].MakeTrans() << std::endl;
		  prevTrans = data_list[parents[i]].MakeTransd() * prevTrans;
	  }

	  return prevTrans;
  }

  void Viewer::AddNewShape(int savedIndx) {

      data().show_overlay_depth = true;
      data().point_size = 10;
      data().line_width = 2;
      data().show_lines = false;
      data().show_overlay_depth = 2;
      data().set_visible(true, 1);
      parents.push_back(-1);
      selected_data_index = savedIndx;

  }
  void Viewer::moveObjects() {
      for (int i = 1; i < data_list.size(); i++) {
          ViewerData* currData = &data_list[i];
          currData->MyTranslate(currData->direction, false);
          Eigen::RowVector4d objectPosition = (currData->MakeTransd() * Eigen::Vector4d(0, 0, 0, 1));
          if (objectPosition(2) <= 5 || objectPosition(2) > 40) { //z
              currData->direction << currData->direction(0), currData->direction(1), -currData->direction(2);
          }
          if (objectPosition(0) > 10|| objectPosition(0) < -10) { //x
              currData->direction << -currData->direction(0), currData->direction(1), currData->direction(2);
          }

      }
  }
  void Viewer::start_level() {
      score = 0;

      int numToAdd = 0;
      Vector3d dir;
      switch (level)
      {
      case 0:
          numToAdd = 3;
          dir = Vector3d(-0.02,0, 0.02);
          break;
      case 1:
          numToAdd = 4;
          data_list[0].direction *= 2;
          dir = Vector3d(0.04, 0, -0.04);
          for (int i = 1; i < numToAdd - 1; i++) {
              load_mesh_from_file("C:/AnimationCourseEngine/tutorial/data/cube.obj");
              int currIndex = data_list.size() - 1;
              AddNewShape(currIndex);
              data_list[currIndex].isPrize = false;
              data_list[currIndex].MyTranslate(Eigen::Vector3d(rand() % 5, 0, rand() % 30 + double(i) * 2), false);
              data_list[currIndex].gamePoints = -1;
              data_list[currIndex].tree.init(data_list[currIndex].V, data_list[currIndex].F);
              data_list[currIndex].set_colors(Eigen::RowVector3d(0.6, 0.2, 0.1));
              data_list[currIndex].direction = dir*i;
              dir = -dir;

          }
      }

      ScoreGoal = (numToAdd * 5);
      for (int i = 1; i <= numToAdd; i++) {
          load_mesh_from_file("C:/AnimationCourseEngine/tutorial/data/sphere.obj");
          int currIndex = data_list.size() - 1;
          AddNewShape(currIndex);
          data_list[currIndex].isPrize = true;
          data_list[currIndex].MyTranslate(Eigen::Vector3d(rand()%5,0,rand() % 30 + double(i) * 2), false);
          data_list[currIndex].gamePoints = 5;
          data_list[currIndex].tree.init(data_list[currIndex].V, data_list[currIndex].F);
          data_list[currIndex].direction = dir*i;
          dir = -dir;

          Eigen::MatrixXd C;
          Eigen::VectorXd Z = data_list[currIndex].V.col(2);
          igl::jet(Z, true, C);
          data_list[currIndex].set_colors(C);
      }

      //set to initial positoin
      data_list[0].MyTranslate((data_list[0].MakeTransd().inverse() * Vector4d(0, 0, 0, 1)).head(3), false);
      data_list[0].MyRotate(data_list[0].GetRotation().inverse());
      time(&level_start_time);
      PlaySound(TEXT("C:/AnimationCourseEngine/sounds/GameSound.wav"), NULL, SND_FILENAME | SND_LOOP | SND_ASYNC);
      isDuringLevel = true;
      isActive = true;

  }

  void Viewer::playBiteSound() {
      PlaySound(TEXT("C:/AnimationCourseEngine/sounds/bite.wav"), NULL, SND_FILENAME);
      PlaySound(TEXT("C:/AnimationCourseEngine/sounds/GameSound.wav"), NULL, SND_FILENAME | SND_LOOP | SND_ASYNC);
  }

  void Viewer::resetScene(bool isWon) {
      int numOfObjects = data_list.size();
      for (int i = numOfObjects - 1; i > 0; i--) {
          std::cout << "inn" << std::endl;
          erase_mesh(i);
      }
      if (isWon) {
         std::cout << " Finish level";
         PlaySound(TEXT("C:/AnimationCourseEngine/sounds/WinLevel.wav"), NULL, SND_FILENAME);
         isDuringLevel = false;
         isWonLevel = true;
         level++;
      }
      else {
          PlaySound(TEXT("C:/AnimationCourseEngine/sounds/GameOver.wav"), NULL, SND_FILENAME);
          std::cout << " YOU LOSE!";
          isDuringLevel = false;
          isWonLevel = false;
      }
  }

} // end namespace
} // end namespace
}


text:
//  Boost cerrno.hpp header  -------------------------------------------------//

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

//  See library home page at http://www.boost.org/libs/system

#ifndef BOOST_CERRNO_HPP_INCLUDED
#define BOOST_CERRNO_HPP_INCLUDED

#include <boost/system/detail/cerrno.hpp>

#endif // #ifndef BOOST_CERRNO_HPP_INCLUDED


text:
/*=============================================================================
    Copyright (c) 2002-2003 Hartmut Kaiser
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
//  Full calculator example
//  [ demonstrating phoenix and subrules ]
//
//  [ Hartmut Kaiser 10/8/2002 ]
//
///////////////////////////////////////////////////////////////////////////////

//#define BOOST_SPIRIT_DEBUG        // define this for debug output

#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <iostream>
#include <string>

///////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace BOOST_SPIRIT_CLASSIC_NS;
using namespace phoenix;

///////////////////////////////////////////////////////////////////////////////
//
//  Our calculator grammar using phoenix to do the semantics and subrule's
//  as it's working horses
//
//  Note:   The top rule propagates the expression result (value) upwards
//          to the calculator grammar self.val closure member which is
//          then visible outside the grammar (i.e. since self.val is the
//          member1 of the closure, it becomes the attribute passed by
//          the calculator to an attached semantic action. See the
//          driver code that uses the calculator below).
//
///////////////////////////////////////////////////////////////////////////////
struct calc_closure : BOOST_SPIRIT_CLASSIC_NS::closure<calc_closure, double>
{
    member1 val;
};

struct calculator : public grammar<calculator, calc_closure::context_t>
{
    template <typename ScannerT>
    struct definition
    {
        definition(calculator const& self)
        {
            top = (
                expression =
                    term[self.val = arg1]
                    >> *(   ('+' >> term[self.val += arg1])
                        |   ('-' >> term[self.val -= arg1])
                        )
                ,

                term =
                    factor[term.val = arg1]
                    >> *(   ('*' >> factor[term.val *= arg1])
                        |   ('/' >> factor[term.val /= arg1])
                        )
                ,

                factor
                    =    ureal_p[factor.val = arg1]
                    |   '(' >> expression[factor.val = arg1] >> ')'
                    |   ('-' >> factor[factor.val = -arg1])
                    |   ('+' >> factor[factor.val = arg1])
            );

            BOOST_SPIRIT_DEBUG_NODE(top);
            BOOST_SPIRIT_DEBUG_NODE(expression);
            BOOST_SPIRIT_DEBUG_NODE(term);
            BOOST_SPIRIT_DEBUG_NODE(factor);
        }

        subrule<0, calc_closure::context_t>  expression;
        subrule<1, calc_closure::context_t>  term;
        subrule<2, calc_closure::context_t>  factor;

        rule<ScannerT> top;

        rule<ScannerT> const&
        start() const { return top; }
    };
};

///////////////////////////////////////////////////////////////////////////////
//
//  Main program
//
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    cout << "/////////////////////////////////////////////////////////\n\n";
    cout << "\t\tExpression parser using Phoenix...\n\n";
    cout << "/////////////////////////////////////////////////////////\n\n";
    cout << "Type an expression...or [q or Q] to quit\n\n";

    calculator calc;    //  Our parser

    string str;
    while (getline(cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        double n = 0;
        parse_info<> info = parse(str.c_str(), calc[var(n) = arg1], space_p);

        //  calc[var(n) = arg1] invokes the calculator and extracts
        //  the result of the computation. See calculator grammar
        //  note above.

        if (info.full)
        {
            cout << "-------------------------\n";
            cout << "Parsing succeeded\n";
            cout << "result = " << n << endl;
            cout << "-------------------------\n";
        }
        else
        {
            cout << "-------------------------\n";
            cout << "Parsing failed\n";
            cout << "stopped at: \": " << info.stop << "\"\n";
            cout << "-------------------------\n";
        }
    }

    cout << "Bye... :-) \n\n";
    return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


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

// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

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

#ifndef BOOST_GEOMETRY_CORE_POINT_ORDER_HPP
#define BOOST_GEOMETRY_CORE_POINT_ORDER_HPP

#include <boost/mpl/assert.hpp>
#include <boost/range.hpp>
#include <boost/type_traits/remove_const.hpp>

#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

namespace boost { namespace geometry
{

/*!
\brief Enumerates options for the order of points within polygons
\ingroup enum
\details The enumeration order_selector describes options for the order of
    points within a polygon. Polygons can be ordered either clockwise or
    counterclockwise. The specific order of a polygon type is defined by the
    point_order metafunction. The point_order metafunction defines a value,
    which is one of the values enumerated in the order_selector

\qbk{
[heading See also]
[link geometry.reference.core.point_order The point_order metafunction]
}
*/
enum order_selector
{
    /// Points are ordered clockwise
    clockwise = 1,
    /// Points are ordered counter clockwise
    counterclockwise = 2,
    /// Points might be stored in any order, algorithms will determine it on the
    /// fly (not yet supported)
    order_undetermined = 0
};

namespace traits
{

/*!
\brief Traits class indicating the order of contained points within a
    ring or (multi)polygon, clockwise, counter clockwise or not known.
\ingroup traits
\tparam Ring ring
*/
template <typename Ring>
struct point_order
{
    static const order_selector value = clockwise;
};

} // namespace traits

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace point_order
{

struct clockwise
{
    static const order_selector value = geometry::clockwise;
};

}} // namespace detail::point_order
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace core_dispatch
{

template <typename Tag, typename Geometry>
struct point_order
{
    BOOST_MPL_ASSERT_MSG
        (
            false, NOT_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE
            , (types<Geometry>)
        );
};

template <typename Point>
struct point_order<point_tag, Point>
    : public detail::point_order::clockwise {};

template <typename Segment>
struct point_order<segment_tag, Segment>
    : public detail::point_order::clockwise {};

template <typename Box>
struct point_order<box_tag, Box>
    : public detail::point_order::clockwise {};

template <typename LineString>
struct point_order<linestring_tag, LineString>
    : public detail::point_order::clockwise {};

template <typename Ring>
struct point_order<ring_tag, Ring>
{
    static const order_selector value
        = geometry::traits::point_order<Ring>::value;
};

// Specialization for polygon: the order is the order of its rings
template <typename Polygon>
struct point_order<polygon_tag, Polygon>
{
    static const order_selector value = core_dispatch::point_order
        <
            ring_tag,
            typename ring_type<polygon_tag, Polygon>::type
        >::value ;
};

} // namespace core_dispatch
#endif // DOXYGEN_NO_DISPATCH

/*!
\brief \brief_meta{value, point order (clockwise\, counterclockwise),
    \meta_geometry_type}
\tparam Geometry \tparam_geometry
\ingroup core

\qbk{[include reference/core/point_order.qbk]}
*/
template <typename Geometry>
struct point_order
{
    static const order_selector value = core_dispatch::point_order
        <
            typename tag<Geometry>::type,
            typename boost::remove_const<Geometry>::type
        >::value;
};

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_CORE_POINT_ORDER_HPP

max_stars_repo_name: bobzabcik/OpenStudio

max_issues_repo_name: bobzabcik/OpenStudio

max_forks_repo_name: bobzabcik/OpenStudio