<commit_before>//
//  main.cpp
//  greedRelate
//  Greedy approach of keeping samples
//  Created by Shing Wan Choi on 18/08/2016.
//  Copyright © 2016 Shing Wan Choi. All rights reserved.
//

#include "misc.hpp"
#include <algorithm>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <unordered_map>
#include <vector>

class Sample
{
public:
    // First occurance = itself, therefore occurance = 0
    Sample(std::string name, double pheno, double rand)
        : m_name(name), phenotype(pheno), rand_number(rand)
    {
        occur = 0;
    }
    // add a relative to the current sample
    int add(Sample* related)
    {
        // not sure why
        // TODO: See if we can skip the step of pushing nullptr
        relatives.push_back(nullptr);
        relatives.back() = related;
        m_removed = false;
        occur++;
        return occur;
    }
    int remove()
    {
        // we are going to start cleaning up these relatives.
        // good thing is that the size of this vector will small
        // check if any relatives have more than us. If not, then proceed,
        // otherwise, return
        if (m_name == "3003339" || m_name == "5128261" || m_name == "1304775"
            || m_name == "5000708" || m_name == "2975133")
        {
            std::cerr << "Removing individual: " << m_name << "\t" << occur
                      << std::endl;
        }
        for (auto&& relative : relatives) {
            if (!relative->removed()
                && (relative->occur > occur
                    || (relative->occur == occur
                        && relative->phenotype < phenotype)
                    || (relative->occur == occur
                        && relative->rand_number > rand_number)
                    || (relative->occur == occur
                        && relative->rand_number == rand_number
                        && relative->m_name > m_name)))
            {

                if (m_name == "3003339" || m_name == "5128261"
                    || m_name == "1304775" || m_name == "5000708"
                    || m_name == "2975133")
                {
                    std::cerr << "Relative Save: " << relative->m_name << "\t"
                              << relative->occur << "\t"
                              << relative->rand_number << "\t" << rand_number
                              << std::endl;
                }
                return 0;
            }
        }
        if (m_name == "3003339" || m_name == "5128261" || m_name == "1304775"
            || m_name == "5000708" || m_name == "2975133")
        {
            std::cerr << "Outside for loop" << std::endl;
        }
        std::cout << m_name << "\t" << occur << std::endl;
        occur = -1;
        m_removed = true;
        for (auto&& relative : relatives) {
            relative->occur--;
            if (relative->occur <= 0) relative->m_removed = true;
            if (relative->m_name == "3003339" || relative->m_name == "5128261"
                || relative->m_name == "1304775"
                || relative->m_name == "5000708"
                || relative->m_name == "2975133")
            {
                std::cerr << "Relative reduce: " << m_name << "\t" << occur
                          << "\t" << relative->m_name << "\t" << relative->occur
                          << "\t" << relative->rand_number << "\t"
                          << rand_number << std::endl;
            }
        }
        std::sort(relatives.begin(), relatives.end(), Sample::compare_sample);
        for (auto&& relative : relatives) {
            if (!relative->removed() && relative->occur > 0) {
                if (relative->m_name == "3003339"
                    || relative->m_name == "5128261"
                    || relative->m_name == "1304775"
                    || relative->m_name == "5000708"
                    || relative->m_name == "2975133")
                {
                    std::cerr << "Start remove relative" << std::endl;
                }
                relative->remove();
            }
        }
        return occur;
    }

    std::string debug() const
    {
        std::string ocur;           // string which will contain the result
        std::ostringstream convert; // stream used for the conversion
        convert << occur; // insert the textual representation of 'Number' in
                          // the characters in the stream
        ocur = convert.str();
        return m_name + " " + ocur;
    }

    static bool compare_sample(Sample const* a, Sample const* b)
    {
        if (a->occur == b->occur) {
            if (a->phenotype == b->phenotype) {
                if (a->rand_number == b->rand_number) {
                    return a->m_name > b->m_name;
                }
                else
                    return a->rand_number > b->rand_number;
            }
            else
                return a->phenotype < b->phenotype;
        }
        else
            return a->occur > b->occur;
    }

    int get_occur() const { return occur; }
    std::string get_name() const { return m_name; }
    bool removed() const
    {
        // add additional condition where the current sample is removed
        if (occur == 0) return true;
        return m_removed;
    }

private:
    std::vector<Sample*> relatives;
    std::string m_name;
    double phenotype;
    double rand_number; // This is a random number to solve the tie
    int occur;
    bool m_removed = true; // so any samples with invalid pairs will be ignoreds
};

void usage()
{
    fprintf(stderr, " GreedyRelate\n");
    fprintf(stderr, " Sam Choi\n");
    fprintf(stderr, " v1.1.1 ( 2018-01-23 )\n");
    fprintf(stderr, " ==============================\n");
    fprintf(stderr, " This programme will try to minize the number of samples "
                    "that need to\n");
    fprintf(stderr, " be removed due to relatedness\n");
    fprintf(stderr,
            " Samples that should be removed are output to the STDOUT\n ");
    fprintf(stderr, " \n");
    fprintf(stderr, " Usage: GreedyRelate [options] -r <relatedness>\n");
    fprintf(stderr, "       -r | --relate      Relationship file (Required)\n");
    fprintf(stderr, "       -p | --pheno       Phenotype file\n");
    fprintf(stderr, "       -t | --threshold   Relatedness Threshold\n");
    fprintf(stderr,
            "       -s | --seed        Seed for the random number generator\n");
    fprintf(stderr,
            "       -h | --help        Display this help message\n\n\n");
    fprintf(stderr, " Details:\n");
    fprintf(stderr,
            "       Relationship file should have the following format:\n");
    fprintf(stderr, "       ID    Pair    Factor\n\n");
    fprintf(stderr, "       We do assume there is a header line\n\n");
    fprintf(stderr,
            "       Phenotype file should have the following format:\n");
    fprintf(stderr, "       ID    Pheno\n\n");
    fprintf(stderr, "       Again, we do assume there is a header line\n");
    fprintf(stderr,
            "       Note: Phenotype information only used to decide which\n");
    fprintf(stderr,
            "             samples to leave behind when there is a tie,\n");
    fprintf(stderr,
            "             where sample with higher phenotype value will be\n");
    fprintf(stderr, "             retained.\n");
    fprintf(stderr,
            "             When no phenotype information is provided, \n");
    fprintf(stderr,
            "             we will randomly select one sample to remove\n");
}

int main(int argc, char* argv[])
{
    if (argc <= 1) {
        usage();
        exit(0);
    }
    static const char* optString = "r:p:t:s:n:h?";
    static const struct option longOpts[] = {
        {"relate", required_argument, nullptr, 'r'},
        {"pheno", required_argument, nullptr, 'p'},
        {"threshold", required_argument, nullptr, 't'},
        {"thread", required_argument, nullptr, 'n'},
        {"seed", required_argument, nullptr, 't'},
        {"help", no_argument, nullptr, 'h'},
        {nullptr, 0, 0, 0}};
    std::string relate_name = "";
    std::string pheno_name = "";
    bool provide_seed = false;
    int seed = 0;
    int thread = 1;
    double threshold = 0.0;
    int longIndex = 0;
    int opt = 0;
    opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
    while (opt != -1) {
        switch (opt)
        {
        case 'r': relate_name = optarg; break;
        case 'p': pheno_name = optarg; break;
        case 't':
            threshold = atof(optarg);
            if (threshold <= 0.0)
                fprintf(stderr,
                        "WARNING: Threshold = %f, will not filter samples\n",
                        threshold);
            break;
        case 's':
            try
            {
                int temp = misc::convert<int>(optarg);
                provide_seed = true;
                seed = temp;
            }
            catch (const std::runtime_error&)
            {
                fprintf(stderr, "Cannot parse the seed into number, will not "
                                "use the provided seed\n");
            }
            break;
        case 'n':
            try
            {
                int temp = misc::convert<int>(optarg);
                thread = temp;
            }
            catch (const std::runtime_error&)
            {
                fprintf(stderr, "Cannot parse the thread into number, will "
                                "only use 1 thread\n");
            }
            if (thread <= 0) {
                fprintf(stderr, "Number of thread must be larger than 0. Will "
                                "use only 1 thread\n");
            }
            break;
        case 'h':
        case '?':
            usage();
            return 0;
            break;
        default:
            throw "Undefined operator, please use --help for more "
                  "information!";
        }
        opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
    }

    std::string line;
    std::unordered_map<std::string, double> phenotype;
    if (!pheno_name.empty()) {
        std::ifstream pheno_file;
        pheno_file.open(pheno_name.c_str());
        if (!pheno_file.is_open()) {
            fprintf(stderr, "ERROR: Cannot open phenotype file %s\n",
                    pheno_name.c_str());
            exit(-1);
        }
        // Assumine phenotype has header?
        getline(pheno_file, line);
        while (getline(pheno_file, line)) {
            misc::trim(line);
            if (line.empty()) continue;
            std::vector<std::string> token = misc::split(line);
            if (token.size() < 2) {
                fprintf(stderr, "ERROR: Phenotype file format incorrect! "
                                "Require at least 2 columns\n");
                exit(-1);
            }
            try
            {
                double factor = 0.0;
                if (token[1].compare("NA") == 0 || token[1].compare("na") == 0)
                    factor = -9;
                else
                    factor = misc::convert<double>(token[1]);
                if (phenotype.find(token[0]) != phenotype.end())
                    fprintf(stderr, "WARNING: Duplicated sample id: %s\n",
                            token[0].c_str());
                phenotype[token[0]] = factor;
            }
            catch (const std::runtime_error& error)
            {
                fprintf(stderr, "ERROR: Undefined factor number\n");
            }
        }
        pheno_file.close();
    }

    std::random_device::result_type cur_seed = std::random_device()();
    ;
    if (provide_seed) cur_seed = seed;
    fprintf(stderr, "Seed used: %d\n", cur_seed);
    std::mt19937 rand_gen(cur_seed);
    std::uniform_real_distribution<double> distribution(0.0, 1.0);
    // Read relationship file
    std::ifstream relate;
    relate.open(relate_name.c_str());
    if (!relate.is_open()) {
        fprintf(stderr, "ERROR: Cannot open relationship file %s\n",
                relate_name.c_str());
        exit(-1);
    }
    std::vector<Sample*> sample_list;
    std::unordered_map<std::string, size_t> sample_index;
    std::unordered_map<size_t, size_t> direction; // First size_t = pair, second
                                                  // size_t = index of the
                                                  // neighbour

    // Assume there is a header
    // Or we can add in
    fprintf(stderr,
            "Assuming there is a header file for the relatedness file\n");
    getline(relate, line);
    std::vector<std::string> token;
    size_t sample_idx = 0;
    while (getline(relate, line)) {
        misc::trim(line);
        if (line.empty()) continue;
        token = misc::split(line);
        if (token.size() != 3) {
            fprintf(stderr, "ERROR: Relationship file format incorrect! "
                            "Require 3 columns\n");
            exit(-1);
        }
        std::string id = token[0];
        size_t pair = 0;
        double factor = 0.0;
        try
        {
            pair = misc::convert<size_t>(token[1]);
            factor = misc::convert<double>(token[2]);
        }
        catch (const std::runtime_error& error)
        {
            fprintf(stderr, "ERROR: Cannot convert some of the information in "
                            "the relationship file\n");
            fprintf(stderr, "Input: %s\n", line.c_str());
            exit(-1);
        }
        // Now we have id pair and factor
        // Ignore any pairs with relatedness less than our threshold
        if (factor <= threshold) continue;
        double pheno = -9;
        if (phenotype.find(id) != phenotype.end()) pheno = phenotype[id];
        if (sample_index.find(id) == sample_index.end()) {
            // this is a new sample
            sample_list.push_back(
                new Sample(id, pheno, distribution(rand_gen)));
            sample_index[id] = sample_idx;
            ++sample_idx;
        }
        // worst case scenario in UKBB -> 109 relatives
        // still better than resorting the whole vector
        if (direction.find(pair) != direction.end()) {
            // this is not a new pair
            size_t dir_id = direction[pair];
            size_t sam_id = sample_index[id];
            sample_list[dir_id]->add(sample_list[sam_id]);
            sample_list[sam_id]->add(sample_list[dir_id]);
        }
        else
        {
            // a new pair is located
            direction[pair] = sample_index[id];
        }
    }
    // Update phenotype informations
    sample_index.clear();
    std::sort(sample_list.begin(), sample_list.end(), Sample::compare_sample);
    for (auto&& sample : sample_list) {
        if (sample->removed()) continue;
        sample->remove();
    }
    return 0;
}
<commit_msg>Update organization<commit_after>//
//  main.cpp
//  greedRelate
//  Greedy approach of keeping samples
//  Created by Shing Wan Choi on 18/08/2016.
//  Copyright © 2016 Shing Wan Choi. All rights reserved.
//

