text:
#include "allovolume/renderer.h"
#include "configparser.h"
#include "allovolume/allosphere_calibration.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <readline/readline.h>

#include <string>
#include <vector>
#include <fstream>

#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <zmq.h>

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

#include "allovolume_protocol.pb.h"

#include "allovolume_common.h"

using namespace std;
using namespace allovolume;

ConfigParser config;
void* zmq_context;

double getPreciseTime() {
    timeval t;
    gettimeofday(&t, 0);
    double s = t.tv_sec;
    s += t.tv_usec / 1000000.0;
    return s;
}

class Controller {
public:
    pthread_t thread;
    void* socket_pubsub;
    void* socket_feedback;
    void* socket_events;
    bool needs_render;
    bool is_rendering;
    double time_render_message;
    double current_fps;

    enum BarrierInfo {
        kRenderPresentBarrier
    };

    // The current state.
    AlloVolumeState state;
    string dataset_name;

    set<string> barrier_clients;
    set<string> all_clients;

    class HDRenderingTask {
    public:
        set<string> waiting;
        Color* pixels;
        int width, height;
        string output_filename;

        HDRenderingTask() {
            pixels = NULL;
        }
        void init(int width_, int height_) {
            width = width_;
            height = height_;
            pixels = new Color[width * height];
        }
        ~HDRenderingTask() {
            if(pixels) delete [] pixels;
        }
    private:
        HDRenderingTask(const HDRenderingTask&) { }
        HDRenderingTask& operator = (const HDRenderingTask&) { return *this; }
    };

    map<string, boost::shared_ptr<HDRenderingTask> > hd_rendering_tasks;
    // set<string> hd_rendering_tasks_waiting;
    // Color* hd_rendering_pixels;
    // int hd_rendering_width, hd_rendering_height;
    // string hd_rendering_output_filename;

    Controller() {
        needs_render = false;
        is_rendering = false;

        register_controller_requests();

        pthread_create(&thread, NULL, thread_process_pthread, this);
    }

    static void* thread_process_pthread(void* this_) {
        ((Controller*)this_)->thread_process();
        return NULL;
    }

    void set_needs_render() {
        if(all_clients.size() == 0) return;
        if(is_rendering) {
            needs_render = true;
        } else {
            is_rendering = true;
            {
                protocol::RendererBroadcast msg;
                msg.set_type(protocol::RendererBroadcast_Type_Render);
                zmq_protobuf_send(msg, socket_pubsub);
                time_render_message = getPreciseTime();
            }
            {
                protocol::RendererBroadcast msg;
                msg.set_type(protocol::RendererBroadcast_Type_Barrier);
                msg.set_barrier_info(kRenderPresentBarrier);
                zmq_protobuf_send(msg, socket_pubsub);
            }
            needs_render = false;
        }
    }

    void process_renderer_feedback(protocol::RendererFeedback& feedback) {
        // Process the feedback message.
        switch(feedback.type()) {
            case protocol::RendererFeedback_Type_Register: {

                all_clients.insert(feedback.client_name());
                printf("Renderer connected: %s\n", feedback.client_name().c_str());

            } break;
            case protocol::RendererFeedback_Type_BarrierReady: {

                barrier_clients.insert(feedback.client_name());
                if(barrier_clients.size() >= all_clients.size()) {
                    barrier_clients.clear();
                    // Barrier cleared.
                    switch(feedback.barrier_info()) {
                        case kRenderPresentBarrier: {
                            current_fps = 1.0 / (getPreciseTime() - time_render_message);
                            // Present!
                            protocol::RendererBroadcast msg;
                            msg.set_type(protocol::RendererBroadcast_Type_Present);
                            zmq_protobuf_send(msg, socket_pubsub);
                            is_rendering = false;
                            if(needs_render) set_needs_render();

                            printf("FPS: %.2lf\n", current_fps);
                        } break;
                    }
                }

            } break;
            case protocol::RendererFeedback_Type_HDRenderingResponse: {

                const protocol::HDRenderingResponse& resp = feedback.hd_rendering_response();

                if(hd_rendering_tasks.find(resp.identifier()) != hd_rendering_tasks.end()) {
                    HDRenderingTask& task = *hd_rendering_tasks[resp.identifier()].get();

                    Color* task_pixels = (Color*)&resp.pixel_data()[0];
                    int vp_x = resp.task_vp_x();
                    int vp_y = resp.task_vp_y();
                    int vp_w = resp.task_vp_w();
                    int vp_h = resp.task_vp_h();
                    for(int y = 0; y < vp_h; y++) {
                        for(int x = 0; x < vp_w; x++) {
                            int px = x + vp_x;
                            int py = y + vp_y;
                            task.pixels[py * task.width + px] = task_pixels[y * vp_w + x];
                        }
                    }

                    task.waiting.erase(resp.task_id());

                    if(task.waiting.empty()) {
                        Image::WriteImageFile(task.output_filename.c_str(), "png16", task.width, task.height, task.pixels);
                        hd_rendering_tasks.erase(resp.identifier());
                        protocol::ParameterChangeEvent event;
                        event.set_sender("controller");
                        event.set_type(protocol::ParameterChangeEvent_Type_HDRenderingComplete);
                        event.set_hd_rendering_filename(task.output_filename);
                        zmq_protobuf_send(event, socket_events);
                    }
                }

            } break;
        }
    }

    void RequestHandler_Render(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        set_needs_render();
    }

    void RequestHandler_LoadVolume(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        dataset_name = request.volume_dataset();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_LoadVolume);
        VolumeBlocks* volume = VolumeBlocks::LoadFromFile(request.volume_filename().c_str());
        size_t length = VolumeBlocks::WriteToBufferSize(volume);
        unsigned char* volume_data = (unsigned char*)malloc(length);
        VolumeBlocks::WriteToBuffer(volume, volume_data, length);
        delete volume;
        msg.set_volume_data(volume_data, length);
        free(volume_data);
        zmq_protobuf_send(msg, socket_pubsub);

