<commit_before>#include <fstream>
#include <sstream>
#include <cassert>
#include "corona.hpp"
#include "graph.hpp"
#include "ppm/ppm.hpp"
#include "tclap/ValueArg.h"

#define DEFAULT_MODEL_NAME "*"

EpidemicConfig* EpidemicConfig::instance_ = nullptr;

WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(DiffusionEvent)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(TriggerEvent)

std::vector<std::shared_ptr<warped::Event> > Location::initializeLP() {

    // Register random number generator to allow kernel to roll it back
    this->registerRNG<std::default_random_engine>(this->rng_);

    std::vector<std::shared_ptr<warped::Event> > events;
    events.emplace_back(new TriggerEvent {this->location_name_,
                                    CONFIG->update_trig_interval_});
    events.emplace_back(new TriggerEvent {this->location_name_,
                                    CONFIG->diffusion_trig_interval_, true});
    return events;
}

std::vector<std::shared_ptr<warped::Event> > Location::receiveEvent(const warped::Event& event) {

    std::vector<std::shared_ptr<warped::Event> > events;

    if (event->eventType() == event_type_t::TRIGGER) {
        auto trigger_event = static_cast<const TriggerEvent&>(event);
        auto timestamp = trigger_event->timestamp();

        /* Check whether a diffusion needs to be triggered */
        if (trigger_event->is_diffusion_) {
            std::string selected_location = diffusion_network_->pickLocation();
            if (selected_location != "") {
                auto travel_time = diffusion_network_->travelTimeToLocation(selected_location);
                unsigned int person_count = state_->current_population_->size();
                if (person_count) {
                    unsigned int person_id = diffusion_network_->pickPerson(person_count);
                    auto map_iter = state_->current_population_->begin();
                    unsigned int temp_cnt = 0;
                    while (temp_cnt < person_id) {
                        map_iter++;
                        temp_cnt++;
                    }
                    std::shared_ptr<Person> person = map_iter->second;
                    events.emplace_back(new EpidemicEvent {selected_location,
                                            timestamp + travel_time, person, DIFFUSION});
                    state_->current_population_->erase(map_iter);
                }
            }
            events.emplace_back(new TriggerEvent {location_name_,
                                timestamp + CONFIG->diffusion_trig_interval_, true});

        } else { /* Update the LP state */
            std::uniform_real_distribution<double> distribution(0.0, 1.0);
            auto rand_factor = distribution(*rng_);
            reaction();
            events.emplace_back(new TriggerEvent {location_name_,
                                timestamp + CONFIG->update_trig_interval_});
        }
    } else {
        std::shared_ptr<Person> person = std::make_shared<Person>(
                        epidemic_event.pid_, epidemic_event.susceptibility_,
                        epidemic_event.vaccination_status_, epidemic_event.infection_state_,
                        timestamp, epidemic_event.prev_state_change_timestamp_);
        state_->current_population_->insert(state_->current_population_->begin(),
                std::pair <unsigned long, std::shared_ptr<Person>> (epidemic_event.pid_, person));
    }
    return events;
}

std::string toString(unsigned int num) {
    std::ostringstream convert;
    convert << num;
    return convert.str();
}

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

    std::string model_config_name   = DEFAULT_MODEL_NAME;

    TCLAP::ValueArg<std::string> model_config_name_arg( "m", "model-config",
                        "Provide name of the model config", false, model_config_name, "string" );
    std::vector<TCLAP::Arg*> args = {&model_config_name_arg};
    warped::Simulation corona_sim {"Covid-19 Pandemic Simulation", argc, argv, args};
    model_config_name   = model_config_name_arg.getValue();

    if (model_config_name == DEFAULT_MODEL_NAME) {
        std::cout << "Need a valid model config filename.\n";
        exit(EXIT_FAILURE);
    }

    std::ifstream config_stream;
    config_stream.open(model_config_name);
    if (!config_stream.is_open()) {
        exit(EXIT_FAILURE);
    }

    std::string buffer;
    std::string delimiter = ",";
    size_t pos = 0;
    std::string token;

    // Diffusion model
    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    graph_type = buffer.substr(0, pos);
    buffer.erase(0, pos + delimiter.length());
    std::string diffusion_params(buffer);

    // Disease model
    getline(config_stream, buffer);
    float transmissibility = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int latent_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float latent_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int incubating_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float incubating_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int infectious_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float infectious_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int asympt_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float asympt_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    float prob_ulu = stof(token);
    buffer.erase(0, pos + delimiter.length());
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    float prob_ulv = std::stof(token);
    buffer.erase(0, pos + delimiter.length());
    float prob_urv = std::stof(buffer);

    getline(config_stream, buffer);
    unsigned int location_state_refresh_interval = (unsigned int) stoul(buffer);

    //Population
    getline(config_stream, buffer);
    num_regions = (unsigned int) std::stoul(buffer);

    std::map<std::string, unsigned int> travel_map;
    std::vector<Location> lps;

    for (unsigned int region_id = 0; region_id < num_regions; region_id++) {

        getline(config_stream, buffer);
        pos = buffer.find(delimiter);
        std::string region_name = buffer.substr(0, pos);
        buffer.erase(0, pos + delimiter.length());
        num_locations = (unsigned int) std::stoul(buffer);

        for (unsigned int location_id = 0; location_id < num_locations; location_id++) {

            getline(config_stream, buffer);
            pos = buffer.find(delimiter);
            std::string location_name = buffer.substr(0, pos);
            std::string location = region_name + location_name;
            buffer.erase(0, pos + delimiter.length());
            pos = buffer.find(delimiter);
            token = buffer.substr(0, pos);
            unsigned int travel_time_to_hub = (unsigned int) std::stoul(token);
            buffer.erase(0, pos + delimiter.length());
            pos = buffer.find(delimiter);
            token = buffer.substr(0, pos);
            unsigned int diffusion_interval = (unsigned int) std::stoul(token);
            buffer.erase(0, pos + delimiter.length());
            unsigned int num_persons = (unsigned int) std::stoul(buffer);

            std::vector<std::shared_ptr<Person>> population;
            travel_map.insert(std::pair<std::string, unsigned int>(location, travel_time_to_hub));

            for (unsigned int person_id = 0; person_id < num_persons; person_id++) {

                getline(config_stream, buffer);
                pos = buffer.find(delimiter);
                token = buffer.substr(0, pos);
                unsigned long pid = std::stoul(token);
                buffer.erase(0, pos + delimiter.length());
                pos = buffer.find(delimiter);
                token = buffer.substr(0, pos);
                double susceptibility = std::stod(buffer);
                buffer.erase(0, pos + delimiter.length());
                pos = buffer.find(delimiter);
                token = buffer.substr(0, pos);
                bool vaccination_status = (bool) std::stoi(token);
                buffer.erase(0, pos + delimiter.length());
                infection_state_t state = (infection_state_t) std::stoi(buffer);

                auto person = std::make_shared<Person> (    pid,
                                                            susceptibility,
                                                            vaccination_status,
                                                            state,
                                                            0,
                                                            0
                                                       );
                population.push_back(person);
            }
            lps.emplace_back(   location,
                                    transmissibility,
                                    latent_dwell_time,
                                    incubating_dwell_time,
                                    infectious_dwell_time,
                                    asympt_dwell_time,
                                    latent_infectivity,
                                    incubating_infectivity,
                                    infectious_infectivity,
                                    asympt_infectivity,
                                    prob_ulu,
                                    prob_ulv,
                                    prob_urv,
                                    location_state_refresh_interval,
                                    diffusion_interval,
                                    population,
                                    travel_time_to_hub,
                                    location_id
                                );
        }
    }
    config_stream.close();

    // Create the Network Graph
    std::vector<std::string> nodes;
    for (auto& lp : lps) {
        nodes.push_back(lp.getLocationName());
    }

    Graph *graph = nullptr;
    if (graph_type == "Watts-Strogatz") { // If the choice is Watts-Strogatz
        pos = diffusion_params.find(delimiter);
        token = diffusion_params.substr(0, pos);
        unsigned int k = (unsigned int) std::stoul(token);
        diffusion_params.erase(0, pos + delimiter.length());
        double beta = std::stod(diffusion_params);
        graph = new WattsStrogatz(nodes, k, beta);

    } else if (graph_type == "Barabasi-Albert") { // If the choice is Barabasi-Albert
        pos = diffusion_params.find(delimiter);
        token = diffusion_params.substr(0, pos);
        unsigned int m = (unsigned int) std::stoul(token);
        diffusion_params.erase(0, pos + delimiter.length());
        double a = std::stod(diffusion_params);
        graph = new BarabasiAlbert(nodes, m, a);

    } else { // Invalid choice
        std::cerr << "Invalid choice of diffusion network." << std::endl;
        return 0;
    }

    // Create the travel map and record initial statistics for each LP
    std::vector<unsigned long> initial_population( lps.size() );
    std::vector<unsigned long> initial_affected_cnt( lps.size() );
    unsigned long i = 0;
    for (auto& lp : lps) {
        // Create the travel map
        std::vector<std::string> connections = graph->adjacencyList(lp.getLocationName());
        std::map<std::string, unsigned int> temp_travel_map;
        for (auto& link : connections) {
            auto travel_map_iter = travel_map.find(link);
            temp_travel_map.insert(std::pair<std::string, unsigned int>
                                (travel_map_iter->first, travel_map_iter->second));
        }
        lp.populateTravelDistances(temp_travel_map);

        // Record the initial statistics
        unsigned long init_popu = 0, init_affected = 0;
        lp.statistics(&init_popu, &init_affected);
        initial_population[i]   = init_popu;
        initial_affected_cnt[i] = init_affected;
        i++;
    }
    delete graph;

    // Simulate the epidemic
    std::vector<warped::LogicalProcess*> lp_pointers;
    for (auto& lp : lps) {
        lp_pointers.push_back(&lp);
    }
    corona_sim.simulate(lp_pointers);

    // Plot the heatmaps
    unsigned long cols = std::ceil( sqrt(lps.size()) );
    unsigned long rows = (lps.size()+cols-1)/cols;
    auto population_diffusion_hmap = new ppm(cols, rows);
    auto disease_growth_hmap = new ppm(cols, rows);

    // Record final statistics for each LP
    i = 0;
    for (auto& lp : lps) {
        unsigned long final_population = 0, final_affected_cnt = 0;
        lp.statistics(&final_population, &final_affected_cnt);

        // If initial population >  final population, color is GREEN
        // If initial population == final population, color is BLACK
        // If initial population  < final population, color is RED
        if (initial_population[i] >= final_population) {
            double ratio = ( (double)(initial_population[i] - final_population) ) /
                                                                    initial_population[i];
            population_diffusion_hmap->g[i] = ratio * 255;

        } else {
            double ratio = ( (double)(final_population - initial_population[i]) ) /
                                                                    final_population;
            population_diffusion_hmap->r[i] = ratio * 255;
        }

        // If initial affected cnt >  final affected cnt, color is YELLOWISH GREEN
        // If initial affected cnt == final affected cnt, color is BLACK
        // If initial affected cnt  < final affected cnt, color is RED
        if (initial_affected_cnt[i] >= final_affected_cnt) {
            double ratio = ( (double)(initial_affected_cnt[i] - final_affected_cnt) ) /
                                                                    initial_affected_cnt[i];
            disease_growth_hmap->g[i] = ratio * 255;

        } else {
            double ratio = ( (double)(final_affected_cnt - initial_affected_cnt[i]) ) /
                                                                    final_affected_cnt;
            disease_growth_hmap->r[i] = ratio * 255;
        }
        i++;
    }
    population_diffusion_hmap->write("population_diffusion_hmap.ppm");
    disease_growth_hmap->write("disease_growth_hmap.ppm");

    delete population_diffusion_hmap;
    delete disease_growth_hmap;

    return 0;
}
<commit_msg>rectified the error in naming of conrona config singleton class<commit_after>#include <fstream>
#include <sstream>
#include <cassert>
#include "corona.hpp"
#include "graph.hpp"
#include "ppm/ppm.hpp"
#include "tclap/ValueArg.h"