#include "misc.hpp"
#include <algorithm>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <unordered_map>
#include <vector>

class Sample
{
public:
    // First occurance = itself, therefore occurance = 0
    Sample(std::string name, double pheno, double rand)
        : m_name(name), phenotype(pheno), rand_number(rand)
    {
        occur = 0;
    }
    // add a relative to the current sample
    int add(Sample* related)
    {
        // not sure why
        // TODO: See if we can skip the step of pushing nullptr
        relatives.push_back(nullptr);
        relatives.back() = related;
        m_removed = false;
        occur++;
        return occur;
    }
    int remove()
    {
        // we are going to start cleaning up these relatives.
        // good thing is that the size of this vector will small
        // check if any relatives have more than us. If not, then proceed,
        // otherwise, return
        for (auto&& relative : relatives) {
            if (!relative->removed()
                && (relative->occur > occur
                    || (relative->occur == occur
                        && relative->phenotype < phenotype)
                    || (relative->occur == occur
                        && relative->rand_number > rand_number)
                    || (relative->occur == occur
                        && relative->rand_number == rand_number
                        && relative->m_name > m_name)))
            {
                return 0;
            }
        }
        std::cout << m_name << "\t" << occur << std::endl;
        occur = -1;
        m_removed = true;
        for (auto&& relative : relatives) {
            relative->occur--;
            if (relative->occur <= 0) relative->m_removed = true;
        }
        std::sort(relatives.begin(), relatives.end(), Sample::compare_sample);
        for (auto&& relative : relatives) {
            if (!relative->removed() && relative->occur > 0) {
                relative->remove();
            }
        }
        return occur;
    }

    std::string debug() const
    {
        std::string ocur;           // string which will contain the result
        std::ostringstream convert; // stream used for the conversion
        convert << occur; // insert the textual representation of 'Number' in
                          // the characters in the stream
        ocur = convert.str();
        return m_name + " " + ocur;
    }

    static bool compare_sample(Sample const* a, Sample const* b)
    {
        if (a->occur == b->occur) {
            if (a->phenotype == b->phenotype) {
                if (a->rand_number == b->rand_number) {
                    return a->m_name > b->m_name;
                }
                else
                    return a->rand_number > b->rand_number;
            }
            else
                return a->phenotype < b->phenotype;
        }
        else
            return a->occur > b->occur;
    }

    int get_occur() const { return occur; }
    std::string get_name() const { return m_name; }
    bool removed() const
    {
        // add additional condition where the current sample is removed
        if (occur == 0) return true;
        return m_removed;
    }

private:
    std::vector<Sample*> relatives;
    std::string m_name;
    double phenotype;
    double rand_number; // This is a random number to solve the tie
    int occur;
    bool m_removed = true; // so any samples with invalid pairs will be ignoreds
};

void usage()
{
    fprintf(stderr, " GreedyRelate\n");
    fprintf(stderr, " Sam Choi\n");
    fprintf(stderr, " v1.1.1 ( 2018-01-23 )\n");
    fprintf(stderr, " ==============================\n");
    fprintf(stderr, " This programme will try to minize the number of samples "
                    "that need to\n");
    fprintf(stderr, " be removed due to relatedness\n");
    fprintf(stderr,
            " Samples that should be removed are output to the STDOUT\n ");
    fprintf(stderr, " \n");
    fprintf(stderr, " Usage: GreedyRelate [options] -r <relatedness>\n");
    fprintf(stderr, "       -r | --relate      Relationship file (Required)\n");
    fprintf(stderr, "       -p | --pheno       Phenotype file\n");
    fprintf(stderr, "       -t | --threshold   Relatedness Threshold\n");
    fprintf(stderr,
            "       -s | --seed        Seed for the random number generator\n");
    fprintf(stderr,
            "       -h | --help        Display this help message\n\n\n");
    fprintf(stderr, " Details:\n");
    fprintf(stderr,
            "       Relationship file should have the following format:\n");
    fprintf(stderr, "       ID    Pair    Factor\n\n");
    fprintf(stderr, "       We do assume there is a header line\n\n");
    fprintf(stderr,
            "       Phenotype file should have the following format:\n");
    fprintf(stderr, "       ID    Pheno\n\n");
    fprintf(stderr, "       Again, we do assume there is a header line\n");
    fprintf(stderr,
            "       Note: Phenotype information only used to decide which\n");
    fprintf(stderr,
            "             samples to leave behind when there is a tie,\n");
    fprintf(stderr,
            "             where sample with higher phenotype value will be\n");
    fprintf(stderr, "             retained.\n");
    fprintf(stderr,
            "             When no phenotype information is provided, \n");
    fprintf(stderr,
            "             we will randomly select one sample to remove\n");
}

