<commit_before>#include <iostream>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <cstdlib>

using namespace std;
using namespace boost;

int main(int argc, char** argv) {
    string input = "";
    /*for(int i = 1; i < argc; i++) {//comment out if using user input
        input += argv[i];//comment out if using user input
    }*///comment out for user input
    //cout << "$ " << input << endl;
    pid_t pid;
    while(1) {//use this for user input
        cout << "$ ";//use this for user input
        getline(cin, input);//use this for user input instead of command line
        typedef tokenizer<char_separator<char> > tokenizer;
        char_separator<char> sep(";");
        tokenizer tkn(input, sep);
        for(tokenizer::iterator tok = tkn.begin(); tok != tkn.end(); tok++) {
            char **ptr;
            vector<char *> v;
            if(v.empty() && (tok->compare("exit") == 0)) {
                return 1;
            }
            if((tok->compare("&") == 0) && (tok->compare("|") == 0)) {

            } else if(tok->compare("&") == 0) {

            } else if(tok->compare("|") == 0) {

            } else {
                string temp = *tok;
                if(temp.find(" ") == 0) {
                    temp.erase(0,1);
                }
                if(temp.find("#") != string::npos) {
                    int index = temp.find("#");
                    temp = temp.substr(0, index);
                }
                if(temp.find(" ") != string::npos) {
                    char_separator<char> sep_2(" ");
                    tokenizer tkn_2(temp, sep_2);
                    for(tokenizer::iterator tok_2 = tkn_2.begin(); tok_2 != tkn_2.end(); tok_2++) {
                        string temp_2 = *tok_2;
                        char *temp_1 = new char[temp_2.size()];
                        copy(temp_2.begin(), temp_2.end(), temp_1);
                        v.push_back(temp_1);
                    }
                    v.push_back('\0');
                    ptr = &v[0];
                } else {
                    char *temp_1 = new char[temp.size() + 1];
                    copy(temp.begin(), temp.end(), temp_1);
                    temp_1[temp.size()] = '\0';
                    v.push_back(temp_1);
                    ptr = &v[0];
                }
                pid = fork();
                if(pid == -1) {
                    return -1;
                }
                if(pid == 0) {
                    if(execvp(ptr[0], ptr) == -1) {
                        perror("Execvp Failed");
                    }
                    exit(1);
                }
                if(pid > 0) {
                    if(wait(0) == -1) {
                        perror("Wait");
                        exit(1);
                    }
                }
                ptr = NULL;
                v.clear();
            }
        }
    }
}<commit_msg>modified main.cpp<commit_after>#include <iostream>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <cstdlib>

using namespace std;
using namespace boost;

bool execute(string);
bool test(string);
bool run(string);

int main(int argc, char** argv) {
    //finding user login info
    string user, info;

    char hostInfo[256];
    struct passwd *u = getpwuid(getuid());
    int h = gethostname(hostInfo, 256);

    if(u != 0 && h != -1) {
        user = u->pw_name;
        info = hostInfo;
        info.append("@");
        info.append(user);
        info.append("$ ");
    } else {
        info = "user@host_name$ ";
    }
    //string input = "";
    /*for(int i = 1; i < argc; i++) {//comment out if using user input
        input += argv[i];//comment out if using user input
    }//comment out for user input
    cout << "$ " << input << endl;*/
    while(1) {//use this for user input
        string input = "";
        cout << info;//use this for user input
        getline(cin, input);//use this for user input instead of command line
        typedef tokenizer<char_separator<char> > tokenizer;
        char_separator<char> sep(";");
        tokenizer tkn(input, sep);
        for(tokenizer::iterator tok = tkn.begin(); tok != tkn.end(); tok++) {
            string currTok = *tok;
            if(currTok.find("&") != string::npos) { //else if
                bool passed = true;
                char_separator<char> sep1("&");
                tokenizer tkn1(currTok, sep1);
                for(tokenizer::iterator tok1 = tkn1.begin(); tok1 != tkn1.end(); tok1++) {
                    if(passed == true) {
                        string temp_and = *tok1;
                        if(temp_and.find("exit") != string::npos) {
                            return 1;
                        }
                        passed = run(temp_and);
                    }
                }
            } else if(currTok.find("|") != string::npos) {
                bool passed = false;
                char_separator<char> sep2("|");
                tokenizer tkn2(currTok, sep2);
                for(tokenizer::iterator tok2 = tkn2.begin(); tok2 != tkn2.end(); tok2++) {
                    if(passed == false) {
                        string temp_or = *tok2;
                        if(temp_or.find("exit") != string::npos) {
                            return 1;
                        }
                        passed = run(temp_or);
                    }
                }
            } else {
                if(currTok == "exit") { //|| currTok.find("exit") != string::npos) {
                    return 1;
                }
                run(currTok);
            }
        }
    }
}

bool run(string temp) {
    bool ret;
    string temp2 = temp;
    if( temp2.find("test") != string::npos ) {
        while(temp2.at(temp2.size() - 1) == ' ') {
            temp2 = temp2.substr(0, temp2.size() - 1);
        }
        ret = test(temp2);
    } else if( temp2.find("[") != string::npos && temp2.find("]") != string::npos ) {
        temp2 = temp2.substr(0, temp2.find("]") - 1);
        ret = test(temp2);
    } else {
        while(temp2.at(temp2.size() - 1) == ' ') {
            temp2 = temp2.substr(0, temp2.size() - 1);
        }
        ret = execute(temp2);
    }
    return ret;
}

bool execute(string temp) {
    bool ret = true;
    pid_t pid;
    typedef tokenizer<char_separator<char> > tokenizer;
    char **ptr;
    string temp1 = temp;
    vector<char *> v;
    while(temp1.find(" ") == 0) {
        temp1.erase(0,1);
    }
    if(temp1.find("#") != string::npos) {
        int index = temp1.find("#");
        temp1 = temp1.substr(0, index);
    }
    if(temp1.find(" ") != string::npos) {
        int i = 0;
        string temp_last;
        char_separator<char> sep_2(" ");
        tokenizer tkn_2(temp1, sep_2);
        for(tokenizer::iterator tok_2 = tkn_2.begin(); tok_2 != tkn_2.end(); tok_2++) {
            string temp_2 = *tok_2;
            char *temp_1 = new char[temp_2.size()];
            copy(temp_2.begin(), temp_2.end(), temp_1);
            v.push_back(temp_1);
            i++;
            temp_last = temp_2;
        }
        //v.push_back('\0');
        char *temp_3 = new char[temp_last.size() + 1];
        copy(temp_last.begin(), temp_last.end(), temp_3);
        temp_3[temp_last.size()] = '\0';
        v.pop_back();
        v.push_back(temp_3);
        ptr = &v[0];
    } else {
        char *temp_1 = new char[temp1.size() + 1];
        copy(temp1.begin(), temp1.end(), temp_1);
        temp_1[temp1.size()] = '\0';
        v.push_back(temp_1);
        ptr = &v[0];
    }
    pid = fork();
    if(pid == -1) {
        return false;
    }
    if(pid == 0) {
        if(execvp(ptr[0], ptr) == -1) {
            perror("Execvp Failed");
        }
        exit(1);
    }
    if(pid > 0) {
        if(wait(0) == -1) {
            perror("Wait");
            exit(1);
        }

    }
    ptr = NULL;
    v.clear();
    return ret;
}

bool test(string temp) {
    struct stat buf;
    if(temp.find("-e") != string::npos) {
        string temp2 = temp.substr(temp.find("-e") + 3);
        if(stat(temp2.c_str(), &buf) == 0) {
            cout << "(TRUE)" << endl;
            return true;
        } else {
            cout << "(FALSE)" << endl;
            return false;
        }
    }
    if(temp.find("-f") != string::npos) {
        string temp2 = temp.substr(temp.find("-f") + 3);
        if(stat(temp2.c_str(), &buf) == 0) {
            if(S_ISREG(buf.st_mode)) {
                cout << "(TRUE)" << endl;
                return true;
            } else {
                cout << "(FALSE)" << endl;
                return false;
            }
        } else {
            cout << "(FALSE)" << endl;
            return false;
        }
    }
    if(temp.find("-d") != string::npos) {
        string temp2 = temp.substr(temp.find("-d") + 3);
        if(stat(temp2.c_str(), &buf) == 0) {
            if(S_ISDIR(buf.st_mode)) {
                cout << "(TRUE)" << endl;
                return true;
            } else {
                cout << "(FALSE)" << endl;
                return false;
            }
        } else {
            cout << "(FALSE)" << endl;
            return false;
        }
    }
    if(temp.find("-e") == string::npos && temp.find("-f") == string::npos && temp.find("-d") == string::npos) {
        string temp2 = temp;
        if(temp2.find("[") != string::npos) {
            temp2 = temp2.substr(temp2.find("[") + 2);
        }
        if(temp2.find("test") != string::npos) {
            temp2 = temp2.substr(temp2.find("test") + 5);
        }
        if(stat(temp2.c_str(), &buf) == 0) {
            cout << "(TRUE)" << endl;
            return true;
        } else {
            cout << "(FALSE)" << endl;
            return false;
        }
    }
}<|endoftext|>


<commit_before>#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <hadouken/application.hpp>
#include <hadouken/logging.hpp>
#include <hadouken/platform.hpp>
#include <hadouken/hosting/host.hpp>
#include <hadouken/hosting/console_host.hpp>

#ifdef WIN32
#include <hadouken/hosting/service_host.hpp>
#endif

namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace pt = boost::property_tree;

po::variables_map load_options(int argc,char *argv[])
{
    po::options_description desc("Allowed options");
    desc.add_options()
        ("config", po::value<std::string>(), "Set path to a JSON configuration file. The default is %appdir%/hadouken.json")
        ("daemon", "Start Hadouken in daemon/service mode.")
#ifdef WIN32
        ("install-service", "Install Hadouken in the SCM.")
        ("uninstall-service", "Uninstall Hadouken from the SCM.")
#endif
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    return vm;
}

fs::path get_config_path(const po::variables_map& options)
{
    if (options.count("config"))
    {
        return options["config"].as<std::string>();
    }
    else if (options.count("daemon"))
    {
        return (hadouken::platform::data_path() / "hadouken.json");
    }
    else
    {
        return (hadouken::platform::get_current_directory() / "hadouken.json");
    }
}

std::unique_ptr<hadouken::hosting::host> get_host(const po::variables_map& options)
{
    if (options.count("daemon"))
    {
#ifdef WIN32
        return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::service_host());
#endif
    }

    return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::console_host());
}