#define DEFAULT_MODEL_NAME "*"

CoronaConfig* CoronaConfig::instance_ = nullptr;

WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(DiffusionEvent)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(TriggerEvent)

std::vector<std::shared_ptr<warped::Event> > Location::initializeLP() {

    // Register random number generator to allow kernel to roll it back
    this->registerRNG<std::default_random_engine>(this->rng_);

    std::vector<std::shared_ptr<warped::Event> > events;
    events.emplace_back(new TriggerEvent {this->location_name_,
                                    CONFIG->update_trig_interval_});
    events.emplace_back(new TriggerEvent {this->location_name_,
                                    CONFIG->diffusion_trig_interval_, true});
    return events;
}

std::vector<std::shared_ptr<warped::Event> > Location::receiveEvent(const warped::Event& event) {

    std::vector<std::shared_ptr<warped::Event> > events;

    if (event->eventType() == event_type_t::TRIGGER) {
        auto trigger_event = static_cast<const TriggerEvent&>(event);
        auto timestamp = trigger_event->timestamp();

        /* Check whether a diffusion needs to be triggered */
        if (trigger_event->is_diffusion_) {
            std::string selected_location = diffusion_network_->pickLocation();
            if (selected_location != "") {
                auto travel_time = diffusion_network_->travelTimeToLocation(selected_location);
                unsigned int person_count = state_->current_population_->size();
                if (person_count) {
                    unsigned int person_id = diffusion_network_->pickPerson(person_count);
                    auto map_iter = state_->current_population_->begin();
                    unsigned int temp_cnt = 0;
                    while (temp_cnt < person_id) {
                        map_iter++;
                        temp_cnt++;
                    }
                    std::shared_ptr<Person> person = map_iter->second;
                    events.emplace_back(new EpidemicEvent {selected_location,
                                            timestamp + travel_time, person, DIFFUSION});
                    state_->current_population_->erase(map_iter);
                }
            }
            events.emplace_back(new TriggerEvent {location_name_,
                                timestamp + CONFIG->diffusion_trig_interval_, true});

        } else { /* Update the LP state */
            std::uniform_real_distribution<double> distribution(0.0, 1.0);
            auto rand_factor = distribution(*rng_);
            reaction();
            events.emplace_back(new TriggerEvent {location_name_,
                                timestamp + CONFIG->update_trig_interval_});
        }
    } else {
        std::shared_ptr<Person> person = std::make_shared<Person>(
                        epidemic_event.pid_, epidemic_event.susceptibility_,
                        epidemic_event.vaccination_status_, epidemic_event.infection_state_,
                        timestamp, epidemic_event.prev_state_change_timestamp_);
        state_->current_population_->insert(state_->current_population_->begin(),
                std::pair <unsigned long, std::shared_ptr<Person>> (epidemic_event.pid_, person));
    }
    return events;
}