int main(int argc, char* argv[])
{
    if (argc <= 1) {
        usage();
        exit(0);
    }
    static const char* optString = "r:p:t:s:n:h?";
    static const struct option longOpts[] = {
        {"relate", required_argument, nullptr, 'r'},
        {"pheno", required_argument, nullptr, 'p'},
        {"threshold", required_argument, nullptr, 't'},
        {"thread", required_argument, nullptr, 'n'},
        {"seed", required_argument, nullptr, 't'},
        {"help", no_argument, nullptr, 'h'},
        {nullptr, 0, nullptr, 0}};
    std::string relate_name = "";
    std::string pheno_name = "";
    bool provide_seed = false;
    int seed = 0;
    int thread = 1;
    double threshold = 0.0;
    int longIndex = 0;
    int opt = 0;
    opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
    while (opt != -1) {
        switch (opt)
        {
        case 'r': relate_name = optarg; break;
        case 'p': pheno_name = optarg; break;
        case 't':
            threshold = atof(optarg);
            if (threshold <= 0.0)
                fprintf(stderr,
                        "WARNING: Threshold = %f, will not filter samples\n",
                        threshold);
            break;
        case 's':
            try
            {
                int temp = misc::convert<int>(optarg);
                provide_seed = true;
                seed = temp;
            }
            catch (const std::runtime_error&)
            {
                fprintf(stderr, "Cannot parse the seed into number, will not "
                                "use the provided seed\n");
            }
            break;
        case 'n':
            try
            {
                int temp = misc::convert<int>(optarg);
                thread = temp;
            }
            catch (const std::runtime_error&)
            {
                fprintf(stderr, "Cannot parse the thread into number, will "
                                "only use 1 thread\n");
            }
            if (thread <= 0) {
                fprintf(stderr, "Number of thread must be larger than 0. Will "
                                "use only 1 thread\n");
            }
            break;
        case 'h':
        case '?':
            usage();
            return 0;
            break;
        default:
            throw "Undefined operator, please use --help for more "
                  "information!";
        }
        opt = getopt_long(argc, argv, optString, longOpts, &longIndex);
    }

    std::string line;
    std::unordered_map<std::string, double> phenotype;
    if (!pheno_name.empty()) {
        std::ifstream pheno_file;
        pheno_file.open(pheno_name.c_str());
        if (!pheno_file.is_open()) {
            fprintf(stderr, "ERROR: Cannot open phenotype file %s\n",
                    pheno_name.c_str());
            exit(-1);
        }
        // Assumine phenotype has header?
        getline(pheno_file, line);
        while (getline(pheno_file, line)) {
            misc::trim(line);
            if (line.empty()) continue;
            std::vector<std::string> token = misc::split(line);
            if (token.size() < 2) {
                fprintf(stderr, "ERROR: Phenotype file format incorrect! "
                                "Require at least 2 columns\n");
                exit(-1);
            }
            try
            {
                double factor = 0.0;
                if (token[1].compare("NA") == 0 || token[1].compare("na") == 0)
                    factor = -9;
                else
                    factor = misc::convert<double>(token[1]);
                if (phenotype.find(token[0]) != phenotype.end())
                    fprintf(stderr, "WARNING: Duplicated sample id: %s\n",
                            token[0].c_str());
                phenotype[token[0]] = factor;
            }
            catch (const std::runtime_error&)
            {
                fprintf(stderr, "ERROR: Undefined factor number\n");
            }
        }
        pheno_file.close();
    }

    std::random_device::result_type cur_seed = std::random_device()();
    ;
    if (provide_seed)
        cur_seed = static_cast<std::random_device::result_type>(seed);
    fprintf(stderr, "Seed used: %d\n", cur_seed);
    std::mt19937 rand_gen(cur_seed);
    std::uniform_real_distribution<double> distribution(0.0, 1.0);
    // Read relationship file
    std::ifstream relate;
    relate.open(relate_name.c_str());
    if (!relate.is_open()) {
        fprintf(stderr, "ERROR: Cannot open relationship file %s\n",
                relate_name.c_str());
        exit(-1);
    }
    std::vector<Sample*> sample_list;
    std::unordered_map<std::string, size_t> sample_index;
    std::unordered_map<size_t, size_t> direction; // First size_t = pair, second
                                                  // size_t = index of the
                                                  // neighbour

    // Assume there is a header
    // Or we can add in
    fprintf(stderr,
            "Assuming there is a header file for the relatedness file\n");
    getline(relate, line);
    std::vector<std::string> token;
    size_t sample_idx = 0;
    while (getline(relate, line)) {
        misc::trim(line);
        if (line.empty()) continue;
        token = misc::split(line);
        if (token.size() != 3) {
            fprintf(stderr, "ERROR: Relationship file format incorrect! "
                            "Require 3 columns\n");
            exit(-1);
        }
        std::string id = token[0];
        size_t pair = 0;
        double factor = 0.0;
        try
        {
            pair = misc::convert<size_t>(token[1]);
            factor = misc::convert<double>(token[2]);
        }
        catch (const std::runtime_error&)
        {
            fprintf(stderr, "ERROR: Cannot convert some of the information in "
                            "the relationship file\n");
            fprintf(stderr, "Input: %s\n", line.c_str());
            exit(-1);
        }
        // Now we have id pair and factor
        // Ignore any pairs with relatedness less than our threshold
        if (factor <= threshold) continue;
        double pheno = -9;
        if (phenotype.find(id) != phenotype.end()) pheno = phenotype[id];
        if (sample_index.find(id) == sample_index.end()) {
            // this is a new sample
            sample_list.push_back(
                new Sample(id, pheno, distribution(rand_gen)));
            sample_index[id] = sample_idx;
            ++sample_idx;
        }
        // worst case scenario in UKBB -> 109 relatives
        // still better than resorting the whole vector
        if (direction.find(pair) != direction.end()) {
            // this is not a new pair
            size_t dir_id = direction[pair];
            size_t sam_id = sample_index[id];
            sample_list[dir_id]->add(sample_list[sam_id]);
            sample_list[sam_id]->add(sample_list[dir_id]);
        }
        else
        {
            // a new pair is located
            direction[pair] = sample_index[id];
        }
    }
    // Update phenotype informations
    sample_index.clear();
    std::sort(sample_list.begin(), sample_list.end(), Sample::compare_sample);
    for (auto&& sample : sample_list) {
        if (sample->removed()) continue;
        sample->remove();
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <SFML/Window.hpp>
#include <GL/glew.h>
#include <iostream>
#include <string>
#include <vector>

#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"

void loadShader(GLuint &program)
{
    GLint compile_ok = GL_FALSE, link_ok = GL_FALSE;

    // Vertex
    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    const char *vs_source =
        "#version 120\n"
        "attribute vec2 coord2d;                  "
        "void main(void) {                        "
        "  gl_Position = vec4(coord2d, 0.0, 1.0); "
        "}";
    glShaderSource(vs, 1, &vs_source, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &compile_ok);
    if (!compile_ok)
        throw std::runtime_error("Error in vertex shader");

    // Fragment
    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    const char *fs_source =
        "#version 120\n"
        "void main(void) {        "
        "  gl_FragColor[0] = 0.3; "
        "  gl_FragColor[1] = 1.0; "
        "  gl_FragColor[2] = 0.3; "
        "}";
    glShaderSource(fs, 1, &fs_source, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &compile_ok);
    if (!compile_ok)
        throw std::runtime_error("Error in fragment shader");

    program = glCreateProgram();
    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &link_ok);
    if (!link_ok)
        throw std::runtime_error("Error in glLinkProgram");

    const char* attribute_name = "coord2d";
}

int main()
{

    /*
    //Buffer
    glGenBuffers(1, &vbo_triangle);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_triangle);
    static const GLfloat triangle_vertices[] =
    {
    0.0,	0.8,
    -0.8,	-0.8,
    0.8, 	-0.8,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_vertices), triangle_vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(attribute_coord2d, 2, GL_FLOAT, GL_FALSE, 0, 0);

    // Some useful info
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
    std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

*/

    std::string inputfile = "models/rungholt/rungholt.obj";
    std::vector<tinyobj::shape_t> shapes;
    std::vector<tinyobj::material_t> materials;

    std::string err;
    bool ret = tinyobj::LoadObj(shapes, materials, err, inputfile.c_str(),"models/rungholt/materials/");

    if (!err.empty()) { // `err` may contain warning message.
        std::cerr << err << std::endl;
    }

    if (!ret) {
        exit(1);
    }

    std::cout << "# of shapes    : " << shapes.size() << std::endl;
    std::cout << "# of materials : " << materials.size() << std::endl;

    for (size_t i = 0; i < shapes.size(); i++)
    {
        printf("shape[%ld].name = %s\n",
                i, shapes[i].name.c_str());
        printf("Size of shape[%ld].indices: %ld\n",
                i, shapes[i].mesh.indices.size());
        printf("Size of shape[%ld].material_ids: %ld\n",
                i, shapes[i].mesh.material_ids.size());

        assert((shapes[i].mesh.indices.size() % 3) == 0);

        for (size_t f = 0; f < shapes[i].mesh.indices.size() / 3; f++)
        {
            printf("  idx[%ld] = %d, %d, %d. mat_id = %d\n",
                    f, shapes[i].mesh.indices[3*f+0],
                    shapes[i].mesh.indices[3*f+1],
                    shapes[i].mesh.indices[3*f+2],
                    shapes[i].mesh.material_ids[f]);
        }

        printf("shape[%ld].vertices: %ld\n",
                i, shapes[i].mesh.positions.size());

        assert((shapes[i].mesh.positions.size() % 3) == 0);

        for (size_t v = 0; v < shapes[i].mesh.positions.size() / 3; v++)
        {
            printf("  v[%ld] = (%f, %f, %f)\n", v,
                    shapes[i].mesh.positions[3*v+0],
                    shapes[i].mesh.positions[3*v+1],
                    shapes[i].mesh.positions[3*v+2]);
        }
    }

    for (size_t i = 0; i < materials.size(); i++) {
        printf("material[%ld].name = %s\n", i, materials[i].name.c_str());
        printf("  material.Ka = (%f, %f ,%f)\n", materials[i].ambient[0], materials[i].ambient[1], materials[i].ambient[2]);
        printf("  material.Kd = (%f, %f ,%f)\n", materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]);
        printf("  material.Ks = (%f, %f ,%f)\n", materials[i].specular[0], materials[i].specular[1], materials[i].specular[2]);
        printf("  material.Tr = (%f, %f ,%f)\n", materials[i].transmittance[0], materials[i].transmittance[1], materials[i].transmittance[2]);
        printf("  material.Ke = (%f, %f ,%f)\n", materials[i].emission[0], materials[i].emission[1], materials[i].emission[2]);
        printf("  material.Ns = %f\n", materials[i].shininess);
        printf("  material.Ni = %f\n", materials[i].ior);
        printf("  material.dissolve = %f\n", materials[i].dissolve);
        printf("  material.illum = %d\n", materials[i].illum);
        printf("  material.map_Ka = %s\n", materials[i].ambient_texname.c_str());
        printf("  material.map_Kd = %s\n", materials[i].diffuse_texname.c_str());
        printf("  material.map_Ks = %s\n", materials[i].specular_texname.c_str());
        printf("  material.map_Ns = %s\n", materials[i].specular_highlight_texname.c_str());
        std::map<std::string, std::string>::const_iterator it(materials[i].unknown_parameter.begin());
        std::map<std::string, std::string>::const_iterator itEnd(materials[i].unknown_parameter.end());
        for (; it != itEnd; it++) {
            printf("  material.%s = %s\n", it->first.c_str(), it->second.c_str());
        }
        printf("\n");
    }

    GLuint program;
    GLuint vbo_triangle;
    GLint attribute_coord2d;
    GLuint vaoIds[shapes.size()];
    GLuint vboIds[shapes.size()];
    sf::Window window(sf::VideoMode(800,600),"NetroTD",sf::Style::Default);

    // Load glew
    GLenum glew_status = glewInit();
    if (glew_status != GLEW_OK)
        throw std::runtime_error("Glewinit");

    // Load Shader
    loadShader(program);

    attribute_coord2d = glGetAttribLocation(program, "coord2d");
    if (attribute_coord2d == -1)
        throw std::runtime_error("Could not bind attribute");

    for(int i = 0; i < shapes.size(); ++i)
    {
        glGenVertexArrays(1,&vaoIds[i]);
        glBindVertexArray(vaoIds[i]);

        glGenBuffers(1,&vboIds[i]);
        glBindBuffer(GL_ARRAY_BUFFER,vboIds[i]);
        glBufferData(GL_ARRAY_BUFFER,shapes[i].mesh.num_vertices.size() * sizeof(shapes[i].mesh.num_vertices[0]),&shapes[i].mesh.num_vertices[0], GL_STATIC_DRAW);
    }
    while (true)
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                glDeleteProgram(program);
                return EXIT_SUCCESS;
            }

            else if (event.type == sf::Event::Resized)
                glViewport(0, 0, event.size.width, event.size.height);
        }

        // Clear
        glClearColor(0, 0, 0, 1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(program);

        //glColor3f(0,1,0);
        for(int i = 0; i < shapes.size();++i)
        {
            glBindBuffer(GL_ARRAY_BUFFER, vboIds[i]);
            //glEnableVertexAttribArray(attribute_coord2d);

            // Draw
            glDrawArrays(GL_TRIANGLES, 0, shapes[i].mesh.num_vertices.size());
        }
        glBindVertexArray(0);
        //glDisableVertexAttribArray(attribute_coord2d);
        glUseProgram(0);

        // Refresh window
        window.display();
    }

}
<commit_msg>revert to triangle<commit_after>#include <SFML/Window.hpp>
#include <GL/glew.h>
#include <iostream>

void loadShader(GLuint &program)
{
	GLint compile_ok = GL_FALSE, link_ok = GL_FALSE;

	// Vertex
	GLuint vs = glCreateShader(GL_VERTEX_SHADER);
	const char *vs_source =
		"#version 120\n"
		"attribute vec2 coord2d;                  "
		"void main(void) {                        "
		"  gl_Position = vec4(coord2d, 0.0, 1.0); "
		"}";
	glShaderSource(vs, 1, &vs_source, NULL);
	glCompileShader(vs);
	glGetShaderiv(vs, GL_COMPILE_STATUS, &compile_ok);
	if (!compile_ok)
		throw std::runtime_error("Error in vertex shader");

	// Fragment
	GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
	const char *fs_source =
		"#version 120\n"
		"void main(void) {        "
		"  gl_FragColor[0] = 0.3; "
		"  gl_FragColor[1] = 1.0; "
		"  gl_FragColor[2] = 0.3; "
		"}";
	glShaderSource(fs, 1, &fs_source, NULL);
	glCompileShader(fs);
	glGetShaderiv(fs, GL_COMPILE_STATUS, &compile_ok);
	if (!compile_ok)
		throw std::runtime_error("Error in fragment shader");

	program = glCreateProgram();
	glAttachShader(program, vs);
	glAttachShader(program, fs);
	glLinkProgram(program);
	glGetProgramiv(program, GL_LINK_STATUS, &link_ok);
	if (!link_ok)
		throw std::runtime_error("Error in glLinkProgram");

	const char* attribute_name = "coord2d";
}