int main(int argc, char *argv[])
{
    po::variables_map vm = load_options(argc, argv);
    hadouken::logging::setup(vm);

    // Do platform-specific initialization as early as possible.
    hadouken::platform::init();

#ifdef WIN32
    if (vm.count("install-service"))
    {
        hadouken::platform::install_service();
        return 0;
    }
    else if (vm.count("uninstall-service"))
    {
        hadouken::platform::uninstall_service();
        return 0;
    }
#endif

    fs::path config_file = get_config_path(vm);
    pt::ptree config;

    if (!fs::exists(config_file))
    {
        BOOST_LOG_TRIVIAL(warning) << "Could not find config file at " << config_file;
    }
    else
    {
        try
        {
            pt::read_json(config_file.string(), config);
            BOOST_LOG_TRIVIAL(info) << "Loaded config file " << config_file;
        }
        catch (const std::exception& ex)
        {
            // To meet expectations, fail if the configuration file cannot be parsed. Otherwise,
            // we will revert to the default config which might be totally wrong.
            BOOST_LOG_TRIVIAL(fatal) << "Error when loading config file " << config_file << ": " << ex.what();
            return EXIT_FAILURE;
        }
    }

    boost::shared_ptr<boost::asio::io_service> io(new boost::asio::io_service());

    hadouken::application app(io, config);
    app.script_host().define_global("__CONFIG__", config_file.string());
    app.script_host().define_global("__CONFIG_PATH__", config_file.parent_path().string());

    app.start();
    int result = get_host(vm)->wait_for_exit(io);
    app.stop();

    return result;
}
<commit_msg>Add quick and dirty --help option.<commit_after>#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <hadouken/application.hpp>
#include <hadouken/logging.hpp>
#include <hadouken/platform.hpp>
#include <hadouken/hosting/host.hpp>
#include <hadouken/hosting/console_host.hpp>

#ifdef WIN32
#include <hadouken/hosting/service_host.hpp>
#endif

namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace pt = boost::property_tree;

po::variables_map load_options(int argc,char *argv[])
{
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Display available commandline options")
        ("config", po::value<std::string>(), "Set path to a JSON configuration file. The default is %appdir%/hadouken.json")
        ("daemon", "Start Hadouken in daemon/service mode.")
#ifdef WIN32
        ("install-service", "Install Hadouken in the SCM.")
        ("uninstall-service", "Uninstall Hadouken from the SCM.")
#endif
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
        return 1;
    }

    return vm;
}

fs::path get_config_path(const po::variables_map& options)
{
    if (options.count("config"))
    {
        return options["config"].as<std::string>();
    }
    else if (options.count("daemon"))
    {
        return (hadouken::platform::data_path() / "hadouken.json");
    }
    else
    {
        return (hadouken::platform::get_current_directory() / "hadouken.json");
    }
}

std::unique_ptr<hadouken::hosting::host> get_host(const po::variables_map& options)
{
    if (options.count("daemon"))
    {
#ifdef WIN32
        return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::service_host());
#endif
    }

    return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::console_host());
}