std::string toString(unsigned int num) {
    std::ostringstream convert;
    convert << num;
    return convert.str();
}

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

    std::string model_config_name   = DEFAULT_MODEL_NAME;

    TCLAP::ValueArg<std::string> model_config_name_arg( "m", "model-config",
                        "Provide name of the model config", false, model_config_name, "string" );
    std::vector<TCLAP::Arg*> args = {&model_config_name_arg};
    warped::Simulation corona_sim {"Covid-19 Pandemic Simulation", argc, argv, args};
    model_config_name   = model_config_name_arg.getValue();

    if (model_config_name == DEFAULT_MODEL_NAME) {
        std::cout << "Need a valid model config filename.\n";
        exit(EXIT_FAILURE);
    }

    std::ifstream config_stream;
    config_stream.open(model_config_name);
    if (!config_stream.is_open()) {
        exit(EXIT_FAILURE);
    }

    std::string buffer;
    std::string delimiter = ",";
    size_t pos = 0;
    std::string token;

    // Diffusion model
    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    graph_type = buffer.substr(0, pos);
    buffer.erase(0, pos + delimiter.length());
    std::string diffusion_params(buffer);

    // Disease model
    getline(config_stream, buffer);
    float transmissibility = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int latent_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float latent_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int incubating_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float incubating_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int infectious_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float infectious_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    unsigned int asympt_dwell_time = (unsigned int) std::stoul(token);
    buffer.erase(0, pos + delimiter.length());
    float asympt_infectivity = std::stof(buffer);

    getline(config_stream, buffer);
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    float prob_ulu = stof(token);
    buffer.erase(0, pos + delimiter.length());
    pos = buffer.find(delimiter);
    token = buffer.substr(0, pos);
    float prob_ulv = std::stof(token);
    buffer.erase(0, pos + delimiter.length());
    float prob_urv = std::stof(buffer);

    getline(config_stream, buffer);
    unsigned int location_state_refresh_interval = (unsigned int) stoul(buffer);

    //Population
    getline(config_stream, buffer);
    num_regions = (unsigned int) std::stoul(buffer);

    std::map<std::string, unsigned int> travel_map;
    std::vector<Location> lps;

    for (unsigned int region_id = 0; region_id < num_regions; region_id++) {

        getline(config_stream, buffer);
        pos = buffer.find(delimiter);
        std::string region_name = buffer.substr(0, pos);
        buffer.erase(0, pos + delimiter.length());
        num_locations = (unsigned int) std::stoul(buffer);

        for (unsigned int location_id = 0; location_id < num_locations; location_id++) {

            getline(config_stream, buffer);
            pos = buffer.find(delimiter);
            std::string location_name = buffer.substr(0, pos);
            std::string location = region_name + location_name;
            buffer.erase(0, pos + delimiter.length());
            pos = buffer.find(delimiter);
            token = buffer.substr(0, pos);
            unsigned int travel_time_to_hub = (unsigned int) std::stoul(token);
            buffer.erase(0, pos + delimiter.length());
            pos = buffer.find(delimiter);
            token = buffer.substr(0, pos);
            unsigned int diffusion_interval = (unsigned int) std::stoul(token);
            buffer.erase(0, pos + delimiter.length());
            unsigned int num_persons = (unsigned int) std::stoul(buffer);

            std::vector<std::shared_ptr<Person>> population;
            travel_map.insert(std::pair<std::string, unsigned int>(location, travel_time_to_hub));

            for (unsigned int person_id = 0; person_id < num_persons; person_id++) {

                getline(config_stream, buffer);
                pos = buffer.find(delimiter);
                token = buffer.substr(0, pos);
                unsigned long pid = std::stoul(token);
                buffer.erase(0, pos + delimiter.length());
                pos = buffer.find(delimiter);
                token = buffer.substr(0, pos);
                double susceptibility = std::stod(buffer);
                buffer.erase(0, pos + delimiter.length());
                pos = buffer.find(delimiter);
                token = buffer.substr(0, pos);
                bool vaccination_status = (bool) std::stoi(token);
                buffer.erase(0, pos + delimiter.length());
                infection_state_t state = (infection_state_t) std::stoi(buffer);

                auto person = std::make_shared<Person> (    pid,
                                                            susceptibility,
                                                            vaccination_status,
                                                            state,
                                                            0,
                                                            0
                                                       );
                population.push_back(person);
            }
            lps.emplace_back(   location,
                                    transmissibility,
                                    latent_dwell_time,
                                    incubating_dwell_time,
                                    infectious_dwell_time,
                                    asympt_dwell_time,
                                    latent_infectivity,
                                    incubating_infectivity,
                                    infectious_infectivity,
                                    asympt_infectivity,
                                    prob_ulu,
                                    prob_ulv,
                                    prob_urv,
                                    location_state_refresh_interval,
                                    diffusion_interval,
                                    population,
                                    travel_time_to_hub,
                                    location_id
                                );
        }
    }
    config_stream.close();

    // Create the Network Graph
    std::vector<std::string> nodes;
    for (auto& lp : lps) {
        nodes.push_back(lp.getLocationName());
    }

    Graph *graph = nullptr;
    if (graph_type == "Watts-Strogatz") { // If the choice is Watts-Strogatz
        pos = diffusion_params.find(delimiter);
        token = diffusion_params.substr(0, pos);
        unsigned int k = (unsigned int) std::stoul(token);
        diffusion_params.erase(0, pos + delimiter.length());
        double beta = std::stod(diffusion_params);
        graph = new WattsStrogatz(nodes, k, beta);

    } else if (graph_type == "Barabasi-Albert") { // If the choice is Barabasi-Albert
        pos = diffusion_params.find(delimiter);
        token = diffusion_params.substr(0, pos);
        unsigned int m = (unsigned int) std::stoul(token);
        diffusion_params.erase(0, pos + delimiter.length());
        double a = std::stod(diffusion_params);
        graph = new BarabasiAlbert(nodes, m, a);

    } else { // Invalid choice
        std::cerr << "Invalid choice of diffusion network." << std::endl;
        return 0;
    }

    // Create the travel map and record initial statistics for each LP
    std::vector<unsigned long> initial_population( lps.size() );
    std::vector<unsigned long> initial_affected_cnt( lps.size() );
    unsigned long i = 0;
    for (auto& lp : lps) {
        // Create the travel map
        std::vector<std::string> connections = graph->adjacencyList(lp.getLocationName());
        std::map<std::string, unsigned int> temp_travel_map;
        for (auto& link : connections) {
            auto travel_map_iter = travel_map.find(link);
            temp_travel_map.insert(std::pair<std::string, unsigned int>
                                (travel_map_iter->first, travel_map_iter->second));
        }
        lp.populateTravelDistances(temp_travel_map);

        // Record the initial statistics
        unsigned long init_popu = 0, init_affected = 0;
        lp.statistics(&init_popu, &init_affected);
        initial_population[i]   = init_popu;
        initial_affected_cnt[i] = init_affected;
        i++;
    }
    delete graph;

    // Simulate the epidemic
    std::vector<warped::LogicalProcess*> lp_pointers;
    for (auto& lp : lps) {
        lp_pointers.push_back(&lp);
    }
    corona_sim.simulate(lp_pointers);

    // Plot the heatmaps
    unsigned long cols = std::ceil( sqrt(lps.size()) );
    unsigned long rows = (lps.size()+cols-1)/cols;
    auto population_diffusion_hmap = new ppm(cols, rows);
    auto disease_growth_hmap = new ppm(cols, rows);

    // Record final statistics for each LP
    i = 0;
    for (auto& lp : lps) {
        unsigned long final_population = 0, final_affected_cnt = 0;
        lp.statistics(&final_population, &final_affected_cnt);

        // If initial population >  final population, color is GREEN
        // If initial population == final population, color is BLACK
        // If initial population  < final population, color is RED
        if (initial_population[i] >= final_population) {
            double ratio = ( (double)(initial_population[i] - final_population) ) /
                                                                    initial_population[i];
            population_diffusion_hmap->g[i] = ratio * 255;

        } else {
            double ratio = ( (double)(final_population - initial_population[i]) ) /
                                                                    final_population;
            population_diffusion_hmap->r[i] = ratio * 255;
        }

        // If initial affected cnt >  final affected cnt, color is YELLOWISH GREEN
        // If initial affected cnt == final affected cnt, color is BLACK
        // If initial affected cnt  < final affected cnt, color is RED
        if (initial_affected_cnt[i] >= final_affected_cnt) {
            double ratio = ( (double)(initial_affected_cnt[i] - final_affected_cnt) ) /
                                                                    initial_affected_cnt[i];
            disease_growth_hmap->g[i] = ratio * 255;

        } else {
            double ratio = ( (double)(final_affected_cnt - initial_affected_cnt[i]) ) /
                                                                    final_affected_cnt;
            disease_growth_hmap->r[i] = ratio * 255;
        }
        i++;
    }
    population_diffusion_hmap->write("population_diffusion_hmap.ppm");
    disease_growth_hmap->write("disease_growth_hmap.ppm");

    delete population_diffusion_hmap;
    delete disease_growth_hmap;

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 EditorConfig Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <sdk.h> // Code::Blocks SDK
#include <configurationpanel.h>
#include <editormanager.h>
#include <manager.h>
#include "cbeditor.h"
#include "cbstyledtextctrl.h"
#include "CBEditorConfig.hpp"
#include <wx/event.h>
#include <wx/menu.h>
#include <wx/msgdlg.h>
#include <editorconfig/editorconfig.h>

// Register the plugin with Code::Blocks.
// We are using an anonymous namespace so we don't litter the global one.
namespace
{
    PluginRegistrant<CBEditorConfig> reg(_T("CBEditorConfig"));
}

// constructor
CBEditorConfig::CBEditorConfig()
{
    // Make sure our resources are available.
    // In the generated boilerplate code we have no resources but when
    // we add some, it will be nice that this code is in place already ;)
    if (!Manager::LoadResource(_T("CBEditorConfig.zip"))) {
        NotifyMissingFile(_T("CBEditorConfig.zip"));
    }
}

// destructor
CBEditorConfig::~CBEditorConfig()
{
}

void CBEditorConfig::OnAttach()
{
    // do initialization

    // register event
    Manager::Get()->RegisterEventSink(cbEVT_EDITOR_OPEN,
            new cbEventFunctor<CBEditorConfig, CodeBlocksEvent>(this,
                &CBEditorConfig::OnEditorOpen));
}

int CBEditorConfig::LoadConfig()
{
    // get the cbEditor and cbStyledTextCtrl
    cbEditor *ed =
        Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();

    if (!ed)
        return -1;

    cbStyledTextCtrl* control = ed->GetControl();

    if (!control)
        return -1;

    editorconfig_handle eh = editorconfig_handle_init();

    /* start parsing */
    int err_num;
    if ((err_num = editorconfig_parse(ed->GetFilename().ToAscii(), eh)) != 0 &&
            /* Ignore full path error, whose error code is
             * EDITORCONFIG_PARSE_NOT_FULL_PATH */
            err_num != EDITORCONFIG_PARSE_NOT_FULL_PATH) {
        editorconfig_handle_destroy(eh);
        return err_num;
    }

    // apply the settings

    struct
    {
        const char*     indent_style;
        int             indent_size;
        int             tab_width;
        const char*     end_of_line;
    } ecConf; // obtained EditorConfig settings will be here

    memset(&ecConf, 0, sizeof(ecConf));

    int name_value_count = editorconfig_handle_get_name_value_count(eh);

    // get settings
    for (int i = 0; i < name_value_count; ++i) {
        const char* name;
        const char* value;

        editorconfig_handle_get_name_value(eh, i, &name, &value);

        if (!strcmp(name, "indent_style"))
            ecConf.indent_style = value;
        else if (!strcmp(name, "tab_width"))
            ecConf.tab_width = atoi(value);
        else if (!strcmp(name, "indent_size"))
            ecConf.indent_size = atoi(value);
        else if (!strcmp(name, "end_of_line"))
            ecConf.end_of_line = value;
    }

    if (ecConf.indent_style) {
        if (!strcmp(ecConf.indent_style, "tab"))
            control->SetUseTabs(true);
        else if (!strcmp(ecConf.indent_style, "space"))
            control->SetUseTabs(false);
    }
    if (ecConf.indent_size > 0) {
        control->SetIndent(ecConf.indent_size);

        // We set the tab width here, so that this could be overrided then
        // if ecConf.tab_wdith > 0
        control->SetTabWidth(ecConf.indent_size);
    }

    if (ecConf.tab_width > 0)
        control->SetTabWidth(ecConf.indent_size);

    // set eol
    if (ecConf.end_of_line) {
        if (!strcmp(ecConf.end_of_line, "lf"))
            control->SetEOLMode(wxSCI_EOL_LF);
        else if (!strcmp(ecConf.end_of_line, "crlf"))
            control->SetEOLMode(wxSCI_EOL_CRLF);
        else if (!strcmp(ecConf.end_of_line, "cr"))
            control->SetEOLMode(wxSCI_EOL_CR);
    }

    editorconfig_handle_destroy(eh);

    return 0;
}

void CBEditorConfig::OnEditorOpen(CodeBlocksEvent& /* event */)
{
    LoadConfig();
}

void CBEditorConfig::OnRelease(bool /* appShutDown */)
{
}

int CBEditorConfig::Configure()
{
    return 0;
}

int CBEditorConfig::GetConfigurationPriority() const
{
    return  50;
}

int CBEditorConfig::GetConfigurationGroup() const
{
    return  cgUnknown;
}

void CBEditorConfig::BuildMenu(wxMenuBar* menuBar)
{
    // Add a menu under "Plugins"
    int pluginMenuPos = menuBar->FindMenu(_T("Plugins"));

    if (pluginMenuPos == wxNOT_FOUND)
        return;

    wxMenu* pluginMenu = menuBar->GetMenu(pluginMenuPos);
    long menuIdReload = wxNewId();
    pluginMenu->Prepend(menuIdReload, _T("Reload &EditorConfig"),
            _T("Reload EditorConfig"));

    //event handling
    Connect(menuIdReload, wxEVT_COMMAND_MENU_SELECTED,
            wxCommandEventHandler(CBEditorConfig::OnReloadEditorConfig));

    return;
}