int main()
{
	GLuint program;
	GLuint vbo_triangle;
	GLint attribute_coord2d;

	sf::Window window(sf::VideoMode(800,600),"NetroTD",sf::Style::Default);

	// Load glew
	GLenum glew_status = glewInit();
	if (glew_status != GLEW_OK)
		throw std::runtime_error("Glewinit");

	// Load Shader
	loadShader(program);

	attribute_coord2d = glGetAttribLocation(program, "coord2d");
	if (attribute_coord2d == -1)
		throw std::runtime_error("Could not bind attribute");

	//Buffer
	glGenBuffers(1, &vbo_triangle);
	glBindBuffer(GL_ARRAY_BUFFER, vbo_triangle);
	static const GLfloat triangle_vertices[] =
	{
		0.0,	0.8,
		-0.8,	-0.8,
		0.8, 	-0.8,
	};
	glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_vertices), triangle_vertices, GL_STATIC_DRAW);
	glVertexAttribPointer(attribute_coord2d, 2, GL_FLOAT, GL_FALSE, 0, 0);

	// Some useful info
	std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
    std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

	while (true)
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
			{
				glDeleteProgram(program);
				return EXIT_SUCCESS;
			}

            else if (event.type == sf::Event::Resized)
                glViewport(0, 0, event.size.width, event.size.height);
        }

		// Clear
		glClearColor(0, 0, 0, 1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glUseProgram(program);
		glBindBuffer(GL_ARRAY_BUFFER, vbo_triangle);
		glEnableVertexAttribArray(attribute_coord2d);

		// Draw
		glDrawArrays(GL_TRIANGLES, 0, 6);

		glDisableVertexAttribArray(attribute_coord2d);
		glUseProgram(0);

		// Refresh window
        window.display();
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <malloc.h>
#ifdef _MSC_VER
extern "C"
{
#include <stdlib.h>
}
#define alignedMalloc(size,align)	_aligned_malloc(size,align)
#elif defined (__GNUC__)
#define alignedMalloc(size,align)	memalign(align,size)
#endif
#include "floatMul.h"

const int ALIGN   = 32; // alignment step for SSE
const int cWidth  = 256;
const int cHeight = cWidth;
const int cSize   = cHeight * cWidth;

bool examineTest(unsigned char *result, unsigned char *result_examine, int cSize)
{
	bool flag = true;
	int i = 0;
	for (i = 0;i < cSize;i++)
	{
		if (result[i] != result_examine[i])
		{
			flag = false;
			break;
		}
	}
	if (flag == false)
	{
		std::cout << "Failed on " << i << " expected:" << result_examine[i] << " actual:" << result[i] << std::endl;
	}
	return flag;
}

int main()
{
	unsigned char* image =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	short* gain  =reinterpret_cast<short*>(alignedMalloc(cSize*2,ALIGN));
	float* gainOriginal = reinterpret_cast<float*>(alignedMalloc(cSize*4,ALIGN));
	unsigned char* result =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	unsigned char* result_examine =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	for (unsigned int i = 0;i < cSize;i++)
	{
		gainOriginal[i] = 1.0f;
		image[i] = (i & 255);
	}
	float2half(gainOriginal, gain, cSize);
	multiply(image, gain, result, cSize);
	multiply_float(image, gainOriginal, result_examine, cSize);
	examineTest(result, result_examine, cSize);
	return 0;
}
<commit_msg>show success message when test passed<commit_after>#include <iostream>
#include <iomanip>
#include <malloc.h>
#ifdef _MSC_VER
extern "C"
{
#include <stdlib.h>
}
#define alignedMalloc(size,align)	_aligned_malloc(size,align)
#elif defined (__GNUC__)
#define alignedMalloc(size,align)	memalign(align,size)
#endif
#include "floatMul.h"

const int ALIGN   = 32; // alignment step for SSE
const int cWidth  = 256;
const int cHeight = cWidth;
const int cSize   = cHeight * cWidth;

bool examineTest(unsigned char *result, unsigned char *result_examine, int cSize)
{
	bool flag = true;
	int i = 0;
	for (i = 0;i < cSize;i++)
	{
		if (result[i] != result_examine[i])
		{
			flag = false;
			break;
		}
	}
	if (flag == false)
	{
		std::cout << "Failed on " << i << " expected:" << result_examine[i] << " actual:" << result[i] << std::endl;
	}
	return flag;
}

int main()
{
	unsigned char* image =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	short* gain  =reinterpret_cast<short*>(alignedMalloc(cSize*2,ALIGN));
	float* gainOriginal = reinterpret_cast<float*>(alignedMalloc(cSize*4,ALIGN));
	unsigned char* result =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	unsigned char* result_examine =reinterpret_cast<unsigned char*>(alignedMalloc(cSize,ALIGN));
	for (unsigned int i = 0;i < cSize;i++)
	{
		gainOriginal[i] = 1.0f;
		image[i] = (i & 255);
	}
	float2half(gainOriginal, gain, cSize);
	multiply(image, gain, result, cSize);
	multiply_float(image, gainOriginal, result_examine, cSize);
	if (examineTest(result, result_examine, cSize))
	{
		std::cout << "test passed" << std::endl;
		return 0;
	}
	else
	{
		return 1;
	}
}
<|endoftext|>


<commit_before>
#include <execinfo.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memset
#include <sys/stat.h> // struct stat

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <string>

#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/shared_ptr.hpp>

#include "event2/event.h"
#include "event2/bufferevent.h"

#include <google/protobuf/descriptor.h>
#include <gtest/gtest.h>

#include "auto_mysql.h"
#include "odbcdatasources.h"

#include "person.pb.h"
#include "wozconfig.pb.h"
#include "wozstatus.pb.h"

//#include <gflags/gflags.h>

using namespace std;
//using namespace boost;
using namespace google;
using namespace google::protobuf;

inline string
render_si_value(double value) {
	int si_unit = 0;
	static const char *si_units[] = {"","k","M","G","T","P","E","Z","Y"};
	while (1000 <= value) {
		++si_unit;
		value /= 1000;
	}
	stringstream tmp;
	tmp << fixed << setprecision(1) << value << si_units[si_unit];
	return tmp.str();
}

//// variadic template
//void
//output() { cout << "\n"; }
//
//// variadic template
//template<class T, class ...Args>
//void
//output(T cls, Args ...args) {
//	cout << cls << " ";
//	if (sizeof...(args) == 0)
//		cout << "\n";
//	else
//		output(args...);
//}

// gets the scalar field value
static string
GetFieldValue(Message *message, const FieldDescriptor *field) {
	switch (field->cpp_type()) {
	case FieldDescriptor::CPPTYPE_BOOL:
		return boost::lexical_cast<string>(message->GetReflection()->GetBool((*message), field));
	case FieldDescriptor::CPPTYPE_INT32:
		return boost::lexical_cast<string>(message->GetReflection()->GetInt32((*message), field));
	case FieldDescriptor::CPPTYPE_UINT64:
		return boost::lexical_cast<string>(message->GetReflection()->GetUInt64((*message), field));
	case FieldDescriptor::CPPTYPE_STRING:
		return boost::lexical_cast<string>(message->GetReflection()->GetString((*message), field));
	default:
		throw runtime_error(field->name());
	}
}

// sets the scalar value/adds to the columnar value (i.e., field can be a repeated field)
static void
SetFieldValue(Message *message, const FieldDescriptor *field, const string& value) {
	switch (field->cpp_type()) {
	case FieldDescriptor::CPPTYPE_BOOL:
		if (field->is_repeated())
			message->GetReflection()->AddBool(message, field, boost::lexical_cast<bool>(value));
		else
			message->GetReflection()->SetBool(message, field, boost::lexical_cast<bool>(value));
		break;
	case FieldDescriptor::CPPTYPE_STRING:
		if (field->is_repeated())
			message->GetReflection()->AddString(message, field, value);
		else
			message->GetReflection()->SetString(message, field, value);
		break;
	default:
		throw runtime_error(field->name()+value);
	}
}

struct OWReadConfigVisitor {
	::google::protobuf::Message *config;
	OWReadConfigVisitor(::google::protobuf::Message *config): config(config) {
	}
	void operator()(map<string, string> row) {
		//ComponentURI|RowId|name|status=active|value
		string name(row["name"]);
		string value(row["value"]);

		match_results<const char *> results;
		regex re("([a-z]+_[a-zA-Z0-9]+)_([0-9]+)"); // e.g., foo_barBaz_1
		if (regex_match(name.c_str(), results, re))
			name = results[1].str(); // e.g., foo_barBaz

		const FieldDescriptor *field = config->GetDescriptor()->FindFieldByName(name);
		if (field)
			SetFieldValue(config, field, value); // works for scalars and columnars
	}
};

/**
 * reads the given iVOG_Config config
 *
 * @param dsn e.g., "OWConfig"
 * @param config
 * @param component_uri e.g., "foo/ch01/sl02/vm3/4"
 */
inline void
OWReadConfig(string dsn, ::google::protobuf::Message *config, string component_uri) {
	auto_mysql handle(OdbcNewConnection(dsn));
	auto_mysql_stmt(handle.get(), "select * from OWConfig where ComponentURI=?", component_uri).execute(OWReadConfigVisitor(config));
}

/**
 * writes the given iVOG_Status status
 *
 * @param dsn e.g., "OWZzzStatus"
 * @param status
 * @param component_uri e.g., "foo/ch01/sl02/vm3/4"
 */
inline void
OWWriteStatus(string dsn, ::google::protobuf::Message *status, string component_uri) {
	auto_mysql handle(OdbcNewConnection(dsn));
	int last_row_id(auto_mysql_stmt(handle.get(), "select coalesce(max(RowId),0) from OWStatus").execute(query_for<int>()).result);
	int new_group_id(auto_mysql_stmt(handle.get(), "select coalesce(max(GroupId),0) from OWStatus").execute(query_for<int>()).result + 1);
	for (int index = 0; index < status->GetDescriptor()->field_count(); ++index) {
		const FieldDescriptor *field = status->GetDescriptor()->field(index);
		if (status->GetReflection()->HasField(*status, field)) {
			string name(field->name());
			string value(GetFieldValue(status, field));
			string sql2("insert into OWStatus (RowId, GroupId, name, value, ComponentURI) values (?,?,?,?,?)");
			auto_mysql_stmt(handle.get(), sql2, ++last_row_id, new_group_id, name, value, component_uri).execute();
		}
	}
}

// Note- rhel54 bundles libboost 1.33, filesystem3 was introduced in libboost 1.44
#include <dirent.h>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

/**
 * Returns the cpu core count.
 */
static int
cpu_core_count() {
	int result = 0;
	regex re("cpu\\d");
	path dir("/sys/devices/system/cpu");
	for (directory_iterator iter(dir), iter_end; iter != iter_end; ++iter) {
		if (regex_search((*iter).path().c_str(), re))
			++result;
	}
	return result;
}

#include "auto_flags.h"

static auto_flags flags;

static int verbose=0;
static int version=0;
static int run_unit_tests=0;
static string listen_addr("0.0.0.0:8000"); // local http proxy listen addr
static string remote_addr("0.0.0.0:8001"); // remote dpp request addr
static string cores("0");

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

	// name, has_arg, flag, val

	add_no_argument(&flags, "verbose", &verbose, "enable verbose output");
	add_no_argument(&flags, "version", &version, "print version");

	add_no_argument(&flags, "run-unit-tests", &run_unit_tests, "run built-in unit-tests");

	add_required_argument(&flags, "cores", &cores, "number of cpu cores to use for media processing (0=auto detect)");
	add_required_argument(&flags, "listen", &listen_addr, "the local addr to use to receive http proxy requests");
	add_required_argument(&flags, "remote", &remote_addr, "the remote addr to use to send dpp requests");

	int arg = parse_auto_flags(&flags, argc, argv);

	while (arg < argc)
		printf("extra non-option ARGV-element: %s\n", argv[arg++]);

	print_auto_flags(&flags);

	auto_mysql handle(OdbcNewConnection("OWConfig"));
//	auto_mysql_stmt(handle.get(), "select * from OWConfig where ComponentURI=?", "foo").execute(print_rows());

	WozConfig config;
	OWReadConfig("OWConfig", &config, "foo");
//	config.PrintDebugString();
//	printf("cli_filebase is %s\n", config.cli_filebase().c_str());

	WozStatus status;
	status.set_bytes_sent(123);
	status.set_bytes_received(456);
	OWWriteStatus("OWZzzStatus", &status, "bar");

	//	printf("the count is %d\n", auto_mysql_stmt(handle.get(), "select * from OWConfig").execute(count_rows()).result);

	boost::shared_ptr<event_base> base(event_base_new(), event_base_free);

	if (run_unit_tests) {
		  ::testing::InitGoogleTest(&argc, argv);
		  return RUN_ALL_TESTS();
	}

	return event_base_dispatch(base.get());
}
<commit_msg>always run gtest<commit_after>
#include <execinfo.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memset
#include <sys/stat.h> // struct stat

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <string>

