<commit_before>#include <iostream>
#include <boost/program_options.hpp>
#include "version.h"

namespace po = boost::program_options;

struct Options
{
    Options() : version(false), help(false), helpEvents(false), stopAfter(0), fileName(false), lineNumber(false) {}
    bool version;
    bool help;
    bool helpEvents;
    unsigned int stopAfter;
    bool fileName;
    bool lineNumber;
    std::vector<std::pair<std::string, std::string>> regexps;
    std::vector<std::string> events;
};

std::vector<std::string> availableEvents
{
    "ADMIN",
    "ATTN",
    "CALL",
    "CONN",
    "CONFLOADFROMFILES",
    "CLSTR",
    "DB2",
    "DBMSSQL",
    "DBMSSQLCONN",
    "DBPOSTGRS",
    "DBORACLE",
    "DBV8DBENG",
    "EDS",
    "EXCP",
    "EXCPCNTX",
    "InputByString",
    "FTEXTCheck",
    "FTEXTUpd",
    "HASP",
    "LEAKS",
    "LIC",
    "MAILPARSEERR",
    "MEM",
    "PROC",
    "QERR",
    "SCALL",
    "SCOM",
    "SDBL",
    "SESN",
    "SRVC",
    "SYSTEM",
    "TDEADLOCK",
    "TTIMEOUT",
    "TLOCK",
    "VRSCACHE",
    "VRSREQUEST",
    "VRSRESPONSE"
};

int main(int argc, const char **argv)
{
    Options options;

    po::options_description allOptions("Allowed options");
    po::options_description visibleOptions("Allowed options");

    po::options_description regexpOptions("Regexp");
    po::options_description miscOptions("Miscellaneous");
    po::options_description outputOptions("Output control");
    po::options_description eventsOptions("Events");

    po::positional_options_description positionalOptions;

    regexpOptions.add_options()("regexp,r", po::value<std::vector<std::string>>()->multitoken(), ": use pattern ARG for matching");

    miscOptions.add_options()("version", po::bool_switch(&options.version), ": display version information and exit");
    miscOptions.add_options()("help", po::bool_switch(&options.help), ": display this help and exit");
    miscOptions.add_options()("help-events", po::bool_switch(&options.helpEvents), ": display events help and exit");

    outputOptions.add_options()("stop-after,s", po::value(&options.stopAfter), ": stop after ARG output lines");
    outputOptions.add_options()("file-name,f", po::bool_switch(&options.fileName), ": print the file name prefix on output");
    outputOptions.add_options()("line-number,l", po::bool_switch(&options.lineNumber), ": print line number with output lines");

    for(auto const& availableEvent: availableEvents)
    {
        eventsOptions.add_options()(availableEvent.c_str(), "");
    }

    positionalOptions.add("regexp", 1);

    allOptions.add(regexpOptions).add(outputOptions).add(miscOptions).add(eventsOptions);
    visibleOptions.add(regexpOptions).add(outputOptions).add(miscOptions);

    try
    {
        po::variables_map vm;

        auto parsed = po::basic_command_line_parser<char>(argc, argv).options(allOptions).allow_unregistered().positional(positionalOptions).run();
        auto unrecognizedOptions = po::collect_unrecognized(parsed.options, po::exclude_positional);

        po::store(parsed, vm);

        po::notify(vm);

        for(auto const& availableEvent: availableEvents)
        {
            if (vm.count(availableEvent))
            {
                options.events.push_back(availableEvent);
            }
        }

        if (vm.count("regexp"))
        {
            for(auto const& value: vm["regexp"].as<std::vector<std::string>>())
            {
                options.regexps.push_back(std::make_pair("", value));
            }
        }

        for(auto const& unrecognizedOption: unrecognizedOptions)
        {
            auto splitted = po::split_unix(unrecognizedOption, "=");

            if (splitted.size() == 2 && unrecognizedOption.find("--") == 0)
            {
                options.regexps.push_back(std::make_pair(splitted[0].substr(2), splitted[1]));
            }
            else
            {
                throw po::unknown_option(unrecognizedOption);
            }
        }
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
        return 2;
    }

    if (options.version)
    {
        std::cout << "techlog "<< VERSION_MAJOR << "." << VERSION_MINOR << std::endl;
        std::cout << LICENSE << std::endl;
        std::cout << WRITTENBY << std::endl;
	    return 1;
    }

    if (options.help)
    {
        std::cout << visibleOptions << std::endl;
        return 1;
    }

    if (options.helpEvents)
    {
        std::cout << eventsOptions << std::endl;
        return 1;
    }

    for(auto const& event: options.events)
    {
        std::cout << event << std::endl;
    }

    for(auto const& regexp: options.regexps)
    {
        std::cout << regexp.first << " : " << regexp.second << std::endl;
    }

    return 0;
}<commit_msg>Program Parameters<commit_after>#include <iostream>
#include <boost/program_options.hpp>
#include "version.h"

namespace po = boost::program_options;

struct Options
{
    Options() : version(false), help(false), helpEvents(false), stopAfter(0), fileName(false), lineNumber(false) {}
    bool version;
    bool help;
    bool helpEvents;
    unsigned int stopAfter;
    bool fileName;
    bool lineNumber;
    std::vector<std::pair<std::string, std::string>> regexps;
    std::vector<std::string> events;
};

std::vector<std::string> availableEvents
{
    "ADMIN",
    "ATTN",
    "CALL",
    "CONN",
    "CONFLOADFROMFILES",
    "CLSTR",
    "DB2",
    "DBMSSQL",
    "DBMSSQLCONN",
    "DBPOSTGRS",
    "DBORACLE",
    "DBV8DBENG",
    "EDS",
    "EXCP",
    "EXCPCNTX",
    "InputByString",
    "FTEXTCheck",
    "FTEXTUpd",
    "HASP",
    "LEAKS",
    "LIC",
    "MAILPARSEERR",
    "MEM",
    "PROC",
    "QERR",
    "SCALL",
    "SCOM",
    "SDBL",
    "SESN",
    "SRVC",
    "SYSTEM",
    "TDEADLOCK",
    "TTIMEOUT",
    "TLOCK",
    "VRSCACHE",
    "VRSREQUEST",
    "VRSRESPONSE"
};

int main(int argc, const char **argv)
{
    Options options;

    po::options_description allOptions("Allowed options");
    po::options_description visibleOptions("Allowed options");

    po::options_description regexpOptions("Regexp");
    po::options_description miscOptions("Miscellaneous");
    po::options_description outputOptions("Output control");
    po::options_description eventsOptions("Events");

    po::positional_options_description positionalOptions;

    regexpOptions.add_options()("regexp,r", po::value<std::vector<std::string>>()->multitoken(), ": use pattern ARG for matching");

    miscOptions.add_options()("version", po::bool_switch(&options.version), ": display version information and exit");
    miscOptions.add_options()("help", po::bool_switch(&options.help), ": display this help and exit");
    miscOptions.add_options()("help-events", po::bool_switch(&options.helpEvents), ": display events help and exit");

    outputOptions.add_options()("stop-after,s", po::value(&options.stopAfter), ": stop after ARG output lines");
    outputOptions.add_options()("file-name,f", po::bool_switch(&options.fileName), ": print the file name prefix on output");
    outputOptions.add_options()("line-number,l", po::bool_switch(&options.lineNumber), ": print line number with output lines");

    for(auto const& availableEvent: availableEvents)
    {
        eventsOptions.add_options()(availableEvent.c_str(), "");
    }

    positionalOptions.add("regexp", 1);

    allOptions.add(regexpOptions).add(outputOptions).add(miscOptions).add(eventsOptions);
    visibleOptions.add(regexpOptions).add(outputOptions).add(miscOptions);

    try
    {
        po::variables_map vm;

        auto parsed = po::basic_command_line_parser<char>(argc, argv).options(allOptions).allow_unregistered().positional(positionalOptions).run();
        auto unrecognizedOptions = po::collect_unrecognized(parsed.options, po::exclude_positional);

        po::store(parsed, vm);

        po::notify(vm);

        for(auto const& availableEvent: availableEvents)
        {
            if (vm.count(availableEvent))
            {
                options.events.push_back(availableEvent);
            }
        }

        if (vm.count("regexp"))
        {
            for(auto const& value: vm["regexp"].as<std::vector<std::string>>())
            {
                options.regexps.push_back(std::make_pair("", value));
            }
        }

        for(auto const& unrecognizedOption: unrecognizedOptions)
        {
            auto splitted = po::split_unix(unrecognizedOption, "=");

            if (splitted.size() == 2 && unrecognizedOption.find("--") == 0)
            {
                options.regexps.push_back(std::make_pair(splitted[0].substr(2), splitted[1]));
            }
            else
            {
                throw po::unknown_option(unrecognizedOption);
            }
        }
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
        return 2;
    }

    if (options.version)
    {
        std::cout << "techlog "<< VERSION_MAJOR << "." << VERSION_MINOR << std::endl;
        std::cout << LICENSE << std::endl;
        std::cout << WRITTENBY << std::endl;
	    return 1;
    }

    if (!options.regexps.size() && !options.events.size())
    {
        std::cout << "usage: techlog [-fl] [-s num] [-r pattern] [--property=pattern] [pattern]" << std::endl;
    }

    if (options.help)
    {
        std::cout << visibleOptions << std::endl;
        return 1;
    }

    if (options.helpEvents)
    {
        std::cout << eventsOptions << std::endl;
        return 1;
    }

    for(auto const& event: options.events)
    {
        std::cout << event << std::endl;
    }

    for(auto const& regexp: options.regexps)
    {
        std::cout << regexp.first << " : " << regexp.second << std::endl;
    }

    return 0;
}<|endoftext|>


<commit_before>/* main.cpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 */

#include <iostream>

#include "algorithm/algorithm.hpp"
#include "individual/individual.hpp"
#include "problem/problem.hpp"
#include "random_generator/random_generator.hpp"

int main() {
  using namespace problem;
  const Problem problem{get_data(), 64, 1024};
  individual::Individual best = algorithm::genetic(problem);
  std::cout << best.print_formula()
	    << best.print_calculation(problem.values);
}
<commit_msg>Changing run values<commit_after>/* main.cpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 */

#include <iostream>

#include "algorithm/algorithm.hpp"
#include "individual/individual.hpp"
#include "problem/problem.hpp"
#include "random_generator/random_generator.hpp"