void CBEditorConfig::BuildModuleMenu(const ModuleType /*type*/,
                                     wxMenu* /*menu*/,
                                     const FileTreeData* /*data*/)
{
    return;
}

bool CBEditorConfig::BuildToolBar(wxToolBar* /*toolBar*/)
{
    return false;
}

void CBEditorConfig::OnReloadEditorConfig(wxCommandEvent& event)
{
    int err_num;

    // Reload EditorConfig
    if ((err_num = LoadConfig()) != 0) {
        wxString err_msg;

        err_msg << wxT("EditorConfig Error: ") <<
            wxString(editorconfig_get_error_msg(err_num), wxConvUTF8) <<
            _T("(") << err_num << _T(")");
        wxMessageDialog(NULL, err_msg, wxT("EditorConfig"), wxOK).ShowModal();

        return;
    }

    wxMessageDialog(NULL, _T("EditorConfig successfully reloaded."),
            _T("EditorConfig"), wxOK).ShowModal();
}
<commit_msg>SetTabWidth should set ecConf.tab_width but not ecConf.indent_size<commit_after>// Copyright (c) 2012 EditorConfig Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <sdk.h> // Code::Blocks SDK
#include <configurationpanel.h>
#include <editormanager.h>
#include <manager.h>
#include "cbeditor.h"
#include "cbstyledtextctrl.h"
#include "CBEditorConfig.hpp"
#include <wx/event.h>
#include <wx/menu.h>
#include <wx/msgdlg.h>
#include <editorconfig/editorconfig.h>

// Register the plugin with Code::Blocks.
// We are using an anonymous namespace so we don't litter the global one.
namespace
{
    PluginRegistrant<CBEditorConfig> reg(_T("CBEditorConfig"));
}

// constructor
CBEditorConfig::CBEditorConfig()
{
    // Make sure our resources are available.
    // In the generated boilerplate code we have no resources but when
    // we add some, it will be nice that this code is in place already ;)
    if (!Manager::LoadResource(_T("CBEditorConfig.zip"))) {
        NotifyMissingFile(_T("CBEditorConfig.zip"));
    }
}

// destructor
CBEditorConfig::~CBEditorConfig()
{
}

void CBEditorConfig::OnAttach()
{
    // do initialization

    // register event
    Manager::Get()->RegisterEventSink(cbEVT_EDITOR_OPEN,
            new cbEventFunctor<CBEditorConfig, CodeBlocksEvent>(this,
                &CBEditorConfig::OnEditorOpen));
}

int CBEditorConfig::LoadConfig()
{
    // get the cbEditor and cbStyledTextCtrl
    cbEditor *ed =
        Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();

    if (!ed)
        return -1;

    cbStyledTextCtrl* control = ed->GetControl();

    if (!control)
        return -1;

    editorconfig_handle eh = editorconfig_handle_init();

    /* start parsing */
    int err_num;
    if ((err_num = editorconfig_parse(ed->GetFilename().ToAscii(), eh)) != 0 &&
            /* Ignore full path error, whose error code is
             * EDITORCONFIG_PARSE_NOT_FULL_PATH */
            err_num != EDITORCONFIG_PARSE_NOT_FULL_PATH) {
        editorconfig_handle_destroy(eh);
        return err_num;
    }

    // apply the settings

    struct
    {
        const char*     indent_style;
        int             indent_size;
        int             tab_width;
        const char*     end_of_line;
    } ecConf; // obtained EditorConfig settings will be here

    memset(&ecConf, 0, sizeof(ecConf));

    int name_value_count = editorconfig_handle_get_name_value_count(eh);

    // get settings
    for (int i = 0; i < name_value_count; ++i) {
        const char* name;
        const char* value;

        editorconfig_handle_get_name_value(eh, i, &name, &value);

        if (!strcmp(name, "indent_style"))
            ecConf.indent_style = value;
        else if (!strcmp(name, "tab_width"))
            ecConf.tab_width = atoi(value);
        else if (!strcmp(name, "indent_size"))
            ecConf.indent_size = atoi(value);
        else if (!strcmp(name, "end_of_line"))
            ecConf.end_of_line = value;
    }

    if (ecConf.indent_style) {
        if (!strcmp(ecConf.indent_style, "tab"))
            control->SetUseTabs(true);
        else if (!strcmp(ecConf.indent_style, "space"))
            control->SetUseTabs(false);
    }
    if (ecConf.indent_size > 0) {
        control->SetIndent(ecConf.indent_size);

        // We set the tab width here, so that this could be overrided then
        // if ecConf.tab_wdith > 0
        control->SetTabWidth(ecConf.indent_size);
    }

    if (ecConf.tab_width > 0)
        control->SetTabWidth(ecConf.tab_width);

    // set eol
    if (ecConf.end_of_line) {
        if (!strcmp(ecConf.end_of_line, "lf"))
            control->SetEOLMode(wxSCI_EOL_LF);
        else if (!strcmp(ecConf.end_of_line, "crlf"))
            control->SetEOLMode(wxSCI_EOL_CRLF);
        else if (!strcmp(ecConf.end_of_line, "cr"))
            control->SetEOLMode(wxSCI_EOL_CR);
    }

    editorconfig_handle_destroy(eh);

    return 0;
}

void CBEditorConfig::OnEditorOpen(CodeBlocksEvent& /* event */)
{
    LoadConfig();
}

void CBEditorConfig::OnRelease(bool /* appShutDown */)
{
}

int CBEditorConfig::Configure()
{
    return 0;
}

int CBEditorConfig::GetConfigurationPriority() const
{
    return  50;
}

int CBEditorConfig::GetConfigurationGroup() const
{
    return  cgUnknown;
}

void CBEditorConfig::BuildMenu(wxMenuBar* menuBar)
{
    // Add a menu under "Plugins"
    int pluginMenuPos = menuBar->FindMenu(_T("Plugins"));

    if (pluginMenuPos == wxNOT_FOUND)
        return;

    wxMenu* pluginMenu = menuBar->GetMenu(pluginMenuPos);
    long menuIdReload = wxNewId();
    pluginMenu->Prepend(menuIdReload, _T("Reload &EditorConfig"),
            _T("Reload EditorConfig"));

    //event handling
    Connect(menuIdReload, wxEVT_COMMAND_MENU_SELECTED,
            wxCommandEventHandler(CBEditorConfig::OnReloadEditorConfig));

    return;
}

void CBEditorConfig::BuildModuleMenu(const ModuleType /*type*/,
                                     wxMenu* /*menu*/,
                                     const FileTreeData* /*data*/)
{
    return;
}

bool CBEditorConfig::BuildToolBar(wxToolBar* /*toolBar*/)
{
    return false;
}

void CBEditorConfig::OnReloadEditorConfig(wxCommandEvent& event)
{
    int err_num;

    // Reload EditorConfig
    if ((err_num = LoadConfig()) != 0) {
        wxString err_msg;

        err_msg << wxT("EditorConfig Error: ") <<
            wxString(editorconfig_get_error_msg(err_num), wxConvUTF8) <<
            _T("(") << err_num << _T(")");
        wxMessageDialog(NULL, err_msg, wxT("EditorConfig"), wxOK).ShowModal();

        return;
    }

    wxMessageDialog(NULL, _T("EditorConfig successfully reloaded."),
            _T("EditorConfig"), wxOK).ShowModal();
}
<|endoftext|>


<commit_before>/*-
 * Copyright (c) 2012, Achilleas Margaritis
 * Copyright (c) 2014, David T. Chisnall
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <cassert>
#include "ast.hh"

namespace {
/**
 * The current AST container.  When constructing an object, this is set and
 * then the constructors for the fields run, accessing it to detect their
 * parents.
 */
// FIXME: Should be thread_local, but that doesn't seem to work on OS X for
// some reason (__thread does)
__thread pegmatite::ASTContainer *current = 0;
/**
 * The current parser delegate.  When constructing an object, this is set and
 * then the constructors for the fields run, accessing it to detect their
 * parents.
 */
__thread pegmatite::ASTParserDelegate *currentParserDelegate;
}

namespace pegmatite {

/** sets the container under construction to be this.
 */
ASTContainer::ASTContainer()
{
	current = this;
}

/** Asks all members to construct themselves from the stack.
	The members are asked to construct themselves in reverse order.
	from a node stack.
	@param st stack.
 */
void ASTContainer::construct(const InputRange &r, ASTStack &st)
{
	for(auto it = members.rbegin(); it != members.rend(); ++it)
	{
		ASTMember *member = *it;
		member->construct(r, st);
	}
	// We don't need the members vector anymore, so clean up the storage it
	// uses.
	ASTMember_vector().swap(members);
}

ASTMember::ASTMember()
{
	assert(current);
	container_node = current;
	current->members.push_back(this);
}
ASTMember::~ASTMember() {}

ASTParserDelegate::ASTParserDelegate()
{
	currentParserDelegate = this;
}

void ASTParserDelegate::set_parse_proc(const Rule &r, parse_proc p)
{
	handlers[std::addressof(r)] = p;
}
void ASTParserDelegate::bind_parse_proc(const Rule &r, parse_proc p)
{
	currentParserDelegate->set_parse_proc(r, p);
}
parse_proc ASTParserDelegate::get_parse_proc(const Rule &r) const
{
	auto it = handlers.find(std::addressof(r));
	if (it == handlers.end()) return 0;
	return it->second;
}

/** parses the given input.
	@param i input.
	@param g root rule of grammar.
	@param ws whitespace rule.
	@param el list of errors.
	@param d user data, passed to the parse procedures.
	@return pointer to AST node created, or null if there was an Error.
		The return object must be deleted by the caller.
 */
std::unique_ptr<ASTNode> parse(Input &i, const Rule &g, const Rule &ws,
                               ErrorList &el, const ParserDelegate &d)
{
	ASTStack st;
	if (!parse(i, g, ws, el, d, &st)) return 0;
	assert(st.size() == 1);
	return std::move(st[0].second);
}

} //namespace pegmatite
<commit_msg>If we have more than one element left on the AST stack after AST construction, dump the contents of the stack.<commit_after>/*-
 * Copyright (c) 2012, Achilleas Margaritis
 * Copyright (c) 2014, David T. Chisnall
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <cassert>
#include "ast.hh"

namespace {
/**
 * The current AST container.  When constructing an object, this is set and
 * then the constructors for the fields run, accessing it to detect their
 * parents.
 */