#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/shared_ptr.hpp>

#include "event2/event.h"
#include "event2/bufferevent.h"

#include <google/protobuf/descriptor.h>
#include <gtest/gtest.h>

#include "auto_mysql.h"
#include "odbcdatasources.h"

#include "person.pb.h"
#include "wozconfig.pb.h"
#include "wozstatus.pb.h"

//#include <gflags/gflags.h>

using namespace std;
//using namespace boost;
using namespace google;
using namespace google::protobuf;

inline string
render_si_value(double value) {
	int si_unit = 0;
	static const char *si_units[] = {"","k","M","G","T","P","E","Z","Y"};
	while (1000 <= value) {
		++si_unit;
		value /= 1000;
	}
	stringstream tmp;
	tmp << fixed << setprecision(1) << value << si_units[si_unit];
	return tmp.str();
}

//// variadic template
//void
//output() { cout << "\n"; }
//
//// variadic template
//template<class T, class ...Args>
//void
//output(T cls, Args ...args) {
//	cout << cls << " ";
//	if (sizeof...(args) == 0)
//		cout << "\n";
//	else
//		output(args...);
//}

// gets the scalar field value
static string
GetFieldValue(Message *message, const FieldDescriptor *field) {
	switch (field->cpp_type()) {
	case FieldDescriptor::CPPTYPE_BOOL:
		return boost::lexical_cast<string>(message->GetReflection()->GetBool((*message), field));
	case FieldDescriptor::CPPTYPE_INT32:
		return boost::lexical_cast<string>(message->GetReflection()->GetInt32((*message), field));
	case FieldDescriptor::CPPTYPE_UINT64:
		return boost::lexical_cast<string>(message->GetReflection()->GetUInt64((*message), field));
	case FieldDescriptor::CPPTYPE_STRING:
		return boost::lexical_cast<string>(message->GetReflection()->GetString((*message), field));
	default:
		throw runtime_error(field->name());
	}
}

// sets the scalar value/adds to the columnar value (i.e., field can be a repeated field)
static void
SetFieldValue(Message *message, const FieldDescriptor *field, const string& value) {
	switch (field->cpp_type()) {
	case FieldDescriptor::CPPTYPE_BOOL:
		if (field->is_repeated())
			message->GetReflection()->AddBool(message, field, boost::lexical_cast<bool>(value));
		else
			message->GetReflection()->SetBool(message, field, boost::lexical_cast<bool>(value));
		break;
	case FieldDescriptor::CPPTYPE_STRING:
		if (field->is_repeated())
			message->GetReflection()->AddString(message, field, value);
		else
			message->GetReflection()->SetString(message, field, value);
		break;
	default:
		throw runtime_error(field->name()+value);
	}
}

struct OWReadConfigVisitor {
	::google::protobuf::Message *config;
	OWReadConfigVisitor(::google::protobuf::Message *config): config(config) {
	}
	void operator()(map<string, string> row) {
		//ComponentURI|RowId|name|status=active|value
		string name(row["name"]);
		string value(row["value"]);

		match_results<const char *> results;
		regex re("([a-z]+_[a-zA-Z0-9]+)_([0-9]+)"); // e.g., foo_barBaz_1
		if (regex_match(name.c_str(), results, re))
			name = results[1].str(); // e.g., foo_barBaz

		const FieldDescriptor *field = config->GetDescriptor()->FindFieldByName(name);
		if (field)
			SetFieldValue(config, field, value); // works for scalars and columnars
	}
};

/**
 * reads the given iVOG_Config config
 *
 * @param dsn e.g., "OWConfig"
 * @param config
 * @param component_uri e.g., "foo/ch01/sl02/vm3/4"
 */
inline void
OWReadConfig(string dsn, ::google::protobuf::Message *config, string component_uri) {
	auto_mysql handle(OdbcNewConnection(dsn));
	auto_mysql_stmt(handle.get(), "select * from OWConfig where ComponentURI=?", component_uri).execute(OWReadConfigVisitor(config));
}

/**
 * writes the given iVOG_Status status
 *
 * @param dsn e.g., "OWZzzStatus"
 * @param status
 * @param component_uri e.g., "foo/ch01/sl02/vm3/4"
 */
inline void
OWWriteStatus(string dsn, ::google::protobuf::Message *status, string component_uri) {
	auto_mysql handle(OdbcNewConnection(dsn));
	int last_row_id(auto_mysql_stmt(handle.get(), "select coalesce(max(RowId),0) from OWStatus").execute(query_for<int>()).result);
	int new_group_id(auto_mysql_stmt(handle.get(), "select coalesce(max(GroupId),0) from OWStatus").execute(query_for<int>()).result + 1);
	for (int index = 0; index < status->GetDescriptor()->field_count(); ++index) {
		const FieldDescriptor *field = status->GetDescriptor()->field(index);
		if (status->GetReflection()->HasField(*status, field)) {
			string name(field->name());
			string value(GetFieldValue(status, field));
			string sql2("insert into OWStatus (RowId, GroupId, name, value, ComponentURI) values (?,?,?,?,?)");
			auto_mysql_stmt(handle.get(), sql2, ++last_row_id, new_group_id, name, value, component_uri).execute();
		}
	}
}

// Note- rhel54 bundles libboost 1.33, filesystem3 was introduced in libboost 1.44
#include <dirent.h>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

/**
 * Returns the cpu core count.
 */
static int
cpu_core_count() {
	int result = 0;
	regex re("cpu\\d");
	path dir("/sys/devices/system/cpu");
	for (directory_iterator iter(dir), iter_end; iter != iter_end; ++iter) {
		if (regex_search((*iter).path().c_str(), re))
			++result;
	}
	return result;
}

#include "auto_flags.h"

static auto_flags flags;

static int verbose=0;
static int version=0;
static int run_unit_tests=0;
static string listen_addr("0.0.0.0:8000"); // local http proxy listen addr
static string remote_addr("0.0.0.0:8001"); // remote dpp request addr
static string cores("0");

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

	// name, has_arg, flag, val

	add_no_argument(&flags, "verbose", &verbose, "enable verbose output");
	add_no_argument(&flags, "version", &version, "print version");

	add_no_argument(&flags, "run-unit-tests", &run_unit_tests, "run built-in unit-tests");

	add_required_argument(&flags, "cores", &cores, "number of cpu cores to use for media processing (0=auto detect)");
	add_required_argument(&flags, "listen", &listen_addr, "the local addr to use to receive http proxy requests");
	add_required_argument(&flags, "remote", &remote_addr, "the remote addr to use to send dpp requests");

	int arg = parse_auto_flags(&flags, argc, argv);

	while (arg < argc)
		printf("extra non-option ARGV-element: %s\n", argv[arg++]);

	print_auto_flags(&flags);

//	auto_mysql handle(OdbcNewConnection("OWConfig"));
////	auto_mysql_stmt(handle.get(), "select * from OWConfig where ComponentURI=?", "foo").execute(print_rows());
//
//	WozConfig config;
//	OWReadConfig("OWConfig", &config, "foo");
////	config.PrintDebugString();
////	printf("cli_filebase is %s\n", config.cli_filebase().c_str());
//
//	WozStatus status;
//	status.set_bytes_sent(123);
//	status.set_bytes_received(456);
//	OWWriteStatus("OWZzzStatus", &status, "bar");

	//	printf("the count is %d\n", auto_mysql_stmt(handle.get(), "select * from OWConfig").execute(count_rows()).result);

	boost::shared_ptr<event_base> base(event_base_new(), event_base_free);

//	if (run_unit_tests)
	{
		  ::testing::InitGoogleTest(&argc, argv);
		  return RUN_ALL_TESTS();
	}

	return event_base_dispatch(base.get());
}
<|endoftext|>


<commit_before>/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond angles, and dihedral
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the molecule.
 */

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>

#include "main.h"
#include "extraction.h"
#include "center_of_mass.h"
#include "bond_angle.h"
#include "dihedral_angle.h"
#include "elements.h"
//#include "bond_length.h"
//#include "bond_number.h"
#include "distance.h"

using namespace std;

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

    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;
    fstream bond_length;

    //Check that inputfile was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 2;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool" << endl;
    }

    //Extract the raw coordinates from the inputfile in the commandline
    if (extract_input(argv[1]) != 0) {
        cout << "Error occured in extracting the coordinates.\n";
    }

    //Print the vector size and vector contents
    if (print_vector_coords() != 0) {
        cout << "Error occured in printing the coordinates.\n";
    }

    //Open the file bond_length.cpp and check that it opened
    bond_length.open("bond_length.cpp");
    if (!bond_length.is_open()) {
         cout << "Error: Unable to open bond_length file.";
	       return 1;
    }

    //Close the file bond_length.cpp
    bond_length.close();
    cout << "Bond length calculation complete." ;

    //Calculate the model's total mass
    double model_mass = calculate_total_mass();

    //Calculate the model's center of mass coordinates
    double xcoord = calc_prod_coords_mass(2) / model_mass;
    double ycoord = calc_prod_coords_mass(3) / model_mass;
    double zcoord = calc_prod_coords_mass(4) / model_mass;

    cout << "Model's Center of Mass coordinates: " << endl
         << xcoord << "     " << ycoord << "     " << zcoord << endl;

    //Output the calculated interatomic distances
    Bond_Angle model;
    model.atom_dist();

    //Calculate the molecule's bond angles

    //Calculate the molecule's dihedral angles

}
<commit_msg>uses bond_length now<commit_after>/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond angles, and dihedral
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the molecule.
 */

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>