        set_needs_render();
    }

    void RequestHandler_LoadVolumeFromFile(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        dataset_name = request.volume_dataset();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_LoadVolumeFromFile);
        msg.set_volume_filename(request.volume_filename());
        zmq_protobuf_send(msg, socket_pubsub);

        set_needs_render();
    }

    void RequestHandler_LoadVolumeFromData(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        dataset_name = request.volume_dataset();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_LoadVolume);
        msg.set_volume_data(request.volume_data());
        zmq_protobuf_send(msg, socket_pubsub);

        set_needs_render();
    }

    void RequestHandler_SetPose(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        state.pose = request.pose();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_SetPose);
        *msg.mutable_pose() = state.pose;
        zmq_protobuf_send(msg, socket_pubsub);

        protocol::ParameterChangeEvent event;
        event.set_sender(request.sender());
        event.set_type(protocol::ParameterChangeEvent_Type_SetPose);
        *event.mutable_pose() = request.pose();
        zmq_protobuf_send(event, socket_events);

        set_needs_render();
    }
    void RequestHandler_GetPose(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        *response.mutable_pose() = state.pose;
    }

    void RequestHandler_SetTransferFunction(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        state.transfer_function = request.transfer_function();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_SetTransferFunction);
        *msg.mutable_transfer_function() = request.transfer_function();
        zmq_protobuf_send(msg, socket_pubsub);

        protocol::ParameterChangeEvent event;
        event.set_sender(request.sender());
        event.set_type(protocol::ParameterChangeEvent_Type_SetTransferFunction);
        *event.mutable_transfer_function() = request.transfer_function();
        zmq_protobuf_send(event, socket_events);

        set_needs_render();
    }
    void RequestHandler_GetTransferFunction(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        *response.mutable_transfer_function() = state.transfer_function;
    }

    void RequestHandler_SetRGBLevels(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        state.rgb_levels = request.rgb_levels();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_SetRGBLevels);
        *msg.mutable_rgb_levels() = request.rgb_levels();
        zmq_protobuf_send(msg, socket_pubsub);

        protocol::ParameterChangeEvent event;
        event.set_sender(request.sender());
        event.set_type(protocol::ParameterChangeEvent_Type_SetRGBLevels);
        *event.mutable_rgb_levels() = request.rgb_levels();
        zmq_protobuf_send(event, socket_events);

        set_needs_render();
    }
    void RequestHandler_GetRGBLevels(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        *response.mutable_rgb_levels() = state.rgb_levels;
    }

    void RequestHandler_SetRendererParameters(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        state.renderer_parameters = request.renderer_parameters();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_SetRendererParameters);
        *msg.mutable_renderer_parameters() = request.renderer_parameters();
        zmq_protobuf_send(msg, socket_pubsub);

        protocol::ParameterChangeEvent event;
        event.set_sender(request.sender());
        event.set_type(protocol::ParameterChangeEvent_Type_SetRendererParameters);
        *event.mutable_renderer_parameters() = request.renderer_parameters();
        zmq_protobuf_send(event, socket_events);

        set_needs_render();
    }
    void RequestHandler_GetRendererParameters(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        *response.mutable_renderer_parameters() = state.renderer_parameters;
    }

    void RequestHandler_SetLensParameters(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        state.lens_parameters = request.lens_parameters();

        protocol::RendererBroadcast msg;
        msg.set_type(protocol::RendererBroadcast_Type_SetLensParameters);
        *msg.mutable_lens_parameters() = request.lens_parameters();
        zmq_protobuf_send(msg, socket_pubsub);

        protocol::ParameterChangeEvent event;
        event.set_sender(request.sender());
        event.set_type(protocol::ParameterChangeEvent_Type_SetLensParameters);
        *event.mutable_lens_parameters() = request.lens_parameters();
        zmq_protobuf_send(event, socket_events);

        set_needs_render();
    }
    void RequestHandler_GetLensParameters(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        *response.mutable_lens_parameters() = state.lens_parameters;
    }

    void RequestHandler_SavePreset(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        protocol::ParameterPreset preset;

        preset.set_dataset(dataset_name);
        preset.set_timestamp(getPreciseTime() * 1000);
        preset.set_name(request.preset_name());
        preset.set_description(request.preset_description());

        *preset.mutable_transfer_function() = state.transfer_function;
        *preset.mutable_pose() = state.pose;
        *preset.mutable_rgb_levels() = state.rgb_levels;
        *preset.mutable_renderer_parameters() = state.renderer_parameters;
        *preset.mutable_lens_parameters() = state.lens_parameters;

        std::fstream output((string("presets/") + request.preset_name()).c_str(), std::ios::out | std::ios::binary);
        preset.SerializeToOstream(&output);
    }

    void RequestHandler_LoadPreset(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        protocol::ParameterPreset preset;
        try {
            std::fstream input((string("presets/") + request.preset_name()).c_str(), std::ios::in | std::ios::binary);
            preset.ParseFromIstream(&input);
        } catch(...) {
            response.set_status("E_NOT_FOUND");
            return;
        }
        {
            state.pose = preset.pose();
            protocol::RendererBroadcast msg;
            msg.set_type(protocol::RendererBroadcast_Type_SetPose);
            *msg.mutable_pose() = state.pose;
            zmq_protobuf_send(msg, socket_pubsub);

            protocol::ParameterChangeEvent event;
            event.set_sender(request.sender());
            event.set_type(protocol::ParameterChangeEvent_Type_SetPose);
            *event.mutable_pose() = state.pose;
            zmq_protobuf_send(event, socket_events);
        }
        {
            state.lens_parameters = preset.lens_parameters();
            protocol::RendererBroadcast msg;
            msg.set_type(protocol::RendererBroadcast_Type_SetLensParameters);
            *msg.mutable_lens_parameters() = state.lens_parameters;
            zmq_protobuf_send(msg, socket_pubsub);

            protocol::ParameterChangeEvent event;
            event.set_sender(request.sender());
            event.set_type(protocol::ParameterChangeEvent_Type_SetLensParameters);
            *event.mutable_lens_parameters() = state.lens_parameters;
            zmq_protobuf_send(event, socket_events);
        }
        {
            state.renderer_parameters = preset.renderer_parameters();
            protocol::RendererBroadcast msg;
            msg.set_type(protocol::RendererBroadcast_Type_SetRendererParameters);
            *msg.mutable_renderer_parameters() = state.renderer_parameters;
            zmq_protobuf_send(msg, socket_pubsub);

            protocol::ParameterChangeEvent event;
            event.set_sender(request.sender());
            event.set_type(protocol::ParameterChangeEvent_Type_SetRendererParameters);
            *event.mutable_renderer_parameters() = state.renderer_parameters;
            zmq_protobuf_send(event, socket_events);
        }
        {
            state.transfer_function = preset.transfer_function();
            protocol::RendererBroadcast msg;
            msg.set_type(protocol::RendererBroadcast_Type_SetTransferFunction);
            *msg.mutable_transfer_function() = state.transfer_function;
            zmq_protobuf_send(msg, socket_pubsub);

            protocol::ParameterChangeEvent event;
            event.set_sender(request.sender());
            event.set_type(protocol::ParameterChangeEvent_Type_SetTransferFunction);
            *event.mutable_transfer_function() = state.transfer_function;
            zmq_protobuf_send(event, socket_events);
        }
        {
            state.rgb_levels = preset.rgb_levels();
            protocol::RendererBroadcast msg;
            msg.set_type(protocol::RendererBroadcast_Type_SetRGBLevels);
            *msg.mutable_rgb_levels() = state.rgb_levels;
            zmq_protobuf_send(msg, socket_pubsub);

            protocol::ParameterChangeEvent event;
            event.set_sender(request.sender());
            event.set_type(protocol::ParameterChangeEvent_Type_SetRGBLevels);
            *event.mutable_rgb_levels() = state.rgb_levels;
            zmq_protobuf_send(event, socket_events);
        }

        set_needs_render();
    }

    void RequestHandler_ListPresets(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        boost::filesystem::directory_iterator iter("presets"), iter_end;
        for(; iter != iter_end; ++iter) {
            if(boost::filesystem::is_regular_file(iter->path())) {
                string filename = iter->path().filename().string();
                *response.add_preset_list() = filename;
            }
        }
    }

    void RequestHandler_GetImage(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        FILE* fin = fopen(request.image_filename().c_str(), "rb");
        if(!fin) return;
        fseeko(fin, 0, SEEK_END);
        size_t file_size = ftello(fin);
        fseeko(fin, 0, SEEK_SET);
        unsigned char* data = new unsigned char[file_size];
        fread(data, 1, file_size, fin);
        fclose(fin);
        response.set_binary_data(data, file_size);
        delete [] data;
    }

    void RequestHandler_HDRendering(protocol::ControllerRequest& request, protocol::ControllerResponse& response) {
        const protocol::HDRenderingTask& task = request.hd_rendering_task();
        int block_width = 500;
        int block_height = 500;
        int total_width = task.total_width();
        int total_height = task.total_height();

        static int hd_rendering_index = 0;

        hd_rendering_index++;
        char identifier[64];
        sprintf(identifier, "task.%d", hd_rendering_index);

        hd_rendering_tasks[identifier].reset(new HDRenderingTask());
        HDRenderingTask& task_struct = *hd_rendering_tasks[identifier].get();
        task_struct.init(total_width, total_height);
        task_struct.output_filename = task.output_filename();

        vector<string> slaves(all_clients.begin(), all_clients.end());
        if(slaves.size() == 0) {
            printf("Unable to perform HDRendering: No renderer connected!\n");
            return;
        }
        int choice_index = 0;

        for(int x = 0; x < total_width; x += block_width) {
            for(int y = 0; y < total_height; y += block_height) {
                int width = min(block_width, total_width - x);
                int height = min(block_height, total_height - y);
                char task_id[64];
                sprintf(task_id, "t.%d.%d.%d.%d", x, y, width, height);
                protocol::HDRenderingTask distributed_task = task;
                distributed_task.set_task_vp_x(x);
                distributed_task.set_task_vp_y(y);
                distributed_task.set_task_vp_w(width);
                distributed_task.set_task_vp_h(height);
                distributed_task.set_identifier(identifier);
                distributed_task.set_task_id(task_id);
                distributed_task.set_task_slave(slaves[choice_index]);
                choice_index = (choice_index + 1) % slaves.size();

                task_struct.waiting.insert(task_id);

                protocol::RendererBroadcast msg;
                msg.set_type(protocol::RendererBroadcast_Type_HDRendering);
                *msg.mutable_hd_rendering_task() = distributed_task;
                zmq_protobuf_send(msg, socket_pubsub);
            }
        }
    }

    typedef void (Controller::*controller_handler_t)(protocol::ControllerRequest&, protocol::ControllerResponse&);

    std::map<protocol::ControllerRequest_Type, controller_handler_t> controller_request_handlers;
    void register_controller_requests() {
        controller_request_handlers[protocol::ControllerRequest_Type_Render] = &Controller::RequestHandler_Render;
        controller_request_handlers[protocol::ControllerRequest_Type_LoadVolume] = &Controller::RequestHandler_LoadVolume;
        controller_request_handlers[protocol::ControllerRequest_Type_LoadVolumeFromFile] = &Controller::RequestHandler_LoadVolumeFromFile;
        controller_request_handlers[protocol::ControllerRequest_Type_LoadVolumeFromData] = &Controller::RequestHandler_LoadVolumeFromData;
        controller_request_handlers[protocol::ControllerRequest_Type_SetPose] = &Controller::RequestHandler_SetPose;
        controller_request_handlers[protocol::ControllerRequest_Type_GetPose] = &Controller::RequestHandler_GetPose;
        controller_request_handlers[protocol::ControllerRequest_Type_SetTransferFunction] = &Controller::RequestHandler_SetTransferFunction;
        controller_request_handlers[protocol::ControllerRequest_Type_GetTransferFunction] = &Controller::RequestHandler_GetTransferFunction;
        controller_request_handlers[protocol::ControllerRequest_Type_SetRGBLevels] = &Controller::RequestHandler_SetRGBLevels;
        controller_request_handlers[protocol::ControllerRequest_Type_GetRGBLevels] = &Controller::RequestHandler_GetRGBLevels;
        controller_request_handlers[protocol::ControllerRequest_Type_SetRendererParameters] = &Controller::RequestHandler_SetRendererParameters;
        controller_request_handlers[protocol::ControllerRequest_Type_GetRendererParameters] = &Controller::RequestHandler_GetRendererParameters;
        controller_request_handlers[protocol::ControllerRequest_Type_SetLensParameters] = &Controller::RequestHandler_SetLensParameters;
        controller_request_handlers[protocol::ControllerRequest_Type_GetLensParameters] = &Controller::RequestHandler_GetLensParameters;

        controller_request_handlers[protocol::ControllerRequest_Type_SavePreset] = &Controller::RequestHandler_SavePreset;
        controller_request_handlers[protocol::ControllerRequest_Type_LoadPreset] = &Controller::RequestHandler_LoadPreset;
        controller_request_handlers[protocol::ControllerRequest_Type_ListPresets] = &Controller::RequestHandler_ListPresets;

        controller_request_handlers[protocol::ControllerRequest_Type_HDRendering] = &Controller::RequestHandler_HDRendering;

        controller_request_handlers[protocol::ControllerRequest_Type_GetImage] = &Controller::RequestHandler_GetImage;
    }

    void thread_process() {
        socket_pubsub = zmq_socket(zmq_context, ZMQ_PUB);

        zmq_setsockopt_ez(socket_pubsub, ZMQ_SNDHWM, config.get<int>("sync.zmq.sndhwm", 10000));
        zmq_setsockopt_ez(socket_pubsub, ZMQ_SNDBUF, config.get<int>("sync.zmq.sndbuf", 0));
        zmq_setsockopt_ez(socket_pubsub, ZMQ_RATE, config.get<int>("sync.zmq.rate", 10000000));

        if(zmq_bind(socket_pubsub, config.get<string>("sync.broadcast").c_str()) < 0) {
            fprintf(stderr, "zmq_bind: %s\n", zmq_strerror(zmq_errno()));
            return;
        }

        socket_feedback = zmq_socket(zmq_context, ZMQ_PULL);
        if(zmq_bind(socket_feedback, config.get<string>("sync.feedback").c_str()) < 0) {
            fprintf(stderr, "zmq_bind: %s\n", zmq_strerror(zmq_errno()));
            return;
        }

        void* socket_commands = zmq_socket(zmq_context, ZMQ_REP);
        if(zmq_bind(socket_commands, config.get<string>("allovolume.controller").c_str()) < 0) {
            fprintf(stderr, "zmq_bind: %s\n", zmq_strerror(zmq_errno()));
            return;
        }

        socket_events = zmq_socket(zmq_context, ZMQ_PUB);
        if(zmq_bind(socket_events, config.get<string>("allovolume.events").c_str()) < 0) {
            fprintf(stderr, "zmq_bind: %s\n", zmq_strerror(zmq_errno()));
            return;
        }

        while(1) {
            zmq_pollitem_t items[2];
            items[0].socket = socket_feedback;
            items[0].events = ZMQ_POLLIN;
            items[1].socket = socket_commands;
            items[1].events = ZMQ_POLLIN;
            if(zmq_poll(items, 2, -1) < 0) {
                fprintf(stderr, "zmq_poll: %s\n", zmq_strerror(zmq_errno()));
                break;
            }
            if(items[0].revents & ZMQ_POLLIN) {
                // We got a message from socket_feedback.
                protocol::RendererFeedback feedback;
                zmq_protobuf_recv(feedback, socket_feedback);
                process_renderer_feedback(feedback);
            }
            if(items[1].revents & ZMQ_POLLIN) {
                // We got a message from socket_commands.
                protocol::ControllerRequest request;
                zmq_protobuf_recv(request, socket_commands);
                // printf("%s\n", protocol::ControllerRequest_Type_Name(request.type()).c_str());
                // Send to the handlers.
                protocol::ControllerResponse response;
                std::map<protocol::ControllerRequest_Type, controller_handler_t>::iterator it =
                    controller_request_handlers.find(request.type());
                if(it != controller_request_handlers.end()) {
                    try {
                        response.set_status("success");
                        (this->*(it->second))(request, response);
                    } catch(...) {
                        response.set_status("E_INTERNAL_ERROR");
                    }
                } else {
                    response.set_status("E_NOT_IMPLEMENTED");
                }
                zmq_protobuf_send(response, socket_commands);
            }
        }
    }
};