// FIXME: Should be thread_local, but that doesn't seem to work on OS X for
// some reason (__thread does)
__thread pegmatite::ASTContainer *current = 0;
/**
 * The current parser delegate.  When constructing an object, this is set and
 * then the constructors for the fields run, accessing it to detect their
 * parents.
 */
__thread pegmatite::ASTParserDelegate *currentParserDelegate;
}

namespace pegmatite {

/** sets the container under construction to be this.
 */
ASTContainer::ASTContainer()
{
	current = this;
}

/** Asks all members to construct themselves from the stack.
	The members are asked to construct themselves in reverse order.
	from a node stack.
	@param st stack.
 */
void ASTContainer::construct(const InputRange &r, ASTStack &st)
{
	for(auto it = members.rbegin(); it != members.rend(); ++it)
	{
		ASTMember *member = *it;
		member->construct(r, st);
	}
	// We don't need the members vector anymore, so clean up the storage it
	// uses.
	ASTMember_vector().swap(members);
}

ASTMember::ASTMember()
{
	assert(current);
	container_node = current;
	current->members.push_back(this);
}
ASTMember::~ASTMember() {}

ASTParserDelegate::ASTParserDelegate()
{
	currentParserDelegate = this;
}

void ASTParserDelegate::set_parse_proc(const Rule &r, parse_proc p)
{
	handlers[std::addressof(r)] = p;
}
void ASTParserDelegate::bind_parse_proc(const Rule &r, parse_proc p)
{
	currentParserDelegate->set_parse_proc(r, p);
}
parse_proc ASTParserDelegate::get_parse_proc(const Rule &r) const
{
	auto it = handlers.find(std::addressof(r));
	if (it == handlers.end()) return 0;
	return it->second;
}

/** parses the given input.
	@param i input.
	@param g root rule of grammar.
	@param ws whitespace rule.
	@param el list of errors.
	@param d user data, passed to the parse procedures.
	@return pointer to AST node created, or null if there was an Error.
		The return object must be deleted by the caller.
 */
std::unique_ptr<ASTNode> parse(Input &i, const Rule &g, const Rule &ws,
                               ErrorList &el, const ParserDelegate &d)
{
	ASTStack st;
	if (!parse(i, g, ws, el, d, &st)) return 0;
	if (st.size() > 1)
	{
		int i = 0;
		for (auto &I : st)
		{
			fprintf(stderr, "[%d] %s\n", i++, typeid(*I.second.get()).name());
		}
	}
	assert(st.size() == 1);
	return std::move(st[0].second);
}

} //namespace pegmatite
<|endoftext|>


<commit_before><commit_msg>Disallow global gradient-enhanced interpolants by default.  Override with #define ALLOW_HERMITE_INTERPOLATION.<commit_after><|endoftext|>


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

#include "CameraListHolder.h"

#include "CameraDiscovery.h"

#include "tcam-semaphores.h"

#include <sys/sem.h>	 /* semaphore functions and structs.     */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>

#include "gige-daemon.h"

#include <stdlib.h>
#include <sstream>
#include <cstring>

#include <sys/types.h>   /* various type definitions.            */
#include <sys/ipc.h>     /* general SysV IPC structures          */

using namespace tis;

void log_message (const char* filename, const char* message)
{
    FILE *logfile;
	logfile=fopen(filename,"a");
	if(!logfile)
        return;
	fprintf(logfile,"%s\n",message);
	fclose(logfile);
}

CameraListHolder::CameraListHolder ()
    : continue_loop(true), run_loop(false), data(nullptr)
{
    // to understand shared memory use this guide:
    // http://beej.us/guide/bgipc/output/html/multipage/shm.html

    shmkey = ftok("/tmp/tcam-gige-camera-list", 'G');
    shmid = shmget(shmkey, sizeof(struct tcam_gige_device_list), 0644 | IPC_CREAT);

    semaphore_key = ftok("/tmp/tcam-gige-semaphore", 'S');
    semaphore_id = tcam::semaphore_create(semaphore_key);

    work_thread = std::thread(&CameraListHolder::index_loop, this);
}

CameraListHolder::~CameraListHolder ()
{
    continue_loop = false;
    if (work_thread.joinable())
    {
        work_thread.join();
    }

    struct tcam_gige_device_list* d = (struct tcam_gige_device_list*)shmat(shmid, NULL, NULL);
    d->device_count = 0;
    memset(d->devices, 0, sizeof(struct tcam_gige_device_list) * TCAM_DEVICE_LIST_MAX);

    shmdt(d);
}

CameraListHolder& CameraListHolder::get_instance ()
{
    static CameraListHolder instance;

    return instance;
}

std::vector<DeviceInfo> CameraListHolder::get_camera_list () const
{
    tcam::semaphore_lock(semaphore_id);
    struct tcam_gige_device_list* d = (struct tcam_gige_device_list*)shmat(shmid, NULL, NULL);

    if (d == nullptr)
    {
        tcam::semaphore_unlock(semaphore_id);

        return std::vector<DeviceInfo>();
    }

    std::vector<DeviceInfo> ret(d->device_count);

    for (unsigned int i = 0; i < d->device_count; ++i)
    {
        ret.push_back(DeviceInfo(d->devices[i]));
    }

    tcam::semaphore_unlock(semaphore_id);

    return ret;
}

void CameraListHolder::run ()
{
    data = shmat(shmid, nullptr, 0);
    work_thread.detach();
}

void CameraListHolder::stop ()
{
    this->continue_loop = false;
    std::unique_lock<std::mutex> lck(mtx);
    run_loop = true;
    cv.notify_all();
    shmctl(shmid, IPC_RMID, NULL);
    data = nullptr;
}

void CameraListHolder::index_loop ()
{

    while (continue_loop)
    {
        loop_function();
    }
}

camera_list getCameraList ()
{
    camera_list cameras;
    std::mutex cam_lock;

    std::function<void(std::shared_ptr<Camera>)> f = [&cameras, &cam_lock] (std::shared_ptr<Camera> camera)
        {
            std::lock_guard<std::mutex> mutex_lock(cam_lock);
            cameras.push_back(camera);
        };

    discoverCameras(f);

    return cameras;
}

std::vector<struct tcam_device_info> get_gige_device_list ()
{
    // out of the tcam-network lib
    auto l = getCameraList();

    std::vector<struct tcam_device_info> ret;

    ret.reserve(l.size());

    for (const auto& c : l)
    {
        struct tcam_device_info info;

        info.type = TCAM_DEVICE_TYPE_ARAVIS;

        strncpy(info.serial_number, c->getSerialNumber().c_str(), sizeof(info.serial_number));
        strncpy(info.name, c->getModelName().c_str(), sizeof(info.name));

        std::string identifier = c->getVendorName() + "-" + c->getSerialNumber();

        strncpy(info.identifier, identifier.c_str(), sizeof(info.identifier));

        ret.push_back(info);
    }

    return ret;
}

void CameraListHolder::loop_function ()
{
        std::unique_lock<std::mutex> lck(mtx);

        cv.wait_for(lck, std::chrono::seconds(2));

        // preemptiv stop
        if (!continue_loop)
        {
            log_message("/tmp/gige.log", "Preemptiv stop");
            return;
        }

        std::vector<struct tcam_device_info> aravis_list = get_gige_device_list();

        if (aravis_list.size() > TCAM_DEVICE_LIST_MAX)
        {
            log_message("/tmp/gige.log", "To many devices. Unable to fill list");
            return;
        }

        tcam::semaphore_lock(semaphore_id);

        struct tcam_gige_device_list* tmp_ptr = (struct tcam_gige_device_list*) shmat(shmid, NULL, NULL);

        tmp_ptr->device_count = aravis_list.size();

        struct tcam_device_info* ptr = tmp_ptr->devices;
        for (const auto dev : aravis_list)
        {
            memcpy(ptr, &dev, sizeof(struct tcam_device_info));
            ++ptr;
        }

        // force update to change time
        struct shmid_ds ds = {};
        shmctl(shmid, IPC_STAT, &ds);
        shmctl(shmid, IPC_SET, &ds);

        // release dataptr
        shmdt(tmp_ptr);

        tcam::semaphore_lock(semaphore_id);
}
<commit_msg>Fixed unreleased semaphore lock<commit_after>/*
 * Copyright 2016 The Imaging Source Europe GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CameraListHolder.h"

#include "CameraDiscovery.h"

#include "tcam-semaphores.h"

#include <sys/sem.h>	 /* semaphore functions and structs.     */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>

#include "gige-daemon.h"

#include <stdlib.h>
#include <sstream>
#include <cstring>

#include <sys/types.h>   /* various type definitions.            */
#include <sys/ipc.h>     /* general SysV IPC structures          */

using namespace tis;

void log_message (const char* filename, const char* message)
{
    FILE *logfile;
	logfile=fopen(filename,"a");
	if(!logfile)
        return;
	fprintf(logfile,"%s\n",message);
	fclose(logfile);
}

CameraListHolder::CameraListHolder ()
    : continue_loop(true), run_loop(false), data(nullptr)
{
    // to understand shared memory use this guide:
    // http://beej.us/guide/bgipc/output/html/multipage/shm.html

    shmkey = ftok("/tmp/tcam-gige-camera-list", 'G');
    shmid = shmget(shmkey, sizeof(struct tcam_gige_device_list), 0644 | IPC_CREAT);

    semaphore_key = ftok("/tmp/tcam-gige-semaphore", 'S');
    semaphore_id = tcam::semaphore_create(semaphore_key);

    work_thread = std::thread(&CameraListHolder::index_loop, this);
}