#include "main.h"
#include "extraction.h"
#include "center_of_mass.h"
#include "bond_angle.h"
#include "dihedral_angle.h"
#include "elements.h"
#include "bond_length.h"
//#include "bond_number.h"
//#include "distance.h"

using namespace std;

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

    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;
    fstream bond_length;

    //Check that inputfile was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 2;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool" << endl;
    }

    //Extract the raw coordinates from the inputfile in the commandline
    if (extract_input(argv[1]) != 0) {
        cout << "Error occured in extracting the coordinates.\n";
    }

    //Print the vector size and vector contents
    if (print_vector_coords() != 0) {
        cout << "Error occured in printing the coordinates.\n";
    }

    //Open the file bond_length.cpp and check that it opened
    bond_length.open("bond_length.cpp");
    if (!bond_length.is_open()) {
         cout << "Error: Unable to open bond_length file.";
	       return 1;
    }

    //Close the file bond_length.cpp
    bond_length.close();
    cout << "Bond length calculation complete." ;

    //Calculate the model's total mass
    double model_mass = calculate_total_mass();

    //Calculate the model's center of mass coordinates
    double xcoord = calc_prod_coords_mass(2) / model_mass;
    double ycoord = calc_prod_coords_mass(3) / model_mass;
    double zcoord = calc_prod_coords_mass(4) / model_mass;

    cout << "Model's Center of Mass coordinates: " << endl
         << xcoord << "     " << ycoord << "     " << zcoord << endl;

    //Output the calculated interatomic distances
    Bond_Length model;
    model.atom_dist();

    //Calculate the molecule's bond angles

    //Calculate the molecule's dihedral angles

}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <SFML/Graphics.hpp>

using namespace sf;

typedef struct mysprite
{
  Sprite sprite;
  bool isActive;
  float moveSpeed;

} MySprite;

int main()
{
  uint8_t c = 'c';
  VideoMode vm(1920,1080);
  RenderWindow window(vm,"MyTimer", Style::Fullscreen);

  Texture textureBackGround;

  textureBackGround.loadFromFile("graphics/background.png");

  Sprite spriteBackGround;

  spriteBackGround.setTexture(textureBackGround);

  spriteBackGround.setPosition(0,0);

  Texture textureTree;

  textureTree.loadFromFile("graphics/tree.png");

  Sprite spriteTree;

  spriteTree.setTexture(textureTree);

  spriteTree.setPosition(810,0);

  Texture textureBee;

  textureBee.loadFromFile("graphics/bee.png");

  Sprite spriteBee;

  spriteBee.setTexture(textureBee);

  spriteBee.setPosition(0,800);

  bool beeActive = false;

  float beeSpeed = 0.0f;

  Texture textureCloud;

  textureCloud.loadFromFile("graphics/cloud.png");

  std::vector<MySprite> clouds;

  for(int i = 0; i < 3; ++i)
  {
    Sprite spriteCloud;
    spriteCloud.setTexture(textureCloud);
    spriteCloud.setPosition(0,250 * i);
    MySprite mySprite;
    mySprite.sprite = spriteCloud;
    mySprite.isActive = false;
    mySprite.moveSpeed = 0.0f;
    clouds.push_back(mySprite);
  }

  Clock clock;

  RectangleShape timeBar;

  float timeBarStartWidth = 400;
  float timeBarHeight = 80;

  timeBar.setSize(Vector2f(timeBarStartWidth, timeBarHeight));

  timeBar.setFillColor(Color::Red);

  timeBar.setPosition(1920 / 2 - timeBarStartWidth / 2, 980);

  Time gameTimeTotal;

  float timeRemaining = 6.0f;

  float timeBarWidthPerSecond = timeBarStartWidth / timeRemaining;

  bool paused = false;

  int score = 0;

  sf::Text messageText;
  sf::Text scoreText;

  Font font;

  font.loadFromFile("fonts/KOMIKAP_.ttf");

  messageText.setFont(font);
  scoreText.setFont(font);

  messageText.setString("Press Enter to Start!");
  scoreText.setString("Score = 0");

  messageText.setCharacterSize(75);
  scoreText.setCharacterSize(100);

  messageText.setFillColor(Color::White);
  scoreText.setFillColor(Color::White);

  FloatRect textRect = messageText.getLocalBounds();

  messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f);

  scoreText.setPosition(20,20);
  messageText.setPosition(1920 / 2.0f, 1080 / 2.0f);

  while(window.isOpen())
  {

    if(!paused)
    {
      Time deltaTime = clock.restart();

      timeRemaining -= deltaTime.asSeconds();

      timeBar.setSize(Vector2f( timeBarWidthPerSecond * timeRemaining, timeBarHeight));

      if(timeRemaining <= 0.0f)
      {
	paused = true;

	messageText.setString("Out of Time!");

	FloatRect textRect = messageText.getLocalBounds();

	messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f);

	messageText.setPosition(1920 / 2.0f, 1080 / 2.0f);
      }

      for(int i = 0; i < 3; ++i)
      {
	if( !(clouds[i].isActive) )
	{
	  clouds[i].isActive = true;

	  //how fast the cloud is
	  srand((int)time(0) * 10 + (10 * i));
	  clouds[i].moveSpeed = (rand() % 200);

	  if(clouds[i].moveSpeed == 0)
	  {
	    std::cout << "Cloud " << i << " speed is zero" << std::endl;
	  }

	  //how high the cloud is
	  srand((int)time(0) * 10 * (i+1));
	  int subs = (i == 0) ? 0 : 150;
	  float height = (rand() % (150 + i * 150)) - subs;
	  clouds[i].sprite.setPosition(-200, height);

	}
	else
	{
	  //Sprite tmp = clouds[i].sprite;
	  clouds[i].sprite.setPosition( clouds[i].sprite.getPosition().x + (clouds[i].moveSpeed * deltaTime.asSeconds()), clouds[i].sprite.getPosition().y );
	  if(clouds[i].sprite.getPosition().x > 1920)
	  {
	    clouds[i].isActive = false;
	  }

	}
      }

      if(!beeActive)
      {
	beeActive = true;

	// how fast the bee is
	srand((int)time(0));
	beeSpeed = (rand() % 200) + 200;

	// how high the bee is
	srand((int)time(0) * 10);
	float height = (rand() % 500) + 500;

	spriteBee.setPosition(2000, height);

      }
      else //move the bee
      {
	spriteBee.setPosition(spriteBee.getPosition().x -
	(beeSpeed * deltaTime.asSeconds()),spriteBee.getPosition().y);

	if(spriteBee.getPosition().x < -100)
	{
	  beeActive = false;
	}

      }
      std::stringstream ss;

      ss << "Score = " << score;

      scoreText.setString(ss.str());

    }// !paused

    if(Keyboard::isKeyPressed(Keyboard::Escape))
    {
      window.close();
    }

    if(Keyboard::isKeyPressed(Keyboard::P))
    {
      paused = true;
    }

    if(Keyboard::isKeyPressed(Keyboard::Return))
    {
      paused = false;
      score = 0;
      timeRemaining = 5;
    }

    window.clear();

    window.draw(spriteBackGround);

    window.draw(spriteTree);

    window.draw(spriteBee);

    for (int i = 0; i < 3; ++i)
    {
      window.draw(clouds[i].sprite);
    }

    if(paused)
    {
      window.draw(messageText);
    }

    window.draw(scoreText);

    window.draw(timeBar);

    window.display();
  }

  std::cout << "MyTimber" << std::endl;
  return 0;
}<commit_msg>time bar<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <SFML/Graphics.hpp>

using namespace sf;

typedef struct mysprite
{
  Sprite sprite;
  bool isActive;
  float moveSpeed;

} MySprite;