int main(int argc, char *argv[])
{
    po::variables_map vm = load_options(argc, argv);
    hadouken::logging::setup(vm);

    // Do platform-specific initialization as early as possible.
    hadouken::platform::init();

#ifdef WIN32
    if (vm.count("install-service"))
    {
        hadouken::platform::install_service();
        return 0;
    }
    else if (vm.count("uninstall-service"))
    {
        hadouken::platform::uninstall_service();
        return 0;
    }
#endif

    fs::path config_file = get_config_path(vm);
    pt::ptree config;

    if (!fs::exists(config_file))
    {
        BOOST_LOG_TRIVIAL(warning) << "Could not find config file at " << config_file;
    }
    else
    {
        try
        {
            pt::read_json(config_file.string(), config);
            BOOST_LOG_TRIVIAL(info) << "Loaded config file " << config_file;
        }
        catch (const std::exception& ex)
        {
            // To meet expectations, fail if the configuration file cannot be parsed. Otherwise,
            // we will revert to the default config which might be totally wrong.
            BOOST_LOG_TRIVIAL(fatal) << "Error when loading config file " << config_file << ": " << ex.what();
            return EXIT_FAILURE;
        }
    }

    boost::shared_ptr<boost::asio::io_service> io(new boost::asio::io_service());

    hadouken::application app(io, config);
    app.script_host().define_global("__CONFIG__", config_file.string());
    app.script_host().define_global("__CONFIG_PATH__", config_file.parent_path().string());

    app.start();
    int result = get_host(vm)->wait_for_exit(io);
    app.stop();

    return result;
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ios>
#include <stan/mcmc/chains.hpp>
#include <cmdstan/stansummary_helper.hpp>
#include <fstream>

void diagnose_usage() {
  std::cout << "USAGE:  diagnose <filename 1> [<filename 2> ... <filename N>]"
            << std::endl
            << std::endl;
}

/**
 * The Stan print function.
 *
 * @param argc Number of arguments
 * @param argv Arguments
 *
 * @return 0 for success,
 *         non-zero otherwise
 */
int main(int argc, const char* argv[]) {

  if (argc == 1) {
    diagnose_usage();
    return 0;
  }

  // Parse any arguments specifying filenames
  std::ifstream ifstream;
  std::vector<std::string> filenames;

  for (int i = 1; i < argc; ++i) {
    ifstream.open(argv[i]);

    if (ifstream.good()) {
      filenames.push_back(argv[i]);
      ifstream.close();
    } else {
      std::cout << "File " << argv[i] << " not found" << std::endl;
    }
  }

  if (!filenames.size()) {
    std::cout << "No valid input files, exiting." << std::endl;
    return 0;
  }

  // Parse specified files
  ifstream.open(filenames[0].c_str());

  stan::io::stan_csv stan_csv
    = stan::io::stan_csv_reader::parse(ifstream, &std::cout);
  stan::mcmc::chains<> chains(stan_csv);

  ifstream.close();

  for (std::vector<std::string>::size_type chain = 1;
       chain < filenames.size(); ++chain) {
    ifstream.open(filenames[chain].c_str());
    stan_csv = stan::io::stan_csv_reader::parse(ifstream, &std::cout);
    chains.add(stan_csv);
    ifstream.close();
  }

  int num_samples = chains.num_samples();

  std::vector<std::string> bad_n_eff_names;
  std::vector<std::string> bad_rhat_names;

  for (int i = 0; i < chains.num_params(); ++i) {
    int max_limit = 10;

    if (chains.param_name(i) == std::string("treedepth__")) {
      int max = chains.samples(i).maxCoeff();
      if (max >= max_limit) {
        int n_max = 0;
        Eigen::VectorXd t_samples = chains.samples(i);
        for (size_t n = 0; n < t_samples.size(); ++n)
          if (t_samples(n) == max) ++n_max;

        std::cout << n_max << " of " << num_samples << " ("
                  << std::setprecision(2)
                  << 100 * static_cast<double>(n_max) / num_samples
                  << "%) transitions hit the maximum treedepth limit of "
                  << max << ", or 2^" << max << " leapfrog steps."
                  << " Trajectories that are prematurely terminated due to this"
                  << " limit will result in slow exploration and you should"
                  << " increase the limit to ensure optimal performance."
                  << std::endl << std::endl;
      }

    } else if (chains.param_name(i) == std::string("divergent__")) {

      int n_divergent = chains.samples(i).sum();
      if (n_divergent > 0)
        std::cout << n_divergent << " of " << num_samples << " ("
                  << std::setprecision(2)
                  << 100 * static_cast<double>(n_divergent) / num_samples
                  << "%) transitions ended with a divergence.  These divergent"
                  << " transitions indicate that HMC is not fully able to"
                  << " explore the posterior distribution.  Try rerunning with"
                  << " adapt delta set to a larger value and see if the"
                  << " divergences vanish.  If increasing adapt delta towards"
                  << " 1 does not remove the divergences then you will likely"
                  << " need to reparameterize your model."
                  << std::endl << std::endl;

    } else if (chains.param_name(i) == std::string("energy__")) {

      Eigen::VectorXd e_samples = chains.samples(i);

      double delta_e_sq_mean = 0;
      double e_mean = 0;
      double e_var = 0;

      e_mean += e_samples(0);
      e_var += e_samples(0) * (e_samples(0) - e_mean);

      for (size_t n = 1; n < e_samples.size(); ++n) {
        double e = e_samples(n);

        double delta_e_sq = (e - e_samples(n - 1)) * (e - e_samples(n - 1));
        double d = delta_e_sq - delta_e_sq_mean;
        delta_e_sq_mean += d / n;

        d = e - e_mean;
        e_mean += d / (n + 1);
        e_var += d * (e - e_mean);
      }

      e_var /= static_cast<double>(e_samples.size() - 1);

      double e_bfmi = delta_e_sq_mean / e_var;

      double e_bfmi_threshold = 0.3;
      if (e_bfmi < e_bfmi_threshold)
        std::cout << "The E-BFMI, " << e_bfmi << ", is below the nominal"
                  << " threshold of " << e_bfmi_threshold << " which suggests"
                  << " that HMC may have trouble exploring the target"
                  << " distribution.  You should consider any"
                  << " reparameterizations if possible."
                  << std::endl << std::endl;

    } else if (chains.param_name(i).find("__") == std::string::npos) {

      double n_eff = chains.effective_sample_size(i);
      if (n_eff / num_samples < 0.001)
        bad_n_eff_names.push_back(chains.param_name(i));

      double split_rhat = chains.split_potential_scale_reduction(i);
      if (split_rhat > 1.1)
        bad_rhat_names.push_back(chains.param_name(i));
    }
  }

  if (bad_n_eff_names.size() > 0) {
    std::cout << "The following parameters had fewer than 0.001 effective"
              << " samples per transition:" << std::endl;
    std::cout << "  ";
    for (int n = 0; n < bad_n_eff_names.size() - 1; ++n)
      std::cout << bad_n_eff_names.at(n) << ", ";
    std::cout << bad_n_eff_names.back() << std::endl;

    std::cout << "Such low values indicate that the effective sample size"
              << " estimators may be biased high and actual performance"
              << " may be substantially lower than quoted."
              << std::endl << std::endl;
  }

  if (bad_rhat_names.size() > 0) {
    std::cout << "The following parameters had split R-hat less than 1.1:"
              << std::endl;
    std::cout << "  ";
    for (int n = 0; n < bad_rhat_names.size() - 1; ++n)
      std::cout << bad_rhat_names.at(n) << ", ";
    std::cout << bad_rhat_names.back() << std::endl;

    std::cout << "Such high values indicate incomplete mixing and biased"
              << "estimation.  You should consider regularization your model"
              << " with additional prior information or looking for a more"
              << " effective parameterization."
              << std::endl << std::endl;
  }

  return 0;

}
<commit_msg>fixed types in diagnose to remove warnings<commit_after>#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ios>
#include <stan/mcmc/chains.hpp>
#include <cmdstan/stansummary_helper.hpp>
#include <fstream>

void diagnose_usage() {
  std::cout << "USAGE:  diagnose <filename 1> [<filename 2> ... <filename N>]"
            << std::endl
            << std::endl;
}

/**
 * The Stan print function.
 *
 * @param argc Number of arguments
 * @param argv Arguments
 *
 * @return 0 for success,
 *         non-zero otherwise
 */
int main(int argc, const char* argv[]) {

  if (argc == 1) {
    diagnose_usage();
    return 0;
  }

  // Parse any arguments specifying filenames
  std::ifstream ifstream;
  std::vector<std::string> filenames;

  for (int i = 1; i < argc; ++i) {
    ifstream.open(argv[i]);

    if (ifstream.good()) {
      filenames.push_back(argv[i]);
      ifstream.close();
    } else {
      std::cout << "File " << argv[i] << " not found" << std::endl;
    }
  }

  if (!filenames.size()) {
    std::cout << "No valid input files, exiting." << std::endl;
    return 0;
  }

  // Parse specified files
  ifstream.open(filenames[0].c_str());

  stan::io::stan_csv stan_csv
    = stan::io::stan_csv_reader::parse(ifstream, &std::cout);
  stan::mcmc::chains<> chains(stan_csv);

  ifstream.close();

  for (std::vector<std::string>::size_type chain = 1;
       chain < filenames.size(); ++chain) {
    ifstream.open(filenames[chain].c_str());
    stan_csv = stan::io::stan_csv_reader::parse(ifstream, &std::cout);
    chains.add(stan_csv);
    ifstream.close();
  }

  int num_samples = chains.num_samples();

  std::vector<std::string> bad_n_eff_names;
  std::vector<std::string> bad_rhat_names;

  for (int i = 0; i < chains.num_params(); ++i) {
    int max_limit = 10;

    if (chains.param_name(i) == std::string("treedepth__")) {
      int max = chains.samples(i).maxCoeff();
      if (max >= max_limit) {
        int n_max = 0;
        Eigen::VectorXd t_samples = chains.samples(i);
        for (long n = 0; n < t_samples.size(); ++n)
          if (t_samples(n) == max) ++n_max;

        std::cout << n_max << " of " << num_samples << " ("
                  << std::setprecision(2)
                  << 100 * static_cast<double>(n_max) / num_samples
                  << "%) transitions hit the maximum treedepth limit of "
                  << max << ", or 2^" << max << " leapfrog steps."
                  << " Trajectories that are prematurely terminated due to this"
                  << " limit will result in slow exploration and you should"
                  << " increase the limit to ensure optimal performance."
                  << std::endl << std::endl;
      }

    } else if (chains.param_name(i) == std::string("divergent__")) {

      int n_divergent = chains.samples(i).sum();
      if (n_divergent > 0)
        std::cout << n_divergent << " of " << num_samples << " ("
                  << std::setprecision(2)
                  << 100 * static_cast<double>(n_divergent) / num_samples
                  << "%) transitions ended with a divergence.  These divergent"
                  << " transitions indicate that HMC is not fully able to"
                  << " explore the posterior distribution.  Try rerunning with"
                  << " adapt delta set to a larger value and see if the"
                  << " divergences vanish.  If increasing adapt delta towards"
                  << " 1 does not remove the divergences then you will likely"
                  << " need to reparameterize your model."
                  << std::endl << std::endl;

    } else if (chains.param_name(i) == std::string("energy__")) {

      Eigen::VectorXd e_samples = chains.samples(i);

      double delta_e_sq_mean = 0;
      double e_mean = 0;
      double e_var = 0;

      e_mean += e_samples(0);
      e_var += e_samples(0) * (e_samples(0) - e_mean);

      for (long n = 1; n < e_samples.size(); ++n) {
        double e = e_samples(n);

        double delta_e_sq = (e - e_samples(n - 1)) * (e - e_samples(n - 1));
        double d = delta_e_sq - delta_e_sq_mean;
        delta_e_sq_mean += d / n;

        d = e - e_mean;
        e_mean += d / (n + 1);
        e_var += d * (e - e_mean);
      }

      e_var /= static_cast<double>(e_samples.size() - 1);

      double e_bfmi = delta_e_sq_mean / e_var;

      double e_bfmi_threshold = 0.3;
      if (e_bfmi < e_bfmi_threshold)
        std::cout << "The E-BFMI, " << e_bfmi << ", is below the nominal"
                  << " threshold of " << e_bfmi_threshold << " which suggests"
                  << " that HMC may have trouble exploring the target"
                  << " distribution.  You should consider any"
                  << " reparameterizations if possible."
                  << std::endl << std::endl;

    } else if (chains.param_name(i).find("__") == std::string::npos) {

      double n_eff = chains.effective_sample_size(i);
      if (n_eff / num_samples < 0.001)
        bad_n_eff_names.push_back(chains.param_name(i));

      double split_rhat = chains.split_potential_scale_reduction(i);
      if (split_rhat > 1.1)
        bad_rhat_names.push_back(chains.param_name(i));
    }
  }

  if (bad_n_eff_names.size() > 0) {
    std::cout << "The following parameters had fewer than 0.001 effective"
              << " samples per transition:" << std::endl;
    std::cout << "  ";
    for (size_t n = 0; n < bad_n_eff_names.size() - 1; ++n)
      std::cout << bad_n_eff_names.at(n) << ", ";
    std::cout << bad_n_eff_names.back() << std::endl;

    std::cout << "Such low values indicate that the effective sample size"
              << " estimators may be biased high and actual performance"
              << " may be substantially lower than quoted."
              << std::endl << std::endl;
  }

  if (bad_rhat_names.size() > 0) {
    std::cout << "The following parameters had split R-hat less than 1.1:"
              << std::endl;
    std::cout << "  ";
    for (size_t n = 0; n < bad_rhat_names.size() - 1; ++n)
      std::cout << bad_rhat_names.at(n) << ", ";
    std::cout << bad_rhat_names.back() << std::endl;

    std::cout << "Such high values indicate incomplete mixing and biased"
              << "estimation.  You should consider regularization your model"
              << " with additional prior information or looking for a more"
              << " effective parameterization."
              << std::endl << std::endl;
  }

  return 0;

}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 */

#include "Robot.h"
#include "Behaviour.h"
#include "Action.h"
#include <player-3.0/libplayerc++/playerc++.h>
#include <iostream>
#include <cstdlib>

#define _GXX_EXPERIMENTAL_CXX0X__
#include <chrono>

using namespace PlayerCc;
using namespace std;

int main(int argc, char **argv) {
	PlayerClient robot("localhost", 6665);
	Position2dProxy pp(&robot);
	LaserProxy lp(&robot);

	RobotDescriptor descriptor;

	Robot r(&pp, &lp, &descriptor);

	srand(time(0));

	/*
	 BehaviourOnObstacleDistance bClose(&r, 180, 0, 1.5);

	 for (int i = 0; i < 10; i++) {
	 bClose.addAction(
	 new Action(rand() % 2 ? ACTION_LINEAR_VEL : ACTION_ANGLUAR_VEL,
	 -1 + (rand() % 200) / 100.0, rand() % 2));
	 }

	 BehaviourOnObstacleDistance bFar(&r, 180, 1.5, 100);

	 for (int i = 0; i < 10; i++) {
	 bFar.addAction(
	 new Action(rand() % 2 ? ACTION_LINEAR_VEL : ACTION_ANGLUAR_VEL,
	 -1 + (rand() % 200) / 100.0, rand() % 2));
	 }

	 */

	BehaviourOnObstacleDistance bClose(&r, 180, 0, 1);
	BehaviourOnObstacleDistance bCloseL(&r, 270, 0, 0.7);
	BehaviourOnObstacleDistance bCloseR(&r, 90, 0, 0.7);
	BehaviourOnObstacleDistance bCloseL2(&r, 360, 0, 0.3);
	BehaviourOnObstacleDistance bCloseR2(&r, 0, 0, 0.3);
	BehaviourOnObstacleDistance bFar(&r, 180, 1, 100);

	bClose.addAction(new Action(ACTION_ANGLUAR_VEL, 0.5, 0.1));
	bCloseL.addAction(new Action(ACTION_ANGLUAR_VEL, -0.5, 0.2));
	bCloseR.addAction(new Action(ACTION_ANGLUAR_VEL, 0.5, 0.2));
	bCloseL2.addAction(new Action(ACTION_ANGLUAR_VEL, -0.5, 0.2));
	bCloseR2.addAction(new Action(ACTION_ANGLUAR_VEL, 0.5, 0.2));
	bFar.addAction(new Action(ACTION_LINEAR_VEL, 1, 0.1));

	descriptor.addBehavior(&bClose);
	descriptor.addBehavior(&bCloseL);
	descriptor.addBehavior(&bCloseR);
	descriptor.addBehavior(&bCloseL2);
	descriptor.addBehavior(&bCloseR2);
	descriptor.addBehavior(&bFar);

	while (true) {
		robot.Read();
		r.update();
	}
}

<commit_msg>Coisas aleatórias<commit_after>/*
 * main.cpp
 *
 */

#include "Robot.h"
#include "Behaviour.h"
#include "Action.h"
#include <player-3.0/libplayerc++/playerc++.h>
#include <iostream>
#include <cstdlib>

#define _GXX_EXPERIMENTAL_CXX0X__
#include <chrono>

using namespace PlayerCc;
using namespace std;

int main(int argc, char **argv) {
	PlayerClient robot("localhost", 6665);
	Position2dProxy pp(&robot);
	LaserProxy lp(&robot);

	RobotDescriptor descriptor;

	Robot r(&pp, &lp, &descriptor);

	srand(time(0));

	// criar comportamentos
	int rb = rand()%5 + 2;
	for(int i = 0; i < rb; i++){
		double minDist = (rand() % 100)/100.0;
		Behaviour *b = new BehaviourOnObstacleDistance(&r, rand()%360, minDist, minDist + (rand() % 400)/100.0);

		int ra = rand() % 10 + 1;
		for(int i = 0; i < ra; i++){
			Action *act;
			if(rand()%2){
				act = new Action(ACTION_LINEAR_VEL, (rand()%200)/100.0 - 1, (rand()%100)/100.0);
			}else{
				act = new Action(ACTION_ANGLUAR_VEL, (rand()%200)/100.0 - 1, (rand()%100)/100.0);
			}
			b->addAction(act);
		}

		descriptor.addBehavior(b);
	}

	BehaviourOnObstacleDistance far(&r, 180, 0, 100);
	far.addAction(new Action(ACTION_LINEAR_VEL, 1, 0.1));

	// senão tem uma grande chance dele ficar parado
	descriptor.addBehavior(&far);

	while (true) {
		robot.Read();
		r.update();
	}
}

<|endoftext|>


<commit_before>#include "circuit.h"
#include "docopt.h"
#include "evaluate_circuit.h"
#include "global.h"
#include "grid.h"
#include "input.h"
#include "memory.h"
#include "ordering.h"

static const char VERSION[] = "qFlex v0.1";
static const char USAGE[] =
    R"(Flexible Quantum Circuit Simulator (qFlex) implements an efficient
tensor network, CPU-based simulator of large quantum circuits.

  Usage:
    qflex <circuit_filename> <ordering_filename> <grid_filename> [<initial_conf> <final_conf> <verbosity_level> <memory_limit> <track_memory_milliseconds>]
    qflex -c <circuit_filename> -o <ordering_filename> -g <grid_filename> [--initial-conf=<initial_conf> --final-conf=<final_conf> --verbosity=<verbosity_level> --memory=<memory_limit> --track-memory=<milliseconds>]
    qflex (-h | --help)
    qflex --version

  Options:
    -h,--help                              Show this help.
    -c,--circuit=<circuit_filename>        Circuit filename.
    -o,--ordering=<ordering_filename>      Ordering filename.
    -g,--grid=<grid_filename>              Grid filename.
    -v,--verbosity=<verbosity_level>       Verbosity level [default: 0].
    -m,--memory=<memory_limit>             Memory limit [default: 1GB].)"