int main(int argc, char* argv[]) {
    zmq_context = zmq_ctx_new();
    config.parseFile("allovolume.yaml");
    char hostname[256];
    gethostname(hostname, 256);
    config.parseFile("allovolume.yaml", hostname);
    config.parseFile("allovolume.yaml", "controller");
    Controller controller;

    void* socket_cmdline = zmq_socket(zmq_context, ZMQ_REQ);
    if(zmq_connect(socket_cmdline, config.get<string>("allovolume.controller").c_str()) < 0) {
        fprintf(stderr, "zmq_connect: %s\n", zmq_strerror(zmq_errno()));
        return -1;
    }

    Pose pose;

    while(1) {
        char* input_ = readline("allovolume.controller $ ");
        if(!input_) break;
        string input(input_);
        free(input_);
        vector<string> args;
        boost::split(args, input, boost::is_any_of("\t "), boost::token_compress_on);
        if(args.size() == 0) continue;
        boost::to_lower(args[0]);

        if(args[0] == "volume" && args.size() == 2) {

            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_LoadVolume);
            req.set_volume_filename(args[1]);
            zmq_protobuf_send(req, socket_cmdline);

        } else
        if(args[0] == "volume-file" && args.size() == 2) {

            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_LoadVolumeFromFile);
            req.set_volume_filename(args[1]);
            zmq_protobuf_send(req, socket_cmdline);

        } else
        if(args[0] == "pos" && args.size() == 4) {

            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_SetPose);
            pose.position.x = ::atof(args[1].c_str());
            pose.position.y = ::atof(args[2].c_str());
            pose.position.z = ::atof(args[3].c_str());
            req.mutable_pose()->set_x(pose.position.x);
            req.mutable_pose()->set_y(pose.position.y);
            req.mutable_pose()->set_z(pose.position.z);
            req.mutable_pose()->set_qw(pose.rotation.w);
            req.mutable_pose()->set_qx(pose.rotation.v.x);
            req.mutable_pose()->set_qy(pose.rotation.v.y);
            req.mutable_pose()->set_qz(pose.rotation.v.z);
            zmq_protobuf_send(req, socket_cmdline);

        } else
        if(args[0] == "rot" && args.size() == 5) {

            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_SetPose);
            pose.rotation = Quaternion::Rotation(
                Vector(::atof(args[1].c_str()), ::atof(args[2].c_str()), ::atof(args[3].c_str())),
                ::atof(args[4].c_str()) / 180.0 * PI
            );
            req.mutable_pose()->set_x(pose.position.x);
            req.mutable_pose()->set_y(pose.position.y);
            req.mutable_pose()->set_z(pose.position.z);
            req.mutable_pose()->set_qw(pose.rotation.w);
            req.mutable_pose()->set_qx(pose.rotation.v.x);
            req.mutable_pose()->set_qy(pose.rotation.v.y);
            req.mutable_pose()->set_qz(pose.rotation.v.z);
            zmq_protobuf_send(req, socket_cmdline);

        } else if(args[0] == "lookat" && args.size() == 5) {
            Vector eye = Vector(::atof(args[1].c_str()), ::atof(args[2].c_str()), ::atof(args[3].c_str()));

            pose.position = eye;
            pose.rotation = Quaternion::Rotation(-pose.position.normalize().cross(Vector(1, 0, 0)), -acos(-pose.position.normalize().dot(Vector(1, 0, 0))));

            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_SetPose);

            req.mutable_pose()->set_x(pose.position.x);
            req.mutable_pose()->set_y(pose.position.y);
            req.mutable_pose()->set_z(pose.position.z);
            req.mutable_pose()->set_qw(pose.rotation.w);
            req.mutable_pose()->set_qx(pose.rotation.v.x);
            req.mutable_pose()->set_qy(pose.rotation.v.y);
            req.mutable_pose()->set_qz(pose.rotation.v.z);
            zmq_protobuf_send(req, socket_cmdline);

        } else
        if(args[0] == "preset" && args.size() == 2) {
            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_LoadPreset);

            req.set_preset_name(args[1]);

            zmq_protobuf_send(req, socket_cmdline);

        } else
        if(args[0] == "hdrendering") {
            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_HDRendering);

            protocol::HDRenderingTask& task = *req.mutable_hd_rendering_task();

            task.set_lens_type(protocol::HDRenderingTask_LensType_Equirectangular);
            task.set_total_width(2000);
            task.set_total_height(1000);

            task.mutable_lens_parameters()->set_eye_separation(0);
            task.mutable_lens_parameters()->set_focal_distance(1);

            task.set_output_filename("aaa.png");

            zmq_protobuf_send(req, socket_cmdline);

        } else
        if(args[0] == "hdrendering-perspective") {
            protocol::ControllerRequest req;
            req.set_type(protocol::ControllerRequest_Type_HDRendering);

            protocol::HDRenderingTask& task = *req.mutable_hd_rendering_task();

            task.set_lens_type(protocol::HDRenderingTask_LensType_Perspective);
            task.set_perspective_fovx(PI / 2.0);
            task.set_total_width(3000);
            task.set_total_height(2000);

            task.set_output_filename("aaa.png");

            task.mutable_lens_parameters()->set_eye_separation(0);
            task.mutable_lens_parameters()->set_focal_distance(1);

            zmq_protobuf_send(req, socket_cmdline);

        } else
        {
            printf("Unknown command: %s\n", args[0].c_str());
            continue;
        }
        protocol::ControllerResponse response;
        zmq_protobuf_recv(response, socket_cmdline);
        printf("Result: %s\n", response.status().c_str());
    }
}

max_stars_repo_name: donghaoren/AlloVolume

max_issues_repo_name: donghaoren/AlloVolume

max_forks_repo_name: donghaoren/AlloVolume


text:
#ifndef SHRS_HPP
#define SHRS_HPP

// std
#include <string>
#include <vector>
#include <utility>
#include <unordered_map>
#include <unordered_set>

// Eigen
#include <Eigen/Dense>

// PCL
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>

#include <GridPoint.hpp>

namespace fsd {

using Eigen::Vector2d;
using std::vector;
using std::unordered_map;
using std::unordered_set;
using std::begin;
using std::end;
using std::endl;

/**
 * @brief The SHRS class spatial hashing radius search,
 * some data structure
 * for fast radius search in sparse pointcloud.
 * currently implemented only for 2D
 * and only for constant search_radius as
 * the cell_size is search_radius * 2.,
 * and no search circle rasterizing is implemented
 * yet but only getting the 1 - 4 cells which
 * this search circle can intersect
 * @tparam non-virtual dataset interface
 */
template<typename DatasetAdaptor>
class SHRS {
public:
    using key_t = typename DatasetAdaptor::key_t;
    using coords = GridPoint::coordinates;
    using hash_func_t = std::hash<key_t>;
    using cell_t = unordered_set<key_t, hash_func_t>;
    using search_map_t = unordered_map<key_t, cell_t, hash_func_t>;

    /**
      *@brief constructor; if adj_matrix is passed, its calculated
      */
    SHRS(DatasetAdaptor dataset_adaptor, double search_radius_,
         unordered_map<key_t, vector<key_t>> *adj_matrix = nullptr) :
        dataset_adaptor(dataset_adaptor), cell_size(search_radius_ * 2.),
        search_radius(search_radius_),
        search_radius_2(pow(search_radius_, 2.)) {
        // curently only search radius of cell_size
        // implemented
        cell_keys_to_search.reserve(4);
        search_map.max_load_factor(0.5);
        if(adj_matrix) {
            calculate_adj_matrix(*adj_matrix);
        }
    }

    SHRS &set_initial_cell_size(size_t value) {
        initial_cell_size = value;
        return *this;
    }

    /**
     * @brief find_neighbours find
     * all neigbours within set radius
     * @param key key of point
     * @return number of neighbours
     */
    size_t find_neighbours(key_t point_key,
                           vector<key_t> &neighbours) {
        neighbours.reserve(initial_neighbours_size);
        return on_find_neighbours(point_key, [&](key_t key) {
            neighbours.push_back(key);
        });
    }

    /**
     * @brief on_find_neighbours found neigbours
     * with callback to eventually avoid copy
     * @param point_key
     * @param func
     * @return
     */
    size_t on_find_neighbours(key_t point_key,
                              std::function<void(key_t)> func) {
        auto vec_pnt = dataset_adaptor.get_point(point_key);
        auto cell_coords =
                GridPoint::to_coordinates(vec_pnt, cell_size);
        auto cell_key = GridPoint::pack_key(cell_coords);
        if(search_map.find(cell_key) == end(search_map)) {
            // this point doesn't exist in search_map
            return 0;
        }
        size_t neighbours_found = 0;
        get_cell_keys_in_range(vec_pnt, cell_keys_to_search);
        // now search all cells ( maximum 4 cells are searched)
        for(auto cell_key_to_search : cell_keys_to_search) {
            if(search_map.find(cell_key_to_search) == end(search_map)) {
                continue;
            }
            auto &point_keys = search_map.at(cell_key_to_search);
            for(auto other_point_key : point_keys) {
                if(point_key == other_point_key) {
                    continue;
                }
                auto other_point =
                        dataset_adaptor.get_point(other_point_key);
                double distance2 = (vec_pnt - other_point).squaredNorm();
                if(distance2 < search_radius_2) {
                    func(other_point_key);
                    neighbours_found++;
                }
            }
        }
        return neighbours_found;
    }

    /**
     * @brief find_neighbours_vec find neigbours to a point
     * not in dataset
     * @param vec_pnt
     * @param neighbours
     * @return num of neigbours
     */
    size_t find_neighbours_vec(Vector2d const &vec_pnt,
                               vector<key_t> &neighbours) {
        neighbours.reserve(initial_neighbours_size);
        return on_find_neighbours_vec(vec_pnt, [&](key_t key) {
            neighbours.push_back(key);
        });
    }

    /**
     * @brief find_neighbours_vec find neigbours to a point
     * not in dataset
     * @param vec_pnt
     * @param neighbours
     * @return num of neigbours
     */
    size_t on_find_neighbours_vec(Vector2d const &vec_pnt,
                                  std::function<void(key_t)> func) {
        auto cell_coords =
                GridPoint::to_coordinates(vec_pnt, cell_size);
        size_t neighbours_found = 0;
        get_cell_keys_in_range(vec_pnt, cell_keys_to_search);
        // now search all cells ( maximum 4 cells are searched)
        for(auto cell_key_to_search : cell_keys_to_search) {
            if(search_map.find(cell_key_to_search) == end(search_map)) {
                continue;
            }
            auto &point_keys = search_map.at(cell_key_to_search);
            for(auto other_point_key : point_keys) {
                auto other_point =
                        dataset_adaptor.get_point(other_point_key);
                double distance2 = (vec_pnt - other_point).squaredNorm();
                if(distance2 < search_radius_2) {
                    func(other_point_key);
                    neighbours_found++;
                }
            }
        }
        return neighbours_found;
    }

    /**
     * @brief find_nn_vec finds like find_neighbours_vec, but
     * nearest neigbour, which is in search radius
     * @param vec_pnt
     * @param neighbours
     * @return
     */
    size_t find_nn_vec(Vector2d const &vec_pnt,
                       vector<key_t> &neighbours) {
        auto cell_coords =
                GridPoint::to_coordinates(vec_pnt, cell_size);
        size_t neighbours_found = 0;
        neighbours.resize(1);
        double min_distance = std::numeric_limits<double>::infinity();
        get_cell_keys_in_range(vec_pnt, cell_keys_to_search);
        // now search all cells ( maximum 4 cells are searched)
        for(auto cell_key_to_search : cell_keys_to_search) {
            if(search_map.find(cell_key_to_search) == end(search_map)) {
                continue;
            }
            auto &point_keys = search_map.at(cell_key_to_search);
            for(auto other_point_key : point_keys) {
                if(points_index.find(other_point_key) == points_index.end()){
                    continue;
                }
                auto other_point =
                        dataset_adaptor.get_point(other_point_key);
                double distance2 = (vec_pnt - other_point).squaredNorm();
                if(distance2 < search_radius_2) {
                    if(distance2 < min_distance) {
                        min_distance = distance2;
                        neighbours[0] = other_point_key;
                        neighbours_found = 1;
                    }
                }
            }
        }
        if(!neighbours_found) {
            neighbours.clear();
        }
        return neighbours_found;
    }