int main() {
  using namespace problem;
  const Problem problem{get_data(), 256, 256, 3, 3};
  individual::Individual best = algorithm::genetic(problem);
  std::cout << best.print_formula()
	    << best.print_calculation(problem.values);
}
<|endoftext|>


<commit_before>#include <limits>
#include <algorithm>
#include <array>
#include <iomanip>
#include <curl/curl.h>
#include <memory>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>

const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");

const std::string file_checksum(const std::string &path);

size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata)
{
    std::string *s = static_cast<std::string *>(userdata);
    s->append(ptr, size * nmemb);
    return size * nmemb;
}

std::vector<std::string> &split(const std::string &s, char delim,
        std::vector<std::string> &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

class Target
{
    public:
        enum class Status {
            Nonexistent,
            Outdated,
            Current
        };
        explicit Target(const std::string &name, const std::string &checksum):
            m_name(name.find_first_of('/') == std::string::npos ? name :
                    name, name.find_first_of('/') + 1, name.size() - 1),
            m_checksum(checksum)
            {}
        std::string name() const { return m_name; }
        const std::string checksum() const { return m_checksum; }

        void fetch()
        {
            std::cout << "Statting target " << name() << "...";
            std::string path;
            std::fstream fs(name(), std::ios_base::in);
            if (!fs.good())
            {
                fs.close();
                std::cout << " doesn't exist, creating new." << std::endl;
                auto elems = split(name(), '/');
                for (size_t i = 0, k = elems.size(); i < k; ++i)
                {
                    const std::string &s(elems[i]);
                    if (s.size() && s != ".")
                    {
                        path.append((i > 0 ? "/" : "") + s);
                        // i indicates a directory.
                        if (i < k - 1)
                        {
                            auto status = mkdir(path.c_str(), S_IRWXU);
                            if (status == -1)
                            {
                                std::error_code err(errno, std::generic_category());
                                if (err != std::errc::file_exists)
                                {
                                    std::cout << "error making dir: "
                                        << path << ": "
                                        << err.message() << std::endl;
                                }
                            }
                        }
                    }
                }
                fs.open(path, std::ios_base::out);
                if (!fs.good())
                {
                    fs.close();
                    std::cout << "Failed to create file: " << path << std::endl;
                }
                else
                {
                    fs.close();
                    do_fetch();
                    return;
                }
            }
            if (fs.good())
            {
                fs.close();
                if (status() == Status::Current)
                {
                    std::cout << " already up to date." << std::endl;
                }
                else
                {
                    std::cout << " outdated, downloading new." << std::endl;
                    do_fetch();
                }
            }
        }
        Status status()
        {
            std::ifstream is(name());
            if (!is.good())
            {
                return Status::Nonexistent;
            }
            is.close();
            auto calcsum(file_checksum(name()));
            if (calcsum == checksum())
            {
                return Status::Current;
            }
            else
            {
                return Status::Outdated;
            }
        }

    private:
        void do_fetch()
        {
            std::string s;
            std::shared_ptr<CURL *> phandle =
                std::make_shared<CURL *>(curl_easy_init());
            std::string url(patch_dir + name());
            curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str());
            curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
            curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s);
            //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0);
            curl_easy_perform(*phandle);
            curl_easy_cleanup(*phandle);
            phandle.reset();
            std::ofstream ofs(name());
            if (ofs.good())
            {
                ofs << s;
                ofs.close();
                std::cout << "Finished downloading " << name() << std::endl;
            }
            else
            {
                std::cout << "Couldn't write to " << name() << std::endl;
            }
        }

        std::string m_name;
        std::string m_checksum;
};

std::ostream& operator<<(std::ostream &os, const Target &t)
{
    return os << "name: " << t.name() << ", checksum: " << t.checksum();
}

class CurlGlobalInit
{
    public:
        CurlGlobalInit()
        {
            curl_global_init(CURL_GLOBAL_ALL);
        }

        ~CurlGlobalInit()
        {
            curl_global_cleanup();
        }
};

const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
    auto md = EVP_md5();
    const int md_len = MD5_DIGEST_LENGTH;
#else
    auto md = EVP_sha1();
    const int md_len = SHA_DIGEST_LENGTH;
#endif
    std::array<unsigned char, md_len> result;
    EVP_MD_CTX *mdctx = nullptr;
    std::ifstream is(path, std::ifstream::binary);
    if (!is.good())
    {
        std::cout << "Couldn't open file " << path
           << " for checksumming." << std::endl;
        return std::string();
    }

    const int length = 8192;
    std::array<unsigned char, length> buffer;
    auto buf = reinterpret_cast<char *>(buffer.data());
    mdctx = EVP_MD_CTX_create();
    int status = EVP_DigestInit_ex(mdctx, md, nullptr);
    while (status && is)
    {
        is.read(buf, length);
        status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
    }
    status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
    EVP_MD_CTX_destroy(mdctx);
    std::stringstream calcsum;
    calcsum << std::setfill('0');

    for (unsigned char c : result)
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
    /*
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](unsigned char c)
            {
            calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
            });
            */

    return calcsum.str();
}

namespace Options
{
    bool checksum(const std::string &val)
    {
        return val == "checksum";
    }
};

bool confirm()
{
    char c;
    do
    {
        std::cin >> c;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        c = tolower(c);
    } while (c != 'y' && c != 'n');
    return c == 'y';
}

class EfuLauncher
{
    public:
        explicit EfuLauncher(const std::string path, const std::string update_check):
            m_path(path), m_update_check(update_check), m_has_update(false)
    {}

        bool has_update()
        {
            std::string fetch;
            auto phandle(std::make_shared<CURL*>(curl_easy_init()));
            curl_easy_setopt(*phandle, CURLOPT_URL, m_update_check.c_str());
            curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
            curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch);
            curl_easy_perform(*phandle);
            curl_easy_cleanup(*phandle);

            std::vector<std::string> lines(split(fetch, '\n'));
            fetch.clear();
            for (auto beg = std::begin(lines), end = std::end(lines);
                    beg != end; ++beg)
            {
                auto keyvals(split(*beg, '='));
                if (keyvals.size() != 2)
                {
                    std::cerr << "Malformed option: " + *beg +
                        ", aborting launcher update check." << std::endl;
                    return m_has_update = false;
                }
                if (Options::checksum(keyvals[0]))
                {
                    const std::string checksum_test(keyvals[1]);
                    m_has_update = checksum_test != file_checksum(path());
                }
            }
            return m_has_update;
        }

    private:
        const std::string path() const { return m_path; }

        const std::string m_path;
        const std::string m_update_check;
        bool m_has_update;
};

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

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "updatecheck/versioncheck");
    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            std::cout << "Done." << std::endl;
        }
    }

    std::string fetch;
    auto phandle(std::make_shared<CURL *>(curl_easy_init()));
    curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str());
    curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
    curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch);
    curl_easy_perform(*phandle);
    curl_easy_cleanup(*phandle);
    phandle.reset();

    auto lines(split(fetch, '\n'));
    std::vector<Target> new_targets, old_targets;
    for (auto beg = std::begin(lines), end = std::end(lines);
            beg != end; ++beg)
    {
        auto data(split(*beg, '@'));
        Target t(data[0], data[data.size() - 1]);
        auto status = t.status();
        if (status == Target::Status::Nonexistent)
        {
            new_targets.push_back(std::move(t));
        }
        else if (status == Target::Status::Outdated)
        {
            old_targets.push_back(std::move(t));
        }
    }
    if (new_targets.size())
    {
        std::cout << "New targets: " << new_targets.size() << std::endl;
        for (auto &t : new_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No new targets." << std::endl;
    }

    if (old_targets.size())
    {
        std::cout << "Outdated targets: " << old_targets.size() << std::endl;
        for (auto &t : old_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No targets out of date." << std::endl;
    }

#ifndef DEBUG
    for (auto &t : new_targets)
    {
        t.fetch();
    }
    for (auto &t : old_targets)
    {
        t.fetch();
    }
#endif

    return 0;
}
<commit_msg>Prettify code.<commit_after>#include <limits>
#include <algorithm>
#include <array>
#include <iomanip>
#include <curl/curl.h>
#include <memory>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>

const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");

const std::string file_checksum(const std::string &path);

size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata)
{
    std::string *s = static_cast<std::string *>(userdata);
    s->append(ptr, size * nmemb);
    return size * nmemb;
}

std::vector<std::string> &split(const std::string &s, char delim,
        std::vector<std::string> &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

class Target
{
    public:
        enum class Status {
            Nonexistent,
            Outdated,
            Current
        };
        explicit Target(const std::string &name, const std::string &checksum):
            m_name(name.find_first_of('/') == std::string::npos ? name :
                    name, name.find_first_of('/') + 1, name.size() - 1),
            m_checksum(checksum)
            {}
        std::string name() const { return m_name; }
        const std::string checksum() const { return m_checksum; }

        void fetch()
        {
            std::cout << "Statting target " << name() << "...";
            std::string path;
            std::fstream fs(name(), std::ios_base::in);
            if (!fs.good())
            {
                fs.close();
                std::cout << " doesn't exist, creating new." << std::endl;
                auto elems = split(name(), '/');
                for (size_t i = 0, k = elems.size(); i < k; ++i)
                {
                    const std::string &s(elems[i]);
                    if (s.size() && s != ".")
                    {
                        path.append((i > 0 ? "/" : "") + s);
                        // i indicates a directory.
                        if (i < k - 1)
                        {
                            auto status = mkdir(path.c_str(), S_IRWXU);
                            if (status == -1)
                            {
                                std::error_code err(errno, std::generic_category());
                                if (err != std::errc::file_exists)
                                {
                                    std::cout << "error making dir: "
                                        << path << ": "
                                        << err.message() << std::endl;
                                }
                            }
                        }
                    }
                }
                fs.open(path, std::ios_base::out);
                if (!fs.good())
                {
                    fs.close();
                    std::cout << "Failed to create file: " << path << std::endl;
                }
                else
                {
                    fs.close();
                    do_fetch();
                    return;
                }
            }
            if (fs.good())
            {
                fs.close();
                if (status() == Status::Current)
                {
                    std::cout << " already up to date." << std::endl;
                }
                else
                {
                    std::cout << " outdated, downloading new." << std::endl;
                    do_fetch();
                }
            }
        }
        Status status()
        {
            std::ifstream is(name());
            if (!is.good())
            {
                return Status::Nonexistent;
            }
            is.close();
            auto calcsum(file_checksum(name()));
            if (calcsum == checksum())
            {
                return Status::Current;
            }
            else
            {
                return Status::Outdated;
            }
        }

    private:
        void do_fetch()
        {
            std::string s;
            std::shared_ptr<CURL *> phandle =
                std::make_shared<CURL *>(curl_easy_init());
            std::string url(patch_dir + name());
            curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str());
            curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
            curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s);
            //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0);
            curl_easy_perform(*phandle);
            curl_easy_cleanup(*phandle);
            phandle.reset();
            std::ofstream ofs(name());
            if (ofs.good())
            {
                ofs << s;
                ofs.close();
                std::cout << "Finished downloading " << name() << std::endl;
            }
            else
            {
                std::cout << "Couldn't write to " << name() << std::endl;
            }
        }

        std::string m_name;
        std::string m_checksum;
};