int main()
{
  uint8_t c = 'c';
  VideoMode vm(1920,1080);
  RenderWindow window(vm,"MyTimer", Style::Fullscreen);

  Texture textureBackGround;

  textureBackGround.loadFromFile("graphics/background.png");

  Sprite spriteBackGround;

  spriteBackGround.setTexture(textureBackGround);

  spriteBackGround.setPosition(0,0);

  Texture textureTree;

  textureTree.loadFromFile("graphics/tree.png");

  Sprite spriteTree;

  spriteTree.setTexture(textureTree);

  spriteTree.setPosition(810,0);

  Texture textureBee;

  textureBee.loadFromFile("graphics/bee.png");

  Sprite spriteBee;

  spriteBee.setTexture(textureBee);

  spriteBee.setPosition(0,800);

  bool beeActive = false;

  float beeSpeed = 0.0f;

  Texture textureCloud;

  textureCloud.loadFromFile("graphics/cloud.png");

  std::vector<MySprite> clouds;

  for(int i = 0; i < 3; ++i)
  {
    Sprite spriteCloud;
    spriteCloud.setTexture(textureCloud);
    spriteCloud.setPosition(0,250 * i);
    MySprite mySprite;
    mySprite.sprite = spriteCloud;
    mySprite.isActive = false;
    mySprite.moveSpeed = 0.0f;
    clouds.push_back(mySprite);
  }

  Clock clock;

  RectangleShape timeBar;

  float timeBarStartWidth = 400;
  float timeBarHeight = 80;

  timeBar.setSize(Vector2f(timeBarStartWidth, timeBarHeight));

  timeBar.setFillColor(Color::Red);

  timeBar.setPosition(1920 / 2 - timeBarStartWidth / 2, 80);

  Time gameTimeTotal;

  float timeRemaining = 6.0f;

  float timeBarWidthPerSecond = timeBarStartWidth / timeRemaining;

  bool paused = false;

  int score = 0;

  sf::Text messageText;
  sf::Text scoreText;

  Font font;

  font.loadFromFile("fonts/KOMIKAP_.ttf");

  messageText.setFont(font);
  scoreText.setFont(font);

  messageText.setString("Press Enter to Start!");
  scoreText.setString("Score = 0");

  messageText.setCharacterSize(75);
  scoreText.setCharacterSize(100);

  messageText.setFillColor(Color::White);
  scoreText.setFillColor(Color::White);

  FloatRect textRect = messageText.getLocalBounds();

  messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f);

  scoreText.setPosition(20,20);
  messageText.setPosition(1920 / 2.0f, 1080 / 2.0f);

  while(window.isOpen())
  {

    if(!paused)
    {
      Time deltaTime = clock.restart();

      timeRemaining -= deltaTime.asSeconds();

      timeBar.setSize(Vector2f( timeBarWidthPerSecond * timeRemaining, timeBarHeight));

      if(timeRemaining <= 0.0f)
      {
	paused = true;

	messageText.setString("Out of Time!");

	FloatRect textRect = messageText.getLocalBounds();

	messageText.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f);

	messageText.setPosition(1920 / 2.0f, 1080 / 2.0f);
      }

      for(int i = 0; i < 3; ++i)
      {
	if( !(clouds[i].isActive) )
	{
	  clouds[i].isActive = true;

	  //how fast the cloud is
	  srand((int)time(0) * 10 + (10 * i));
	  clouds[i].moveSpeed = (rand() % 200);

	  if(clouds[i].moveSpeed == 0)
	  {
	    std::cout << "Cloud " << i << " speed is zero" << std::endl;
	  }

	  //how high the cloud is
	  srand((int)time(0) * 10 * (i+1));
	  int subs = (i == 0) ? 0 : 150;
	  float height = (rand() % (150 + i * 150)) - subs;
	  clouds[i].sprite.setPosition(-200, height);

	}
	else
	{
	  //Sprite tmp = clouds[i].sprite;
	  clouds[i].sprite.setPosition( clouds[i].sprite.getPosition().x + (clouds[i].moveSpeed * deltaTime.asSeconds()), clouds[i].sprite.getPosition().y );
	  if(clouds[i].sprite.getPosition().x > 1920)
	  {
	    clouds[i].isActive = false;
	  }

	}
      }

      if(!beeActive)
      {
	beeActive = true;

	// how fast the bee is
	srand((int)time(0));
	beeSpeed = (rand() % 200) + 200;

	// how high the bee is
	srand((int)time(0) * 10);
	float height = (rand() % 500) + 500;

	spriteBee.setPosition(2000, height);

      }
      else //move the bee
      {
	spriteBee.setPosition(spriteBee.getPosition().x -
	(beeSpeed * deltaTime.asSeconds()),spriteBee.getPosition().y);

	if(spriteBee.getPosition().x < -100)
	{
	  beeActive = false;
	}

      }
      std::stringstream ss;

      ss << "Score = " << score;

      scoreText.setString(ss.str());

    }// !paused

    if(Keyboard::isKeyPressed(Keyboard::Escape))
    {
      window.close();
    }

    if(Keyboard::isKeyPressed(Keyboard::P))
    {
      paused = true;
    }

    if(Keyboard::isKeyPressed(Keyboard::Return))
    {
      paused = false;
      score = 0;
      timeRemaining = 5;
    }

    window.clear();

    window.draw(spriteBackGround);

    window.draw(spriteTree);

    window.draw(spriteBee);

    for (int i = 0; i < 3; ++i)
    {
      window.draw(clouds[i].sprite);
    }

    if(paused)
    {
      window.draw(messageText);
    }

    window.draw(scoreText);

    window.draw(timeBar);

    window.display();
  }

  std::cout << "MyTimber" << std::endl;
  return 0;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Jussi Pakkanen.
 *
 * This file is part of mcdemo.
 *
 * Mcdemo is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * Mcdemo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Mcdemo; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include<SDL.h>
#include<cstdio>
#include<cstdlib>
#include<memory>
#include<cassert>
#include"blue.h"

const int SCREEN_WIDTH = 1920/2;
const int SCREEN_HEIGHT = 1080/2;
const uint32_t FTIME = (1000/60);

SDL_Texture* unpack(SDL_Renderer *rend, const unsigned char* data, size_t data_size) {
    auto *io = SDL_RWFromConstMem(data, data_size);
    std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> s(SDL_LoadBMP_RW(io, 1), SDL_FreeSurface);
    assert(s.get());
    return SDL_CreateTextureFromSurface(rend, s.get());
}

struct resources {
    std::unique_ptr<SDL_Texture, void(*)(SDL_Texture *)> blue_tex;

    resources(SDL_Renderer *rend) : blue_tex(unpack(rend, blue, sizeof(blue)), SDL_DestroyTexture) {
        assert(blue_tex.get());
    }
};

void render(SDL_Renderer *rend, const resources &res) {
    SDL_Rect r;
    assert(!SDL_SetRenderDrawColor(rend, 0, 0, 0, 0));
    SDL_RenderClear(rend);
    assert(!SDL_SetRenderDrawColor(rend, 255, 255, 255, 0));
    r.x = 100;
    r.y = 100;
    r.w = 100;
    r.h = 100;
    assert(!SDL_RenderCopy(rend, res.blue_tex.get(), nullptr, &r));
    SDL_RenderPresent(rend);
}

void mainloop(SDL_Window *win, SDL_Renderer *rend) {
    SDL_Event e;
    resources res(rend);
    auto last_frame = SDL_GetTicks();
    SDL_RendererInfo f;
    SDL_GetRendererInfo(rend, &f);
    bool has_vsync = f.flags & SDL_RENDERER_PRESENTVSYNC;
    while(true) {
        while(SDL_PollEvent(&e)) {
            if(e.type == SDL_QUIT) {
                return;
            } else if(e.type == SDL_KEYDOWN) {
                switch(e.key.keysym.sym) {
                case  SDLK_ESCAPE:
                case  SDLK_q:
                    return;
                }
            } else if(e.type == SDL_JOYBUTTONDOWN) {
                return;
            }
        }
        render(rend, res);
        if(!has_vsync) {
            auto time_spent = SDL_GetTicks() - last_frame;
            if(time_spent < FTIME) {
                SDL_Delay(FTIME - time_spent);
            }
        }
        last_frame = SDL_GetTicks(); // Not accurate, but good enough.
    }
}