    /**
      *
      * @brief inserts all points and calaculates adj_matrix
      */
    void calculate_adj_matrix(unordered_map<key_t, vector<key_t>> &adj_matrix) {
        insert_all();
        auto num_points = points_index.size();
        adj_matrix.max_load_factor(0.5);
        adj_matrix.reserve(num_points);
        dataset_adaptor.for_all_keys([&](key_t key) {
            find_neighbours(key, adj_matrix[key]);
        });
    }

    /**
     * @brief insert_point inserts the point in the seach_map,
     * the point is referenced by key, this means in must be first
     * have inserted in the underlying datastructure provided by
     * DatasetAdaptor
     * @param point_key
     * @return true if inserted
     */
    void insert_point(key_t point_key) {
        auto vec_pnt = dataset_adaptor.get_point(point_key);
        auto cell_coords =
                GridPoint::to_coordinates(vec_pnt, cell_size);
        auto cell_key = GridPoint::pack_key(cell_coords);
        if(search_map.find(cell_key) == end(search_map)) {
            auto set_to_insert = cell_t(initial_cell_size);
            set_to_insert.max_load_factor(.5f);
            search_map.emplace(cell_key, set_to_insert);
        }
        search_map.at(cell_key).insert(point_key);
        points_index.insert(point_key);
    }

    /**
     * @brief insert_all inserts all points currently in the
     * dataset
     */
    void insert_all() {
        points_index.reserve(dataset_adaptor.size());
        dataset_adaptor.for_all_keys([&](key_t key) {
            insert_point(key);
        });
    }

    /**
     * @brief delete_point deleted point must be available
     * while deleting, it can be deleted only
     * aftewards from the underlying datastructure provided by
     * DatasetAdaptor
     * @param point_key
     * @return true if deleted
     */
    bool delete_point(key_t point_key) {
        if(!dataset_adaptor.find_point(point_key)) {
            return false;
        }
        auto vec_pnt = dataset_adaptor.get_point(point_key);
        auto cell_key = GridPoint::to_key(vec_pnt, cell_size);
        auto &points = search_map.at(cell_key);
        points.erase(point_key);
        points_index.erase(point_key);
        if(points.empty()) {
            search_map.erase(cell_key);
        }
        return true;
    }

    /**
     * @brief get_cell_keys_in_range gets all cells on which
     * a circle with diameter cell_size and the center vec_pnt
     * lays
     * @param vec_pnt the point which is the center
     * @param OUT keys of these cells
     *
     */
    void get_cell_keys_in_range(Vector2d const &vec_pnt,
                                vector<key_t> &keys) {
        keys.clear();
        auto cell_coords =
                GridPoint::to_coordinates(vec_pnt, cell_size);
        keys.push_back(GridPoint::pack_key(cell_coords));
        // offset of this point from center
        double const half_cell_size = cell_size / 2.;
        double row_d = vec_pnt.x();
        double column_d = vec_pnt.y();
        double row_offset = fmod(row_d, cell_size);
        double column_offset = fmod(column_d, cell_size);
        auto fourth_point = cell_coords;
        if(row_offset < 0) {
            row_offset += cell_size;
        }
        if(column_offset < 0) {
            column_offset += cell_size;
        }
        // to jump from -1 to 1 evtl, as
        // 0 is not used as row and column
        if(row_offset < half_cell_size) {
            if(cell_coords.row == 1) {
                fourth_point.row -= 2;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row - 2,
                                                          cell_coords.column)));
            } else {
                fourth_point.row -= 1;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row - 1,
                                                          cell_coords.column)));
            }
        } else if(row_offset > half_cell_size) {
            if(cell_coords.row == -1) {
                fourth_point.row += 2;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row + 2,
                                                          cell_coords.column)));
            } else {
                fourth_point.row += 1;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row + 1,
                                                          cell_coords.column)));
            }
        }
        if(column_offset < half_cell_size) {
            if(cell_coords.column == 1) {
                fourth_point.column -= 2;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,
                                                          cell_coords.column - 2)));
            } else {
                fourth_point.column -= 1;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,
                                                          cell_coords.column - 1)));
            }
        } else if(column_offset > half_cell_size) {
            if(cell_coords.column == -1) {
                fourth_point.column += 2;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,
                                                          cell_coords.column + 2)));
            } else {
                fourth_point.column += 1;
                keys.push_back(GridPoint::pack_key(coords(cell_coords.row,
                                                          cell_coords.column + 1)));
            }
        }

        if(keys.size() == 3) {
            keys.push_back(GridPoint::pack_key(fourth_point));
        }
    }

    /**
     * @brief get_points_index
     * @return
     */
    cell_t const &get_points_index() const {
        return points_index;
    }

    void set_initial_neighbours_size(size_t value) {
        initial_neighbours_size = value;
    }

    /**
     * @brief clear clears the whole shrs map, but not the
     * undelying data structure
     */
    void clear() {
        points_index.clear();
        search_map.clear();
    }

    void delete_from_index(key_t idx) {
        points_index.erase(idx);
    }

protected:
    /**
     * @brief initial_cell_size initial size to reserve
     * on a new cell when constructing
     */
    size_t initial_cell_size = 7;

    /**
     * @brief initial_neighbours_size initial size to
     * allocate for neigbours
     */
    size_t initial_neighbours_size = 5;

    /**
     * @brief search_map
     */
    search_map_t search_map;

    /**
     * @brief dataset_adaptor
     */
    DatasetAdaptor dataset_adaptor;

    /**
     * @brief cell_size
     */
    double cell_size;

    /**
     * @brief search_radius
     */
    double search_radius;

    /**
     * @brief search_radius_2 squared_search_radius
     */
    double search_radius_2;

    /**
     * @brief cells_to_search cells to search on
     * radius query, memebr to avoid realocation
     */
    vector<key_t> cell_keys_to_search;

    /**
     * @brief points_index which points are saved
     * in the shrs grid
     */
    cell_t points_index;

};

} // end namespace fsd

#endif

ext: hpp


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "validators/protobuf/proto_query_validator.hpp"

#include <gmock/gmock-matchers.h>
#include <boost/optional/optional_io.hpp>
#include "module/shared_model/validators/validators_fixture.hpp"
#include "queries.pb.h"
#include "validators/validation_error_output.hpp"

using testing::HasSubstr;

class ProtoQueryValidatorTest : public ValidatorsTest {
 public:
  shared_model::validation::ProtoQueryValidator validator;
};

/**
 * @given Protobuf query object with unset query
 * @when validate is called
 * @then there is an error returned
 */
TEST_F(ProtoQueryValidatorTest, UnsetQuery) {
  iroha::protocol::Query qry;
  qry.mutable_payload()->mutable_meta()->set_created_time(created_time);
  qry.mutable_payload()->mutable_meta()->set_creator_account_id(account_id);
  qry.mutable_payload()->mutable_meta()->set_query_counter(counter);

  auto error = validator.validate(qry);
  ASSERT_TRUE(error);
  ASSERT_THAT(error->toString(), HasSubstr("undefined"));
}

/**
 * @given well-formed protobuf query object
 * @when validated is called
 * @then validation is passed
 */
TEST_F(ProtoQueryValidatorTest, SetQuery) {
  iroha::protocol::Query qry;
  qry.mutable_payload()->mutable_get_account()->set_account_id(account_id);

  ASSERT_EQ(validator.validate(qry), boost::none);
}

iroha::protocol::Query generateGetAccountAssetTransactionsQuery(
    const std::string &first_tx_hash) {
  iroha::protocol::Query result;
  result.mutable_payload()
      ->mutable_get_account_asset_transactions()
      ->mutable_pagination_meta()
      ->set_first_tx_hash(first_tx_hash);
  return result;
}

iroha::protocol::Query generateGetAccountTransactionsQuery(
    const std::string &first_tx_hash) {
  iroha::protocol::Query result;
  result.mutable_payload()
      ->mutable_get_account_transactions()
      ->mutable_pagination_meta()
      ->set_first_tx_hash(first_tx_hash);
  return result;
}

static std::string valid_tx_hash("123abc");
static std::string invalid_tx_hash("not_hex");

// valid pagination query tests

class ValidProtoPaginationQueryValidatorTest
    : public ProtoQueryValidatorTest,
      public ::testing::WithParamInterface<iroha::protocol::Query> {};

TEST_P(ValidProtoPaginationQueryValidatorTest, ValidPaginationQuery) {
  ASSERT_EQ(validator.validate(GetParam()), boost::none)
      << GetParam().DebugString();
}

INSTANTIATE_TEST_SUITE_P(
    ProtoPaginationQueryTest,
    ValidProtoPaginationQueryValidatorTest,
    ::testing::Values(generateGetAccountAssetTransactionsQuery(valid_tx_hash),
                      generateGetAccountTransactionsQuery(valid_tx_hash)));

// invalid pagination query tests

class InvalidProtoPaginationQueryTest
    : public ProtoQueryValidatorTest,
      public ::testing::WithParamInterface<iroha::protocol::Query> {};

TEST_P(InvalidProtoPaginationQueryTest, InvalidPaginationQuery) {
  ASSERT_TRUE(validator.validate(GetParam())) << GetParam().DebugString();
}

INSTANTIATE_TEST_SUITE_P(
    InvalidProtoPaginationQueryTest,
    InvalidProtoPaginationQueryTest,
    ::testing::Values(generateGetAccountAssetTransactionsQuery(invalid_tx_hash),
                      generateGetAccountTransactionsQuery(invalid_tx_hash)));

ext: cpp

max_stars_repo_name: e-ivkov/iroha

max_issues_repo_name: e-ivkov/iroha

max_forks_repo_name: e-ivkov/iroha


text:
#include <iostream>
#include <boost/any.hpp>

int main() {
  // New in Boost 1.55
  boost::any foo = 42;
  foo.clear();

  std::cout << "Hello world!" << std::endl;
  return 0;
}

max_stars_repo_name: thatrobotguy/cmake-superbuild

max_issues_repo_name: thatrobotguy/cmake-superbuild

max_forks_repo_name: thatrobotguy/cmake-superbuild


text:
//  (C) Copyright Edward Diener 2011
//  Use, modification and distribution are 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).

#include "test_mf_has_mem_fun.hpp"
#include <boost/detail/lightweight_test.hpp>
#include <boost/tti/mf/mf_has_member_function.hpp>

int main()
  {

  using namespace boost::mpl::placeholders;

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                BOOST_TTI_HAS_MEMBER_FUNCTION_GEN(VoidFunction)<_,_>,
                boost::mpl::identity<AType>,
                void
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                FunctionReturningInt<_,_>,
                boost::mpl::identity<AType>,
                int
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                FunctionReturningInt<_,_,_>,
                boost::mpl::identity<AnotherType>,
                double,
                boost::mpl::vector<int>
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                BOOST_TTI_HAS_MEMBER_FUNCTION_GEN(aFunction)<_,_,_>,
                boost::mpl::identity<AnotherType>,
                boost::mpl::identity<AType>,
                boost::mpl::vector<int>
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                AnotherIntFunction<_,_,_>,
                boost::mpl::identity<AnotherType>,
                int,
                boost::mpl::vector<boost::mpl::identity<AType> >
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                BOOST_TTI_HAS_MEMBER_FUNCTION_GEN(sFunction)<_,_,_>,
                boost::mpl::identity<AnotherType>,
                BOOST_TTI_MEMBER_TYPE_GEN(AnIntType)<AType>,
                boost::mpl::vector
                  <
                  int,
                  long,
                  double
                  >
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                boost::mpl::quote4<BOOST_TTI_HAS_MEMBER_FUNCTION_GEN(VoidFunction)>,
                boost::mpl::identity<AType>,
                void
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                boost::mpl::quote4<FunctionReturningInt>,
                boost::mpl::identity<AType>,
                int
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                boost::mpl::quote4<FunctionReturningInt>,
                boost::mpl::identity<AnotherType>,
                double,
                boost::mpl::vector<int>
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                boost::mpl::quote4<BOOST_TTI_HAS_MEMBER_FUNCTION_GEN(aFunction)>,
                boost::mpl::identity<AnotherType>,
                boost::mpl::identity<AType>,
                boost::mpl::vector<int>
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                boost::mpl::quote4<AnotherIntFunction>,
                boost::mpl::identity<AnotherType>,
                int,
                boost::mpl::vector<boost::mpl::identity<AType> >
                >
              ::value
            ));

  BOOST_TEST((boost::tti::mf_has_member_function
                <
                boost::mpl::quote4<BOOST_TTI_HAS_MEMBER_FUNCTION_GEN(sFunction)>,
                boost::mpl::identity<AnotherType>,
                BOOST_TTI_MEMBER_TYPE_GEN(AnIntType)<AType>,
                boost::mpl::vector
                  <
                  int,
                  long,
                  double
                  >
                >
              ::value
            ));

  return boost::report_errors();

  }