std::ostream& operator<<(std::ostream &os, const Target &t)
{
    return os << "name: " << t.name() << ", checksum: " << t.checksum();
}

class CurlGlobalInit
{
    public:
        CurlGlobalInit()
        {
            curl_global_init(CURL_GLOBAL_ALL);
        }

        ~CurlGlobalInit()
        {
            curl_global_cleanup();
        }
};

const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
    auto md = EVP_md5();
    const int md_len = MD5_DIGEST_LENGTH;
#else
    auto md = EVP_sha1();
    const int md_len = SHA_DIGEST_LENGTH;
#endif
    std::array<unsigned char, md_len> result;
    EVP_MD_CTX *mdctx = nullptr;
    std::ifstream is(path, std::ifstream::binary);
    if (!is.good())
    {
        std::cout << "Couldn't open file " << path
           << " for checksumming." << std::endl;
        return std::string();
    }

    const int length = 8192;
    std::array<unsigned char, length> buffer;
    auto buf = reinterpret_cast<char *>(buffer.data());
    mdctx = EVP_MD_CTX_create();
    int status = EVP_DigestInit_ex(mdctx, md, nullptr);
    while (status && is)
    {
        is.read(buf, length);
        status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
    }
    status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
    EVP_MD_CTX_destroy(mdctx);
    std::stringstream calcsum;
    calcsum << std::setfill('0');

    for (unsigned char c : result)
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
    /*
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](unsigned char c)
            {
            calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
            });
            */

    return calcsum.str();
}

namespace Options
{
    bool checksum(const std::string &val)
    {
        return val == "checksum";
    }
};

bool confirm()
{
    char c;
    do
    {
        std::cin >> c;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        c = tolower(c);
    } while (c != 'y' && c != 'n');
    return c == 'y';
}

class EfuLauncher
{
    public:
        explicit EfuLauncher(const std::string path,
                const std::string update_check):
            m_path(path),
            m_update_check(update_check),
            m_has_update(false)
    {}

        bool has_update()
        {
            std::string fetch;
            auto phandle(std::make_shared<CURL*>(curl_easy_init()));
            curl_easy_setopt(*phandle, CURLOPT_URL, m_update_check.c_str());
            curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
            curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch);
            curl_easy_perform(*phandle);
            curl_easy_cleanup(*phandle);