CameraListHolder::~CameraListHolder ()
{
    continue_loop = false;
    if (work_thread.joinable())
    {
        work_thread.join();
    }

    struct tcam_gige_device_list* d = (struct tcam_gige_device_list*)shmat(shmid, NULL, NULL);
    d->device_count = 0;
    memset(d->devices, 0, sizeof(struct tcam_gige_device_list) * TCAM_DEVICE_LIST_MAX);

    shmdt(d);
}

CameraListHolder& CameraListHolder::get_instance ()
{
    static CameraListHolder instance;

    return instance;
}

std::vector<DeviceInfo> CameraListHolder::get_camera_list () const
{
    tcam::semaphore_lock(semaphore_id);
    struct tcam_gige_device_list* d = (struct tcam_gige_device_list*)shmat(shmid, NULL, NULL);

    if (d == nullptr)
    {
        tcam::semaphore_unlock(semaphore_id);

        return std::vector<DeviceInfo>();
    }

    std::vector<DeviceInfo> ret(d->device_count);

    for (unsigned int i = 0; i < d->device_count; ++i)
    {
        ret.push_back(DeviceInfo(d->devices[i]));
    }

    tcam::semaphore_unlock(semaphore_id);

    return ret;
}

void CameraListHolder::run ()
{
    data = shmat(shmid, nullptr, 0);
    work_thread.detach();
}

void CameraListHolder::stop ()
{
    this->continue_loop = false;
    std::unique_lock<std::mutex> lck(mtx);
    run_loop = true;
    cv.notify_all();
    shmctl(shmid, IPC_RMID, NULL);
    data = nullptr;
}

void CameraListHolder::index_loop ()
{

    while (continue_loop)
    {
        loop_function();
    }
}

camera_list getCameraList ()
{
    camera_list cameras;
    std::mutex cam_lock;

    std::function<void(std::shared_ptr<Camera>)> f = [&cameras, &cam_lock] (std::shared_ptr<Camera> camera)
        {
            std::lock_guard<std::mutex> mutex_lock(cam_lock);
            cameras.push_back(camera);
        };

    discoverCameras(f);

    return cameras;
}

std::vector<struct tcam_device_info> get_gige_device_list ()
{
    // out of the tcam-network lib
    auto l = getCameraList();

    std::vector<struct tcam_device_info> ret;

    ret.reserve(l.size());

    for (const auto& c : l)
    {
        struct tcam_device_info info;

        info.type = TCAM_DEVICE_TYPE_ARAVIS;

        strncpy(info.serial_number, c->getSerialNumber().c_str(), sizeof(info.serial_number));
        strncpy(info.name, c->getModelName().c_str(), sizeof(info.name));

        std::string identifier = c->getVendorName() + "-" + c->getSerialNumber();

        strncpy(info.identifier, identifier.c_str(), sizeof(info.identifier));

        ret.push_back(info);
    }

    return ret;
}

void CameraListHolder::loop_function ()
{
        std::unique_lock<std::mutex> lck(mtx);

        cv.wait_for(lck, std::chrono::seconds(2));

        // preemptiv stop
        if (!continue_loop)
        {
            log_message("/tmp/gige.log", "Preemptiv stop");
            return;
        }

        std::vector<struct tcam_device_info> aravis_list = get_gige_device_list();

        if (aravis_list.size() > TCAM_DEVICE_LIST_MAX)
        {
            log_message("/tmp/gige.log", "To many devices. Unable to fill list");
            return;
        }

        tcam::semaphore_lock(semaphore_id);

        struct tcam_gige_device_list* tmp_ptr = (struct tcam_gige_device_list*) shmat(shmid, NULL, NULL);

        tmp_ptr->device_count = aravis_list.size();

        struct tcam_device_info* ptr = tmp_ptr->devices;
        for (const auto dev : aravis_list)
        {
            memcpy(ptr, &dev, sizeof(struct tcam_device_info));
            ++ptr;
        }

        // force update to change time
        struct shmid_ds ds = {};
        shmctl(shmid, IPC_STAT, &ds);
        shmctl(shmid, IPC_SET, &ds);

        // release dataptr
        shmdt(tmp_ptr);

        tcam::semaphore_unlock(semaphore_id);
}
<|endoftext|>


<commit_before><commit_msg>Removed extraneous comment.<commit_after><|endoftext|>


<commit_before><commit_msg>initialized<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream.h>
#include <fstream.h>
#include <string.h>

#include "debug.h"
#include "condor_updown.h"
#include "condor_disk.h"

extern	"C"		dprintf(int, char *, char *);

// constructor
File::File(const char* filename)
{
	fileName = new char[strlen(filename)+1];
	strcpy(fileName, filename);
}

// destructior
File::~File()
{
	delete fileName;
}

// this method writes an UpDown object onto disk file
int File::operator << (const UpDown & upDown)
{
	int  fd;

	ofstream fout(fileName);   // open the output file
	if ( fout.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot open file for writing: %s\n",fileName);
		return Error;
	}

	header.activeUsers 	= upDown.activeUsers;
	fout.write((char*) &header, sizeof header);
	if ( fout.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot write into file: %s\n", fileName);
		return Error;
	}

	data = new Data[header.activeUsers];
	for ( int i=0; i < upDown.activeUsers; i++)
	{
		strncpy(data[i].userName, upDown.table[i].name,
		   min(MaxUserNameSize-1,strlen(upDown.table[i].name)+1));
		data[i].priority = upDown.table[i].priority;
	}
	fout.write((char*) data, sizeof (Data)*header.activeUsers);
	delete data;
	if ( fout.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot write into file: %s\n", fileName);
		return Error;
	}
	fout.close();
	return Success;
}

// reading in the file
int File::operator >> (UpDown & upDown)
{
	int  fd;

	ifstream fin(fileName);   // open the input file
	if ( fin.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot open file for reading: %s\n",fileName);
		return Error;
	}

	fin.read((char*) &header, sizeof header);
	if ( fin.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot read from file: %s\n", fileName);
		return Error;
	}

	if ( header.activeUsers > upDown.maxUsers )
		upDown.AllocateSpaceMoreUsers(header.activeUsers);

	data = new Data[header.activeUsers];
	fin.read((char*) data, sizeof(Data)*header.activeUsers);
	if ( fin.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot read from file: %s\n", fileName);
		delete data;
		return Error;
	}
	// copying from temp data structure to upDown object
	for ( int i=0; i < header.activeUsers; i++)
	{
		// check if some name is already there
		if ( i<upDown.activeUsers && upDown.table[i].name)
				delete upDown.table[i].name;

		upDown.table[i].name= new char[strlen(data[i].userName)+1];

		strcpy(upDown.table[i].name, data[i].userName);
		upDown.table[i].priority = data[i].priority;
	}
	upDown.activeUsers 	= header.activeUsers;
	fin.close();
	delete data;
	return Success;
}
<commit_msg>fixed memory leaks: several delete mismatches<commit_after>#include <stdio.h>
#include <iostream.h>
#include <fstream.h>
#include <string.h>

#include "debug.h"
#include "condor_updown.h"
#include "condor_disk.h"

extern	"C"		dprintf(int, char *, char *);

// constructor
File::File(const char* filename)
{
	fileName = new char[strlen(filename)+1];
	strcpy(fileName, filename);
}

// destructior
File::~File()
{
	delete []fileName;
}

// this method writes an UpDown object onto disk file
int File::operator << (const UpDown & upDown)
{
	int  fd;

	ofstream fout(fileName);   // open the output file
	if ( fout.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot open file for writing: %s\n",fileName);
		return Error;
	}

	header.activeUsers 	= upDown.activeUsers;
	fout.write((char*) &header, sizeof header);
	if ( fout.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot write into file: %s\n", fileName);
		return Error;
	}

	data = new Data[header.activeUsers];
	for ( int i=0; i < upDown.activeUsers; i++)
	{
		strncpy(data[i].userName, upDown.table[i].name,
		   min(MaxUserNameSize-1,strlen(upDown.table[i].name)+1));
		data[i].priority = upDown.table[i].priority;
	}
	fout.write((char*) data, sizeof (Data)*header.activeUsers);
	delete []data;
	if ( fout.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot write into file: %s\n", fileName);
		return Error;
	}
	fout.close();
	return Success;
}

// reading in the file
int File::operator >> (UpDown & upDown)
{
	int  fd;

	ifstream fin(fileName);   // open the input file
	if ( fin.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot open file for reading: %s\n",fileName);
		return Error;
	}

	fin.read((char*) &header, sizeof header);
	if ( fin.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot read from file: %s\n", fileName);
		return Error;
	}

	if ( header.activeUsers > upDown.maxUsers )
		upDown.AllocateSpaceMoreUsers(header.activeUsers);

	data = new Data[header.activeUsers];
	fin.read((char*) data, sizeof(Data)*header.activeUsers);
	if ( fin.fail() )
	{
		dprintf(D_FULLDEBUG, "Cannot read from file: %s\n", fileName);
		delete data;
		return Error;
	}
	// copying from temp data structure to upDown object
	for ( int i=0; i < header.activeUsers; i++)
	{
		// check if some name is already there
		if ( i<upDown.activeUsers && upDown.table[i].name)
				delete upDown.table[i].name;

		upDown.table[i].name= new char[strlen(data[i].userName)+1];

		strcpy(upDown.table[i].name, data[i].userName);
		upDown.table[i].priority = data[i].priority;
	}
	upDown.activeUsers 	= header.activeUsers;
	fin.close();
	delete []data;
	return Success;
}
<|endoftext|>