max_stars_repo_name: juslee/boost-svn

max_issues_repo_name: juslee/boost-svn

max_forks_repo_name: juslee/boost-svn


text: #include <boost/hana/fwd/none.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

namespace FederationUnitTests
{
    using namespace std;
    using namespace Common;
    using namespace Federation;

    class RoutingTokenTests
    {
    };

    BOOST_FIXTURE_TEST_SUITE(RoutingTokenTestsSuite,RoutingTokenTests)

    BOOST_AUTO_TEST_CASE(TestEmptyTokenConstructor)
    {
        RoutingToken token = RoutingToken();
        VERIFY_IS_TRUE(token.IsEmpty);
        VERIFY_IS_TRUE(!token.IsFull);
        VERIFY_IS_TRUE(token.Version == 0);

        RoutingToken token2 = token;
        VERIFY_IS_TRUE(token2.IsEmpty);
        VERIFY_IS_TRUE(!token2.IsFull);
        VERIFY_IS_TRUE(token2.Version == 0);

    }

    BOOST_AUTO_TEST_CASE(TestVersionIsCorrect)
    {
        RoutingToken token(NodeIdRange::Empty, 1);
        VERIFY_IS_TRUE(token.Version == 1);
        VERIFY_IS_TRUE(!token.IsRecoverySafe(0));
        VERIFY_IS_TRUE(token.IsRecoverySafe(1));

        RoutingToken token1(NodeIdRange::Empty, 3ULL << sizeof(uint) * 8);
        VERIFY_IS_TRUE(!token1.IsMergeSafe(1ULL << sizeof(uint) * 8));
        VERIFY_IS_TRUE(token1.IsMergeSafe((3ULL << sizeof(uint) * 8) - 1));
        token1.IncrementRecoveryVersion();
        VERIFY_IS_TRUE(token1.Version == 4ULL << sizeof(uint) * 8);
    }

    BOOST_AUTO_TEST_CASE(TestRangeArithmeticIsCorrect)
    {
        NodeId middle(LargeInteger(4, 0));
        RoutingToken token(NodeIdRange(NodeId(LargeInteger(3, 3)), NodeId::MaxNodeId), 1);
        VERIFY_IS_TRUE(token.Contains(middle));
        RoutingToken token1(NodeIdRange(NodeId::MinNodeId, NodeId(LargeInteger(3, 2))), 1);
        VERIFY_IS_TRUE(token.IsPredAdjacent(token1));
        VERIFY_IS_TRUE(token1.IsSuccAdjacent(token));
    }

    BOOST_AUTO_TEST_CASE(TestAccept)
    {
        NodeId start1(LargeInteger(0, 7));
        NodeId end1(LargeInteger(1, 1));
        NodeId start2(LargeInteger(9,1));
        NodeId end2(LargeInteger(0,6));
        NodeId start3(LargeInteger(1,2));
        NodeId end3(LargeInteger(3,3));
        RoutingToken token1(NodeIdRange(start1, end1), 1);
        RoutingToken token2(NodeIdRange(start2, end2), 1);
        RoutingToken token3(NodeIdRange(start3, end3), 1);
        RoutingToken token4(NodeIdRange(start1, end1), 0);
        RoutingToken token5(NodeIdRange(start1, start1), 1);

        VERIFY_IS_TRUE(token1.Accept(token2, NodeId(LargeInteger(9,2))));
        VERIFY_IS_TRUE(token1.Range.Begin == start2);
        VERIFY_IS_TRUE(token1.Range.End == end1);
        VERIFY_IS_TRUE(token1.Accept(token3, NodeId(LargeInteger(1,3))));
        VERIFY_IS_TRUE(token1.Range.Begin == start2);
        VERIFY_IS_TRUE(token1.Range.End == end3);
        VERIFY_IS_TRUE(!token2.Accept(token3, NodeId(LargeInteger(2,4))));
        VERIFY_IS_TRUE(!token5.Accept(token3, NodeId(LargeInteger(9,2))));
    }

    BOOST_AUTO_TEST_CASE(AcceptThrow)
    {
        NodeId start1(LargeInteger(0, 7));
        NodeId end1(LargeInteger(1, 1));
        RoutingToken token1(NodeIdRange(start1, end1), 1);
        RoutingToken token2(NodeIdRange(start1, end1), 0);

        Assert::DisableDebugBreakInThisScope disableDebugBreakInThisScope;
        VERIFY_THROWS(token2.Accept(token1, NodeId(LargeInteger(0, 8))), std::system_error); // microsoft::windows_error::assertion_failure
    }

    BOOST_AUTO_TEST_SUITE_END()

//#pragma region Helper Methods
//        const wstring prefix = L"addr_";
//
//        NodeConfig CreateNodeConfig(size_t low)
//        {
//            NodeId id(LargeInteger(0, low));
//            return NodeConfig(prefix + id.ToString(), id);
//        }
//
//        FederationPartnerNodeHeader CreateNodeHeader(size_t low, NodePhase::Enum phase)
//        {
//            NodeId id(LargeInteger(0, low));
//            return FederationPartnerNodeHeader(NodeInstance(id, 0), phase, prefix + id.ToString());
//        }
//
//        PartnerNodeSPtr CreatePtr(size_t low, NodePhase::Enum phase, SiteNodeSPtr siteNode)
//        {
//            return make_shared<PartnerNode>(CreateNodeHeader(low, phase), siteNode);
//        }
//
//        NodeIdRange CreateRange(uint64 low1, uint64 high1, uint64 low2, uint64 high2, bool isFull)
//        {
//            NodeId id1(LargeInteger(low1, high1));
//            NodeId id2(LargeInteger(low2, high2));
//            return NodeIdRange(id1, id2, isFull);
//        }
//#pragma endregion Helper Methods
}

max_stars_repo_name: gridgentoo/ServiceFabricAzure

max_issues_repo_name: gridgentoo/ServiceFabricAzure

max_forks_repo_name: gridgentoo/ServiceFabricAzure


text:
// Copyright Alexander Nasonov 2007-2008
//
// 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 <iostream>
#include <ostream>
#include <string>

#include <boost/scope_exit.hpp>

#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/string.hpp>
#include <boost/test/unit_test.hpp>

using namespace boost::unit_test;

std::string g_str;

template<int Dummy = 0>
struct Holder
{
    static long g_long;
};

template<int Dummy> long Holder<Dummy>::g_long;

void test_non_local()
{
    // ... and one local variable as well:
    int i = 0;

    BOOST_SCOPE_EXIT( (i) )
    {
        BOOST_CHECK(i == 0);
        BOOST_CHECK(Holder<>::g_long == 3);
        BOOST_CHECK(g_str == "try: g_str");
    } BOOST_SCOPE_EXIT_END

    BOOST_SCOPE_EXIT( (&i) )
    {
        BOOST_CHECK(i == 3);
        BOOST_CHECK(Holder<>::g_long == 3);
        BOOST_CHECK(g_str == "try: g_str");
    } BOOST_SCOPE_EXIT_END

    {
        g_str = "";
        Holder<>::g_long = 1;

        BOOST_SCOPE_EXIT( (&i) )
        {
            i = 1;
            g_str = "g_str";
        } BOOST_SCOPE_EXIT_END

        BOOST_SCOPE_EXIT( (&i) )
        {
          try
          {
              i = 2;
              Holder<>::g_long = 2;
              throw 0;
          } catch(...) {}
        } BOOST_SCOPE_EXIT_END

        BOOST_CHECK(i == 0);
        BOOST_CHECK(g_str == "");
        BOOST_CHECK(Holder<>::g_long == 1);
    }

    BOOST_CHECK(Holder<>::g_long == 2);
    BOOST_CHECK(g_str == "g_str");
    BOOST_CHECK(i == 1); // Check that first declared is executed last

    BOOST_SCOPE_EXIT( (&i) )
    {
        BOOST_CHECK(i == 3);
        BOOST_CHECK(Holder<>::g_long == 3);
        BOOST_CHECK(g_str == "try: g_str");
    } BOOST_SCOPE_EXIT_END

    BOOST_SCOPE_EXIT( (i) )
    {
        BOOST_CHECK(i == 1);
        BOOST_CHECK(Holder<>::g_long == 3);
        BOOST_CHECK(g_str == "try: g_str");
    } BOOST_SCOPE_EXIT_END

    try
    {
        BOOST_SCOPE_EXIT( (&i) )
        {
            i = 3;
            g_str = "try: g_str";
        } BOOST_SCOPE_EXIT_END

        BOOST_SCOPE_EXIT( (&i) )
        {
            i = 4;
            Holder<>::g_long = 3;
        } BOOST_SCOPE_EXIT_END

        BOOST_CHECK(i == 1);
        BOOST_CHECK(g_str == "g_str");
        BOOST_CHECK(Holder<>::g_long == 2);

        throw 0;
    }
    catch(int)
    {
        BOOST_CHECK(Holder<>::g_long == 3);
        BOOST_CHECK(g_str == "try: g_str");
        BOOST_CHECK(i == 3); // Check that first declared is executed last
    }
}

bool foo()
{
    return true;
}

void test_types()
{
    bool (*pf)() = 0;
    bool (&rf)() = foo;
    bool results[2] = {};

    {
        BOOST_SCOPE_EXIT( (&results)(&pf)(&rf) )
        {
            results[0] = pf();
            results[1] = rf();
        }
        BOOST_SCOPE_EXIT_END

        pf = &foo;

        BOOST_CHECK(results[0] == false);
        BOOST_CHECK(results[1] == false);
    }

    BOOST_CHECK(results[0] == true);
    BOOST_CHECK(results[1] == true);

    {
        BOOST_SCOPE_EXIT( (&results)(pf) )
        {
            results[0] = !pf();
            results[1] = !pf();
        }
        BOOST_SCOPE_EXIT_END

        pf = 0;

        BOOST_CHECK(results[0] == true);
        BOOST_CHECK(results[1] == true);
    }

    BOOST_CHECK(results[0] == false);
    BOOST_CHECK(results[1] == false);
}

test_suite* init_unit_test_suite( int, char* [] )
{
    framework::master_test_suite().p_name.value = "Unit test for ScopeExit";
    framework::master_test_suite().add( BOOST_TEST_CASE( &test_non_local ));
    framework::master_test_suite().add( BOOST_TEST_CASE( &test_types     ));
    return 0;
}