            std::vector<std::string> lines(split(fetch, '\n'));
            fetch.clear();
            for (auto beg = std::begin(lines), end = std::end(lines);
                    beg != end; ++beg)
            {
                auto keyvals(split(*beg, '='));
                if (keyvals.size() != 2)
                {
                    std::cerr << "Malformed option: " + *beg +
                        ", aborting launcher update check." << std::endl;
                    return m_has_update = false;
                }
                if (Options::checksum(keyvals[0]))
                {
                    const std::string checksum_test(keyvals[1]);
                    m_has_update = checksum_test != file_checksum(path());
                }
            }
            return m_has_update;
        }

    private:
        const std::string path() const { return m_path; }

        const std::string m_path;
        const std::string m_update_check;
        bool m_has_update;
};

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

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "updatecheck/versioncheck");
    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            std::cout << "Done." << std::endl;
        }
    }

    std::string fetch;
    auto phandle(std::make_shared<CURL *>(curl_easy_init()));
    curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str());
    curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
    curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch);
    curl_easy_perform(*phandle);
    curl_easy_cleanup(*phandle);
    phandle.reset();

    auto lines(split(fetch, '\n'));
    std::vector<Target> new_targets, old_targets;
    for (auto beg = std::begin(lines), end = std::end(lines);
            beg != end; ++beg)
    {
        auto data(split(*beg, '@'));
        Target t(data[0], data[data.size() - 1]);
        auto status = t.status();
        if (status == Target::Status::Nonexistent)
        {
            new_targets.push_back(std::move(t));
        }
        else if (status == Target::Status::Outdated)
        {
            old_targets.push_back(std::move(t));
        }
    }
    if (new_targets.size())
    {
        std::cout << "New targets: " << new_targets.size() << std::endl;
        for (auto &t : new_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No new targets." << std::endl;
    }

    if (old_targets.size())
    {
        std::cout << "Outdated targets: " << old_targets.size() << std::endl;
        for (auto &t : old_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No targets out of date." << std::endl;
    }

#ifndef DEBUG
    for (auto &t : new_targets)
    {
        t.fetch();
    }
    for (auto &t : old_targets)
    {
        t.fetch();
    }
#endif

    return 0;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *                                                                         *
 * Copyright (C) 2007-2015 by frePPLe bvba                                 *
 *                                                                         *
 * This library is free software; you can redistribute it and/or modify it *
 * under the terms of the GNU Affero General Public License as published   *
 * by the Free Software Foundation; either version 3 of the License, or    *
 * (at your option) any later version.                                     *
 *                                                                         *
 * This library 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 Affero General Public License for more details.                     *
 *                                                                         *
 * You should have received a copy of the GNU Affero General Public        *
 * License along with this program.                                        *
 * If not, see <http://www.gnu.org/licenses/>.                             *
 *                                                                         *
 ***************************************************************************/

#include "freppleinterface.h"
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
using namespace std;

void usage()
{
  cout << "\nfrePPLe v" << FreppleVersion() << " command line application\n"
      "\nUsage:\n"
      "  frepple [options] [files | directories]\n"
      "\nThis program reads XML input data, and executes the modeling and\n"
      "planning commands included in them.\n"
      "The XML input can be provided in the following ways:\n"
      "  - Passing one or more XML files and/or directories as arguments.\n"
      "    When a directory is specified, the application will process\n"
      "    all files with the extension '.xml'.\n"
      "  - Passing one or more Python files with the extension '.py'\n"
      "    The Python commands are executed in the embedded interpreter.\n"
      "  - When passing no file or directory arguments, input will be read\n"
      "    from the standard input. XML data can be piped to the application.\n"
      "\nOptions:\n"
      "  -validate -v  Validate the XML input for correctness.\n"
      "  -check -c     Only validate the input, without executing the content.\n"
      "  -? -h -help   Show these instructions.\n"
      "\nEnvironment: The variable FREPPLE_HOME optionally points to a\n"
      "     directory where the initialization files init.xml, init.py,\n"
      "     frepple.xsd and module libraries will be searched.\n"
      "\nReturn codes: 0 when successful, non-zero in case of errors\n"
      "\nMore information on this program: http://www.frepple.com\n\n"
      << endl;
}

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

  // Storing the chosen options...
  bool validate = false;
  bool validate_only = false;
  bool input = false;

  try
  {
    // Analyze the command line arguments.
    for (int i = 1; i < argc; ++i)
    {
      if (argv[i][0] == '-')
      {
        // An option on the command line
        if (!strcmp(argv[i],"-validate") || !strcmp(argv[i],"-v"))
          validate = true;
        else if (!strcmp(argv[i],"-check") || !strcmp(argv[i],"-c"))
          validate_only = true;
        else
        {
          if (strcmp(argv[i],"-?")
              && strcmp(argv[i],"-h")
              && strcmp(argv[i],"-help"))
            cout << "\nError: Option '" << argv[i]
                << "' not recognized." << endl;
          usage();
          return EXIT_FAILURE;
        }
      }
      else
      {
        // A file or directory name on the command line
        if (!input)
        {
          // Initialize the library if this wasn't done before
          FreppleInitialize();
          input = true;
        }
        if (strlen(argv[i])>=3 && !strcmp(argv[i]+strlen(argv[i])-3,".py"))
          // Execute as Python file
          FreppleReadPythonFile(argv[i]);
        else
          // Execute as XML file
          FreppleReadXMLFile(argv[i], validate, validate_only);
      }
    }

    // When no filenames are specified, we read the standard input
    if (!input)
    {
      FreppleInitialize();
      FreppleReadXMLFile(nullptr, validate, validate_only);
    }
  }
  catch (const exception& e)
  {
    ostringstream ch;
    ch << "Error: " << e.what();
    FreppleLog(ch.str());
    return EXIT_FAILURE;
  }
  catch (...)
  {
    FreppleLog("Error: Unknown exception type");
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
<commit_msg>Adding signal handlers to print a message when a crash occurs<commit_after>/***************************************************************************
 *                                                                         *
 * Copyright (C) 2007-2015 by frePPLe bvba                                 *
 *                                                                         *
 * This library is free software; you can redistribute it and/or modify it *
 * under the terms of the GNU Affero General Public License as published   *
 * by the Free Software Foundation; either version 3 of the License, or    *
 * (at your option) any later version.                                     *
 *                                                                         *
 * This library 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 Affero General Public License for more details.                     *
 *                                                                         *
 * You should have received a copy of the GNU Affero General Public        *
 * License along with this program.                                        *
 * If not, see <http://www.gnu.org/licenses/>.                             *
 *                                                                         *
 ***************************************************************************/

#include "freppleinterface.h"
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <signal.h>
using namespace std;

void usage()
{
  cout << "\nfrePPLe v" << FreppleVersion() << " command line application\n"
      "\nUsage:\n"
      "  frepple [options] [files | directories]\n"
      "\nThis program reads XML input data, and executes the modeling and\n"
      "planning commands included in them.\n"
      "The XML input can be provided in the following ways:\n"
      "  - Passing one or more XML files and/or directories as arguments.\n"
      "    When a directory is specified, the application will process\n"
      "    all files with the extension '.xml'.\n"
      "  - Passing one or more Python files with the extension '.py'\n"
      "    The Python commands are executed in the embedded interpreter.\n"
      "  - When passing no file or directory arguments, input will be read\n"
      "    from the standard input. XML data can be piped to the application.\n"
      "\nOptions:\n"
      "  -validate -v  Validate the XML input for correctness.\n"
      "  -check -c     Only validate the input, without executing the content.\n"
      "  -? -h -help   Show these instructions.\n"
      "\nEnvironment: The variable FREPPLE_HOME optionally points to a\n"
      "     directory where the initialization files init.xml, init.py,\n"
      "     frepple.xsd and module libraries will be searched.\n"
      "\nReturn codes: 0 when successful, non-zero in case of errors\n"
      "\nMore information on this program: http://www.frepple.com\n\n"
      << endl;
}

void handler(int sig)
{
  cout << "Planning engine terminated with signal " << sig << endl;
  exit(1);
}

int main (int argc, char *argv[])
{
  // Install signal handlers
  signal(SIGABRT, handler);
  signal(SIGFPE, handler);
  signal(SIGILL, handler);
  signal(SIGINT, handler);
  signal(SIGSEGV, handler);
  signal(SIGTERM, handler);

  // Storing the chosen options...
  bool validate = false;
  bool validate_only = false;
  bool input = false;

  try
  {
    // Analyze the command line arguments.
    for (int i = 1; i < argc; ++i)
    {
      if (argv[i][0] == '-')
      {
        // An option on the command line
        if (!strcmp(argv[i],"-validate") || !strcmp(argv[i],"-v"))
          validate = true;
        else if (!strcmp(argv[i],"-check") || !strcmp(argv[i],"-c"))
          validate_only = true;
        else
        {
          if (strcmp(argv[i],"-?")
              && strcmp(argv[i],"-h")
              && strcmp(argv[i],"-help"))
            cout << "\nError: Option '" << argv[i]
                << "' not recognized." << endl;
          usage();
          return EXIT_FAILURE;
        }
      }
      else
      {
        // A file or directory name on the command line
        if (!input)
        {
          // Initialize the library if this wasn't done before
          FreppleInitialize();
          input = true;
        }
        if (strlen(argv[i])>=3 && !strcmp(argv[i]+strlen(argv[i])-3,".py"))
          // Execute as Python file
          FreppleReadPythonFile(argv[i]);
        else
          // Execute as XML file
          FreppleReadXMLFile(argv[i], validate, validate_only);
      }
    }

    // When no filenames are specified, we read the standard input
    if (!input)
    {
      FreppleInitialize();
      FreppleReadXMLFile(nullptr, validate, validate_only);
    }
  }
  catch (const exception& e)
  {
    ostringstream ch;
    ch << "Error: " << e.what();
    FreppleLog(ch.str());
    return EXIT_FAILURE;
  }
  catch (...)
  {
    FreppleLog("Error: Unknown exception type");
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <math.h>

#if defined(_WIN32)
#include <Windows.h>
#include <gl/GL.h>
#else
#include <OpenGL/gl.h>
#endif
#include <api.h>

extern void render_next_gl(uint64_t time_micros)
{
        double const phase = 6.30 * time_micros / 1e6 / 6.0;
        float sincos[2] = {
                0.49f * sinf(phase),
                0.49f * cosf(phase),
        };
        float const argb[4] = {
                0.0f, 0.31f + 0.09f * sincos[0], 0.27f + 0.09f * sincos[1], 0.29f
        };
        glClearColor (argb[1], argb[2], argb[3], argb[0]);
        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

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

        runtime_init();

        return 0;
}
<commit_msg>example audio (a drone at around 220hz)<commit_after>#include <math.h>

#if defined(_WIN32)
#include <Windows.h>
#include <gl/GL.h>
#else
#include <OpenGL/gl.h>
#endif
#include <api.h>

extern void render_next_2chn_48khz_audio(uint64_t time_micros,
                int const sample_count, double left[/*sample_count*/],
                double right[/*sample_count*/])
{
        static double sc_phase = 0.0;
        static double l_phase = 0.0;
        static double r_phase = 0.0;
        double const drone_hz = 220.0;

        for (int i = 0; i < sample_count; i++) {
                double sincos[2] = {
                        0.49 * sin(sc_phase),
                        0.49 * cos(sc_phase),
                };

                left[i] = 0.5 * sin(l_phase);
                right[i] = 0.5 * sin(r_phase);
                l_phase += (1.0f + 0.02f * sincos[0]) * drone_hz * 6.30 / 48000.0;
                r_phase += (1.0f + 0.02f * sincos[1]) * drone_hz * 6.30 / 48000.0;
                sc_phase += 6.30 / 48000.0 / 6.0;
        }
}

extern void render_next_gl(uint64_t time_micros)
{
        double const phase = 6.30 * time_micros / 1e6 / 6.0;
        float sincos[2] = {
                0.49f * sinf(phase),
                0.49f * cosf(phase),
        };
        float const argb[4] = {
                0.0f, 0.31f + 0.09f * sincos[0], 0.27f + 0.09f * sincos[1], 0.29f
        };
        glClearColor (argb[1], argb[2], argb[3], argb[0]);
        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

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

        runtime_init();

        return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
 * Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
 * Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
 *
 * This file is part of SuperKaramba.
 *
 *  SuperKaramba is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  SuperKaramba 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SuperKaramba; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#include <karambaapp.h>
#include <qobject.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmainwindow.h>
#include <qfileinfo.h>
#include <qstringlist.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kdeversion.h>

#include "karamba.h"
#include "karambasessionmanaged.h"
#include "karambainterface.h"
#include "karamba_python.h"

static const char *description =
    I18N_NOOP("A KDE Eye-candy Application");

static const char *version = "0.37";

static KCmdLineOptions options[] =
{
  // { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
  // { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
  { "+file", I18N_NOOP("A required argument 'file'"), 0 },
  { 0, 0, 0 }
};

// This is for redirecting all qWarning, qDebug,... messages to file.
// Usefull when testing session management issues etc.
// #define KARAMBA_LOG 1

#ifdef KARAMBA_LOG

void karambaMessageOutput(QtMsgType type, const char *msg)
{
  FILE* fp = fopen("/tmp/karamba.log", "a");
  if(fp)
  {
    pid_t pid = getpid();

    switch ( type )
    {
        case QtDebugMsg:
            fprintf( fp, "Debug (%d): %s\n", pid, msg );
            break;
        case QtWarningMsg:
            if (strncmp(msg, "X Error", 7) != 0)
              fprintf( fp, "Warning (%d): %s\n", pid, msg );
            break;
        case QtFatalMsg:
            fprintf( fp, "Fatal (%d): %s\n", pid, msg );
            abort();                    // deliberately core dump
    }
    fclose(fp);
  }
}

#endif

int main(int argc, char **argv)
{
#ifdef KARAMBA_LOG
    qInstallMsgHandler(karambaMessageOutput);
#endif
    KAboutData about("superkaramba", I18N_NOOP("SuperKaramba"),
                     version, description,
                     KAboutData::License_GPL,
                     "(c) 2003-2005 The SuperKaramba developers");
    about.addAuthor("Adam Geitgey", 0, "adam@rootnode.org");
    about.addAuthor("Hans Karlsson", 0, "karlsson.h@home.se");
    about.addAuthor("Ryan Nickell", 0, "p0z3r@earthlink.net");
    about.addAuthor("Petri Damstén", 0, "petri.damsten@iki.fi");
    KCmdLineArgs::init(argc, argv, &about);
    KCmdLineArgs::addCmdLineOptions(options);
    KSessionManaged ksm;
    //karamba *mainWin = 0;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    QStringList lst;
    int ret = 0;

    // Create ~/.superkaramba if necessary
    KarambaApplication::checkSuperKarambaDir();

    KarambaApplication::lockKaramba();

    KarambaApplication app;

    QString mainAppId = app.getMainKaramba();
    if(!mainAppId.isEmpty())
    {
      app.initDcopStub(mainAppId.ascii());
    }
    else
    {
      //Set up systray icon
      app.setUpSysTray(&about);
      app.initDcopStub();
    }

    KarambaApplication::unlockKaramba();

    app.connect(qApp,SIGNAL(lastWindowClosed()),qApp,SLOT(quit()));

    // Try to restore a previous session if applicable.
    app.checkPreviousSession(app, lst);
    if(lst.size() == 0)
    {
      //Not a saved session - check for themes given on command line
      app.checkCommandLine(args, lst);

      if(lst.size() == 0)
      {
        //No themes given on command line and no saved session.
        //Show welcome dialog.
        app.globalShowThemeDialog();
      }
    }

    args->clear();

    KarambaPython::initPython();
    //qDebug("startThemes");
    if(app.startThemes(lst) || mainAppId.isEmpty())
      ret = app.exec();
    KarambaPython::shutdownPython();
    return ret;
}
<commit_msg>BUG:118920 Don't pop up the Theme Dialog when restoring a session and there aren't any themes saved in the session.<commit_after>/*
 * Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
 * Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
 * Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
 *
 * This file is part of SuperKaramba.
 *
 *  SuperKaramba is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  SuperKaramba 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SuperKaramba; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#include <karambaapp.h>
#include <qobject.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmainwindow.h>
#include <qfileinfo.h>
#include <qstringlist.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kdeversion.h>

#include "karamba.h"
#include "karambasessionmanaged.h"
#include "karambainterface.h"
#include "karamba_python.h"

static const char *description =
    I18N_NOOP("A KDE Eye-candy Application");

static const char *version = "0.37";

static KCmdLineOptions options[] =
{
  // { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
  // { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
  { "+file", I18N_NOOP("A required argument 'file'"), 0 },
  { 0, 0, 0 }
};

// This is for redirecting all qWarning, qDebug,... messages to file.
// Usefull when testing session management issues etc.
// #define KARAMBA_LOG 1

#ifdef KARAMBA_LOG

void karambaMessageOutput(QtMsgType type, const char *msg)
{
  FILE* fp = fopen("/tmp/karamba.log", "a");
  if(fp)
  {
    pid_t pid = getpid();

    switch ( type )
    {
        case QtDebugMsg:
            fprintf( fp, "Debug (%d): %s\n", pid, msg );
            break;
        case QtWarningMsg:
            if (strncmp(msg, "X Error", 7) != 0)
              fprintf( fp, "Warning (%d): %s\n", pid, msg );
            break;
        case QtFatalMsg:
            fprintf( fp, "Fatal (%d): %s\n", pid, msg );
            abort();                    // deliberately core dump
    }
    fclose(fp);
  }
}

#endif

int main(int argc, char **argv)
{
#ifdef KARAMBA_LOG
    qInstallMsgHandler(karambaMessageOutput);
#endif
    KAboutData about("superkaramba", I18N_NOOP("SuperKaramba"),
                     version, description,
                     KAboutData::License_GPL,
                     "(c) 2003-2005 The SuperKaramba developers");
    about.addAuthor("Adam Geitgey", 0, "adam@rootnode.org");
    about.addAuthor("Hans Karlsson", 0, "karlsson.h@home.se");
    about.addAuthor("Ryan Nickell", 0, "p0z3r@earthlink.net");
    about.addAuthor("Petri Damstén", 0, "petri.damsten@iki.fi");
    KCmdLineArgs::init(argc, argv, &about);
    KCmdLineArgs::addCmdLineOptions(options);
    KSessionManaged ksm;
    //karamba *mainWin = 0;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    QStringList lst;
    int ret = 0;

    // Create ~/.superkaramba if necessary
    KarambaApplication::checkSuperKarambaDir();

    KarambaApplication::lockKaramba();

    KarambaApplication app;

    QString mainAppId = app.getMainKaramba();
    if(!mainAppId.isEmpty())
    {
      app.initDcopStub(mainAppId.ascii());
    }
    else
    {
      //Set up systray icon
      app.setUpSysTray(&about);
      app.initDcopStub();
    }

    KarambaApplication::unlockKaramba();

    app.connect(qApp,SIGNAL(lastWindowClosed()),qApp,SLOT(quit()));

    // Try to restore a previous session if applicable.
    app.checkPreviousSession(app, lst);
    if( (lst.size() == 0) && !app.isRestored() )
    {
      //Not a saved session - check for themes given on command line
      app.checkCommandLine(args, lst);

      if(lst.size() == 0)
      {
        //No themes given on command line and no saved session.
        //Show welcome dialog.
        app.globalShowThemeDialog();
      }
    }

    args->clear();

    KarambaPython::initPython();
    //qDebug("startThemes");
    if(app.startThemes(lst) || mainAppId.isEmpty())
      ret = app.exec();
    KarambaPython::shutdownPython();
    return ret;
}
<|endoftext|>


<commit_before>#include "common.h"
#include "parser.h"
#include "wrap.h"
#include "ir.h"
#include "cps.h"
#include "compile.h"
#include <iostream>
#include "assets.h"

using namespace cirth;

void compile(const std::string& src) {

}

int main(int argc, char** argv) {
  std::string str;
  std::ostringstream os;
  os << assets::PRELUDE_CTH << "\n";

  while(getline(std::cin, str)) {
    os << str << '\n';
  }

  try {
    std::vector<PTR<ast::Expression> > ast;
    bool r = parser::parse(os.str(), ast);
    if(!r) throw expectation_failure("failed parsing!");

    std::vector<PTR<ir::Expression> > ir;
    wrap::ir_prepend(ir);
    ir::Name lastval(NULL_VALUE);
    ir::convert(ast, ir, lastval);
    ast.clear();

    PTR<cps::Expression> cps;
    cps::transform(ir, lastval, cps);
    ir.clear();

    compile::compile(cps, std::cout);
  } catch (const std::exception& e) {
    std::cerr << "failure: " << e.what() << std::endl;
    return 1;
  }

  return 0;
}
<commit_msg>cruft<commit_after>#include "common.h"
#include "parser.h"
#include "wrap.h"
#include "ir.h"
#include "cps.h"
#include "compile.h"
#include <iostream>
#include "assets.h"

using namespace cirth;

int main(int argc, char** argv) {
  std::string str;
  std::ostringstream os;
  os << assets::PRELUDE_CTH << "\n";

  while(getline(std::cin, str)) {
    os << str << '\n';
  }

  try {
    std::vector<PTR<ast::Expression> > ast;
    bool r = parser::parse(os.str(), ast);
    if(!r) throw expectation_failure("failed parsing!");

    std::vector<PTR<ir::Expression> > ir;
    wrap::ir_prepend(ir);
    ir::Name lastval(NULL_VALUE);
    ir::convert(ast, ir, lastval);
    ast.clear();

    PTR<cps::Expression> cps;
    cps::transform(ir, lastval, cps);
    ir.clear();

    compile::compile(cps, std::cout);
  } catch (const std::exception& e) {
    std::cerr << "failure: " << e.what() << std::endl;
    return 1;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "main.hpp"

#include <cstring>
#include <iostream>

using namespace std;

int main(int argc, const char* argv[]) {
    // Print help
    if (argc == 0 || strcmp(argv[0], "--help")) {
        cout << "Headerize is a tool to convert resource files to headers for inclusion in C/C++ projects." << endl
             << "Usage:" << endl
             << "Headerize input output" << endl;
        return 0;
    }

    /// @todo: Actual usage

    return 0;
}
<commit_msg>Get input and output filenames<commit_after>#include "main.hpp"

#include <cstring>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    // Print help
    if (argc == 1 || strcmp(argv[0], "--help") == 0) {
        cout << "Headerize is a tool to convert resource files to headers for inclusion in C/C++ projects." << endl
             << "Usage:" << endl
             << "Headerize input output" << endl;
        return 0;
    }

    // Get input and output names.
    string inputName = argv[1];
    string outputName;
    if (argc > 2)
        outputName = argv[2];
    else
        outputName = inputName + ".hzz";

    cout << inputName << " " << outputName;

    /// @todo: Read and write files

    return 0;
}
<|endoftext|>


<commit_before>//
//  ns_classes.cpp
//  NetworkSimulator
//
//  Created by Tommi Gröhn on 13.11.2015.
//

#include <iostream>
#include "network/NetworkSimulator.h"
#include "ui/NetworkSimulatorTestUI.h"
#include "application/TestRouter.h"
#include "link/TestLink.h"
#include "link/ParametricLink.h"
#include "application/PacketGenerator.h"
#include "application/PacketReceiver.h"
#include "application/RandomRouter.h"

/**
 * Simple test case.
 */
int main() {

    NetworkSimulator ns;

    // create some nodes
    ns.addNode("A");
    ns.addNode("B");
    ns.addNode("C");
    ns.addNode("D");

    // add some applications running on nodes
    ns.getNode("A")->addApplications(new PacketReceiver);
    ns.getNode("A")->addApplications(new TestRouter);
    ns.getNode("B")->addApplications(new PacketReceiver);
    ns.getNode("B")->addApplications(new TestRouter);
    ns.getNode("C")->addApplications(new PacketReceiver);
    ns.getNode("C")->addApplications(new TestRouter);
    ns.getNode("D")->addApplications(new PacketReceiver);
    ns.getNode("D")->addApplications(new PacketGenerator(1, ns.getAddresses()));
    ns.getNode("D")->addApplications(new TestRouter);
    //ns.getNode("A")->receivePacket(new Packet("A", "C", "P1"));
    //ns.getNode("A")->receivePacket(new Packet("A", "C", "P2"));

    // create some links between nodes
    ns.addLink("A", "B", 1, new ParametricLink(10.0, 100.0));
    ns.addLink("B", "C", 1, new ParametricLink(5.0, 10.0));
    ns.addLink("C", "D", 1, new ParametricLink(2.0, 10.0));
    ns.addLink("D", "A", 1, new ParametricLink(1.0, 10.0));

    // try some node deletion, some issues with this...
    // ns.removeNode("B");

    // set UI
    ns.setUI(new NetworkSimulatorTestUI);

    // run (timer has currently some hard-coded test values)
    ns.startTimer();

    for (auto& l : ns.getLinks()) {
        // print traffic logs
        std::cout
            << "Transmission log for link "
            <<l->getSource()->getAddress()
            << l->getDestination()->getAddress()
            << " : "
            << std::endl;
        for (auto& logEntry : l->getTransmissionLog()) {
            std::cout
                << "["
                << logEntry.first
                << ", "
                << logEntry.second / 1000.0
                << "]"
                << std::endl;
        }

        // print queue lengths
        std::cout
        << "Queue length in front of link "
        <<l->getSource()->getAddress()
        << l->getDestination()->getAddress()
        << " : "
        << l->getQueueLength()
        << std::endl;

        std::cout<< std::endl;
    }

}
<commit_msg>Minor changes to main() to test simultaneous transmission of multiple packets on same link.<commit_after>//
//  ns_classes.cpp
//  NetworkSimulator
//
//  Created by Tommi Gröhn on 13.11.2015.
//

#include <iostream>
#include "network/NetworkSimulator.h"
#include "ui/NetworkSimulatorTestUI.h"
#include "application/TestRouter.h"
#include "link/TestLink.h"
#include "link/ParametricLink.h"
#include "application/PacketGenerator.h"
#include "application/PacketReceiver.h"
#include "application/RandomRouter.h"

/**
 * Simple test case.
 */
int main() {

    NetworkSimulator ns;

    // create some nodes
    ns.addNode("A");
    ns.addNode("B");
    ns.addNode("C");
    ns.addNode("D");

    // add some applications running on nodes
    ns.getNode("A")->addApplications(new PacketReceiver);
    ns.getNode("A")->addApplications(new TestRouter);
    ns.getNode("B")->addApplications(new PacketReceiver);
    ns.getNode("B")->addApplications(new TestRouter);
    ns.getNode("C")->addApplications(new PacketReceiver);
    ns.getNode("C")->addApplications(new TestRouter);
    ns.getNode("D")->addApplications(new PacketReceiver);
    ns.getNode("D")->addApplications(new PacketGenerator(1, ns.getAddresses()));
    ns.getNode("D")->addApplications(new TestRouter);
    //ns.getNode("A")->receivePacket(new Packet("A", "C", "P1"));
    //ns.getNode("A")->receivePacket(new Packet("A", "C", "P2"));

    // create some links between nodes
    ns.addLink("A", "B", 1, new ParametricLink(10.0, 200.0));
    ns.addLink("B", "C", 1, new ParametricLink(5.0, 100.0));
    ns.addLink("C", "D", 1, new ParametricLink(2.0, 50.0));
    ns.addLink("D", "A", 1, new ParametricLink(1.0, 50.0));

    // try some node deletion, some issues with this...
    // ns.removeNode("B");

    // set UI
    ns.setUI(new NetworkSimulatorTestUI);

    // run (timer has currently some hard-coded test values)
    ns.startTimer();

    for (auto& l : ns.getLinks()) {
        // print traffic logs
        std::cout
            << "Transmission log for link "
            <<l->getSource()->getAddress()
            << l->getDestination()->getAddress()
            << " : "
            << std::endl;
        for (auto& logEntry : l->getTransmissionLog()) {
            std::cout
                << "["
                << logEntry.first
                << ", "
                << logEntry.second / 1000.0
                << "]"
                << std::endl;
        }

        // print queue lengths
        std::cout
        << "Queue length in front of link "
        <<l->getSource()->getAddress()
        << l->getDestination()->getAddress()
        << " : "
        << l->getQueueLength()
        << std::endl;

        std::cout<< std::endl;
    }

}
<|endoftext|>


<commit_before>#include <fstream>

#include <boost/filesystem.hpp>

#include <simple-web-server/server_http.hpp>
#include <neatnet/genalg.h>

using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;

void default_resource_send(const HttpServer &server, const std::shared_ptr<HttpServer::Response> &response,
                           const std::shared_ptr<std::ifstream> &ifs);

int main(int argc, const char* argv[])
{
    HttpServer server;
    server.config.port = 8080;

    server.default_resource["GET"] = [&server](std::shared_ptr<HttpServer::Response> response,
                                               std::shared_ptr<HttpServer::Request> request)
    {
        try
        {
            auto web_root_path = boost::filesystem::canonical("web");
            auto path = boost::filesystem::canonical(web_root_path / request->path);

            std::cout << path << std::endl;
            if(boost::filesystem::is_directory(path))
            {
                path /= "index.html";
            }

            if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
            {
                throw std::invalid_argument("file does not exist");
            }

            auto ifs = std::make_shared<std::ifstream>();
            ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate);

            if(*ifs)
            {
                auto length = ifs->tellg();
                ifs->seekg(0, std::ios::beg);
                auto cache_control = "Cache-Control: no-cache, no-store, must_revalidate\r\nPragma: no-cache\r\nExpires: 0\r\n";

                *response << "HTTP/1.1 200 OK\r\n" << cache_control << "Content-Length: " << length << "\r\n\r\n";
                default_resource_send(server, response, ifs);
            }
            else
            {
                throw std::invalid_argument("could not read file");
            }
        }
        catch(const std::exception& e)
        {
            std::string content = "Could not open path " + request->path + ": " + e.what();
            *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: "
                      << content.length()
                      << "\r\n\r\n"
                      << content;
        }
    };

    std::thread server_thread([&server]()
    {
        server.start();
    });

    std::this_thread::sleep_for(std::chrono::seconds(1));

    server_thread.join();

    return 0;
}

void default_resource_send(const HttpServer &server,
                           const std::shared_ptr<HttpServer::Response> &response,
                           const std::shared_ptr<std::ifstream> &ifs)
{
    //read and send 128 KB at a time
    std::vector<char> buffer(131072); // Safe when server is running on one thread
    std::streamsize read_length;
    if((read_length=ifs->read(&buffer[0], buffer.size()).gcount())>0)
    {
        response->write(&buffer[0], read_length);

        if(read_length == static_cast<std::streamsize>(buffer.size()))
        {
            server.send(response,
                [&server, response, ifs](const boost::system::error_code &ec)
                {
                    if(!ec)
                        default_resource_send(server, response, ifs);
                    else
                        std::cerr << "Connection interrupted" << std::endl;
                }
            );
        }
    }
}
<commit_msg>Refactor request handlers<commit_after>#include <fstream>

#include <boost/filesystem.hpp>
#include "json.hpp"

#include <simple-web-server/server_http.hpp>
#include <neatnet/genalg.h>

using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;

const std::string HEAD = "HTTP/1.1 ";

//================== Function declarations ====================
void default_resource_send(const HttpServer &server, const std::shared_ptr<HttpServer::Response> &response,
                           const std::shared_ptr<std::ifstream> &ifs);

void fitness_handler(std::shared_ptr<HttpServer::Response> response,
                     std::shared_ptr<HttpServer::Request> request);

void default_resource_handler(HttpServer& server, std::shared_ptr<HttpServer::Response>& response,
                              std::shared_ptr<HttpServer::Request>& request);

//================== Main ====================
int main(int argc, const char* argv[])
{
    HttpServer server;
    server.config.port = 8080;

    // Register request handlers here
    server.resource["^/fitness$"]["POST"] = fitness_handler;

    server.default_resource["GET"] = [&server](std::shared_ptr<HttpServer::Response> response,
                                               std::shared_ptr<HttpServer::Request> request)
    {
        default_resource_handler(server, response, request);
    };

    std::thread server_thread([&server]()
    {
        server.start();
    });

    std::this_thread::sleep_for(std::chrono::seconds(1));

    server_thread.join();

    return 0;
}

//================== Function definitions ====================

/**
 * All requests that are not defined explicitly are assumed to be file reqeusts, and this handler fetches them.
 */
void default_resource_handler(HttpServer& server,
                              std::shared_ptr<HttpServer::Response>& response,
                              std::shared_ptr<HttpServer::Request>& request)
{
    try
    {
        auto web_root_path = boost::filesystem::canonical("web");
        auto path = boost::filesystem::canonical(web_root_path / request->path);

        std::cout << path << std::endl;
        if(boost::filesystem::is_directory(path))
        {
            path /= "index.html";
        }

        if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
        {
            throw std::invalid_argument("file does not exist");
        }

        auto ifs = std::make_shared<std::ifstream>();
        ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate);

        if(*ifs)
        {
            auto length = ifs->tellg();
            ifs->seekg(0, std::ios::beg);
            auto cache_control = "Cache-Control: no-cache, no-store, must_revalidate\r\nPragma: no-cache\r\nExpires: 0\r\n";

            *response << "HTTP/1.1 200 OK\r\n" << cache_control << "Content-Length: " << length << "\r\n\r\n";
            default_resource_send(server, response, ifs);
        }
        else
        {
            throw std::invalid_argument("could not read file");
        }
    }
    catch(const std::exception& e)
    {
        std::string content = "Could not open path " + request->path + ": " + e.what();
        *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: "
                  << content.length()
                  << "\r\n\r\n"
                  << content;
    }
}

/**
 * Handles fitnesses coming from the client.
 */
void fitness_handler(std::shared_ptr<HttpServer::Response> response,
                     std::shared_ptr<HttpServer::Request> request)
{
    using json = nlohmann::json;
    try
    {
        std::string post_data = request->content.string();
        std::cout << "Content: " << post_data << std::endl;
        json obj = json::parse(post_data);

        json json_response;
        json_response["success"] = true;

        std::string result = json_response.dump();
        *response << HEAD << "200 OK\r\n"
                  << "Content-Type: application/json\r\n"
                  << "Content-Length: " << result.length() << "\r\n\r\n"
                  << result;
    }
    catch(std::exception& e)
    {
        std::cerr << "Didn't handle /fitness POST: " << e.what() << std::endl;
        *response << HEAD << "400 Bad Request\r\nContent-Length: " << std::strlen(e.what()) << "\r\n\r\n" << e.what();
    }
}

/**
 * Send contents of input file stream to the client
 */
void default_resource_send(const HttpServer& server,
                           const std::shared_ptr<HttpServer::Response>& response,
                           const std::shared_ptr<std::ifstream>& ifs)
{
    //read and send 128 KB at a time
    std::shared_ptr<std::vector<char>> buffer = std::make_shared<std::vector<char>>(131072);
    std::streamsize read_length;
    if((read_length=ifs->read(&(*(buffer))[0], buffer->size()).gcount())>0)
    {
        response->write(&(*(buffer))[0], read_length);

        if(read_length == static_cast<std::streamsize>(buffer->size()))
        {
            server.send(response,
                [&server, response, ifs](const boost::system::error_code &ec)
                {
                    if(!ec)
                        default_resource_send(server, response, ifs);
                    else
                        std::cerr << "Connection interrupted" << std::endl;
                }
            );
        }
    }
}
<|endoftext|>


<commit_before>#include <ch.hpp>
#include <hal.h>
#include <chprintf.h>

#include <config.hpp>

// Estimators
#include <estimator/dcm_attitude_estimator.hpp>

// Drivers
#include <drivers/l3gd20.hpp>
#include <drivers/lsm303dlhc.hpp>

// Input sources
#include <input/pwm_receiver_input_source.hpp>

// Controllers
#include <controller/controller_pipeline.hpp>
#include <controller/attitude_controller.hpp>
#include <controller/attitude_rate_controller.hpp>

// Misc
// #include <communicator.hpp>
// TODO: Think about how to integrate debugging cleanly.
#include <debugger.hpp>

// Systems
#include <system/default_multirotor_vehicle_system.hpp>

using namespace chibios_rt;

class HeartbeatThread : public BaseStaticThread<64> {
public:
  HeartbeatThread() : BaseStaticThread<64>() {
  }

  virtual msg_t main() {
    setName("heartbeat");

    while(true) {
      palSetPad(GPIOE, GPIOE_LED3_RED);
      sleep(MS2ST(500));
      palClearPad(GPIOE, GPIOE_LED3_RED);
      sleep(MS2ST(500));
    }

    return 0;
  }
};

static HeartbeatThread heartbeatThread;
static Debugger debugger;

int main(void) {
  halInit();
  System::init();

  // Start the background threads
  heartbeatThread.start(NORMALPRIO + 10);
  debugger.start(NORMALPRIO + 10);

  spiInit();
  i2cInit();

  // Start USART
  sdStart(&SD1, &usart1_config);
  palSetPadMode(GPIOA, 9, PAL_MODE_ALTERNATE(7));
  palSetPadMode(GPIOA, 10, PAL_MODE_ALTERNATE(7));

  // Build and initialize the system
  L3GD20 gyro(&SPID1);
  LSM303DLHC accel(&I2CD1);

  gyro.init();
  accel.init();

  DefaultMultirotorVehicleSystem system(&accel, &gyro);
  system.init();

  // Loop at a fixed rate forever
  // NOTE: If the deadline is ever missed then the loop will hang indefinitely.
  systime_t deadline = chTimeNow();
  while(true) {
    deadline += MS2ST(DT * 2000);

    system.update();

    debugger.printf("Hello world 1!!!\r\n");

    BaseThread::sleepUntil(deadline);
 }

  return 0;
}
<commit_msg>Fix main loop deadline.<commit_after>#include <ch.hpp>
#include <hal.h>
#include <chprintf.h>

#include <config.hpp>

// Estimators
#include <estimator/dcm_attitude_estimator.hpp>

// Drivers
#include <drivers/l3gd20.hpp>
#include <drivers/lsm303dlhc.hpp>

// Input sources
#include <input/pwm_receiver_input_source.hpp>

// Controllers
#include <controller/controller_pipeline.hpp>
#include <controller/attitude_controller.hpp>
#include <controller/attitude_rate_controller.hpp>

// Misc
// #include <communicator.hpp>
// TODO: Think about how to integrate debugging cleanly.
#include <debugger.hpp>

// Systems
#include <system/default_multirotor_vehicle_system.hpp>

using namespace chibios_rt;

class HeartbeatThread : public BaseStaticThread<64> {
public:
  HeartbeatThread() : BaseStaticThread<64>() {
  }

  virtual msg_t main() {
    setName("heartbeat");

    while(true) {
      palSetPad(GPIOE, GPIOE_LED3_RED);
      sleep(MS2ST(500));
      palClearPad(GPIOE, GPIOE_LED3_RED);
      sleep(MS2ST(500));
    }

    return 0;
  }
};

static HeartbeatThread heartbeatThread;
static Debugger debugger;

int main(void) {
  halInit();
  System::init();

  // Start the background threads
  heartbeatThread.start(NORMALPRIO + 10);
  debugger.start(NORMALPRIO + 10);

  spiInit();
  i2cInit();

  // Start USART
  sdStart(&SD1, &usart1_config);
  palSetPadMode(GPIOA, 9, PAL_MODE_ALTERNATE(7));
  palSetPadMode(GPIOA, 10, PAL_MODE_ALTERNATE(7));

  // Build and initialize the system
  L3GD20 gyro(&SPID1);
  LSM303DLHC accel(&I2CD1);

  gyro.init();
  accel.init();

  DefaultMultirotorVehicleSystem system(&accel, &gyro);
  system.init();

  // Loop at a fixed rate forever
  // NOTE: If the deadline is ever missed then the loop will hang indefinitely.
  systime_t deadline = chTimeNow();
  while(true) {
    deadline += MS2ST(DT * 1000);

    system.update();

    BaseThread::sleepUntil(deadline);
 }

  return 0;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Michal Korbela, Filip Pokryvka, Ondrej Slamecka
 * See the LICENSE file for more information.
 */

#include <bits/stdc++.h>
#include "brca_image.hpp"
#include "MLP.hpp"

using namespace std;

/**
 * Encodes true as {0, 1}, false as {1, 0}.
 */
vector<double> one_hot_bool(bool i) {
    if (i) {
        return {0, 1};
    } else {
        return {1, 0};
    }
}

/**
 *
 */
double validate(MLP &nn, vector<BrcaImage> &validation) {
    int n_correct = 0,
        n_incorrect = 0,
        n_unsure = 0;

    vector<double> result;
    for (unsigned i = 0; i<validation.size(); i++) {
        result = nn.feed(validation[i].data);
        result[0] = result[0] < 0.5 ? 0 : 1;
        result[1] = result[1] < 0.5 ? 0 : 1;

        if(result == one_hot_bool(validation[i].malignant)) {
            n_correct++;
        } else if (result == one_hot_bool(!validation[i].malignant)){
            n_incorrect++;
        } else {
            n_unsure++;
        }
    }

    double correctness = (n_correct * 100.0) / validation.size();
    cout << correctness << "%: "
        << n_correct << "/" << validation.size()
        << " (" << n_incorrect << " incorrect, " << n_unsure << " unsure)\n";

    return correctness;
}

void normalize(vector<BrcaImage> &input) {
    double a, b;

    double min_input = input[0].data[0];
    double max_input = input[0].data[0];
    for (auto & img: input) {
        for (auto & data: img.data) {
            if (data<min_input) {
                min_input = data;
            }

            if (data>max_input) {
                max_input = data;
            }
        }
    }

    a = (max_input + min_input) / 2;
    b = (max_input - min_input) / 2;
    cout << "Using normalization constants: (X - " << a << ") / " << b << endl;
    for (auto & img: input) {
        for (auto & data: img.data) {
            data = (data - a) / b;
        }
    }

    // test the normalization
    int bad = 0;
    for (auto & img: input) {
        for (auto & data: img.data) {
            if (data < -1 || data > 1)
                bad++;
        }
    }

    if (bad) {
        cout << "Normalization went wrong, "
            << bad << " numbers are not in range <-1,1>!" << endl;
    }
}

int main(int argc, char** argv) {
    if (argc < 3) {
        cerr << "Usage:\t" << argv[0] << " data_path training_set_size\n" << endl;
        cerr << "\tThe program opens the file at the data_path " << endl;
        exit(1);
    }

    unsigned training_size = atoi(argv[2]);

    vector<BrcaImage> all_data = parse_brca_dataset(argv[1]);
    normalize(all_data);

    if (training_size > all_data.size()) {
        cerr << "The given training set size is greater than"
                "the size of the data set." << endl;
        exit(1);
    }

    vector<BrcaImage> training, validation;
    for (unsigned i = 0; i < training_size; ++i) {
        training.push_back(all_data[i]);
    }

    // how often is validation run
    unsigned interval = 1000;
    // when to stop
    double treshold = 92.5;

    MLP nn({30,2});
    nn.randomize_weights(-1, 1);
    int i = -1;

    while (validate(nn, all_data) < treshold) {
        ++i;
        for (unsigned i = 0; i<interval; i++) {
            for (unsigned j = 0; j<training_size; j++) {
                nn.learn(training[j].data,
                    one_hot_bool(training[j].malignant),
                    0.5, 0.0);
            }
        }
    }

    cout << "Learning finished, reached treshold " << treshold << "%" << endl;

    return 0;
}
<commit_msg>Increase momentum factor (speeds up learning)<commit_after>/**
 * Copyright 2016 Michal Korbela, Filip Pokryvka, Ondrej Slamecka
 * See the LICENSE file for more information.
 */

#include <bits/stdc++.h>
#include "brca_image.hpp"
#include "MLP.hpp"

using namespace std;

/**
 * Encodes true as {0, 1}, false as {1, 0}.
 */
vector<double> one_hot_bool(bool i) {
    if (i) {
        return {0, 1};
    } else {
        return {1, 0};
    }
}

/**
 *
 */
double validate(MLP &nn, vector<BrcaImage> &validation) {
    int n_correct = 0,
        n_incorrect = 0,
        n_unsure = 0;

    vector<double> result;
    for (unsigned i = 0; i<validation.size(); i++) {
        result = nn.feed(validation[i].data);
        result[0] = result[0] < 0.5 ? 0 : 1;
        result[1] = result[1] < 0.5 ? 0 : 1;

        if(result == one_hot_bool(validation[i].malignant)) {
            n_correct++;
        } else if (result == one_hot_bool(!validation[i].malignant)){
            n_incorrect++;
        } else {
            n_unsure++;
        }
    }

    double correctness = (n_correct * 100.0) / validation.size();
    cout << correctness << "%: "
        << n_correct << "/" << validation.size()
        << " (" << n_incorrect << " incorrect, " << n_unsure << " unsure)\n";

    return correctness;
}

void normalize(vector<BrcaImage> &input) {
    double a, b;

    double min_input = input[0].data[0];
    double max_input = input[0].data[0];
    for (auto & img: input) {
        for (auto & data: img.data) {
            if (data<min_input) {
                min_input = data;
            }

            if (data>max_input) {
                max_input = data;
            }
        }
    }

    a = (max_input + min_input) / 2;
    b = (max_input - min_input) / 2;
    cout << "Using normalization constants: (X - " << a << ") / " << b << endl;
    for (auto & img: input) {
        for (auto & data: img.data) {
            data = (data - a) / b;
        }
    }

    // test the normalization
    int bad = 0;
    for (auto & img: input) {
        for (auto & data: img.data) {
            if (data < -1 || data > 1)
                bad++;
        }
    }

    if (bad) {
        cout << "Normalization went wrong, "
            << bad << " numbers are not in range <-1,1>!" << endl;
    }
}

int main(int argc, char** argv) {
    if (argc < 3) {
        cerr << "Usage:\t" << argv[0] << " data_path training_set_size\n" << endl;
        cerr << "\tThe program opens the file at the data_path " << endl;
        exit(1);
    }

    unsigned training_size = atoi(argv[2]);

    vector<BrcaImage> all_data = parse_brca_dataset(argv[1]);
    normalize(all_data);

    if (training_size > all_data.size()) {
        cerr << "The given training set size is greater than"
                "the size of the data set." << endl;
        exit(1);
    }

    vector<BrcaImage> training, validation;
    for (unsigned i = 0; i < training_size; ++i) {
        training.push_back(all_data[i]);
    }

    // how often is validation run
    unsigned interval = 1000;
    // when to stop
    double treshold = 92.5;

    MLP nn({30,2});
    nn.randomize_weights(-1, 1);
    int i = -1;

    while (validate(nn, all_data) < treshold) {
        ++i;
        for (unsigned i = 0; i<interval; i++) {
            for (unsigned j = 0; j<training_size; j++) {
                nn.learn(training[j].data,
                    one_hot_bool(training[j].malignant),
                    0.5, 0.2);
            }
        }
    }

    cout << "Learning finished, reached treshold " << treshold << "%" << endl;

    return 0;
}
<|endoftext|>


<commit_before>#include <node.h>
#include <v8.h>
#include <nan.h>

extern "C"{
  #include "ABE_IoPi.h"
}

using namespace v8;

void initIOPI(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  IOPi_init(address);
}

void setPortDirection(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_port_direction(address, port, direction);
}

void setPinDirection(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_pin_direction(address, pin, direction);
}

void writePort(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_port(address, port, value);
}

void writePin(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_pin(address, pin, value);
}

void readPin(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  int value = read_pin(address,pin);
  Local<Number> num = Nan::New(value);
  args.GetReturnValue().Set(num);
}

void setup(Handle<Object> exports) {
  exports->Set(Nan::New("init").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(initIOPI)->GetFunction());
  exports->Set(Nan::New("setPortDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPortDirection)->GetFunction());
  exports->Set(Nan::New("setPinDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPinDirection)->GetFunction());
  exports->Set(Nan::New("writePort").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePort)->GetFunction());
  exports->Set(Nan::New("writePin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePin)->GetFunction());
  exports->Set(Nan::New("readPin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(readPin)->GetFunction());
}

NODE_MODULE(iopi, setup)
<commit_msg>Added functions<commit_after>#include <node.h>
#include <v8.h>
#include <nan.h>

extern "C"{
  #include "ABE_IoPi.h"
}

using namespace v8;

void initIOPI(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  IOPi_init(address);
}

void setPortDirection(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_port_direction(address, port, direction);
}

void setPinDirection(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char direction = args[2]->NumberValue();
  set_pin_direction(address, pin, direction);
}

void writePort(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char port = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_port(address, port, value);
}

void writePin(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  write_pin(address, pin, value);
}

void readPin(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  int value = read_pin(address,pin);
  Local<Number> num = Nan::New(value);
  args.GetReturnValue().Set(num);
}

void setPinPullup(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pinval = args[1]->NumberValue();
  char value = args[2]->NumberValue();
  set_pin_pullup(address, pinval, value);
}

void invertPin(const Nan::FunctionCallbackInfo<Value>& args){
  char address = args[0]->NumberValue();
  char pin = args[1]->NumberValue();
  char polarity = args[2]->NumberValue();
  value = read_pin(address, pin, polarity);
}

void setup(Handle<Object> exports) {
  exports->Set(Nan::New("init").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(initIOPI)->GetFunction());
  exports->Set(Nan::New("setPortDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPortDirection)->GetFunction());
  exports->Set(Nan::New("setPinDirection").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPinDirection)->GetFunction());
  exports->Set(Nan::New("writePort").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePort)->GetFunction());
  exports->Set(Nan::New("writePin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writePin)->GetFunction());
  exports->Set(Nan::New("readPin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(readPin)->GetFunction());
  exports->Set(Nan::New("setPinPullup").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(setPinPullup)->GetFunction());
  exports->Set(Nan::New("invertPin").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(invertPin)->GetFunction());
}

NODE_MODULE(iopi, setup)
<|endoftext|>


<commit_before>#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Basic/Version.h>

#include <iostream>

#include "core/clang_interface.hpp"
#include "export/dump_export.hpp"
#include "export/protobuf_export.hpp"

using namespace llvm;

static cl::OptionCategory toolCat("CppTool options");
static cl::extrahelp CommonHelp(clang::tooling::CommonOptionsParser::HelpMessage);

static cl::opt<std::string> OutputDirectory("out",
	cl::desc("Output directory for the binary data files"),
	cl::value_desc("directory"),
	cl::init("data_out"),
	cl::cat(toolCat)
);

inline char os_filesep() {
#ifdef _WIN32
	return '\\';
#else
	return '/';
#endif //_WIN32
}

llvm::SmallString<1024> getAbsoluteOutputPath() {
	llvm::SmallString<1024> tmp;
	tmp.assign(OutputDirectory);
	llvm::sys::fs::make_absolute(tmp);

	//Ensure it ends with a file separator
	if (!(tmp.endswith("/") && tmp.endswith("\\"))) {
		tmp.append(1, os_filesep());
	}

	return tmp;
}

llvm::SmallString<1024> &cachedAbsolutePath() {
    // Cached as a static variable since it cannot change once we reach this point
    static llvm::SmallString<1024> outputDirectory = getAbsoluteOutputPath();
    return outputDirectory;
}

std::FILE *generateOutputFile(llvm::StringRef const fileName) {
	using namespace llvm::sys;

	//Get last part of the path
	auto targetFileName = fileName.rsplit(os_filesep()).second.str();

	//Add last part to the output directory and add a unique identifier token
	Twine const nonUniqueFile = Twine(cachedAbsolutePath()).concat(targetFileName).concat("-%%-%%-%%-%%.pb");

	//Ensure the name is unique.
	llvm::SmallString<1024> tmpFile;
	auto err = fs::createUniqueFile(nonUniqueFile, tmpFile);

	if (err) {
		llvm::errs() << "Error creating binary output fileName" << err.message() << "\n";
	}

    std::FILE *ptr = std::fopen(tmpFile.c_str(), "w");
    if (!ptr) {
        llvm::outs() << "fopen failed: " << std::strerror(errno) << "\n";
        return nullptr;
    } else {
        return ptr;
    }
}

std::unique_ptr<ct::CTExport> createBinaryExport(llvm::StringRef const fileName, clang::CompilerInstance const &ci) {
	llvm::outs() << "EXPORT: " << fileName.str() << "\n";
	return std::unique_ptr<ct::CTExport>(new ct::ProtoBufExport(generateOutputFile(fileName), fileName, ci));
}

int main(int argc, const char *argv[]) {
	llvm::outs() << clang::getClangToolFullVersion("CppTool - clang") << "\n";

    clang::tooling::CommonOptionsParser options(argc, argv, toolCat);
    clang::tooling::ClangTool tool(options.getCompilations(), options.getSourcePathList());

	{
		//Ensure binary export directory is a directory and exists
		using namespace llvm::sys;
		Twine const directory(cachedAbsolutePath());

		if (directory.isTriviallyEmpty()) {
			llvm::errs() << "Output directory cannot be unspecified.\n";
		} else if (fs::exists(directory) && !fs::is_directory(directory)) {
			//Ensure its a directory
			llvm::errs() << "Given output directory \"" << OutputDirectory << "\" is not a directory.\n";
			exit(EXIT_FAILURE);
		} else {
			auto err = fs::create_directory(directory);
			if (err) {
				llvm::errs() << "Error whilst creating output directory: " << err.message() << "\n";
				exit(err.value());
			}
		}

		llvm::SmallString<1024> tmpFile;
		directory.toVector(tmpFile);
		fs::make_absolute(tmpFile);
		llvm::outs() << "Using output directory: \"" << tmpFile << "\"\n";
	}

	llvm::outs().flush();

	return tool.run(ct::buildActionFactory(
		&createBinaryExport,
		ct::createInputIdSet(options.getSourcePathList(), tool.getFiles())
	).get());
}<commit_msg>Missed import of dump_export.hpp<commit_after>#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Basic/Version.h>

#include <iostream>

#include "core/clang_interface.hpp"
#include "export/protobuf_export.hpp"

using namespace llvm;

static cl::OptionCategory toolCat("CppTool options");
static cl::extrahelp CommonHelp(clang::tooling::CommonOptionsParser::HelpMessage);

static cl::opt<std::string> OutputDirectory("out",
	cl::desc("Output directory for the binary data files"),
	cl::value_desc("directory"),
	cl::init("data_out"),
	cl::cat(toolCat)
);

inline char os_filesep() {
#ifdef _WIN32
	return '\\';
#else
	return '/';
#endif //_WIN32
}

llvm::SmallString<1024> getAbsoluteOutputPath() {
	llvm::SmallString<1024> tmp;
	tmp.assign(OutputDirectory);
	llvm::sys::fs::make_absolute(tmp);

	//Ensure it ends with a file separator
	if (!(tmp.endswith("/") && tmp.endswith("\\"))) {
		tmp.append(1, os_filesep());
	}

	return tmp;
}

llvm::SmallString<1024> &cachedAbsolutePath() {
    // Cached as a static variable since it cannot change once we reach this point
    static llvm::SmallString<1024> outputDirectory = getAbsoluteOutputPath();
    return outputDirectory;
}

std::FILE *generateOutputFile(llvm::StringRef const fileName) {
	using namespace llvm::sys;

	//Get last part of the path
	auto targetFileName = fileName.rsplit(os_filesep()).second.str();

	//Add last part to the output directory and add a unique identifier token
	Twine const nonUniqueFile = Twine(cachedAbsolutePath()).concat(targetFileName).concat("-%%-%%-%%-%%.pb");

	//Ensure the name is unique.
	llvm::SmallString<1024> tmpFile;
	auto err = fs::createUniqueFile(nonUniqueFile, tmpFile);

	if (err) {
		llvm::errs() << "Error creating binary output fileName" << err.message() << "\n";
	}

    std::FILE *ptr = std::fopen(tmpFile.c_str(), "w");
    if (!ptr) {
        llvm::outs() << "fopen failed: " << std::strerror(errno) << "\n";
        return nullptr;
    } else {
        return ptr;
    }
}

std::unique_ptr<ct::CTExport> createBinaryExport(llvm::StringRef const fileName, clang::CompilerInstance const &ci) {
	llvm::outs() << "EXPORT: " << fileName.str() << "\n";
	return std::unique_ptr<ct::CTExport>(new ct::ProtoBufExport(generateOutputFile(fileName), fileName, ci));
}

int main(int argc, const char *argv[]) {
	llvm::outs() << clang::getClangToolFullVersion("CppTool - clang") << "\n";

    clang::tooling::CommonOptionsParser options(argc, argv, toolCat);
    clang::tooling::ClangTool tool(options.getCompilations(), options.getSourcePathList());

	{
		//Ensure binary export directory is a directory and exists
		using namespace llvm::sys;
		Twine const directory(cachedAbsolutePath());

		if (directory.isTriviallyEmpty()) {
			llvm::errs() << "Output directory cannot be unspecified.\n";
		} else if (fs::exists(directory) && !fs::is_directory(directory)) {
			//Ensure its a directory
			llvm::errs() << "Given output directory \"" << OutputDirectory << "\" is not a directory.\n";
			exit(EXIT_FAILURE);
		} else {
			auto err = fs::create_directory(directory);
			if (err) {
				llvm::errs() << "Error whilst creating output directory: " << err.message() << "\n";
				exit(err.value());
			}
		}

		llvm::SmallString<1024> tmpFile;
		directory.toVector(tmpFile);
		fs::make_absolute(tmpFile);
		llvm::outs() << "Using output directory: \"" << tmpFile << "\"\n";
	}

	llvm::outs().flush();

	return tool.run(ct::buildActionFactory(
		&createBinaryExport,
		ct::createInputIdSet(options.getSourcePathList(), tool.getFiles())
	).get());
}<|endoftext|>