<commit_before>#include "response.h"
#include "client.h"
#include "settings.h"

#include "timing/timingfactory.h"

Response::Response(QObject *parent)
: QObject(parent)
{
}

Response::~Response()
{
}

void Response::finished()
{
}

LoginResponse::LoginResponse(QObject *parent)
: Response(parent)
{
}

bool LoginResponse::fillFromVariant(const QVariantMap &variant)
{
    m_sessionId = variant.value("session_id").toString();
    m_registeredDevice = variant.value("registered_device", true).toBool();

    return !m_sessionId.isEmpty();
}

void LoginResponse::finished()
{
    Client* client = Client::instance();

    // Update the settings
    Settings* settings = client->settings();
    settings->setSessionId(m_sessionId);

    // Set registered status (after settings!)
    client->setStatus(Client::Registered);
}

QString LoginResponse::sessionId() const
{
    return m_sessionId;
}

bool LoginResponse::registeredDevice() const
{
    return m_registeredDevice;
}

RegisterDeviceResponse::RegisterDeviceResponse(QObject *parent)
: Response(parent)
{
}

bool RegisterDeviceResponse::fillFromVariant(const QVariantMap &variant)
{
    Q_UNUSED(variant);
    return true;
}

GetConfigResponse::GetConfigResponse(QObject *parent)
: Response(parent)
{
}

bool GetConfigResponse::fillFromVariant(const QVariantMap &variant)
{
    m_controllerAddress = variant.value("controller_address").toString();
    m_fetchTaskSchedule = TimingFactory::timingFromVariant(variant.value("fetch_task_schedule"));
    m_keepaliveAddress = variant.value("keepalive_address").toString();
    m_keepaliveSchedule = TimingFactory::timingFromVariant(variant.value("keepalive_schedule"));
    m_updateConfigSchedule = TimingFactory::timingFromVariant(variant.value("update_config_schedule"));

    return true;
}

QVariant GetConfigResponse::toVariant() const
{
    QVariantMap map;
    map.insert("controller_address", m_controllerAddress);
    map.insert("fetch_task_schedule", m_fetchTaskSchedule->toVariant());
    map.insert("keepalive_address", m_keepaliveAddress);
    map.insert("keepalive_schedule", m_keepaliveSchedule->toVariant());
    map.insert("update_config_schedule", m_updateConfigSchedule->toVariant());
    return map;
}

void GetConfigResponse::finished()
{
    emit responseChanged();
}

void GetConfigResponse::setControllerAddress(const QString &controllerAddress)
{
    m_controllerAddress = controllerAddress;
}

QString GetConfigResponse::controllerAddress() const
{
    return m_controllerAddress;
}

TimingPtr GetConfigResponse::fetchTaskSchedule() const
{
    return m_fetchTaskSchedule;
}

QString GetConfigResponse::keepaliveAddress() const
{
    return m_keepaliveAddress;
}

TimingPtr GetConfigResponse::keepaliveSchedule() const
{
    return m_keepaliveSchedule;
}

TimingPtr GetConfigResponse::updateConfigSchedule() const
{
    return m_updateConfigSchedule;
}
<commit_msg>Fixes #39: don't save empty config<commit_after>#include "response.h"
#include "client.h"
#include "settings.h"

#include "timing/timingfactory.h"

Response::Response(QObject *parent)
: QObject(parent)
{
}

Response::~Response()
{
}

void Response::finished()
{
}

LoginResponse::LoginResponse(QObject *parent)
: Response(parent)
{
}

bool LoginResponse::fillFromVariant(const QVariantMap &variant)
{
    m_sessionId = variant.value("session_id").toString();
    m_registeredDevice = variant.value("registered_device", true).toBool();

    return !m_sessionId.isEmpty();
}

void LoginResponse::finished()
{
    Client* client = Client::instance();

    // Update the settings
    Settings* settings = client->settings();
    settings->setSessionId(m_sessionId);

    // Set registered status (after settings!)
    client->setStatus(Client::Registered);
}

QString LoginResponse::sessionId() const
{
    return m_sessionId;
}

bool LoginResponse::registeredDevice() const
{
    return m_registeredDevice;
}

RegisterDeviceResponse::RegisterDeviceResponse(QObject *parent)
: Response(parent)
{
}

bool RegisterDeviceResponse::fillFromVariant(const QVariantMap &variant)
{
    Q_UNUSED(variant);
    return true;
}

GetConfigResponse::GetConfigResponse(QObject *parent)
: Response(parent)
{
}

bool GetConfigResponse::fillFromVariant(const QVariantMap &variant)
{
    m_controllerAddress = variant.value("controller_address").toString();
    m_fetchTaskSchedule = TimingFactory::timingFromVariant(variant.value("fetch_task_schedule"));
    m_keepaliveAddress = variant.value("keepalive_address").toString();
    m_keepaliveSchedule = TimingFactory::timingFromVariant(variant.value("keepalive_schedule"));
    m_updateConfigSchedule = TimingFactory::timingFromVariant(variant.value("update_config_schedule"));

    return true;
}

QVariant GetConfigResponse::toVariant() const
{
    if (m_fetchTaskSchedule.isNull())
        return QVariant();

    QVariantMap map;
    map.insert("controller_address", m_controllerAddress);
    map.insert("fetch_task_schedule", m_fetchTaskSchedule->toVariant());
    map.insert("keepalive_address", m_keepaliveAddress);
    map.insert("keepalive_schedule", m_keepaliveSchedule->toVariant());
    map.insert("update_config_schedule", m_updateConfigSchedule->toVariant());
    return map;
}

void GetConfigResponse::finished()
{
    emit responseChanged();
}

void GetConfigResponse::setControllerAddress(const QString &controllerAddress)
{
    m_controllerAddress = controllerAddress;
}

QString GetConfigResponse::controllerAddress() const
{
    return m_controllerAddress;
}

TimingPtr GetConfigResponse::fetchTaskSchedule() const
{
    return m_fetchTaskSchedule;
}

QString GetConfigResponse::keepaliveAddress() const
{
    return m_keepaliveAddress;
}

TimingPtr GetConfigResponse::keepaliveSchedule() const
{
    return m_keepaliveSchedule;
}

TimingPtr GetConfigResponse::updateConfigSchedule() const
{
    return m_updateConfigSchedule;
}
<|endoftext|>


<commit_before><commit_msg>updated plotting<commit_after><|endoftext|>


<commit_before>//===- tools/seec-trace-view/ActionRecord.hpp -----------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#ifndef SEEC_TRACE_VIEW_ACTIONRECORD_HPP
#define SEEC_TRACE_VIEW_ACTIONRECORD_HPP

#include "seec/Util/Parsing.hpp"

#include <wx/panel.h>
#include <wx/xml/xml.h>

#include <chrono>
#include <memory>
#include <vector>

namespace seec {
  namespace cm {
    class ProcessTrace;
  }
}

class wxButton;
class wxPoint;
class wxSize;
class wxXmlDocument;
class wxXmlNode;

/// \brief Interface for an attribute.
///
class IAttributeReadOnly
{
protected:
  virtual std::string const &get_name_impl() const = 0;
  virtual std::string to_string_impl() const = 0;

public:
  virtual ~IAttributeReadOnly() =0;
  std::string const &get_name() const { return get_name_impl(); }
  std::string to_string() const { return to_string_impl(); }
};

/// \brief Interface for a writable attribute.
///
class IAttributeReadWrite : public IAttributeReadOnly
{
protected:
  virtual bool from_string_impl(std::string const &) = 0;

public:
  bool from_string(std::string const &S) { return from_string_impl(S); }
};

/// \brief A single attribute of a recorded event.
///
template<typename ValueT, typename Enable = void>
class Attribute; // undefined

/// \brief Check if a type is a non-writable (const or rvalue) arithmetic type.
///
template<typename T, typename DerefT = typename std::remove_reference<T>::type>
struct is_ro_arithmetic
: std::integral_constant<bool,
    std::is_arithmetic<DerefT>::value
    && (!std::is_lvalue_reference<T>::value || std::is_const<DerefT>::value)>
{};

/// \brief A single read-only attribute of a recorded event.
///
/// Generic implementation for arithmetic types using std::to_string().
///
template<typename T>
class Attribute<T, typename std::enable_if<is_ro_arithmetic<T>::value>::type>
: public IAttributeReadOnly
{
  std::string const Name;
  T const &Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return std::to_string(Value); }