text:
/* $Id: tree_view_node.hpp 49173 2011-04-10 16:48:33Z mordante $ */
/*
   Copyright (C) 2010 - 2011 by Mark de Wever <koraq@xs4all.nl>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#ifndef GUI_WIDGETS_TREE_VIEW_NODE_HPP_INCLUDED
#define GUI_WIDGETS_TREE_VIEW_NODE_HPP_INCLUDED

#include "gui/auxiliary/window_builder/tree_view.hpp"

#include <boost/ptr_container/ptr_vector.hpp>

namespace gui2 {

class tselectable_;
class ttoggle_button;
class ttree_view;

class ttree_view_node
	: public twidget
{
	friend struct ttree_view_node_implementation;
	friend class ttree_view;

public:

	typedef implementation::tbuilder_tree_view::tnode tnode_definition;
	ttree_view_node(const std::string& id
			, const std::vector<tnode_definition>& node_definitions
			, ttree_view_node* parent_node
			, ttree_view& parent_tree_view
			, const std::map<std::string /* widget id */, string_map>& data);

	~ttree_view_node();

	/**
	 * Adds a child item to the list of child nodes.
	 *
	 * @param id                  The id of the node definition to use for the
	 *                            new node.
	 * @param data                The data to send to the set_members of the
	 *                            widgets. If the member id is not an empty
	 *                            string it is only send to the widget that has
	 *                            the wanted id (if any). If the member id is an
	 *                            empty string, it is send to all members.
	 *                            Having both empty and non-empty id's gives
	 *                            undefined behaviour.
	 * @param index               The item before which to add the new item,
	 *                            0 == begin, -1 == end.
	 */
	ttree_view_node& add_child(const std::string& id
			, const std::map<std::string /* widget id */, string_map>& data
			, const int index = -1);

	/**
	 * Adds a sibbling for a node at the end of the list.
	 *
	 * @param id                  The id of the node definition to use for the
	 *                            new node.
	 * @param data                The data to send to the set_members of the
	 *                            widgets. If the member id is not an empty
	 *                            string it is only send to the widget that has
	 *                            the wanted id (if any). If the member id is an
	 *                            empty string, it is send to all members.
	 *                            Having both empty and non-empty id's gives
	 *                            undefined behaviour.
	 */
	ttree_view_node& add_sibling(const std::string& id
			, const std::map<std::string /* widget id */, string_map>& data)
	{
		assert(!is_root_node());
		return parent_node().add_child(id, data);
	}

	/**
	 * Is this node the root node?
	 *
	 * When the parent tree view is created it adds one special node, the root
	 * node. This node has no parent node and some other special features so
	 * several code paths need to check whether they are the parent node.
	 */
	bool is_root_node() const { return parent_node_ == NULL; }

	/**
	 * The indention level of the node.
	 *
	 * The root node starts at level 0.
	 */
	unsigned get_indention_level() const;

	/** Does the node have children? */
	bool empty() const { return children_.empty(); }

	/** Is the node folded? */
	bool is_folded() const;

#if 0
	enum texpand_mode
	{
		  recursive_restore // recursively restores collapse mode
		, recursive_expand // recursively expands the children
		, not_recursive
	};

	// If recursive all children will be closed recursively causing
	// restore expaning not to expand anything
//		void fold(const bool recursive); // FIXME implement

//		void unfold(const texpand_mode mode); // FIXME implement
#endif

	/**
	 * Inherited from twidget.
	 *
	 * @todo Implement properly.
	 */
	virtual iterator::twalker_* create_walker() { return NULL; }

	/** Inherited from twidget.*/
	twidget* find_at(const tpoint& coordinate, const bool must_be_active);

	/** Inherited from twidget.*/
	const twidget* find_at(
			  const tpoint& coordinate
			, const bool must_be_active) const;

	/** Inherited from twidget.*/
	twidget* find(const std::string& id, const bool must_be_active)
	{
		twidget* result = twidget::find(id, must_be_active);
		return result ? result : grid_.find(id, must_be_active);
	}

	/** Inherited from twidget.*/
	const twidget* find(const std::string& id
			, const bool must_be_active) const
	{
		const twidget* result = twidget::find(id, must_be_active);
		return result ? result : grid_.find(id, must_be_active);
	}

	/**
	 * The "size" of the widget.
	 *
	 * @todo Rename this function, names to close to the size of the widget.
	 */
	size_t size() const { return children_.size(); }

	/**
	 * Removes all child items from the widget.
	 */
	void clear();

	/***** ***** ***** setters / getters for members ***** ****** *****/

	/**
	 * Returns the parent node.
	 *
	 * @pre                       is_root_node() == false.
	 */
	ttree_view_node& parent_node();

	/** The const version of @ref parent_node. */
	const ttree_view_node& parent_node() const;

	ttree_view& tree_view();

	const ttree_view& tree_view() const;

private:

	/** Inherited from twidget. */
	void request_reduce_width(const unsigned /*maximum_width*/) {}

	/**
	 * Our parent node.
	 *
	 * All nodes except the root node have a parent node.
	 */
	ttree_view_node* parent_node_;

	/** The tree view that owns us. */
	ttree_view& tree_view_;

	/** Grid holding our contents. */
	tgrid grid_;

	/**
	 * Our children.
	 *
	 * We want the returned child nodes to remain stable so store pointers.
	 */
	boost::ptr_vector<ttree_view_node> children_;

	/**
	 * The node definitions known to use.
	 *
	 * This list is needed to create new nodes.
	 *
	 * @todo Maybe store this list in the tree_view to avoid copying the
	 * reference.
	 */
	const std::vector<tnode_definition>& node_definitions_;

	/** The icon to show the folded state. */
	ttoggle_button* icon_;

	/** The label to show our selected state. */
	tselectable_* label_;

	/**
	 * "Inherited" from twidget.
	 *
	 * This version needs to call its children, which are it's child nodes.
	 */
	void impl_populate_dirty_list(twindow& caller,
			const std::vector<twidget*>& call_stack);

	tpoint calculate_best_size() const;

	bool disable_click_dismiss() const { return true; }

	tpoint calculate_best_size(const int indention_level
			, const unsigned indention_step_size) const;

	tpoint get_current_size() const;
	tpoint get_folded_size() const;
	tpoint get_unfolded_size() const;

	void set_origin(const tpoint& origin);

	void place(const tpoint& origin, const tpoint& size);

	unsigned place(
			  const unsigned indention_step_size
			, tpoint origin
			, unsigned width);

	void set_visible_area(const SDL_Rect& area);

	void impl_draw_children(surface& frame_buffer);

	// FIXME rename to icon
	void signal_handler_left_button_click(const event::tevent event);

	void signal_handler_label_left_button_click(
			  const event::tevent event
			, bool& handled
			, bool& halt);

	void init_grid(tgrid* grid
			, const std::map<
				std::string /* widget id */, string_map>& data);

	const std::string& get_control_type() const;
};

} // namespace gui2

#endif

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
#ifndef BOOST_METAPARSE_V1_IMPL_FWD_ITERATE_IMPL_HPP
#define BOOST_METAPARSE_V1_IMPL_FWD_ITERATE_IMPL_HPP

// Copyright Abel Sinkovics (abel@sinkovics.hu)  2013.
// 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/metaparse/v1/is_error.hpp>
#include <boost/metaparse/v1/get_result.hpp>
#include <boost/metaparse/v1/get_remaining.hpp>
#include <boost/metaparse/v1/get_position.hpp>

#include <boost/mpl/deque.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/push_back.hpp>

namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      namespace impl
      {
        template <int N, class P, class Accum>
        struct iterate_impl;
      }
    }
  }
}

#endif


text:
#include <catch/catch.hpp>

#include "utils.h"
#include <ibm/IBMEndpoint.h>

#include <faasm/files.h>
#include <scheduler/GlobalMessageBus.h>
#include <rapidjson/pointer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <boost/filesystem.hpp>
#include <util/strings.h>

using namespace Pistache;
using namespace rapidjson;

namespace tests {
    TEST_CASE("Test ibm initialisation", "[ibm]") {
        cleanSystem();

        // Set up config to something that we know will change
        util::SystemConfig &conf = util::getSystemConfig();
        std::string originalStorage = conf.functionStorage;
        std::string originalCGroup = conf.cgroupMode;
        std::string originalNetns = conf.netNsMode;

        conf.functionStorage = "foobar";
        conf.cgroupMode = "blah";
        conf.netNsMode = "blahblah";

        std::string requestStr;
        ibm::IBMEndpoint endpoint;
        endpoint.testMode = true;
        endpoint.doHandleInit(requestStr);

        REQUIRE(conf.functionStorage == "ibm");
        REQUIRE(conf.cgroupMode == "off");
        REQUIRE(conf.netNsMode == "off");

        conf.functionStorage = originalStorage;
        conf.cgroupMode = originalCGroup;
        conf.netNsMode = originalNetns;
    }

    Document createJsonRequest(const std::string &user, const std::string &function, const std::string &mode) {
        Document d;
        d.SetObject();

        Document::AllocatorType &a = d.GetAllocator();
        rapidjson::Value valueObject(rapidjson::kObjectType);
        d.AddMember("value", valueObject, a);

        d["value"].AddMember("user", Value(user.c_str(), user.size(), a).Move(), a);
        d["value"].AddMember("function", Value(function.c_str(), function.size(), a).Move(), a);
        d["value"].AddMember("mode", Value(mode.c_str(), mode.size(), a).Move(), a);

        return d;
    }

    void checkIbmResponse(Document &d, const std::string &expectedText, int expectedStatusCode) {
        // Make sure it's async
        d["value"].AddMember("async", true, d.GetAllocator());

        StringBuffer sb;
        Writer<StringBuffer> writer(sb);
        d.Accept(writer);
        std::string jsonStr = sb.GetString();

        ibm::IBMEndpoint endpoint;
        endpoint.testMode = true;
        const std::string actual = endpoint.doHandleCall(jsonStr);

        Document d2;
        d2.Parse(actual.c_str());
        std::string resultMsg = d2.FindMember("result")->value.GetString();
        int actualStatusCode = d2.FindMember("status_code")->value.GetInt();

        REQUIRE(actualStatusCode == expectedStatusCode);

        if (expectedText == "ASYNCID") {
            // In this case we're expecting an async ID message ID
            if (!util::stringIsInt(resultMsg)) {
                std::string failMsg = "Did not get an int response to async call: " + resultMsg;
                FAIL(failMsg);
            }
        } else {
            REQUIRE(resultMsg == expectedText);
        }
    }

    TEST_CASE("Test invoking", "[ibm]") {
        cleanSystem();

        Document d = createJsonRequest("demo", "echo", INVOKE_MODE);
        std::string expected = "ASYNCID";

        SECTION("No input") {

        }

        SECTION("With input") {
            std::string input = "foobarbaz";
            d["value"].AddMember("input", Value(input.c_str(), input.size(), d.GetAllocator()).Move(),
                                 d.GetAllocator());
        }

        message::Message msg = util::messageFactory("demo", "echo");
        checkIbmResponse(d, expected, 200);

        scheduler::Scheduler &sch = scheduler::getScheduler();
        REQUIRE(sch.getFunctionInFlightCount(msg) == 1);
        REQUIRE(sch.getBindQueue()->size() == 1);
    }

    TEST_CASE("Test invalid invocations", "[ibm]") {
        cleanSystem();

        Document d;
        std::string expected;
        message::Message msg;

        SECTION("No user") {
            msg = util::messageFactory("", "echo");
            d = createJsonRequest("", "echo", INVOKE_MODE);
            expected = "User and function must be present in request";
        }

        SECTION("No function") {
            msg = util::messageFactory("demo", "");
            d = createJsonRequest("demo", "", INVOKE_MODE);
            expected = "User and function must be present in request";
        }

        SECTION("Invalid mode") {
            msg = util::messageFactory("demo", "echo");
            d = createJsonRequest("demo", "echo", "afafaf");
            expected = "Invalid call mode: afafaf";
        }

        checkIbmResponse(d, expected, 200);

        scheduler::Scheduler &sch = scheduler::getScheduler();
        REQUIRE(sch.getFunctionInFlightCount(msg) == 0);
        REQUIRE(sch.getBindQueue()->size() == 0);
    }