#ifdef __linux__
"\n" R"(    -t,--track-memory=<milliseconds>       If <verbosity_level> > 0, track memory usage [default: 0].)"
#endif
"\n" R"(    --initial-conf=<initial_conf>          Initial configuration.
    --final-conf=<final_conf>              Final configuration.
    --version                              Show version.

)";

/*
 * Example:
 * $ src/qflex.x config/circuits/bristlecone_48_1-24-1_0.txt \
 *               config/ordering/bristlecone_48.txt \
 *               config/grid/bristlecone_48.txt
 *
 */
int main(int argc, char** argv) {
  try {
    std::map<std::string, docopt::value> args =
        docopt::docopt(USAGE, {argv + 1, argv + argc}, true, VERSION);

    // Reading input
    qflex::QflexInput input;

    // Update global qflex::global::verbose
    if (static_cast<bool>(args["--verbosity"]))
      qflex::global::verbose = args["--verbosity"].asLong();
    else if (static_cast<bool>(args["<verbosity_level>"]))
      qflex::global::verbose = args["<verbosity_level>"].asLong();

    // Update global qflex::global::memory_limit
    if (static_cast<bool>(args["--memory"]))
      qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
          args["--memory"].asString());
    else if (static_cast<bool>(args["<memory_limit>"]))
      qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
          args["<memory_limit>"].asString());

#ifdef __linux__
    if (static_cast<bool>(args["--track-memory"]))
      qflex::global::track_memory = args["--track-memory"].asLong();
    else if (static_cast<bool>(args["<track_memory_milliseconds>"]))
      qflex::global::track_memory =
          args["<track_memory_milliseconds>"].asLong();

    // Alarms can interfere with the flow of the program if called to often in a
    // short period of time
    if (qflex::global::track_memory > 0 && qflex::global::track_memory < 100) {
      std::cerr << "WARNING! Minimum allowed tracking time is 100ms. Setting "
                   "to 100ms."
                << std::endl;
      qflex::global::track_memory = 100;
    }
#endif

    // Get initial/final configurations
    if (static_cast<bool>(args["--initial-conf"]))
      input.initial_state = args["--initial-conf"].asString();
    else if (static_cast<bool>(args["<initial_conf>"]))
      input.initial_state = args["<initial_conf>"].asString();

    if (static_cast<bool>(args["--final-conf"]))
      input.final_state = args["--final-conf"].asString();
    else if (static_cast<bool>(args["<final_conf>"]))
      input.final_state = args["<final_conf>"].asString();

    // Getting filenames
    std::string circuit_filename = static_cast<bool>(args["--circuit"])
                                       ? args["--circuit"].asString()
                                       : args["<circuit_filename>"].asString();
    std::string ordering_filename =
        static_cast<bool>(args["--ordering"])
            ? args["--ordering"].asString()
            : args["<ordering_filename>"].asString();
    std::string grid_filename = static_cast<bool>(args["--grid"])
                                    ? args["--grid"].asString()
                                    : args["<grid_filename>"].asString();

    // Print info on maximum memory
#ifdef __linux__
    if (qflex::global::verbose > 0)
      std::cerr << "Maximum allowed memory: "
                << qflex::utils::readable_memory_string(
                       qflex::global::memory_limit)
                << std::endl;

    // set alarms to get memory usage in real time
    if (qflex::global::verbose > 0 && qflex::global::track_memory > 0) {
      signal(SIGALRM, qflex::memory::print_memory_usage);
      ualarm(qflex::global::track_memory * 1e3,
             qflex::global::track_memory * 1e3);
    }
#endif

    // Load circuit
    input.circuit.load(std::ifstream(circuit_filename));

    // Load ordering
    input.ordering.load(std::ifstream(ordering_filename));

    // Load grid
    input.grid.load(grid_filename);

    // Evaluating circuit.
    std::vector<std::pair<std::string, std::complex<double>>> amplitudes;
    try {
      amplitudes = qflex::EvaluateCircuit(&input);
    } catch (const std::string& err_msg) {
      throw ERROR_MSG("Failed to call EvaluateCircuit(). Error:\n\t[", err_msg,
                      "]");
    }
    // If no error is caught, amplitudes will be initialized.

#ifdef __linux__
    if (qflex::global::verbose > 0 && qflex::global::track_memory > 0)
      qflex::memory::print_memory_usage();
#endif

    // Printing output.
    for (std::size_t c = 0; c < amplitudes.size(); ++c) {
      const auto& state = amplitudes[c].first;
      const auto& amplitude = amplitudes[c].second;
      std::cout << input.initial_state << " --> " << state << ": "
                << std::real(amplitude) << " " << std::imag(amplitude)
                << std::endl;
    }

  } catch (const std::exception& ex) {
    std::cerr << ex.what() << std::endl;
    return 1;

  } catch (const std::string& msg) {
    std::cerr << msg << std::endl;
    return 2;
  }

  return 0;
}
<commit_msg>Fix format.<commit_after>#include "circuit.h"
#include "docopt.h"
#include "evaluate_circuit.h"
#include "global.h"
#include "grid.h"
#include "input.h"
#include "memory.h"
#include "ordering.h"

static const char VERSION[] = "qFlex v0.1";
static const char USAGE[] =
    R"(Flexible Quantum Circuit Simulator (qFlex) implements an efficient
tensor network, CPU-based simulator of large quantum circuits.

  Usage:
    qflex <circuit_filename> <ordering_filename> <grid_filename> [<initial_conf> <final_conf> <verbosity_level> <memory_limit> <track_memory_milliseconds>]
    qflex -c <circuit_filename> -o <ordering_filename> -g <grid_filename> [--initial-conf=<initial_conf> --final-conf=<final_conf> --verbosity=<verbosity_level> --memory=<memory_limit> --track-memory=<milliseconds>]
    qflex (-h | --help)
    qflex --version

  Options:
    -h,--help                              Show this help.
    -c,--circuit=<circuit_filename>        Circuit filename.
    -o,--ordering=<ordering_filename>      Ordering filename.
    -g,--grid=<grid_filename>              Grid filename.
    -v,--verbosity=<verbosity_level>       Verbosity level [default: 0].
    -m,--memory=<memory_limit>             Memory limit [default: 1GB].)"
#ifdef __linux__
    "\n"
    R"(    -t,--track-memory=<milliseconds>       If <verbosity_level> > 0, track memory usage [default: 0].)"
#endif
    "\n"
    R"(    --initial-conf=<initial_conf>          Initial configuration.
    --final-conf=<final_conf>              Final configuration.
    --version                              Show version.

)";

/*
 * Example:
 * $ src/qflex.x config/circuits/bristlecone_48_1-24-1_0.txt \
 *               config/ordering/bristlecone_48.txt \
 *               config/grid/bristlecone_48.txt
 *
 */
int main(int argc, char** argv) {
  try {
    std::map<std::string, docopt::value> args =
        docopt::docopt(USAGE, {argv + 1, argv + argc}, true, VERSION);

    // Reading input
    qflex::QflexInput input;

    // Update global qflex::global::verbose
    if (static_cast<bool>(args["--verbosity"]))
      qflex::global::verbose = args["--verbosity"].asLong();
    else if (static_cast<bool>(args["<verbosity_level>"]))
      qflex::global::verbose = args["<verbosity_level>"].asLong();

    // Update global qflex::global::memory_limit
    if (static_cast<bool>(args["--memory"]))
      qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
          args["--memory"].asString());
    else if (static_cast<bool>(args["<memory_limit>"]))
      qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
          args["<memory_limit>"].asString());

#ifdef __linux__
    if (static_cast<bool>(args["--track-memory"]))
      qflex::global::track_memory = args["--track-memory"].asLong();
    else if (static_cast<bool>(args["<track_memory_milliseconds>"]))
      qflex::global::track_memory =
          args["<track_memory_milliseconds>"].asLong();

    // Alarms can interfere with the flow of the program if called to often in a
    // short period of time
    if (qflex::global::track_memory > 0 && qflex::global::track_memory < 100) {
      std::cerr << "WARNING! Minimum allowed tracking time is 100ms. Setting "
                   "to 100ms."
                << std::endl;
      qflex::global::track_memory = 100;
    }
#endif

    // Get initial/final configurations
    if (static_cast<bool>(args["--initial-conf"]))
      input.initial_state = args["--initial-conf"].asString();
    else if (static_cast<bool>(args["<initial_conf>"]))
      input.initial_state = args["<initial_conf>"].asString();

    if (static_cast<bool>(args["--final-conf"]))
      input.final_state = args["--final-conf"].asString();
    else if (static_cast<bool>(args["<final_conf>"]))
      input.final_state = args["<final_conf>"].asString();

    // Getting filenames
    std::string circuit_filename = static_cast<bool>(args["--circuit"])
                                       ? args["--circuit"].asString()
                                       : args["<circuit_filename>"].asString();
    std::string ordering_filename =
        static_cast<bool>(args["--ordering"])
            ? args["--ordering"].asString()
            : args["<ordering_filename>"].asString();
    std::string grid_filename = static_cast<bool>(args["--grid"])
                                    ? args["--grid"].asString()
                                    : args["<grid_filename>"].asString();

    // Print info on maximum memory
#ifdef __linux__
    if (qflex::global::verbose > 0)
      std::cerr << "Maximum allowed memory: "
                << qflex::utils::readable_memory_string(
                       qflex::global::memory_limit)
                << std::endl;

    // set alarms to get memory usage in real time
    if (qflex::global::verbose > 0 && qflex::global::track_memory > 0) {
      signal(SIGALRM, qflex::memory::print_memory_usage);
      ualarm(qflex::global::track_memory * 1e3,
             qflex::global::track_memory * 1e3);
    }
#endif

    // Load circuit
    input.circuit.load(std::ifstream(circuit_filename));

    // Load ordering
    input.ordering.load(std::ifstream(ordering_filename));

    // Load grid
    input.grid.load(grid_filename);

    // Evaluating circuit.
    std::vector<std::pair<std::string, std::complex<double>>> amplitudes;
    try {
      amplitudes = qflex::EvaluateCircuit(&input);
    } catch (const std::string& err_msg) {
      throw ERROR_MSG("Failed to call EvaluateCircuit(). Error:\n\t[", err_msg,
                      "]");
    }
    // If no error is caught, amplitudes will be initialized.