public:
  Attribute(std::string WithName, T const &WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief Check if a type is a writable (non-const lvalue) arithmetic type.
///
template<typename T, typename DerefT = typename std::remove_reference<T>::type>
struct is_rw_arithmetic
: std::integral_constant<bool,
    std::is_arithmetic<DerefT>::value
    && (std::is_lvalue_reference<T>::value && !std::is_const<DerefT>::value)>
{};

/// \brief A single attribute of a recorded event.
///
/// Generic implementation using std::to_string() and seec::parseTo().
///
template<typename T>
class Attribute<T, typename std::enable_if<is_rw_arithmetic<T>::value>::type>
: public IAttributeReadWrite
{
  std::string const Name;
  T &Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return std::to_string(Value); }
  bool from_string_impl(std::string const &String) {
    return seec::parseTo(String, Value);
  }

public:
  Attribute(std::string WithName, T &WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief A single read-only attribute of a recorded event.
///
/// Implementation for const string values.
///
template<unsigned N>
class Attribute<char const (&)[N]>
: public IAttributeReadOnly
{
  std::string const Name;
  char const * const Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return Value; }

public:
  Attribute(std::string WithName, char const (&WithValue)[N])
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief A single attribute of a recorded event.
///
/// Implementation for std::string values.
///
template<>
class Attribute<std::string &>
: public IAttributeReadWrite
{
  std::string const Name;
  std::string &Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return Value; }
  bool from_string_impl(std::string const &String) {
    Value = String;
    return true;
  }

public:
  Attribute(std::string WithName, std::string &WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief Create an Attribute<T> with the given name and value.
///
template<typename T>
Attribute<T> make_attribute(std::string Name, T &&Value)
{
  return Attribute<T>(std::move(Name), std::forward<T>(Value));
}

/// \brief Records user interactions with the trace viewer.
///
class ActionRecord
{
  /// The process trace that the user is viewing.
  seec::cm::ProcessTrace const &Trace;

  /// Whether or not recording is enabled for this record.
  bool Enabled;

  /// The time at which the record was created.
  std::chrono::time_point<std::chrono::steady_clock> Started;

  /// Used to record user interactions.
  std::unique_ptr<wxXmlDocument> RecordDocument;

  /// The most recently inserted node in the record.
  wxXmlNode *LastNode;

  /// \brief Write an archive of this recording (and trace) to the given stream.
  ///
  bool archiveTo(wxOutputStream &Stream);

public:
  /// \brief Create a new action record.
  ///
  ActionRecord(seec::cm::ProcessTrace const &ForTrace);

  /// \brief Check if the recording is enabled.
  ///
  bool isEnabled() const { return Enabled; }

  /// \brief Enable recording for this record.
  ///
  bool enable();

  /// \brief Disable recording for this record.
  ///
  void disable();

  /// \brief Record an event.
  ///
  void recordEventV(std::string const &Handler,
                    std::vector<IAttributeReadOnly const *> const &Attributes);

  /// \brief Record an event.
  ///
  template<typename... Ts>
  void recordEventL(std::string const &Handler,
                    Ts &&... Attributes)
  {
    if (Enabled)
      recordEventV(Handler, std::vector<IAttributeReadOnly const *>
                                       {&Attributes...});
  }

  /// \brief Finish this action record and submit it to the server.
  ///
  bool finalize();
};

/// \brief A control that allows the user to enable/disable recording.
///
class ActionRecordingControl : public wxPanel
{
  ActionRecord *Recording;

  wxButton *ButtonEnable;

  wxImage ImgRecordingOn;

  wxImage ImgRecordingOff;

public:
  /// \brief Constructor (without creation).
  ///
  ActionRecordingControl()
  : Recording(nullptr),
    ButtonEnable(nullptr),
    ImgRecordingOn(),
    ImgRecordingOff()
  {}

  /// \brief Constructor (with creation).
  ///
  ActionRecordingControl(wxWindow *Parent, ActionRecord &WithRecord)
  : ActionRecordingControl()
  {
    Create(Parent, WithRecord);
  }

  /// \brief Create this object.
  ///
  bool Create(wxWindow *Parent, ActionRecord &WithRecord);
};

#endif // SEEC_TRACE_VIEW_ACTIONRECORD_HPP
<commit_msg>Add read only Attribute<> specialization for char const * values (C strings).<commit_after>//===- tools/seec-trace-view/ActionRecord.hpp -----------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#ifndef SEEC_TRACE_VIEW_ACTIONRECORD_HPP
#define SEEC_TRACE_VIEW_ACTIONRECORD_HPP

#include "seec/Util/Parsing.hpp"

#include <wx/panel.h>
#include <wx/xml/xml.h>

#include <chrono>
#include <memory>
#include <vector>

namespace seec {
  namespace cm {
    class ProcessTrace;
  }
}

class wxButton;
class wxPoint;
class wxSize;
class wxXmlDocument;
class wxXmlNode;

/// \brief Interface for an attribute.
///
class IAttributeReadOnly
{
protected:
  virtual std::string const &get_name_impl() const = 0;
  virtual std::string to_string_impl() const = 0;

public:
  virtual ~IAttributeReadOnly() =0;
  std::string const &get_name() const { return get_name_impl(); }
  std::string to_string() const { return to_string_impl(); }
};

/// \brief Interface for a writable attribute.
///
class IAttributeReadWrite : public IAttributeReadOnly
{
protected:
  virtual bool from_string_impl(std::string const &) = 0;

public:
  bool from_string(std::string const &S) { return from_string_impl(S); }
};

/// \brief A single attribute of a recorded event.
///
template<typename ValueT, typename Enable = void>
class Attribute; // undefined

/// \brief Check if a type is a non-writable (const or rvalue) arithmetic type.
///
template<typename T, typename DerefT = typename std::remove_reference<T>::type>
struct is_ro_arithmetic
: std::integral_constant<bool,
    std::is_arithmetic<DerefT>::value
    && (!std::is_lvalue_reference<T>::value || std::is_const<DerefT>::value)>
{};

/// \brief A single read-only attribute of a recorded event.
///
/// Generic implementation for arithmetic types using std::to_string().
///
template<typename T>
class Attribute<T, typename std::enable_if<is_ro_arithmetic<T>::value>::type>
: public IAttributeReadOnly
{
  std::string const Name;
  T const &Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return std::to_string(Value); }

public:
  Attribute(std::string WithName, T const &WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief Check if a type is a writable (non-const lvalue) arithmetic type.
///
template<typename T, typename DerefT = typename std::remove_reference<T>::type>
struct is_rw_arithmetic
: std::integral_constant<bool,
    std::is_arithmetic<DerefT>::value
    && (std::is_lvalue_reference<T>::value && !std::is_const<DerefT>::value)>
{};

/// \brief A single attribute of a recorded event.
///
/// Generic implementation using std::to_string() and seec::parseTo().
///
template<typename T>
class Attribute<T, typename std::enable_if<is_rw_arithmetic<T>::value>::type>
: public IAttributeReadWrite
{
  std::string const Name;
  T &Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return std::to_string(Value); }
  bool from_string_impl(std::string const &String) {
    return seec::parseTo(String, Value);
  }

public:
  Attribute(std::string WithName, T &WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief A single read-only attribute of a recorded event.
///
/// Implementation for const string values.
///
template<unsigned N>
class Attribute<char const (&)[N]>
: public IAttributeReadOnly
{
  std::string const Name;
  char const * const Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return Value; }

public:
  Attribute(std::string WithName, char const (&WithValue)[N])
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief A single read-only attribute of a recorded event.
///
/// Implementation for const string values.
///
template<>
class Attribute<char const *>
: public IAttributeReadOnly
{
  std::string const Name;
  char const * const Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return Value; }

public:
  Attribute(std::string WithName, char const *WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief A single attribute of a recorded event.
///
/// Implementation for std::string values.
///
template<>
class Attribute<std::string &>
: public IAttributeReadWrite
{
  std::string const Name;
  std::string &Value;

protected:
  std::string const &get_name_impl() const { return Name; }
  std::string to_string_impl() const { return Value; }
  bool from_string_impl(std::string const &String) {
    Value = String;
    return true;
  }

public:
  Attribute(std::string WithName, std::string &WithValue)
  : Name(std::move(WithName)),
    Value(WithValue)
  {}
};

/// \brief Create an Attribute<T> with the given name and value.
///
template<typename T>
Attribute<T> make_attribute(std::string Name, T &&Value)
{
  return Attribute<T>(std::move(Name), std::forward<T>(Value));
}

/// \brief Records user interactions with the trace viewer.
///
class ActionRecord
{
  /// The process trace that the user is viewing.
  seec::cm::ProcessTrace const &Trace;

  /// Whether or not recording is enabled for this record.
  bool Enabled;

  /// The time at which the record was created.
  std::chrono::time_point<std::chrono::steady_clock> Started;

  /// Used to record user interactions.
  std::unique_ptr<wxXmlDocument> RecordDocument;

  /// The most recently inserted node in the record.
  wxXmlNode *LastNode;

  /// \brief Write an archive of this recording (and trace) to the given stream.
  ///
  bool archiveTo(wxOutputStream &Stream);

public:
  /// \brief Create a new action record.
  ///
  ActionRecord(seec::cm::ProcessTrace const &ForTrace);

  /// \brief Check if the recording is enabled.
  ///
  bool isEnabled() const { return Enabled; }

  /// \brief Enable recording for this record.
  ///
  bool enable();

  /// \brief Disable recording for this record.
  ///
  void disable();

  /// \brief Record an event.
  ///
  void recordEventV(std::string const &Handler,
                    std::vector<IAttributeReadOnly const *> const &Attributes);

  /// \brief Record an event.
  ///
  template<typename... Ts>
  void recordEventL(std::string const &Handler,
                    Ts &&... Attributes)
  {
    if (Enabled)
      recordEventV(Handler, std::vector<IAttributeReadOnly const *>
                                       {&Attributes...});
  }

  /// \brief Finish this action record and submit it to the server.
  ///
  bool finalize();
};

/// \brief A control that allows the user to enable/disable recording.
///
class ActionRecordingControl : public wxPanel
{
  ActionRecord *Recording;

  wxButton *ButtonEnable;

  wxImage ImgRecordingOn;

  wxImage ImgRecordingOff;

public:
  /// \brief Constructor (without creation).
  ///
  ActionRecordingControl()
  : Recording(nullptr),
    ButtonEnable(nullptr),
    ImgRecordingOn(),
    ImgRecordingOff()
  {}

  /// \brief Constructor (with creation).
  ///
  ActionRecordingControl(wxWindow *Parent, ActionRecord &WithRecord)
  : ActionRecordingControl()
  {
    Create(Parent, WithRecord);
  }

  /// \brief Create this object.
  ///
  bool Create(wxWindow *Parent, ActionRecord &WithRecord);
};

#endif // SEEC_TRACE_VIEW_ACTIONRECORD_HPP
<|endoftext|>


<commit_before><commit_msg>implement new palette file reading<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed cleanup bug for async demuxer.<commit_after><|endoftext|>