int main(int /*argc*/, char **/*argv*/) {
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER |
            SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
    atexit(SDL_Quit);
    std::unique_ptr<SDL_Window, void (*)(SDL_Window*)>
        win(SDL_CreateWindow("Mcdemo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0),
                SDL_DestroyWindow);
    std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> rend(SDL_CreateRenderer(win.get(), -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC),
            SDL_DestroyRenderer);
    mainloop(win.get(), rend.get());
    return 0;
}
<commit_msg>Animate item.<commit_after>/*
 * Copyright (c) 2015 Jussi Pakkanen.
 *
 * This file is part of mcdemo.
 *
 * Mcdemo is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * Mcdemo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Mcdemo; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include<SDL.h>
#include<cstdio>
#include<cstdlib>
#include<memory>
#include<cassert>
#include<math.h>
#include"blue.h"

const int SCREEN_WIDTH = 1920/2;
const int SCREEN_HEIGHT = 1080/2;
const uint32_t FTIME = (1000/60);

// For simplicity.
const int texw = 100;
const int texh = 100;

SDL_Texture* unpack(SDL_Renderer *rend, const unsigned char* data, size_t data_size) {
    auto *io = SDL_RWFromConstMem(data, data_size);
    std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> s(SDL_LoadBMP_RW(io, 1), SDL_FreeSurface);
    assert(s.get());
    return SDL_CreateTextureFromSurface(rend, s.get());
}

struct resources {
    std::unique_ptr<SDL_Texture, void(*)(SDL_Texture *)> blue_tex;

    resources(SDL_Renderer *rend) : blue_tex(unpack(rend, blue, sizeof(blue)), SDL_DestroyTexture) {
        assert(blue_tex.get());
    }
};

void render(SDL_Renderer *rend, const resources &res, const double ratio) {
    SDL_Rect r;
    assert(!SDL_SetRenderDrawColor(rend, 0, 0, 0, 0));
    SDL_RenderClear(rend);
    assert(!SDL_SetRenderDrawColor(rend, 255, 255, 255, 0));
    int centerx = SCREEN_WIDTH/2;
    int centery = SCREEN_HEIGHT/2;
    r.x = centerx - texw/2 + SCREEN_WIDTH*0.4*sin(2*M_PI*ratio);
    r.y = centery - texh/2 + SCREEN_HEIGHT*0.4*cos(2*2*M_PI*(ratio) + M_PI/2);
    r.w = texw;
    r.h = texh;
    assert(!SDL_RenderCopy(rend, res.blue_tex.get(), nullptr, &r));
    SDL_RenderPresent(rend);
}

void mainloop(SDL_Window *win, SDL_Renderer *rend) {
    SDL_Event e;
    resources res(rend);
    auto start_time = SDL_GetTicks();
    const int cycle = 2000;
    auto last_frame = SDL_GetTicks();
    SDL_RendererInfo f;
    SDL_GetRendererInfo(rend, &f);
    bool has_vsync = f.flags & SDL_RENDERER_PRESENTVSYNC;
    while(true) {
        while(SDL_PollEvent(&e)) {
            if(e.type == SDL_QUIT) {
                return;
            } else if(e.type == SDL_KEYDOWN) {
                switch(e.key.keysym.sym) {
                case  SDLK_ESCAPE:
                case  SDLK_q:
                    return;
                }
            } else if(e.type == SDL_JOYBUTTONDOWN) {
                return;
            }
        }
        render(rend, res, ((SDL_GetTicks() - start_time) % cycle)/double(cycle));
        if(!has_vsync) {
            auto time_spent = SDL_GetTicks() - last_frame;
            if(time_spent < FTIME) {
                SDL_Delay(FTIME - time_spent);
            }
        }
        last_frame = SDL_GetTicks(); // Not accurate, but good enough.
    }
}

int main(int /*argc*/, char **/*argv*/) {
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER |
            SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
        return 1;
    }
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
    atexit(SDL_Quit);
    std::unique_ptr<SDL_Window, void (*)(SDL_Window*)>
        win(SDL_CreateWindow("Mcdemo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0),
                SDL_DestroyWindow);
    std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> rend(SDL_CreateRenderer(win.get(), -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC),
            SDL_DestroyRenderer);
    mainloop(win.get(), rend.get());
    return 0;
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>

#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>

#include "errors.h"
#include "external_readonly_parameter.h"
#include "external_readwrite_parameter.h"
#include "object_dictionary.h"
#include "managed_readwrite_parameter.h"
#include "managed_readonly_parameter.h"
#include "scheme_protocol.h"
#include "scheme_monitor_protocol.h"
#include "server.h"
#include "tree_element.h"

Server decofServer;

struct my_managed_readwrite_parameter : public managed_readwrite_parameter<std::string>
{
    my_managed_readwrite_parameter(std::string name, node *parent = nullptr, std::string value = std::string())
     : managed_readwrite_parameter<std::string>(name, parent, value)
    {}

    virtual void verify(const std::string& value) override {
        if (value != "true" && value != "false")
            throw invalid_value_error();

        std::cout << "my_managed_readwrite_parameter was changed to " << value << std::endl;
    }
};

struct my_managed_readonly_parameter : public managed_readonly_parameter<std::string>
{
    my_managed_readonly_parameter(std::string name, node *parent = nullptr, std::string value = std::string())
     : managed_readonly_parameter<std::string>(name, parent, value)
    {}

    virtual bool notify(const std::string& value) {
        std::cout << "my_managed_readonly_parameter was changed to " << value << std::endl;
        return true;
    }
};

struct time_parameter : public external_readonly_parameter<std::string>
{
    time_parameter(std::string name, node *parent = nullptr)
     : external_readonly_parameter<std::string>(name, parent)
    {}

private:
    std::string get_external_value() override {
        std::time_t t = std::time(nullptr);
        return std::asctime(std::localtime(&t));
    }
};

struct ip_address_parameter : public external_readwrite_parameter<std::string>
{
    ip_address_parameter(std::string name, node *parent = nullptr)
     : external_readwrite_parameter<std::string>(name, parent)
    {}

private:
    bool set_external_value(const value_type &value) override {
        std::fstream file(filename_, std::ios_base::out | std::ios_base::trunc);
        if (file.rdstate() & std::ios_base::failbit)
            return false;

        file << value;
        return true;
    }

    std::string get_external_value() override {
        std::string str;
        std::fstream file_(filename_, std::ios_base::in);
        std::getline(file_, str);
        return str;
    }

    std::string filename_ = "C:\\Users\\willy\\data.txt";
};

int main()
{
    // Setup object dictionary
    // root
    //  |-- enabled: string (rw)
    //  |-- subnode: node (r)
    //  | |-- time: string (r)
    //  | |-- leaf2: stringlist (rw)
    //  | |-- ip-address: string (rw)
    ObjectDictionary& od = decofServer.objectDictionary();
    new my_managed_readwrite_parameter("enabled", &od, "false");
    node* subnode = new node("subnode", &od);
    new time_parameter("time", subnode);
    stringlist sl = { "value1", "value2", "value3" };
    new managed_readwrite_parameter<stringlist>("leaf2", subnode, sl);
    new ip_address_parameter("ip-address", subnode);

    // Setup client connections
    boost::asio::ip::tcp::endpoint cmd_endpoint(boost::asio::ip::tcp::v4(), 1998);
    scheme_protocol sp(decofServer, cmd_endpoint);
    sp.preload();

    boost::asio::ip::tcp::endpoint mon_endpoint(boost::asio::ip::tcp::v4(), 1999);
    scheme_monitor_protocol smp(decofServer, mon_endpoint);
    smp.preload();

    decofServer.ioService().run();

    return 0;
}
<commit_msg>Fixed newline in time string issue.<commit_after>#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>

#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>

#include "errors.h"
#include "external_readonly_parameter.h"
#include "external_readwrite_parameter.h"
#include "object_dictionary.h"
#include "managed_readwrite_parameter.h"
#include "managed_readonly_parameter.h"
#include "scheme_protocol.h"
#include "scheme_monitor_protocol.h"
#include "server.h"
#include "tree_element.h"

Server decofServer;

struct my_managed_readwrite_parameter : public managed_readwrite_parameter<std::string>
{
    my_managed_readwrite_parameter(std::string name, node *parent = nullptr, std::string value = std::string())
     : managed_readwrite_parameter<std::string>(name, parent, value)
    {}

    virtual void verify(const std::string& value) override {
        if (value != "true" && value != "false")
            throw invalid_value_error();

        std::cout << "my_managed_readwrite_parameter was changed to " << value << std::endl;
    }
};

struct my_managed_readonly_parameter : public managed_readonly_parameter<std::string>
{
    my_managed_readonly_parameter(std::string name, node *parent = nullptr, std::string value = std::string())
     : managed_readonly_parameter<std::string>(name, parent, value)
    {}

    virtual bool notify(const std::string& value) {
        std::cout << "my_managed_readonly_parameter was changed to " << value << std::endl;
        return true;
    }
};

struct time_parameter : public external_readonly_parameter<std::string>
{
    time_parameter(std::string name, node *parent = nullptr)
     : external_readonly_parameter<std::string>(name, parent)
    {}

private:
    std::string get_external_value() override {
        const size_t max_length = 40;
        char str[max_length];
        std::time_t now = std::time(nullptr);
        std::strftime(str, sizeof(str), "%c", std::localtime(&now));
        return std::string(str);
    }
};

struct ip_address_parameter : public external_readwrite_parameter<std::string>
{
    ip_address_parameter(std::string name, node *parent = nullptr)
     : external_readwrite_parameter<std::string>(name, parent)
    {}

private:
    bool set_external_value(const value_type &value) override {
        std::fstream file(filename_, std::ios_base::out | std::ios_base::trunc);
        if (file.rdstate() & std::ios_base::failbit)
            return false;

        file << value;
        return true;
    }

    std::string get_external_value() override {
        std::string str;
        std::fstream file_(filename_, std::ios_base::in);
        std::getline(file_, str);
        return str;
    }

    std::string filename_ = "C:\\Users\\willy\\data.txt";
};

int main()
{
    // Setup object dictionary
    // root
    //  |-- enabled: string (rw)
    //  |-- subnode: node (r)
    //  | |-- time: string (r)
    //  | |-- leaf2: stringlist (rw)
    //  | |-- ip-address: string (rw)
    ObjectDictionary& od = decofServer.objectDictionary();
    new my_managed_readwrite_parameter("enabled", &od, "false");
    node* subnode = new node("subnode", &od);
    new time_parameter("time", subnode);
    stringlist sl = { "value1", "value2", "value3" };
    new managed_readwrite_parameter<stringlist>("leaf2", subnode, sl);
    new ip_address_parameter("ip-address", subnode);

    // Setup client connections
    boost::asio::ip::tcp::endpoint cmd_endpoint(boost::asio::ip::tcp::v4(), 1998);
    scheme_protocol sp(decofServer, cmd_endpoint);
    sp.preload();

    boost::asio::ip::tcp::endpoint mon_endpoint(boost::asio::ip::tcp::v4(), 1999);
    scheme_monitor_protocol smp(decofServer, mon_endpoint);
    smp.preload();

    decofServer.ioService().run();

    return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <list>
#include <vector>
#include <stack>

typedef std::vector< std::list<int> > graph;
typedef std::list<int>::iterator iter;

int output1 = 0, output2 = 0, output3 = 0;

namespace DFS { enum { WHITE=-1, GREY, BLACK }; }

void DFS_visit(graph &g, int v, int color[], std::stack<int> &stack) {
    color[v] = DFS::GREY;
    for (iter vIter = g[v].begin(); vIter != g[v].end(); vIter++) {
        int u = *vIter;
        if (color[u] == DFS::WHITE) {
            DFS_visit(g, u, color, stack);
        }
    }
    color[v] = DFS::BLACK;
    stack.push(v);
}

int DFS_visit2(graph &g, int u, int color[], bool &out_edge) {
    int size = 1;
    color[u] = output1;
    for (iter vIter = g[u].begin(); vIter != g[u].end(); vIter++) {
        int v = *vIter;
        if (color[v] == DFS::WHITE) {
             size += DFS_visit2(g, v, color, out_edge);
        } else if (color[v] != output1) {
            out_edge = true;
        }
    }
    return size;
}

void create_transpose_graph(graph &g, graph &t) {
    for (int i = 0; i < (int) g.size(); i++) {
        for (iter vIter = g[i].begin(); vIter != g[i].end(); vIter++) {
            int u = *vIter;
            t[u].push_back(i);
        }
    }
}

/* this function recieves a graph and solves the project! */
void solve(graph &g) {
    int V = g.size();
    int color[V], i;
    std::stack<int> stack;

    graph t(V);
    create_transpose_graph(g, t);

    for (i = 0; i < V; i++) { color[i] = DFS::WHITE; }
    for (i = 0; i < V; i++) {
        if (color[i] == DFS::WHITE) {
            DFS_visit(t, i, color, stack);
        }
    }

    for (i = 0; i < V; i++) { color[i] = DFS::WHITE; }
    while (stack.size() > 0) {
        int u = stack.top();
        stack.pop();
        if (color[u] == DFS::WHITE) {
            bool out_edge = false;
            int size = DFS_visit2(g, u, color, out_edge);
            if (!out_edge) output3++;
            output2 = std::max(size, output2);
            output1++;
        }
    }
}

int main() {
    int V, E;
    int v1, v2;
    scanf("%d", &V);
    scanf("%d", &E);
    getchar();

    graph g(V);

    for (int i = 0; i < E; i++) {
        scanf("%d", &v1);
        scanf("%d", &v2);
        getchar();
        g[v1-1].push_back(v2-1);
    }

    solve(g);

    printf("%d\n%d\n%d\n", output1, output2, output3);

    return 0;
}
<commit_msg>main.cpp refactor<commit_after>#include <cstdio>
#include <list>
#include <vector>
#include <stack>

#define WHITE -1

typedef std::vector< std::list<int> > graph;
typedef std::list<int>::iterator iter;

int output1 = 0, output2 = 0, output3 = 0;

void DFS_visit(graph &g, int v, int color[], std::stack<int> &stack) {
    color[v] = !WHITE;
    for (iter vIter = g[v].begin(); vIter != g[v].end(); vIter++) {
        int u = *vIter;
        if (color[u] == WHITE) {
            DFS_visit(g, u, color, stack);
        }
    }
    stack.push(v);
}

int DFS_visit2(graph &g, int u, int color[], bool &out_edge) {
    int size = 1;
    color[u] = output1;
    for (iter vIter = g[u].begin(); vIter != g[u].end(); vIter++) {
        if (color[*vIter] == WHITE)
            size += DFS_visit2(g, *vIter, color, out_edge);
        else if (color[*vIter] != output1)
            out_edge = true;
    }
    return size;
}

void create_transpose_graph(graph &g, graph &t) {
    for (int i = 0; i < (int) g.size(); i++)
        for (iter vIter = g[i].begin(); vIter != g[i].end(); vIter++)
            t[*vIter].push_back(i);
}

void solve(graph &g) {
    int V = g.size();
    int color[V], i;
    std::stack<int> stack;

    graph t(V);
    create_transpose_graph(g, t);

    for (i = 0; i < V; i++) { color[i] = WHITE; }
    for (i = 0; i < V; i++) {
        if (color[i] == WHITE) {
            DFS_visit(t, i, color, stack);
        }
    }

    for (i = 0; i < V; i++) { color[i] = WHITE; }
    while (stack.size() > 0) {
        int u = stack.top();
        stack.pop();
        if (color[u] == WHITE) {
            bool out_edge = false;
            int size = DFS_visit2(g, u, color, out_edge);
            if (!out_edge) output3++;
            output2 = std::max(size, output2);
            output1++;
        }
    }
}

int main() {
    int V, E, v1, v2;

    scanf("%d %d%*c", &V, &E);
    graph g(V);

    for (int i = 0; i < E; i++) {
        scanf("%d %d%*c", &v1, &v2);
        g[v1-1].push_back(v2-1);
    }

    solve(g);

    printf("%d\n%d\n%d\n", output1, output2, output3);

    return 0;
}
<|endoftext|>


<commit_before>555ce19e-ad58-11e7-ab31-ac87a332f658<commit_msg>Does anyone even read these anymore???<commit_after>55d1e585-ad58-11e7-8081-ac87a332f658<|endoftext|>