#ifdef __linux__
    if (qflex::global::verbose > 0 && qflex::global::track_memory > 0)
      qflex::memory::print_memory_usage();
#endif

    // Printing output.
    for (std::size_t c = 0; c < amplitudes.size(); ++c) {
      const auto& state = amplitudes[c].first;
      const auto& amplitude = amplitudes[c].second;
      std::cout << input.initial_state << " --> " << state << ": "
                << std::real(amplitude) << " " << std::imag(amplitude)
                << std::endl;
    }

  } catch (const std::exception& ex) {
    std::cerr << ex.what() << std::endl;
    return 1;

  } catch (const std::string& msg) {
    std::cerr << msg << std::endl;
    return 2;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "configure.hpp"
#include "parsers/md_parser.hpp"
#include "display_drivers/ncurses_display_driver.hpp"

using namespace std;

int main(int argc, char ** argv) {
	cout << "mdl v" << MDL_VERSION_STRING << endl;
	if (argc < 2) {
		cerr << "mdl: missing at least one argument" << endl;
		return 1;
	}

	MdParser parser(argv[1]);
	NcursesDisplayDriver drv;
	drv.display(parser.get_document());
	return 0;
}
<commit_msg>Make program usable for all locales<commit_after>#include "configure.hpp"
#include "parsers/md_parser.hpp"
#include "display_drivers/ncurses_display_driver.hpp"

#include <iostream>
#include <locale.h>

using namespace std;

int main(int argc, char ** argv) {
	setlocale(LC_ALL, "");
	cout << "mdl v" << MDL_VERSION_STRING << endl;
	if (argc < 2) {
		cerr << "mdl: missing at least one argument" << endl;
		return 1;
	}

	MdParser parser(argv[1]);
	NcursesDisplayDriver drv;
	drv.display(parser.get_document());
	return 0;
}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <fstream>
using namespace std;

#include "options.hpp"
#include "version.h"

int main(int argc, char * argv[]) {
	ifstream theFile;
	CmdLineOptions parsedOptions(argc, argv);

	cout << "awg20400-lattice-gen " << GIT_VERSION << endl;

	cout << "\nRunning via command: `" << argv[0] << "'" << endl;

	if ( parsedOptions.getHelp() ) {
		parsedOptions.printUsage();
		return -1;
	}
	return 0;
}
<commit_msg>Main program: reads in file, processes<commit_after>#include <string>
#include <iostream>
#include <fstream>
using namespace std;

#include "options.hpp"
#include "version.h"
#include "latticePair.hpp"

int main(int argc, char * argv[]) {
	ifstream theFile;
	CmdLineOptions parsedOptions(argc, argv);

	cout << "awg20400-lattice-gen " << GIT_VERSION << endl;

	if ( parsedOptions.getDebug() ) {
		cout << "Command invoked as: `" << argv[0];
		for(int arg=1; arg<argc; arg++) {
			cout << ' ' << argv[arg];
		}
		cout << "'\n";
	}

	if ( parsedOptions.getHelp() ) {
		parsedOptions.printUsage();
		return -1;
	}

	string inputFilePath("AWGSpec.csv");
	if ( parsedOptions.getInputPath().size() > 0 ) inputFilePath = parsedOptions.getInputPath();

	cout << "\nReading file from: " << inputFilePath << endl;
	theFile.open(inputFilePath.c_str());
	if (!theFile.is_open() || !theFile.good()) {
		cerr << "Problem opening data file!" << endl;
		theFile.close();
		return -1;
	}

	string theLine;
	unsigned int linesRead=0;
	latticePair ourPair;
	while( theFile.good() ) {
		std::getline(theFile, theLine);
		theFile.peek();
		linesRead++;
		ourPair.processLine(theLine);
		if ( parsedOptions.getDebug() ) cout << linesRead << "\t| " << theLine << endl;

	}
	cout << "Done!" << endl;

	string master, slave;
	cout << "Getting master string" << endl;
	master = ourPair.masterProgrammingString();
	cout << "Getting slave string" << endl;
	slave  = ourPair.slaveProgrammingString();

	cout << "Master Programming String:" << endl;
	cout << master;
	cout << endl << endl;

	cout << "Slave Programming String:" << endl;
	cout << slave;

	return 0;
}

<|endoftext|>


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

#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_
#define RCLCPP_RCLCPP_UTILITIES_HPP_

// TODO(wjwwood): remove
#include <iostream>

#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstring>
#include <mutex>
#include <string.h>
#include <thread>

#include <rmw/error_handling.h>
#include <rmw/macros.h>
#include <rmw/rmw.h>

// Determine if sigaction is available
#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define HAS_SIGACTION
#endif

namespace
{
/// Represent the status of the global interrupt signal.
volatile sig_atomic_t g_signal_status = 0;
/// Guard condition for interrupting the rmw implementation when the global interrupt signal fired.
rmw_guard_condition_t * g_sigint_guard_cond_handle = \
  rmw_create_guard_condition();
/// Condition variable for timed sleep (see sleep_for).
std::condition_variable g_interrupt_condition_variable;
std::atomic<bool> g_is_interrupted = false;
/// Mutex for protecting the global condition variable.
std::mutex g_interrupt_mutex;

#ifdef HAS_SIGACTION
struct sigaction old_action;
#else
void (* old_signal_handler)(int) = 0;
#endif

/// Handle the interrupt signal.
/** When the interrupt signal fires, the signal handler notifies the condition variable to wake up
 * and triggers the interrupt guard condition, so that all global threads managed by rclcpp
 * are interrupted.
 */
void
#ifdef HAS_SIGACTION
signal_handler(int signal_value, siginfo_t * siginfo, void * context)
#else
signal_handler(int signal_value)
#endif
{
  // TODO(wjwwood): remove
  std::cout << "signal_handler(" << signal_value << ")" << std::endl;
#ifdef HAS_SIGACTION
  if (old_action.sa_flags & SA_SIGINFO) {
    if (old_action.sa_sigaction != NULL) {
      old_action.sa_sigaction(signal_value, siginfo, context);
    }
  } else {
    // *INDENT-OFF*
    if (
      old_action.sa_handler != NULL && // Is set
      old_action.sa_handler != SIG_DFL && // Is not default
      old_action.sa_handler != SIG_IGN) // Is not ignored
    // *INDENT-ON*
    {
      old_action.sa_handler(signal_value);
    }
  }
#else
  if (old_signal_handler) {
    old_signal_handler(signal_value);
  }
#endif
  g_signal_status = signal_value;
  rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  if (status != RMW_RET_OK) {
    fprintf(stderr,
      "[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
  }
  g_is_interrupted.store(true);
  g_interrupt_condition_variable.notify_all();
}
} // namespace

namespace rclcpp
{

RMW_THREAD_LOCAL size_t thread_id = 0;

namespace utilities
{

/// Initialize communications via the rmw implementation and set up a global signal handler.
/**
 * \param[in] argc Number of arguments.
 * \param[in] argv Argument vector. Will eventually be used for passing options to rclcpp.
 */
void
init(int argc, char * argv[])
{
  (void)argc;
  (void)argv;
  g_is_interrupted.store(false);
  rmw_ret_t status = rmw_init();
  if (status != RMW_RET_OK) {
    // *INDENT-OFF* (prevent uncrustify from making unecessary indents here)
    throw std::runtime_error(
      std::string("failed to initialize rmw implementation: ") + rmw_get_error_string_safe());
    // *INDENT-ON*
  }
#ifdef HAS_SIGACTION
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = ::signal_handler;
  action.sa_flags = SA_SIGINFO;
  ssize_t ret = sigaction(SIGINT, &action, &old_action);
  if (ret == -1)
#else
  ::old_signal_handler = std::signal(SIGINT, ::signal_handler);
  if (::old_signal_handler == SIG_ERR)
#endif
  {
    const size_t error_length = 1024;
    char error_string[error_length];
#ifndef _WIN32
    strerror_r(errno, error_string, error_length);
#else
    strerror_s(error_string, error_length, errno);
#endif
    // *INDENT-OFF*
    throw std::runtime_error(
      std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") +
      error_string);
    // *INDENT-ON*
  }
}

/// Check rclcpp's status.
// \return True if SIGINT hasn't fired yet, false otherwise.
bool
ok()
{
  return ::g_signal_status == 0;
}

/// Notify the signal handler and rmw that rclcpp is shutting down.
void
shutdown()
{
  g_signal_status = SIGINT;
  rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  if (status != RMW_RET_OK) {
    fprintf(stderr,
      "[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
  }
  g_is_interrupted.store(true);
  g_interrupt_condition_variable.notify_all();
}

/// Get a handle to the rmw guard condition that manages the signal handler.
rmw_guard_condition_t *
get_global_sigint_guard_condition()
{
  return ::g_sigint_guard_cond_handle;
}

/// Use the global condition variable to block for the specified amount of time.
/**
 * \param[in] nanoseconds A std::chrono::duration representing how long to sleep for.
 * \return True if the condition variable did not timeout.
 */
bool
sleep_for(const std::chrono::nanoseconds & nanoseconds)
{
  // TODO: determine if posix's nanosleep(2) is more efficient here
  std::chrono::nanoseconds time_left = nanoseconds;
  {
    std::unique_lock<std::mutex> lock(::g_interrupt_mutex);
    auto start = std::chrono::steady_clock::now();
    ::g_interrupt_condition_variable.wait_for(lock, nanoseconds);
    time_left -= std::chrono::steady_clock::now() - start;
  }
  if (time_left > std::chrono::nanoseconds::zero() && !g_is_interrupted) {
    return sleep_for(time_left);
  }
  // Return true if the timeout elapsed successfully, otherwise false.
  return !g_is_interrupted;
}

} /* namespace utilities */
} /* namespace rclcpp */

#ifdef HAS_SIGACTION
#undef HAS_SIGACTION
#endif

#endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */
<commit_msg>fix deleted invocation of copy constructor on Linux<commit_after>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_
#define RCLCPP_RCLCPP_UTILITIES_HPP_

// TODO(wjwwood): remove
#include <iostream>

#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstring>
#include <mutex>
#include <string.h>
#include <thread>

#include <rmw/error_handling.h>
#include <rmw/macros.h>
#include <rmw/rmw.h>

// Determine if sigaction is available
#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define HAS_SIGACTION
#endif

namespace
{
/// Represent the status of the global interrupt signal.
volatile sig_atomic_t g_signal_status = 0;
/// Guard condition for interrupting the rmw implementation when the global interrupt signal fired.
rmw_guard_condition_t * g_sigint_guard_cond_handle = \
  rmw_create_guard_condition();
/// Condition variable for timed sleep (see sleep_for).
std::condition_variable g_interrupt_condition_variable;
std::atomic<bool> g_is_interrupted(false);
/// Mutex for protecting the global condition variable.
std::mutex g_interrupt_mutex;

#ifdef HAS_SIGACTION
struct sigaction old_action;
#else
void (* old_signal_handler)(int) = 0;
#endif

/// Handle the interrupt signal.
/** When the interrupt signal fires, the signal handler notifies the condition variable to wake up
 * and triggers the interrupt guard condition, so that all global threads managed by rclcpp
 * are interrupted.
 */
void
#ifdef HAS_SIGACTION
signal_handler(int signal_value, siginfo_t * siginfo, void * context)
#else
signal_handler(int signal_value)
#endif
{
  // TODO(wjwwood): remove
  std::cout << "signal_handler(" << signal_value << ")" << std::endl;
#ifdef HAS_SIGACTION
  if (old_action.sa_flags & SA_SIGINFO) {
    if (old_action.sa_sigaction != NULL) {
      old_action.sa_sigaction(signal_value, siginfo, context);
    }
  } else {
    // *INDENT-OFF*
    if (
      old_action.sa_handler != NULL && // Is set
      old_action.sa_handler != SIG_DFL && // Is not default
      old_action.sa_handler != SIG_IGN) // Is not ignored
    // *INDENT-ON*
    {
      old_action.sa_handler(signal_value);
    }
  }
#else
  if (old_signal_handler) {
    old_signal_handler(signal_value);
  }
#endif
  g_signal_status = signal_value;
  rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  if (status != RMW_RET_OK) {
    fprintf(stderr,
      "[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
  }
  g_is_interrupted.store(true);
  g_interrupt_condition_variable.notify_all();
}
} // namespace

namespace rclcpp
{

RMW_THREAD_LOCAL size_t thread_id = 0;

namespace utilities
{

/// Initialize communications via the rmw implementation and set up a global signal handler.
/**
 * \param[in] argc Number of arguments.
 * \param[in] argv Argument vector. Will eventually be used for passing options to rclcpp.
 */
void
init(int argc, char * argv[])
{
  (void)argc;
  (void)argv;
  g_is_interrupted.store(false);
  rmw_ret_t status = rmw_init();
  if (status != RMW_RET_OK) {
    // *INDENT-OFF* (prevent uncrustify from making unecessary indents here)
    throw std::runtime_error(
      std::string("failed to initialize rmw implementation: ") + rmw_get_error_string_safe());
    // *INDENT-ON*
  }
#ifdef HAS_SIGACTION
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigemptyset(&action.sa_mask);
  action.sa_sigaction = ::signal_handler;
  action.sa_flags = SA_SIGINFO;
  ssize_t ret = sigaction(SIGINT, &action, &old_action);
  if (ret == -1)
#else
  ::old_signal_handler = std::signal(SIGINT, ::signal_handler);
  if (::old_signal_handler == SIG_ERR)
#endif
  {
    const size_t error_length = 1024;
    char error_string[error_length];
#ifndef _WIN32
    strerror_r(errno, error_string, error_length);
#else
    strerror_s(error_string, error_length, errno);
#endif
    // *INDENT-OFF*
    throw std::runtime_error(
      std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") +
      error_string);
    // *INDENT-ON*
  }
}

/// Check rclcpp's status.
// \return True if SIGINT hasn't fired yet, false otherwise.
bool
ok()
{
  return ::g_signal_status == 0;
}

/// Notify the signal handler and rmw that rclcpp is shutting down.
void
shutdown()
{
  g_signal_status = SIGINT;
  rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
  if (status != RMW_RET_OK) {
    fprintf(stderr,
      "[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
  }
  g_is_interrupted.store(true);
  g_interrupt_condition_variable.notify_all();
}

/// Get a handle to the rmw guard condition that manages the signal handler.
rmw_guard_condition_t *
get_global_sigint_guard_condition()
{
  return ::g_sigint_guard_cond_handle;
}

/// Use the global condition variable to block for the specified amount of time.
/**
 * \param[in] nanoseconds A std::chrono::duration representing how long to sleep for.
 * \return True if the condition variable did not timeout.
 */
bool
sleep_for(const std::chrono::nanoseconds & nanoseconds)
{
  // TODO: determine if posix's nanosleep(2) is more efficient here
  std::chrono::nanoseconds time_left = nanoseconds;
  {
    std::unique_lock<std::mutex> lock(::g_interrupt_mutex);
    auto start = std::chrono::steady_clock::now();
    ::g_interrupt_condition_variable.wait_for(lock, nanoseconds);
    time_left -= std::chrono::steady_clock::now() - start;
  }
  if (time_left > std::chrono::nanoseconds::zero() && !g_is_interrupted) {
    return sleep_for(time_left);
  }
  // Return true if the timeout elapsed successfully, otherwise false.
  return !g_is_interrupted;
}

} /* namespace utilities */
} /* namespace rclcpp */

#ifdef HAS_SIGACTION
#undef HAS_SIGACTION
#endif

#endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */
<|endoftext|>


<commit_before>/*
  This file is part of the PhantomJS project from Ofi Labs.

  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "consts.h"
#include "utils.h"
#include "env.h"
#include "phantom.h"

#ifdef Q_OS_LINUX
#include "client/linux/handler/exception_handler.h"
#endif
#ifdef Q_OS_MAC
#include "client/mac/handler/exception_handler.h"
#endif

#include <QApplication>

#ifdef Q_OS_WIN32
#if !defined(QT_SHARED) && !defined(QT_DLL)
#include <QtPlugin>

// HACK: When linking a static PhantomJS + MSVC agains the
// static Qt included in PhantomJS, we get linker errors.
// This noop function can cure them.
#include <QUuid>
#include <QPainter>
#include <QXmlStreamAttributes>
void makeLinkerHappy()
{
    QWidget().colorCount();
    QUuid().createUuid();
    QPainter().drawImage(QPointF(), QImage(), QRect());
    const QXmlStreamAttributes foo;
    foo[0];
}
// End of linker hack.

Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
#endif
#endif

#if QT_VERSION != QT_VERSION_CHECK(4, 8, 2)
#error Something is wrong with the setup. Please report to the mailing list!
#endif

int main(int argc, char** argv, const char** envp)
{
    // Setup Google Breakpad exception handler
#ifdef Q_OS_LINUX
    google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true);
#endif
#ifdef Q_OS_MAC
    google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true, NULL);
#endif

    QApplication app(argc, argv);

    app.setWindowIcon(QIcon(":/phantomjs-icon.png"));
    app.setApplicationName("PhantomJS");
    app.setOrganizationName("Ofi Labs");
    app.setOrganizationDomain("www.ofilabs.com");
    app.setApplicationVersion(PHANTOMJS_VERSION_STRING);

    // Prepare the "env" singleton using the environment variables
    Env::instance()->parse(envp);

    // Get the Phantom singleton
    Phantom *phantom = Phantom::instance();

    // Registering an alternative Message Handler
    Utils::printDebugMessages = phantom->printDebugMessages();
    qInstallMsgHandler(Utils::messageHandler);

    // Start script execution
    if (phantom->execute()) {
        app.exec();
    }

    // End script execution: delete the phantom singleton and set execution return value
    int retVal = phantom->returnValue();
    delete phantom;
    return retVal;
}
<commit_msg>Make the msvc linker happy again.<commit_after>/*
  This file is part of the PhantomJS project from Ofi Labs.

  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "consts.h"
#include "utils.h"
#include "env.h"
#include "phantom.h"

#ifdef Q_OS_LINUX
#include "client/linux/handler/exception_handler.h"
#endif
#ifdef Q_OS_MAC
#include "client/mac/handler/exception_handler.h"
#endif

#include <QApplication>

#ifdef Q_OS_WIN32
#if !defined(QT_SHARED) && !defined(QT_DLL)
#include <QtPlugin>

// HACK: When linking a static PhantomJS + MSVC agains the
// static Qt included in PhantomJS, we get linker errors.
// This noop function can cure them.
#include <QUuid>
#include <QPainter>
#include <QXmlStreamAttributes>
#include <QFileDialog>
#include <QPainter>
#include <QToolTip>
#include <QStandardItem>
void makeLinkerHappy()
{
    QWidget().colorCount();
    QUuid().createUuid();
    QPainter().drawImage(QPointF(), QImage(), QRect());
    const QXmlStreamAttributes foo;
    foo[0];
    QFileDialog().getOpenFileName();
    QPainter::staticMetaObject.indexOfMethod(0);
    QToolTip::hideText();
    QStandardItem standardItem;
    standardItem.setForeground(QBrush());
    standardItem.setBackground(QBrush());
    standardItem.setToolTip(QString());
}
// End of linker hack.

Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
#endif
#endif

#if QT_VERSION != QT_VERSION_CHECK(4, 8, 2)
#error Something is wrong with the setup. Please report to the mailing list!
#endif

int main(int argc, char** argv, const char** envp)
{
    // Setup Google Breakpad exception handler
#ifdef Q_OS_LINUX
    google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true);
#endif
#ifdef Q_OS_MAC
    google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true, NULL);
#endif

    QApplication app(argc, argv);

    app.setWindowIcon(QIcon(":/phantomjs-icon.png"));
    app.setApplicationName("PhantomJS");
    app.setOrganizationName("Ofi Labs");
    app.setOrganizationDomain("www.ofilabs.com");
    app.setApplicationVersion(PHANTOMJS_VERSION_STRING);

    // Prepare the "env" singleton using the environment variables
    Env::instance()->parse(envp);

    // Get the Phantom singleton
    Phantom *phantom = Phantom::instance();

    // Registering an alternative Message Handler
    Utils::printDebugMessages = phantom->printDebugMessages();
    qInstallMsgHandler(Utils::messageHandler);

    // Start script execution
    if (phantom->execute()) {
        app.exec();
    }

    // End script execution: delete the phantom singleton and set execution return value
    int retVal = phantom->returnValue();
    delete phantom;
    return retVal;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <atomic>
#include <chrono>
#include <iostream>

#include "dll/rbm/rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

namespace {

constexpr const size_t K = 3;

template <typename C>
float distance_knn(const C& lhs, const C& rhs) {
    return etl::sum((lhs - rhs) >> (lhs - rhs));
}

struct distance_t {
    float dist;
    uint32_t label;
};

size_t vote_knn(const std::vector<distance_t>& distances) {
    size_t votes[10]{};

    for (size_t k = 0; k < K; ++k) {
        ++votes[distances[k].label];
    }

    size_t label = 0;

    for (size_t k = 1; k < 10; ++k) {
        if (votes[k] > votes[label]) {
            label = k;
        }
    }

    return label;
}

template <typename C, typename L>
double evaluate_knn(const C& training, const C& test, const L& training_labels, const L& test_labels) {
    std::atomic<size_t> correct;

    correct = 0;

    cpp::default_thread_pool<> pool(8);

    cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
        std::vector<distance_t> distances(training.size());

        for (size_t j = 0; j < training.size(); ++j) {
            float d      = distance_knn(test[i], training[j]);
            distances[j] = {d, training_labels[j]};
        }

        std::sort(distances.begin(), distances.end(), [](const distance_t& lhs, const distance_t& rhs) {
            return lhs.dist < rhs.dist;
        });

        if (vote_knn(distances) == test_labels[i]) {
            ++correct;
        }
    });

    return correct / double(test.size());
}

template <size_t I, typename N, typename D>
double evaluate_knn_net(const N& net, const D& dataset) {
    std::vector<etl::dyn_vector<float>> training(dataset.training_images.size());
    std::vector<etl::dyn_vector<float>> test(dataset.test_images.size());

    cpp::default_thread_pool<> pool(8);

    cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
        training[i] = net->template features_sub<I>(dataset.training_images[i]);
    });

    cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
        test[i] = net->template features_sub<I>(dataset.test_images[i]);
    });

    return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels);
}

template <size_t I, typename Net, typename D>
void evaluate_net(size_t N, const Net& net, const D& dataset) {
    std::cout << "__result__(KNN): dense_ae_" << N << ":" << evaluate_knn_net<I>(net, dataset) << std::endl;
}

template <typename R, typename D>
double evaluate_knn_rbm(const R& rbm, const D& dataset) {
    std::vector<etl::dyn_vector<float>> training(dataset.training_images.size());
    std::vector<etl::dyn_vector<float>> test(dataset.test_images.size());

    cpp::default_thread_pool<> pool(8);

    cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
        training[i] = rbm->features(dataset.training_images[i]);
    });

    cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
        test[i] = rbm->features(dataset.test_images[i]);
    });

    return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels);
}

template <typename R, typename D>
void evaluate_rbm(size_t N, const R& rbm, const D& dataset) {
    std::cout << "__result__: dense_rbm_" << N << ":" << evaluate_knn_rbm(rbm, dataset) << std::endl;
}

} // end of anonymous

int main(int argc, char* argv[]) {
    std::string model = "raw";
    if (argc > 1) {
        model = argv[1];
    }

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>();

    if (model == "raw") {
        double accuracy = evaluate_knn(dataset.training_images, dataset.test_images, dataset.training_labels, dataset.test_labels);
        std::cout << "Raw: " << accuracy << std::endl;
    } else if (model == "dense") {
        mnist::binarize_dataset(dataset);

        static constexpr size_t epochs = 100;
        static constexpr size_t batch_size = 100;

#define SINGLE_RBM(N)                                                            \
        {                                                                        \
            using rbm_t = dll::rbm_desc<                                         \
                28 * 28, N,                                                      \
                dll::batch_size<batch_size>,                                     \
                dll::momentum>::layer_t;                                         \
            auto rbm              = std::make_unique<rbm_t>();                   \
            rbm->learning_rate    = 0.1;                                         \
            rbm->initial_momentum = 0.9;                                         \
            rbm->final_momentum   = 0.9;                                         \
            auto error            = rbm->train(dataset.training_images, epochs); \
            std::cout << "pretrain_error:" << error << std::endl;                \
            evaluate_rbm(N, rbm, dataset);                                       \
        }

#define SINGLE_AE(N)                                                                  \
        {                                                                             \
            using network_t =                                                         \
                dll::dbn_desc<dll::dbn_layers<dll::dense_desc<28 * 28, N>::layer_t,   \
                                              dll::dense_desc<N, 28 * 28>::layer_t>,  \
                              dll::momentum, dll::trainer<dll::sgd_trainer>,          \
                              dll::batch_size<batch_size>>::dbn_t;                    \
            auto ae              = std::make_unique<network_t>();                     \
            ae->learning_rate    = 0.1;                                               \
            ae->initial_momentum = 0.9;                                               \
            ae->final_momentum   = 0.9;                                               \
            auto ft_error        = ae->fine_tune_ae(dataset.training_images, epochs); \
            std::cout << "ft_error:" << ft_error << std::endl;                        \
            evaluate_net<1>(N, ae, dataset); \
        }

        SINGLE_RBM(50);
        SINGLE_RBM(100);
        SINGLE_RBM(200);
        SINGLE_RBM(400);
        SINGLE_RBM(600);
        SINGLE_RBM(800);
        SINGLE_RBM(1000);

        SINGLE_AE(50);
        SINGLE_AE(100);
        SINGLE_AE(200);
        SINGLE_AE(400);
        SINGLE_AE(600);
        SINGLE_AE(800);
        SINGLE_AE(1000);
    }

    return 0;
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright (c) 2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <atomic>
#include <chrono>
#include <iostream>

#include "dll/rbm/rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

namespace {

constexpr const size_t K = 3;

template <typename C>
float distance_knn(const C& lhs, const C& rhs) {
    return etl::sum((lhs - rhs) >> (lhs - rhs));
}

struct distance_t {
    float dist;
    uint32_t label;
};

size_t vote_knn(const std::vector<distance_t>& distances) {
    size_t votes[10]{};

    for (size_t k = 0; k < K; ++k) {
        ++votes[distances[k].label];
    }

    size_t label = 0;

    for (size_t k = 1; k < 10; ++k) {
        if (votes[k] > votes[label]) {
            label = k;
        }
    }

    return label;
}

template <typename C, typename L>
double evaluate_knn(const C& training, const C& test, const L& training_labels, const L& test_labels) {
    std::atomic<size_t> correct;

    correct = 0;

    cpp::default_thread_pool<> pool(8);

    cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
        std::vector<distance_t> distances(training.size());

        for (size_t j = 0; j < training.size(); ++j) {
            float d      = distance_knn(test[i], training[j]);
            distances[j] = {d, training_labels[j]};
        }

        std::sort(distances.begin(), distances.end(), [](const distance_t& lhs, const distance_t& rhs) {
            return lhs.dist < rhs.dist;
        });

        if (vote_knn(distances) == test_labels[i]) {
            ++correct;
        }
    });

    return correct / double(test.size());
}

template <size_t I, typename N, typename D>
double evaluate_knn_net(const N& net, const D& ds) {
    std::vector<etl::dyn_vector<float>> training(ds.training_images.size());
    std::vector<etl::dyn_vector<float>> test(ds.test_images.size());

    cpp::default_thread_pool<> pool(8);

    cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
        training[i] = net->template features_sub<I>(ds.training_images[i]);
    });

    cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
        test[i] = net->template features_sub<I>(ds.test_images[i]);
    });

    return evaluate_knn(training, test, ds.training_labels, ds.test_labels);
}

template <size_t I, typename Net, typename D>
void evaluate_net(size_t N, const Net& net, const D& ds) {
    std::cout << "__result__(KNN): dense_ae_" << N << ":" << evaluate_knn_net<I>(net, ds) << std::endl;
}

template <typename R, typename D>
double evaluate_knn_rbm(const R& rbm, const D& ds) {
    std::vector<etl::dyn_vector<float>> training(ds.training_images.size());
    std::vector<etl::dyn_vector<float>> test(ds.test_images.size());

    cpp::default_thread_pool<> pool(8);

    cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
        training[i] = rbm->features(ds.training_images[i]);
    });

    cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
        test[i] = rbm->features(ds.test_images[i]);
    });

    return evaluate_knn(training, test, ds.training_labels, ds.test_labels);
}

template <typename R, typename D>
void evaluate_rbm(size_t N, const R& rbm, const D& ds) {
    std::cout << "__result__: dense_rbm_" << N << ":" << evaluate_knn_rbm(rbm, ds) << std::endl;
}

} // end of anonymous

int main(int argc, char* argv[]) {
    std::string model = "raw";
    if (argc > 1) {
        model = argv[1];
    }

    auto ds = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>();

    if (model == "raw") {
        std::cout << "Raw(KNN): " << evaluate_knn(ds.training_images, ds.test_images, ds.training_labels, ds.test_labels) << std::endl;
    } else if (model == "dense") {
        mnist::binarize_dataset(ds);

        static constexpr size_t epochs = 100;
        static constexpr size_t batch_size = 100;

#define SINGLE_RBM(N)                                                   \
        {                                                                   \
            using rbm_t = dll::rbm_desc<                                    \
                28 * 28, N,                                                 \
                dll::batch_size<batch_size>,                                \
                dll::momentum>::layer_t;                                    \
            auto rbm              = std::make_unique<rbm_t>();              \
            rbm->learning_rate    = 0.1;                                    \
            rbm->initial_momentum = 0.9;                                    \
            rbm->final_momentum   = 0.9;                                    \
            auto error            = rbm->train(ds.training_images, epochs); \
            std::cout << "pretrain_error:" << error << std::endl;           \
            evaluate_rbm(N, rbm, ds);                                       \
        }

#define SINGLE_AE(N)                                                             \
        {                                                                            \
            using network_t =                                                        \
                dll::dbn_desc<dll::dbn_layers<dll::dense_desc<28 * 28, N>::layer_t,  \
                                              dll::dense_desc<N, 28 * 28>::layer_t>, \
                              dll::momentum, dll::trainer<dll::sgd_trainer>,         \
                              dll::batch_size<batch_size>>::dbn_t;                   \
            auto ae              = std::make_unique<network_t>();                    \
            ae->learning_rate    = 0.1;                                              \
            ae->initial_momentum = 0.9;                                              \
            ae->final_momentum   = 0.9;                                              \
            auto ft_error        = ae->fine_tune_ae(ds.training_images, epochs);     \
            std::cout << "ft_error:" << ft_error << std::endl;                       \
            evaluate_net<1>(N, ae, ds);                                              \
        }

        SINGLE_RBM(50);
        SINGLE_RBM(100);
        SINGLE_RBM(200);
        SINGLE_RBM(400);
        SINGLE_RBM(600);
        SINGLE_RBM(800);
        SINGLE_RBM(1000);

        SINGLE_AE(50);
        SINGLE_AE(100);
        SINGLE_AE(200);
        SINGLE_AE(400);
        SINGLE_AE(600);
        SINGLE_AE(800);
        SINGLE_AE(1000);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <Arduino.h>
#include <avr/wdt.h>
#include <TinyGPS++.h>
#include <idDHT11.h>
#include <SDCard.h>
#include <Utils.h>
#include <PinMap.h>

#ifdef DEBUG
#include <MemoryFree.h>
#include <SoftwareSerial.h>
SoftwareSerial gpsSerial(8, 9);
#endif

SDCard sd(SD_PIN);
TinyGPSPlus gps;
Utils utils;

bool firstEntry = true;
char fileName [11];
int ledState = LOW;

/**
 * initialize dht as on library documentation
 * @see https://github.com/niesteszeck/idDHT11/blob/master/examples/idDHT11_Lib_example/idDHT11_Lib_example.ino
 * @see https://www.arduino.cc/en/Reference/AttachInterrupt
 */
void dht11_wrapper();
idDHT11 dht(DHT_PIN, 1, dht11_wrapper);
void dht11_wrapper() {
    dht.isrCallback();
}

/**
 * wrap all data together to be appended to csv log file
 */
void serialize(char* entry) {
    while(dht.acquiring());
    int result = dht.getStatus();
    if (result != IDDHTLIB_OK) {
        #ifdef DEBUG
        dht.printError(result);
        #endif
    } else {
        // save new values
        dht.saveLastValidData();
    }
    sprintf(
        entry,
        "%i,%i,%i,%i,%0.6f,%0.6f,%0.2f",
        utils.readMQ(MQ2_PIN), utils.readMQ(MQ135_PIN),
        (int)dht.getLastValidCelsius(), (int)dht.getLastValidHumidity(),
        gps.location.lat(), gps.location.lng(), gps.altitude.meters()
    );
}

void createFileName(char *str) {
    // limited to 8.3 file format https://en.wikipedia.org/wiki/8.3_filename
    // so .csv was removed
    sprintf(str, "%d-%d-%d", gps.date.day(), gps.time.hour(), gps.time.minute());
}

/**
 * delay while keep reading gps data
 */
void smartDelay(const unsigned long &delay) {
    unsigned long initialTime = millis();
    unsigned long currentTime;
    do {
        #ifdef DEBUG
        if (gpsSerial.available() > 0) {
            gps.encode(gpsSerial.read());
        #else
        if (Serial.available() > 0) {
            gps.encode(Serial.read());
        #endif
        }
        currentTime = millis();
    } while (currentTime - initialTime < delay);
}

void setup() {

    Serial.begin(9600);
    #ifdef DEBUG
    Serial.println(F("setup: initializing sensor platform..."));
    gpsSerial.begin(9600);
    #endif

    // setup control led
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);

    // enable watchdog with 2 seconds timer
    wdt_enable(WDTO_2S);

    if(!sd.begin()) {
        utils.error("setup: sd could not begin!");
    }

    // start acquiring first value, result is interrupt driven
    // the dht sensor is having issues since the soldering on the board,
    // this is a tmeporary work around to get valid values
    if (dht.acquireAndWait() != IDDHTLIB_OK) {
        utils.error("setup: dht could not acquire proper data!");
    } else {
        dht.saveLastValidData();
    }

    #ifdef DEBUG
    Serial.println(F("setup: initialization went okay!"));
    #endif

}

void loop() {
    smartDelay(255);
    if (firstEntry && gps.date.isValid() && gps.location.isValid()) {
        // if valid state is entered, led is on
        digitalWrite(LED_PIN, HIGH);
        createFileName(fileName);
        if (sd.exists(fileName)) {
            #ifdef DEBUG
            Serial.print(F("appending to file "));
            Serial.println(fileName);
            #endif
            firstEntry = false;
        } else {
            #ifdef DEBUG
            Serial.print(F("new log file "));
            Serial.println(fileName);
            #endif
            firstEntry = false;
        }
    }
    if (!firstEntry && gps.location.isValid()) {
        // if valid state is entered, led is on
        digitalWrite(LED_PIN, HIGH);
        if (gps.location.isUpdated()) {
            // get new dht value
            dht.acquire();
            char entry [40];
            serialize(entry);
            #ifdef DEBUG
            Serial.println(entry);
            #endif
            if (!sd.writeToFile(fileName, entry)) {
                utils.error("could not write data to file");
            }
        }
    } else {
        // blink for invalid gps data
        if (ledState == LOW) {
            ledState = HIGH;
        } else {
            ledState = LOW;
        }
        digitalWrite(LED_PIN, ledState);
    }
    // reset watchdog timer
    wdt_reset();
}
<commit_msg>add time to file entries, save data whenever location is valid<commit_after>#include <Arduino.h>
#include <avr/wdt.h>
#include <TinyGPS++.h>
#include <idDHT11.h>
#include <SDCard.h>
#include <Utils.h>
#include <PinMap.h>

#ifdef DEBUG
#include <MemoryFree.h>
#include <SoftwareSerial.h>
SoftwareSerial gpsSerial(8, 9);
#endif

SDCard sd(SD_PIN);
TinyGPSPlus gps;
Utils utils;

bool firstEntry = true;
char fileName [11];
int ledState = LOW;

/**
 * initialize dht as on library documentation
 * @see https://github.com/niesteszeck/idDHT11/blob/master/examples/idDHT11_Lib_example/idDHT11_Lib_example.ino
 * @see https://www.arduino.cc/en/Reference/AttachInterrupt
 */
void dht11_wrapper();
idDHT11 dht(DHT_PIN, 1, dht11_wrapper);
void dht11_wrapper() {
    dht.isrCallback();
}

/**
 * wrap all data together to be appended to csv log file
 */
void serialize(char* entry) {
    while(dht.acquiring());
    int result = dht.getStatus();
    if (result != IDDHTLIB_OK) {
        #ifdef DEBUG
        dht.printError(result);
        #endif
    } else {
        // save new values
        dht.saveLastValidData();
    }
    sprintf(
        entry,
        "%i,%i,%i,%i,%0.6f,%0.6f,%0.2f,%lu",
        utils.readMQ(MQ2_PIN), utils.readMQ(MQ135_PIN),
        (int)dht.getLastValidCelsius(), (int)dht.getLastValidHumidity(),
        gps.location.lat(), gps.location.lng(), gps.altitude.meters(),
        gps.time.value()
    );
}

void createFileName(char *str) {
    // limited to 8.3 file format https://en.wikipedia.org/wiki/8.3_filename
    // so .csv was removed
    sprintf(str, "%d-%d-%d", gps.date.day(), gps.time.hour(), gps.time.minute());
}

/**
 * delay while keep reading gps data
 */
void smartDelay(const unsigned long &delay) {
    unsigned long initialTime = millis();
    unsigned long currentTime;
    do {
        #ifdef DEBUG
        if (gpsSerial.available() > 0) {
            gps.encode(gpsSerial.read());
        #else
        if (Serial.available() > 0) {
            gps.encode(Serial.read());
        #endif
        }
        currentTime = millis();
    } while (currentTime - initialTime < delay);
}

void setup() {

    Serial.begin(9600);
    #ifdef DEBUG
    Serial.println(F("setup: initializing sensor platform..."));
    gpsSerial.begin(9600);
    #endif

    // setup control led
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);

    // enable watchdog with 2 seconds timer
    wdt_enable(WDTO_2S);

    if(!sd.begin()) {
        utils.error("setup: sd could not begin!");
    }

    // start acquiring first value, result is interrupt driven
    // the dht sensor is having issues since the soldering on the board,
    // this is a tmeporary work around to get valid values
    if (dht.acquireAndWait() != IDDHTLIB_OK) {
        utils.error("setup: dht could not acquire proper data!");
    } else {
        dht.saveLastValidData();
    }

    #ifdef DEBUG
    Serial.println(F("setup: initialization went okay!"));
    #endif

}

void loop() {
    smartDelay(255);
    if (firstEntry && gps.date.isValid() && gps.location.isValid()) {
        // if valid state is entered, led is on
        digitalWrite(LED_PIN, HIGH);
        createFileName(fileName);
        if (sd.exists(fileName)) {
            #ifdef DEBUG
            Serial.print(F("appending to file "));
            Serial.println(fileName);
            #endif
            firstEntry = false;
        } else {
            #ifdef DEBUG
            Serial.print(F("new log file "));
            Serial.println(fileName);
            #endif
            firstEntry = false;
        }
    }
    if (!firstEntry && gps.location.isValid()) {
        // if valid state is entered, led is on
        digitalWrite(LED_PIN, HIGH);
        // get new dht value
        dht.acquire();
        char entry [40];
        serialize(entry);
        #ifdef DEBUG
        Serial.println(entry);
        #endif
        if (!sd.writeToFile(fileName, entry)) {
            utils.error("could not write data to file");
        }
    } else {
        // blink for invalid gps data
        if (ledState == LOW) {
            ledState = HIGH;
        } else {
            ledState = LOW;
        }
        digitalWrite(LED_PIN, ledState);
    }
    // reset watchdog timer
    wdt_reset();
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016, Mike Tzou
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of foo_xspf_1 nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdafx.h"
#include "main.h"
#include "helper.h"

#define PLUGIN_NAME "XSPF Playlist"
#define PLUGIN_VERSION "2.6.2"
DECLARE_COMPONENT_VERSION
(
	PLUGIN_NAME , PLUGIN_VERSION ,

	PLUGIN_NAME"\n"
	"Compiled on: "__DATE__"\n"
	"https://github.com/Chocobo1/foo_xspf_1\n"
	"This plugin is released under BSD 3-Clause license\n"
	"\n"
	"Mike Tzou (Chocobo1)\n"
	"\n"
	"This plugin links statically with the following open source library:\n"
	"TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n"
);

const char *xspf::get_extension()
{
	return "xspf";
}

bool xspf::is_our_content_type( const char *p_content_type )
{
	const char mime[] = "application/xspf+xml";
	if( strcmp( p_content_type , mime ) != 0 )
		return false;
	return true;
}

bool xspf::is_associatable()
{
	return true;
}

bool xspf::can_write()
{
	return true;
}

void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort )
{
	// avoid file open loop
	if( file_list.find( p_path ) != file_list.cend() )
		return;
	file_list.emplace( p_path );

	pfc::hires_timer t;
	t.start();
	try
	{
		p_callback->on_progress( p_path );
		open_helper( p_path , p_file , p_callback , p_abort );
	}
	catch( ... )
	{
		file_list.erase( p_path );
		throw;
	}
	console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path );

	file_list.erase( p_path );
	return;
}

void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort )
{
	pfc::hires_timer t;
	t.start();
	write_helper( p_path , p_file , p_data , p_abort );
	console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path );

	return;
}
<commit_msg>bump version<commit_after>/*
Copyright (c) 2016, Mike Tzou
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of foo_xspf_1 nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdafx.h"
#include "main.h"
#include "helper.h"

#define PLUGIN_NAME "XSPF Playlist"
#define PLUGIN_VERSION "2.6.3"
DECLARE_COMPONENT_VERSION
(
	PLUGIN_NAME , PLUGIN_VERSION ,

	PLUGIN_NAME"\n"
	"Compiled on: "__DATE__"\n"
	"https://github.com/Chocobo1/foo_xspf_1\n"
	"This plugin is released under BSD 3-Clause license\n"
	"\n"
	"Mike Tzou (Chocobo1)\n"
	"\n"
	"This plugin links statically with the following open source library:\n"
	"TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n"
);

const char *xspf::get_extension()
{
	return "xspf";
}

bool xspf::is_our_content_type( const char *p_content_type )
{
	const char mime[] = "application/xspf+xml";
	if( strcmp( p_content_type , mime ) != 0 )
		return false;
	return true;
}

bool xspf::is_associatable()
{
	return true;
}

bool xspf::can_write()
{
	return true;
}

void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort )
{
	// avoid file open loop
	if( file_list.find( p_path ) != file_list.cend() )
		return;
	file_list.emplace( p_path );

	pfc::hires_timer t;
	t.start();
	try
	{
		p_callback->on_progress( p_path );
		open_helper( p_path , p_file , p_callback , p_abort );
	}
	catch( ... )
	{
		file_list.erase( p_path );
		throw;
	}
	console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path );

	file_list.erase( p_path );
	return;
}

void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort )
{
	pfc::hires_timer t;
	t.start();
	write_helper( p_path , p_file , p_data , p_abort );
	console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path );

	return;
}
<|endoftext|>