    TEST_CASE("Test codegen", "[ibm]") {
        std::string expected = "Codegen successful";

        // Make sure obj file doesn't exist
        const message::Message msg = util::messageFactory("demo", "ibm_test");
        const std::string objFilePath = util::getFunctionObjectFile(msg);
        boost::filesystem::remove(objFilePath);

        // Run the codegen
        Document d = createJsonRequest("demo", "ibm_test", CODEGEN_MODE);
        checkIbmResponse(d, expected, 200);

        // Check file is now there
        REQUIRE(boost::filesystem::exists(objFilePath));

        // Check there's something in it
        REQUIRE(faasm::getFileLength(objFilePath.c_str()) > 0);
    }
}

max_stars_repo_name: jchesterpivotal/Faasm

max_issues_repo_name: TNTtian/Faasm

max_forks_repo_name: TNTtian/Faasm


text:
#include "FastqIterator.hpp"
#include <iostream>
#include <stdexcept>
#include "span.hpp"

using std::runtime_error;
using std::cout;
using std::cerr;

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>

using namespace boost::accumulators;

typedef accumulator_set<float, features<tag::count, tag::mean, tag::variance>> stats_accumulator;

using overlap_analysis::quality_char_to_error_probability;
using overlap_analysis::FastqIterator;
using overlap_analysis::FastqElement;

bool classify_palindromic_q_scores(span<char> qualities){
    bool is_palindromic = false;

    stats_accumulator left_stats;
    stats_accumulator right_stats;

    auto length = qualities.size();

    if (length < 6){
        return is_palindromic;
    }

    size_t midpoint = length/2;

    for (size_t i=0; i<midpoint; i++){
        auto q = qualities[i];
        auto p = quality_char_to_error_probability(q);

        left_stats(p);
    }

    for (size_t i=midpoint; i<length; i++){
        auto q = qualities[i];
        auto p = quality_char_to_error_probability(q);

        right_stats(p);
    }

    float left_mean = mean(left_stats);
    float left_variance = variance(left_stats);

    float right_mean = mean(right_stats);
    float right_variance = variance(right_stats);

//    cout << left_mean << '\t' << left_variance << '\n';
//    cout << right_mean << '\t' << right_variance << '\n';

    if (right_mean - left_mean > 0.09 and right_mean >= 0.15){
        if (right_variance > left_variance and right_variance > 0.025){
            is_palindromic = true;
        }
    }

    return is_palindromic;
}

void split_palindrome_by_quality(FastqElement& element, vector<FastqElement>& result){
    span<char> q_scores(&element.quality_string.front(), &element.quality_string.back());

    bool is_palindromic = classify_palindromic_q_scores(q_scores);

    if (not is_palindromic){
        cout << '@' << element.name << '\n';
        cout << element.sequence << '\n';
        cout << '+' << '\n';
        cout << element.quality_string << '\n';
    }
}

int main(int argc, char **argv){
    if (argc == 1 or argc > 2){
        cerr << "Usage: split_palindromes_by_quality /path/to/file.fastq\n";
        return 1;
    }

    path fastq_path = argv[1];
    FastqIterator iterator(fastq_path);
    FastqElement e;
    vector<FastqElement> result;

    size_t i = 0;
    while (iterator.next_element(e)) {
        if (i % 100 == 0) {
            cerr << "\33[2K\r" << i << std::flush;
        }

        split_palindrome_by_quality(e, result);

        i++;
    }
    cerr << '\n';

    return 0;
}


text:
// test_mb_external_encoding.cc
#include "menon/encoding.hh"
#include <boost/core/lightweight_test.hpp>
#include <iostream>

int main()
{
  // default_encoding_keyのテストコード
  BOOST_TEST(menon::detail::default_encoding_key >= 0);
  BOOST_TEST_CSTR_EQ(menon::mb_external_encoding(), menon::detail::encoding_list[menon::detail::default_encoding_key]);

#if defined(_MSC_VER) || (defined(__MINGW32__) && !defined(__clang__))
  // Windows向けのテストコード
  BOOST_TEST_CSTR_EQ(menon::mb_external_encoding(), "CP932");
  // 外部エンコーディングをEUC-JPに設定
  BOOST_TEST_CSTR_EQ(menon::mb_external_encoding("EUC-JP"), "CP932");
#else
  // Windows以外向けのテストコード
  BOOST_TEST_CSTR_EQ(menon::mb_external_encoding(), "UTF-8");
  // 外部エンコーディングをEUC-JPに設定
  BOOST_TEST_CSTR_EQ(menon::mb_external_encoding("EUC-JP"), "UTF-8");
#endif
  // 外部エンコーディングEUC-JPになっていることを確認
  BOOST_TEST_CSTR_EQ(menon::mb_external_encoding(), "EUC-JP");
  // 不正なエンコーディングを指定した場合のエラー処理
  BOOST_TEST_EQ(menon::mb_external_encoding("xxx"), nullptr);
  return boost::report_errors();
}

ext: cc


text:
// ======================================================================
/*!
 * \file
 * \brief Regression tests for Fmi::AsyncTaskGroup
 */
// ======================================================================

#include "AsyncTaskGroup.h"
#include "Exception.h"
#include "TypeName.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <regression/tframe.h>
#include <atomic>
#include <iostream>
#include <memory>
#include <string>
#include <thread>

using namespace boost::posix_time;

namespace AsyncTaskGroupTest
{
// Verify that there is no corruption when wait() is not called
void not_waiting_for_result()
{
  std::unique_ptr<std::string> test(new std::string);
  std::unique_ptr<Fmi::AsyncTaskGroup> tg(new Fmi::AsyncTaskGroup);
  tg->add("not waiting for result",
          [&]()
          {
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            *test = "foobar";
          });
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
  tg.reset();
  test.reset();
  TEST_PASSED();
}

void empty_group()
{
  Fmi::AsyncTaskGroup tg;
  tg.wait();
  TEST_PASSED();
}

void single_task()
{
  std::atomic<int> test(0);
  Fmi::AsyncTaskGroup tg;
  tg.add("", [&]() { test++; });
  tg.wait();
  if (test != 1)
  {
    TEST_FAILED("Not expected result");
  }
  TEST_PASSED();
}

void several_tasks()
{
  std::atomic<int> test(0);
  Fmi::AsyncTaskGroup tg;
  for (int i = 0; i < 10; i++)
  {
    tg.add("", [&]() { test++; });
  }
  tg.wait();
  if (test != 10)
  {
    TEST_FAILED("Not expected result");
  }
  TEST_PASSED();
}

struct TestException
{
};

void task_throws_not_std_exception()
{
  std::string exception_name;
  std::string task_name;
  Fmi::AsyncTaskGroup tg;
  tg.on_task_error(
      [&](const std::string& name)
      {
        exception_name = Fmi::current_exception_type();
        task_name = name;
      });
  tg.add("foobar", []() { throw TestException(); });
  tg.wait();
  if (exception_name != "AsyncTaskGroupTest::TestException")
  {
    TEST_FAILED("Did not get exception name");
  }
  if (task_name != "foobar")
  {
    TEST_FAILED("Did not get task name");
  }
  TEST_PASSED();
}

void large_number_of_tasks()
{
  bool failed = false;
  std::atomic<int> test(0);
  Fmi::AsyncTaskGroup tg(10);
  for (int i = 0; i < 100; i++)
  {
    tg.add("test",
           [&]()
           {
             std::this_thread::sleep_for(std::chrono::milliseconds(10));
             test++;
           });
  }
  if (not failed and tg.get_num_active_tasks() > 10)
  {
    TEST_FAILED("Too many parallel tasks");
    failed = true;
  }
  tg.wait();
  if (test != 100)
  {
    TEST_FAILED("Not all tasks executed");
  }
  TEST_PASSED();
}

void test_interrupting_1()
{
  std::unique_ptr<Fmi::AsyncTaskGroup> tg(new Fmi::AsyncTaskGroup(10));
  for (int i = 0; i < 5; i++)
  {
    tg->add("test", []() { boost::this_thread::sleep_for(boost::chrono::milliseconds(1000)); });
  }

  const ptime t1 = microsec_clock::universal_time();
  tg->stop();
  tg->wait();
  const ptime t2 = microsec_clock::universal_time();
  tg.reset();
  const ptime t3 = microsec_clock::universal_time();
  // std::cout << '\n' << (t2-t1) << std::endl;
  // std::cout << '\n' << (t3-t1) << std::endl;
  if ((t2 - t1).total_milliseconds() > 50)
  {
    TEST_FAILED("Did not stop in time");
  }
  if ((t3 - t1).total_milliseconds() > 50)
  {
    TEST_FAILED("Stuck in destructor for too long time");
  }
  TEST_PASSED();
}

void try_adding_task_after_stop_request()
{
  std::atomic<int> counter(0);
  std::unique_ptr<Fmi::AsyncTaskGroup> tg(new Fmi::AsyncTaskGroup(10));
  tg->add("task 1", [&counter]() { counter++; });
  tg->wait();
  tg->stop();
  tg->add("task ", [&counter]() { counter++; });
  tg->wait();
  switch (int(counter))
  {
    case 0:
      TEST_FAILED("No task executed");
      break;
    case 1:
      break;
    case 2:
      TEST_FAILED("Task added after stop should not be executed");
      break;
    default:
      TEST_FAILED("Unexpected value of counter");
      break;
  }
  TEST_PASSED();
}

void test_stop_on_error()
{
  std::atomic<int> counter(0);
  const auto task_1 = [&]()
  {
    for (int i = 0; i < 10; i++)
    {
      Fmi::AsyncTask::interruption_point();
      std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    counter++;
  };

  const auto task_2 = []() { throw std::runtime_error("An error"); };

  std::unique_ptr<Fmi::AsyncTaskGroup> tg(new Fmi::AsyncTaskGroup(10));
  tg->stop_on_error(true);
  tg->add("task 1a", task_1);
  tg->add("task 1b", task_1);
  tg->add("task_2", task_2);

  const ptime t1 = microsec_clock::universal_time();

  try
  {
    tg->wait();
    TEST_FAILED("Excepted exception not thrown");
  }
  catch (const tframe::failed&)
  {
    throw;
  }
  catch (const Fmi::Exception&)
  {
  }

  const ptime t2 = microsec_clock::universal_time();
  if ((t2 - t1).total_milliseconds() > 30)
  {
    TEST_FAILED("Did not stop in time");
  }

  if (counter != 0)
  {
    TEST_FAILED("Tasks not stopped as expected");
  }

  TEST_PASSED();
}

// ----------------------------------------------------------------------
/*!
 * The actual test suite
 */
// ----------------------------------------------------------------------

class tests : public tframe::tests
{
  virtual const char* error_message_prefix() const { return "\n\t"; }

  void test(void)
  {
    TEST(not_waiting_for_result);
    TEST(empty_group);
    TEST(single_task);
    TEST(several_tasks);
    TEST(task_throws_not_std_exception);
    TEST(large_number_of_tasks);
    TEST(test_interrupting_1);
    TEST(try_adding_task_after_stop_request);
    TEST(test_stop_on_error);
  }
};

}  // namespace AsyncTaskGroupTest

int main(void)
{
  std::cout << std::endl
            << "AsyncTaskGroup tester" << std::endl
            << "=====================" << std::endl;
  AsyncTaskGroupTest::tests t;
  return t.run();
}

max_stars_repo_name: fmidev/smartmet-library-macgyver

max_issues_repo_name: fmidev/smartmet-library-macgyver

max_forks_repo_name: fmidev/smartmet-library-macgyver


text:
/*
 * @Description: ceres residual block for lidar frontend relative pose measurement
 * @Author: Ge Yao
 * @Date: 2020-11-29 15:47:49
 */
#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_RELATIVE_POSE_HPP_
#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_RELATIVE_POSE_HPP_

#include <ceres/ceres.h>

#include <Eigen/Eigen>
#include <Eigen/Core>
#include <Eigen/Dense>

#include <sophus/so3.hpp>

#include "glog/logging.h"

namespace sliding_window {

class FactorPRVAGRelativePose : public ceres::SizedCostFunction<6, 15, 15> {
public:
	static const int INDEX_P = 0;
	static const int INDEX_R = 3;

  FactorPRVAGRelativePose(void) {};

  void SetMeasurement(const Eigen::VectorXd &m) {
		m_ = m;
	}

  void SetInformation(const Eigen::MatrixXd &I) {
    I_ = I;
  }

  virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {
    //
    // parse parameters:
    //
    // a. pose i
    Eigen::Map<const Eigen::Vector3d>     pos_i(&parameters[0][INDEX_P]);
    Eigen::Map<const Eigen::Vector3d> log_ori_i(&parameters[0][INDEX_R]);
    const Sophus::SO3d                    ori_i = Sophus::SO3d::exp(log_ori_i);

    // b. pose j
    Eigen::Map<const Eigen::Vector3d>     pos_j(&parameters[1][INDEX_P]);
    Eigen::Map<const Eigen::Vector3d> log_ori_j(&parameters[1][INDEX_R]);
    const Sophus::SO3d                    ori_j = Sophus::SO3d::exp(log_ori_j);

    //
    // parse measurement:
    //
		const Eigen::Vector3d     &pos_ij = m_.block<3, 1>(INDEX_P, 0);
		const Eigen::Vector3d &log_ori_ij = m_.block<3, 1>(INDEX_R, 0);
    const Sophus::SO3d         ori_ij = Sophus::SO3d::exp(log_ori_ij);

    //
    // TODO: get square root of information matrix:
    //

    //
    // TODO: compute residual:
    //

    //
    // TODO: compute jacobians:
    //
    if ( jacobians ) {
      // compute shared intermediate results:

      if ( jacobians[0] ) {
        // implement computing:
      }

      if ( jacobians[1] ) {
        // implement computing:
      }
    }

    //
    // TODO: correct residual by square root of information matrix:
    //

    return true;
  }

private:
  static Eigen::Matrix3d JacobianRInv(const Eigen::Vector3d &w) {
      Eigen::Matrix3d J_r_inv = Eigen::Matrix3d::Identity();

      double theta = w.norm();

      if ( theta > 1e-5 ) {
          Eigen::Vector3d k = w.normalized();
          Eigen::Matrix3d K = Sophus::SO3d::hat(k);

          J_r_inv = J_r_inv
                    + 0.5 * K
                    + (1.0 - (1.0 + std::cos(theta)) * theta / (2.0 * std::sin(theta))) * K * K;
      }

      return J_r_inv;
  }

  Eigen::VectorXd m_;
  Eigen::MatrixXd I_;
};

} // namespace sliding_window

#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_RELATIVE_POSE_HPP_


text:
// [===========================================================================]
// [                                M o n e t a                                ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2005-2015                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

// TODO: Continue this Joel-de-Guzman-inspired charm.

#pragma once
#include <boost/preprocessor/tuple/size.hpp>

#define MONETA_PP_ADD_PARENTHESES_2_1(A, B) ((A, B)) MONETA_PP_ADD_PARENTHESES_2_2
#define MONETA_PP_ADD_PARENTHESES_2_2(A, B) ((A, B)) MONETA_PP_ADD_PARENTHESES_2_1
#define MONETA_PP_ADD_PARENTHESES_2_1_END
#define MONETA_PP_ADD_PARENTHESES_2_2_END
#define MONETA_PP_ADD_PARENTHESES_2(S) BOOST_PP_CAT(MONETA_PP_ADD_PARENTHESES_2_1 S, _END)

#define MONETA_PP_ADD_PARENTHESES_3_1(A, B, C) ((A, B, C)) MONETA_PP_ADD_PARENTHESES_3_2
#define MONETA_PP_ADD_PARENTHESES_3_2(A, B, C) ((A, B, C)) MONETA_PP_ADD_PARENTHESES_3_1
#define MONETA_PP_ADD_PARENTHESES_3_1_END
#define MONETA_PP_ADD_PARENTHESES_3_2_END
#define MONETA_PP_ADD_PARENTHESES_3(S) BOOST_PP_CAT(MONETA_PP_ADD_PARENTHESES_3_1 S, _END)

ext: hxx

max_stars_repo_name: madera/Moneta

max_issues_repo_name: madera/Moneta

max_forks_repo_name: madera/Moneta


text:
#ifndef WITHIN_BIGGLES_KALMAN_FILTER_HPP__
#error "This file should only be included by kalman_filter.hpp"
#endif // WITHIN_BIGGLES_KALMAN_FILTER_HPP__

#include <boost/assert.hpp>
#include <boost/foreach.hpp>
#include <cmath>
#include <deque>
#include <Eigen/Dense>

#include "detail/physics.hpp"
#include "tools/debug.hpp"

namespace biggles
{

template<typename OutputIterator>
void rts_smooth(const kalman_filter& filter,
                OutputIterator output_reversed_states_and_covariances)
{
    // Rauch-Tung-Striebel smoother:
    //
    // L_t = Sigma_{t|t} A^T P_{t+1|t}^{-1}
    //
    // mu_{t|T} = mu_{t|t} + L_t(mu_{t+1|T} - mu_{t+1|t})
    //
    // P_{t|T} = P_{t|t} + L_t(P_{t+1|T} - P_{t+1|t})L^T_t

    // the state evolution matrix: X_{k+1} = A X_k + <noise>
    Eigen::Matrix4f A(Eigen::Matrix4f::Identity());
    BOOST_ASSERT(filter.dynamic_drag() == 1);
    A(0,1) = A(2,3) = filter.dynamic_drag(); // <- off-diagonal velocity integration

    const kalman_filter::states_and_cov_deque& correction_states_and_covs(filter.corrections());
    const kalman_filter::states_and_cov_deque& prediction_states_and_covs(filter.predictions());

    // final interpolated state is output of forward filter, this is mu_{T|T} and Sigma_{T|T}
    if (not is_symmetric(correction_states_and_covs.back().second) and
            measure_asymmetry(correction_states_and_covs.back().second) > 0.f) {
        OK("foo");
        OK1(correction_states_and_covs.back().second);
        OK1(correction_states_and_covs.back().first);
        BOOST_ASSERT(measure_asymmetry(correction_states_and_covs.back().second)==0.f);
    }
    *output_reversed_states_and_covariances = correction_states_and_covs.back();
    ++output_reversed_states_and_covariances;

    // iterator pointing to mu_{t+1|t}, starting at t = T-1
    kalman_filter::states_and_cov_deque::const_reverse_iterator pred_it(prediction_states_and_covs.rbegin());

    // iterator pointing to mu_{t|t}, starting at t = T-1
    kalman_filter::states_and_cov_deque::const_reverse_iterator corr_it(++correction_states_and_covs.rbegin());

    for(kalman_filter::state_covariance_pair prior_pair(correction_states_and_covs.back());
        corr_it != correction_states_and_covs.rend();
        ++pred_it, ++corr_it, ++output_reversed_states_and_covariances)
    {
        // mu_{t+1|t} and Sigma_{t+1|t}
        const Eigen::Vector4f& pred_state(pred_it->first);
        const Eigen::Matrix4f& pred_cov(pred_it->second);

        // mu_{t|t} and Sigma_{t|t}
        const Eigen::Vector4f& corr_state(corr_it->first);
        const Eigen::Matrix4f& corr_cov(corr_it->second);

        // mu_{t+1|T} and Sigma_{t+1|T}
        const Eigen::Vector4f& last_smoothed_state(prior_pair.first);
        const Eigen::Matrix4f& last_smoothed_cov(prior_pair.second);

        // calculate the RTS smoothed values
        Eigen::Matrix4f L = corr_cov * A.transpose() * pred_cov.inverse();
        Eigen::Vector4f smoothed_state = corr_state + L * (last_smoothed_state - pred_state);
        Eigen::Matrix4f smoothed_cov = corr_cov + L * (last_smoothed_cov - pred_cov) * L.transpose();
        smoothed_cov = enforce_symmetry(smoothed_cov);

        if (not is_symmetric(corr_cov) and measure_asymmetry(corr_cov) > 0.f) {
            OK("rts_smooth");
            OK1(corr_cov);
            OK(measure_asymmetry(corr_cov));
            BOOST_ASSERT(measure_asymmetry(corr_cov)==0.f);
        }

        if (not is_symmetric(smoothed_cov) and measure_asymmetry(smoothed_cov) > 0.f) {
            OK("rts_smooth");
            OK1(smoothed_cov);
            OK(measure_asymmetry(corr_cov));
            OK(measure_asymmetry(smoothed_cov));
            BOOST_ASSERT(measure_asymmetry(smoothed_cov)==0.f);
        }

        // record smoothed state and covariance
        prior_pair = kalman_filter::state_covariance_pair(smoothed_state, smoothed_cov);
        *output_reversed_states_and_covariances = prior_pair;
    }
}

}

ext: tcc

max_stars_repo_name: fbi-octopus/biggles

max_issues_repo_name: fbi-octopus/biggles

max_forks_repo_name: fbi-octopus/biggles


text:
#include "stream.h"
#include <cassert>
#include <limits>
#include <cstring>  // for memcpy
#include <sstream>
#include <boost/exception/all.hpp>

namespace Akumuli {

StreamError::StreamError(std::string line, int pos)
    : line_(line)
    , pos_(pos)
{
}

const char* StreamError::what() const throw() {
    return line_.c_str();
}

std::string StreamError::get_bottom_line() const {
    std::stringstream s;
    for (int i = 0; i < (pos_-1); i++) {
        s << ' ';
    }
    s << '^';
    return s.str();
}

ByteStreamReader::~ByteStreamReader() {}

// MemStreamReader implementation

MemStreamReader::MemStreamReader(const Byte *buffer, size_t buffer_len)
    : buf_(buffer)
    , size_(buffer_len)
    , pos_(0ul)
{
    assert(size_ < std::numeric_limits<int>::max());
}

Byte MemStreamReader::get() {
    if (pos_ < size_) {
        return buf_[pos_++];
    }
    BOOST_THROW_EXCEPTION(StreamError("unexpected end of stream", pos_));
}

Byte MemStreamReader::pick() const {
    if (pos_ < size_) {
        return buf_[pos_];
    }
    BOOST_THROW_EXCEPTION(StreamError("unexpected end of stream", pos_));
}

bool MemStreamReader::is_eof() {
    return pos_ == size_;
}

int MemStreamReader::read(Byte *buffer, size_t buffer_len) {
    int nbytes = static_cast<int>(std::min(buffer_len, size_ - pos_));
    memcpy(buffer, buf_ + pos_, nbytes);
    pos_ += nbytes;
    return nbytes;
}

void MemStreamReader::close() {
    pos_ = size_;
}

std::tuple<std::string, size_t> MemStreamReader::get_error_context(const char* error_message) const {
    return std::make_tuple(error_message, 0u);
}

}

max_stars_repo_name: vladon/Akumuli

max_issues_repo_name: vladon/Akumuli

max_forks_repo_name: vladon/Akumuli


text: #include <boost/interprocess/sync/named_condition.hpp>