<commit_before>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <unistd.h>

using namespace std;
using namespace cv;

typedef Vec3b Color;
typedef vector<Mat> World;
typedef Color (*Rule)(Color, const vector<Color> &);
typedef struct {
    unsigned int thread_id;
    unsigned int thread_count;
    World *src;
    World *dst;
    Rule r;
} thread_data;

void set_color(World &, int x, int y, int t, Color);
Color get_color(const World &, int x, int y, int t);
void *update_thread(void *);
void update(World *src, World *dst, Rule, unsigned int thread_count);
Color my_rule(Color, const vector<Color> &);

/*** Customize this rule ***/
Color my_rule(Color c, const vector<Color> &cs) {
    float r = 0;
    float g = 0;
    float b = 0;
    for (int i = 0; i < (int)cs.size(); i++) {
        r += cs[i][2];
        g += cs[i][1];
        b += cs[i][0];
    }
    r /= cs.size()-1;
    g /= cs.size()-1;
    b /= cs.size()-1;
    c[0] = b;
    c[1] = g;
    c[2] = r;
    return c;
}
/***************************/

void set_color(World &w, int x, int y, int t, Color c) {
    Mat m = w.at(t);
    m.at<Vec3b>(y,x) = c;
}

Color get_color(const World &w, int x, int y, int t) {
    Mat m = w.at(t);
    return m.at<Vec3b>(y,x);
}

void *update_thread(void *data) {
    thread_data *d = (thread_data*)data;

    World *src = d->src;
    World *dst = d->dst;
    Rule r = d->r;

    int x_min = 0;
    int y_min = 0;
    int t_min = 0;
    int x_max = src->at(0).cols-1;
    int y_max = src->at(0).rows-1;
    int t_max = src->size()-1;
    for (int t = d->thread_id; t < (int)src->size(); t+=d->thread_count) {
        cout << ".";
        for (int y = 0; y < src->at(t).rows; y++)
        for (int x = 0; x < src->at(t).cols; x++) {
            Color c = get_color(*src, x, y, t);
            vector<Color> neighbors;
            for (int dt = -1; dt <= 1; dt++) {
                if (t+dt >= t_min && t+dt <= t_max) {
                    if (x-1 >= x_min) neighbors.push_back(get_color(*src,x-1,y,t+dt));
                    if (x+1 <= x_max) neighbors.push_back(get_color(*src,x+1,y,t+dt));
                    if (y-1 >= y_min) neighbors.push_back(get_color(*src,x,y-1,t+dt));
                    if (y+1 <= y_max) neighbors.push_back(get_color(*src,x,y+1,t+dt));
                    if (x-1 >= x_min && y-1 >= y_min) neighbors.push_back(get_color(*src,x-1,y-1,t+dt));
                    if (x+1 <= x_max && y-1 >= y_min) neighbors.push_back(get_color(*src,x+1,y-1,t+dt));
                    if (x-1 >= x_min && y+1 <= y_max) neighbors.push_back(get_color(*src,x-1,y+1,t+dt));
                    if (x+1 <= x_max && y+1 <= y_max) neighbors.push_back(get_color(*src,x+1,y+1,t+dt));
                    if (dt != 0) neighbors.push_back(get_color(*src,x,y,t+dt));
                }
            }
            set_color(*dst, x, y, t, r(c, neighbors));
        }
    }

    return NULL;
}

void update(World *src, World *dst, Rule r, unsigned int thread_count) {
    pthread_t threads[thread_count];
    int irets[thread_count];
    thread_data data[thread_count];

    for (unsigned int i = 0; i < thread_count; i++) {
        data[i] = thread_data{i, thread_count, src, dst, my_rule};
        irets[i] = pthread_create(&threads[i], NULL, update_thread, &data);
        if (irets[i]) {
            fprintf(stderr,"Error - pthread_create() return code: %d\n",irets[i]);
            exit(EXIT_FAILURE);
        }
    }

    for (unsigned int i = 0; i < thread_count; i++) {
        pthread_join(threads[i], NULL);
    }
}

int main(int argc, char **argv) {
    setbuf(stdout, NULL);

    int tvalue  = 1;
    char *ivalue = NULL;
    int c;
    opterr = 0;
    while ((c = getopt(argc, argv, "t:i:")) != -1) {
        switch (c) {
            case 't':
                tvalue = atoi(optarg);
                break;
            case 'i':
                ivalue = optarg;
                break;
            case '?':
                if (optopt == 'i')
                    fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                else if(isprint(optopt))
                    fprintf(stderr, "Unknown option `-%c'.\n", optopt);
                else
                    fprintf(stderr,
                            "Unknown option character `\\x%x'.\n",
                            optopt);
                return 1;
            default:
                abort();
        }
    }

    cout << argc - optind<< endl;
    char usage[] = "usage: %s -i inputfile [-t threadcount] outputfile\n";
    if (ivalue == NULL || argc - optind != 1) {
        fprintf(stderr, usage, argv[0]);
        return 1;
    }

    VideoCapture vc = VideoCapture(ivalue);
    if (!vc.isOpened())
        return 1;

    vector<Mat> framesFront, framesBack;

    Mat f;
    for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
        cout << "Frame " << i << "..." << endl;
        vc >> f;
        framesFront.push_back(f.clone());
        framesBack.push_back(f.clone());
    }

    VideoWriter vw;
    int ex = CV_FOURCC('I', 'Y', 'U', 'V');
    vw.open("out.avi", ex, vc.get(CV_CAP_PROP_FPS), f.size());

    vector<Mat> *src = &framesFront;
    vector<Mat> *dst = &framesBack;
    for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
        cout << "Frame " << i;
        update(src, dst, my_rule, tvalue);
        cout << "writing...";
        vw.write(dst->at(i));
        swap(src, dst);
        cout << "done." << endl;
    }

    return 0;
}
<commit_msg>removed some debugging stuff i forgot to remove on the last commit<commit_after>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <unistd.h>

using namespace std;
using namespace cv;

typedef Vec3b Color;
typedef vector<Mat> World;
typedef Color (*Rule)(Color, const vector<Color> &);
typedef struct {
    unsigned int thread_id;
    unsigned int thread_count;
    World *src;
    World *dst;
    Rule r;
} thread_data;

void set_color(World &, int x, int y, int t, Color);
Color get_color(const World &, int x, int y, int t);
void *update_thread(void *);
void update(World *src, World *dst, Rule, unsigned int thread_count);
Color my_rule(Color, const vector<Color> &);

/*** Customize this rule ***/
Color my_rule(Color c, const vector<Color> &cs) {
    float r = 0;
    float g = 0;
    float b = 0;
    for (int i = 0; i < (int)cs.size(); i++) {
        r += cs[i][2];
        g += cs[i][1];
        b += cs[i][0];
    }
    r /= cs.size();
    g /= cs.size();
    b /= cs.size();
    c[0] = b;
    c[1] = g;
    c[2] = r;
    return c;
}
/***************************/

void set_color(World &w, int x, int y, int t, Color c) {
    Mat m = w.at(t);
    m.at<Vec3b>(y,x) = c;
}

Color get_color(const World &w, int x, int y, int t) {
    Mat m = w.at(t);
    return m.at<Vec3b>(y,x);
}

void *update_thread(void *data) {
    thread_data *d = (thread_data*)data;

    World *src = d->src;
    World *dst = d->dst;
    Rule r = d->r;

    int x_min = 0;
    int y_min = 0;
    int t_min = 0;
    int x_max = src->at(0).cols-1;
    int y_max = src->at(0).rows-1;
    int t_max = src->size()-1;
    for (int t = d->thread_id; t < (int)src->size(); t+=d->thread_count) {
        cout << ".";
        for (int y = 0; y < src->at(t).rows; y++)
        for (int x = 0; x < src->at(t).cols; x++) {
            Color c = get_color(*src, x, y, t);
            vector<Color> neighbors;
            for (int dt = -1; dt <= 1; dt++) {
                if (t+dt >= t_min && t+dt <= t_max) {
                    if (x-1 >= x_min) neighbors.push_back(get_color(*src,x-1,y,t+dt));
                    if (x+1 <= x_max) neighbors.push_back(get_color(*src,x+1,y,t+dt));
                    if (y-1 >= y_min) neighbors.push_back(get_color(*src,x,y-1,t+dt));
                    if (y+1 <= y_max) neighbors.push_back(get_color(*src,x,y+1,t+dt));
                    if (x-1 >= x_min && y-1 >= y_min) neighbors.push_back(get_color(*src,x-1,y-1,t+dt));
                    if (x+1 <= x_max && y-1 >= y_min) neighbors.push_back(get_color(*src,x+1,y-1,t+dt));
                    if (x-1 >= x_min && y+1 <= y_max) neighbors.push_back(get_color(*src,x-1,y+1,t+dt));
                    if (x+1 <= x_max && y+1 <= y_max) neighbors.push_back(get_color(*src,x+1,y+1,t+dt));
                    if (dt != 0) neighbors.push_back(get_color(*src,x,y,t+dt));
                }
            }
            set_color(*dst, x, y, t, r(c, neighbors));
        }
    }

    return NULL;
}

void update(World *src, World *dst, Rule r, unsigned int thread_count) {
    pthread_t threads[thread_count];
    int irets[thread_count];
    thread_data data[thread_count];

    for (unsigned int i = 0; i < thread_count; i++) {
        data[i] = thread_data{i, thread_count, src, dst, my_rule};
        irets[i] = pthread_create(&threads[i], NULL, update_thread, &data);
        if (irets[i]) {
            fprintf(stderr,"Error - pthread_create() return code: %d\n",irets[i]);
            exit(EXIT_FAILURE);
        }
    }

    for (unsigned int i = 0; i < thread_count; i++) {
        pthread_join(threads[i], NULL);
    }
}

int main(int argc, char **argv) {
    setbuf(stdout, NULL);

    int tvalue  = 1;
    char *ivalue = NULL;
    int c;
    opterr = 0;
    while ((c = getopt(argc, argv, "t:i:")) != -1) {
        switch (c) {
            case 't':
                tvalue = atoi(optarg);
                break;
            case 'i':
                ivalue = optarg;
                break;
            case '?':
                if (optopt == 'i')
                    fprintf(stderr, "Option -%c requires an argument.\n", optopt);
                else if(isprint(optopt))
                    fprintf(stderr, "Unknown option `-%c'.\n", optopt);
                else
                    fprintf(stderr,
                            "Unknown option character `\\x%x'.\n",
                            optopt);
                return 1;
            default:
                abort();
        }
    }

    cout << argc - optind<< endl;
    char usage[] = "usage: %s -i inputfile [-t threadcount] outputfile\n";
    if (ivalue == NULL || argc - optind != 1) {
        fprintf(stderr, usage, argv[0]);
        return 1;
    }

    VideoCapture vc = VideoCapture(ivalue);
    if (!vc.isOpened())
        return 1;

    vector<Mat> framesFront, framesBack;

    Mat f;
    for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
        cout << "Frame " << i << "..." << endl;
        vc >> f;
        framesFront.push_back(f.clone());
        framesBack.push_back(f.clone());
    }

    VideoWriter vw;
    int ex = CV_FOURCC('I', 'Y', 'U', 'V');
    vw.open("out.avi", ex, vc.get(CV_CAP_PROP_FPS), f.size());

    vector<Mat> *src = &framesFront;
    vector<Mat> *dst = &framesBack;
    for (int i = 0; i < vc.get(CV_CAP_PROP_FRAME_COUNT); i++) {
        cout << "Frame " << i;
        update(src, dst, my_rule, tvalue);
        cout << "writing...";
        vw.write(dst->at(i));
        swap(src, dst);
        cout << "done." << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <multihash/multihash.h>
#include <boost/program_options.hpp>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>

namespace po = boost::program_options;

int main(int argc, char* argv[])
{
    // Declare the supported options.
    std::ostringstream os;
    os << "Usage: multihash [OPTION]... [FILE]...\n"
       << "Print cryptographic digests.\n"
       << "With no FILE or when file is -, read standard input";
    po::options_description desc(os.str());
    desc.add_options()
        ("help", "display help message")
        ("hash-type", po::value<std::string>(), "algorithm, e.g sha1")
        ("list-hash-types", "list all available algorithms");

    po::variables_map vm;

    try
    {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << desc << std::endl;
        return 1;
    }
    if (vm.count("help") > 0)
    {
        std::cout << desc << std::endl;
        return 0;
    }
    if (vm.count("list-hash-types") > 0)
    {
        for (auto hash_type : multihash::hashTypes())
        {
            std::cout << hash_type.name() << std::endl;
        }
        return 0;
    }

    /** Actually do some work if an algo is specified */
    std::string algo;
    if (vm.count("hash-type") == 1)
    {
        algo = vm["hash-type"].as<std::string>();
    }
    else
    {
        std::cerr << "Must specify a hash type" << std::endl;
        std::cerr << desc << std::endl;
        return 1;
    }

    try
    {
        auto hash_function = multihash::HashFunction(algo);

        std::ios_base::sync_with_stdio(false); //enable fast io

        std::vector<std::string> filenames;
        if (argc > 3)
        {
            filenames.assign(&argv[3], &argv[argc-1]);
        }

        auto num_files = filenames.size();
        if ((num_files == 1 && (filenames.front() == "-")) or num_files == 0)
        {
            auto hash =  hash_function(std::cin);
            std::cout << hash << " -" << std::endl;
        }
        else
        {
            for (auto filename : filenames)
            {
                if (!boost::filesystem::exists(filename))
                {
                    std::cerr << "multihash: " << filename
                              << ": No such file or directory" << std::endl;
                    continue;
                }
                else if (boost::filesystem::is_directory(filename))
                {
                    std::cerr << "multihash: " << filename
                              << ": Is a directory" << std::endl;
                    continue;
                }
                auto filestream = std::ifstream(filename);
                if (filestream.good())
                {
                    auto hash = hash_function(filestream);
                    std::cout << hash << " " << filename << std::endl;
                }
                else
                {
                    std::cerr << "multihash: " << filename << ": "
                              << "Permission denied" << std::endl;
                }
            }
        }
    }
    catch (multihash::InvalidHashException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl;
        std::cout << "Available hash types: " << std::endl;
        for (auto hash_type : multihash::hashTypes())
        {
            std::cout << hash_type.name() << std::endl;
        }
    }
    return 0;
}
<commit_msg>Fixed off-by-one error in filelist<commit_after>#include <iostream>
#include <fstream>
#include <multihash/multihash.h>
#include <boost/program_options.hpp>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>

namespace po = boost::program_options;

int main(int argc, char* argv[])
{
    // Declare the supported options.
    std::ostringstream os;
    os << "Usage: multihash [OPTION]... [FILE]...\n"
       << "Print cryptographic digests.\n"
       << "With no FILE or when file is -, read standard input";
    po::options_description desc(os.str());
    desc.add_options()
        ("help", "display help message")
        ("hash-type", po::value<std::string>(), "algorithm, e.g sha1")
        ("list-hash-types", "list all available algorithms");

    po::variables_map vm;

    try
    {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << desc << std::endl;
        return 1;
    }
    if (vm.count("help") > 0)
    {
        std::cout << desc << std::endl;
        return 0;
    }
    if (vm.count("list-hash-types") > 0)
    {
        for (auto hash_type : multihash::hashTypes())
        {
            std::cout << hash_type.name() << std::endl;
        }
        return 0;
    }

    /** Actually do some work if an algo is specified */
    std::string algo;
    if (vm.count("hash-type") == 1)
    {
        algo = vm["hash-type"].as<std::string>();
    }
    else
    {
        std::cerr << "Must specify a hash type" << std::endl;
        std::cerr << desc << std::endl;
        return 1;
    }

    try
    {
        auto hash_function = multihash::HashFunction(algo);

        std::ios_base::sync_with_stdio(false); //enable fast io

        std::vector<std::string> filenames;
        if (argc > 3)
        {
            filenames.assign(&argv[3], &argv[argc]);
        }

        auto num_files = filenames.size();
        if ((num_files == 1 && (filenames.front() == "-")) or num_files == 0)
        {
            auto hash =  hash_function(std::cin);
            std::cout << hash << " -" << std::endl;
        }
        else
        {
            for (auto filename : filenames)
            {
                if (!boost::filesystem::exists(filename))
                {
                    std::cerr << "multihash: " << filename
                              << ": No such file or directory" << std::endl;
                    continue;
                }
                else if (boost::filesystem::is_directory(filename))
                {
                    std::cerr << "multihash: " << filename
                              << ": Is a directory" << std::endl;
                    continue;
                }
                auto filestream = std::ifstream(filename);
                if (filestream.good())
                {
                    auto hash = hash_function(filestream);
                    std::cout << hash << " " << filename << std::endl;
                }
                else
                {
                    std::cerr << "multihash: " << filename << ": "
                              << "Permission denied" << std::endl;
                }
            }
        }
    }
    catch (multihash::InvalidHashException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl;
        std::cout << "Available hash types: " << std::endl;
        for (auto hash_type : multihash::hashTypes())
        {
            std::cout << hash_type.name() << std::endl;
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>

#include "visuserver.h"
#include "visuapplication.h"
#include "exceptions/configloadexception.h"

#define DEFAULT_CONFIG "configs/default.xml"

void showMessageBox(QString message)
{
    QMessageBox::warning(
                NULL,
                "Error",
                message);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    try
    {
        if (argc > 1 && QString(argv[1]) == "--editor" )
        {
            new MainWindow();
        }
        else
        {
            QString xmlPath = (argc > 1) ? QString(argv[1]) : DEFAULT_CONFIG;
            VisuApplication *application = new VisuApplication(xmlPath);
            application->show();
            application->run();
        }
    }
    catch(ConfigLoadException e)
    {
        showMessageBox(e.what());
        return 1;
    }
    catch(...)
    {
        showMessageBox("Unknown exception!");
        return 1;
    }

    return a.exec();
}
<commit_msg>Application starts in editor mode by default<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>

#include "visuserver.h"
#include "visuapplication.h"
#include "exceptions/configloadexception.h"

#define DEFAULT_CONFIG "configs/default.xml"

void showMessageBox(QString message)
{
    QMessageBox::warning(
                NULL,
                "Error",
                message);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    try
    {
        if (argc == 1)
        {
            new MainWindow();
        }
        else
        {
            QString xmlPath = (argc > 1) ? QString(argv[1]) : DEFAULT_CONFIG;
            VisuApplication *application = new VisuApplication(xmlPath);
            application->show();
            application->run();
        }
    }
    catch(ConfigLoadException e)
    {
        showMessageBox(e.what());
        return 1;
    }
    catch(...)
    {
        showMessageBox("Unknown exception!");
        return 1;
    }

    return a.exec();
}
<|endoftext|>


<commit_before>// Copyright © 2014-2016 Ryan Leckey, All Rights Reserved.

// Distributed under the MIT License
// See accompanying file LICENSE

#include <cstdio>
#include <deque>
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

#include "cppformat/format.h"
#include "arrow/tokenizer.hpp"
#include "arrow/command.hpp"

void help(char* binary_path) {
  std::printf(
    "Usage: \x1b[0;36m%s\x1b[0m [<command>] [<options>] <input-file>\n",
    binary_path);

  std::printf("\n");
}

int main(int argc, char** argv, char** environ) {
    // Register available commands
  std::deque<std::shared_ptr<arrow::Command>> commands;
  commands.push_back(std::make_shared<arrow::command::Parse>());
  commands.push_back(std::make_shared<arrow::command::Tokenize>());

  // Check for a specified command
  std::vector<char*> args(argv, argv + argc);
  unsigned cmd_index = 0;
  bool found = false;
  if (args.size() >= 2) {
    std::string a1(args[1]);
    if (a1.size() >= 3 && a1[0] == '-' && a1[1] == '-') {
      // The first arguments is `--[...]`
      auto command_name = a1.substr(2);
      for (unsigned i = 0; i < commands.size(); ++i) {
        if (command_name == commands[i]->name()) {
          found = true;
          cmd_index = i;
          break;
        }
      }

      if (found) {
        // Remove the command argument
        args.erase(args.begin() + 1);
      }
    }
  } else {
    // Show help
    // help(argv[0], commands);
    help(argv[0]);
    return 0;
  }

  if (!found) {
    std::string a1(args[1]);
    if (a1.substr(2) == "help" || a1.substr(1) == "h") {
      // Show help
      // help(argv[0], commands);
      help(argv[0]);
      return 0;
    }
  }

  // Get the requested command
  auto cmd = commands.at(cmd_index);

  // Run the received command
  return (*cmd)(args.size(), args.data(), environ);
}
<commit_msg>Improve help display<commit_after>// Copyright © 2014-2016 Ryan Leckey, All Rights Reserved.

// Distributed under the MIT License
// See accompanying file LICENSE

#include <cstdio>
#include <deque>
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

#include "cppformat/format.h"
#include "arrow/tokenizer.hpp"
#include "arrow/command.hpp"

void help(char* binary_path,
          const std::deque<std::shared_ptr<arrow::Command>>& commands) {
  std::printf(
    "Usage: \x1b[0;36m%s\x1b[0m [<command>] [<options>] <input-file>\n",
    binary_path);

  std::printf("Commands:\n");
  for (auto& cmd : commands) {
    std::printf("  \x1b[0;33m--%-10s\x1b[0m", cmd->name());
    std::printf("%s", cmd->description());
    std::printf("\n");
  }

  std::printf("  \x1b[0;33m--%-10s\x1b[0m", "help");
  std::printf("Display this help information");
  std::printf("\n");

  std::printf("\n");
}

int main(int argc, char** argv, char** environ) {
    // Register available commands
  std::deque<std::shared_ptr<arrow::Command>> commands;
  commands.push_back(std::make_shared<arrow::command::Parse>());
  commands.push_back(std::make_shared<arrow::command::Tokenize>());

  // Check for a specified command
  std::vector<char*> args(argv, argv + argc);
  unsigned cmd_index = 0;
  bool found = false;
  if (args.size() >= 2) {
    std::string a1(args[1]);
    if (a1.size() >= 3 && a1[0] == '-' && a1[1] == '-') {
      // The first arguments is `--[...]`
      auto command_name = a1.substr(2);
      for (unsigned i = 0; i < commands.size(); ++i) {
        if (command_name == commands[i]->name()) {
          found = true;
          cmd_index = i;
          break;
        }
      }

      if (found) {
        // Remove the command argument
        args.erase(args.begin() + 1);
      }
    }
  } else {
    // Show help
    help(argv[0], commands);
    return 0;
  }

  if (!found) {
    std::string a1(args[1]);
    if (a1.substr(2) == "help" || a1.substr(1) == "h") {
      // Show help
      help(argv[0], commands);
      return 0;
    }
  }

  // Get the requested command
  auto cmd = commands.at(cmd_index);

  // Run the received command
  return (*cmd)(args.size(), args.data(), environ);
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2016-2017 Genome Research Ltd.
Author: Marcus D. R. Klarqvist <mk21@sanger.ac.uk>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <getopt.h>

#include "utility.h"
#include "calc.h"
#include "import.h"
#include "view.h"
#include "sort.h"
#include "index.h"
#include "concat.h"
#include "stats.h"

int main(int argc, char** argv){
	if(Tomahawk::Helpers::isBigEndian()){
		std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Tomahawk does not support big endian systems..." << std::endl;
		return(1);
	}

	if(argc == 1){
		programMessage();
		programHelpDetailed();
		return(1);
	}

	// Literal string input line
	Tomahawk::Constants::LITERAL_COMMAND_LINE = Tomahawk::Constants::PROGRAM_NAME;
	for(U32 i = 1; i < argc; ++i)
		Tomahawk::Constants::LITERAL_COMMAND_LINE += " " + std::string(&argv[i][0]);

	if(strncmp(&argv[1][0], "import", 5) == 0){
		return(import(argc, argv));

	} else if(strncmp(&argv[1][0], "calc", 4) == 0){
		return(calc(argc, argv));

	} else if(strncmp(&argv[1][0], "view", 4) == 0){
		return(view(argc, argv));

	} else if(strncmp(&argv[1][0], "sort", 4) == 0){
		return(sort(argc, argv));

	} else if(strncmp(&argv[1][0], "index", 5) == 0){
		//return(index(argc, argv));
		std::cerr << "Not implemented" << std::endl;
		return(1);

	} else if(strncmp(&argv[1][0], "concat", 6) == 0){
		return(concat(argc, argv));

	} else if(strncmp(&argv[1][0], "stats", 5) == 0){
		return(stats(argc, argv));
		//std::cerr << "Not implemented" << std::endl;
		//return(1);

	} else if(strncmp(&argv[1][0], "--version", 9) == 0 || strncmp(&argv[1][0], "version", 7) == 0){
		programMessage(false);
		return(0);

	} else if(strncmp(&argv[1][0], "--help", 6) == 0 || strncmp(&argv[1][0], "help", 4) == 0){
		programMessage();
		programHelpDetailed();
		return(0);

	} else {
		programMessage();
		programHelpDetailed();
		std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Illegal command" << std::endl;
		return(1);
	}
	return(1);
}
<commit_msg>trigger<commit_after>/*
Copyright (C) 2016-2017 Genome Research Ltd.
Author: Marcus D. R. Klarqvist <mk21@sanger.ac.uk>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <getopt.h>

#include "utility.h"
#include "calc.h"
#include "import.h"
#include "view.h"
#include "sort.h"
#include "index.h"
#include "concat.h"
#include "stats.h"

int main(int argc, char** argv){
	if(Tomahawk::Helpers::isBigEndian()){
		std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Tomahawk does not support big endian systems..." << std::endl;
		return(1);
	}

	if(argc == 1){
		programMessage();
		programHelpDetailed();
		return(1);
	}

	// Literal string input line
	Tomahawk::Constants::LITERAL_COMMAND_LINE = Tomahawk::Constants::PROGRAM_NAME;
	for(U32 i = 1; i < argc; ++i)
		Tomahawk::Constants::LITERAL_COMMAND_LINE += " " + std::string(&argv[i][0]);

	if(strncmp(&argv[1][0], "import", 5) == 0){
		return(import(argc, argv));

	} else if(strncmp(&argv[1][0], "calc", 4) == 0){
		return(calc(argc, argv));

	} else if(strncmp(&argv[1][0], "view", 4) == 0){
		return(view(argc, argv));

	} else if(strncmp(&argv[1][0], "sort", 4) == 0){
		return(sort(argc, argv));

	} else if(strncmp(&argv[1][0], "index", 5) == 0){
		//return(index(argc, argv));
		std::cerr << "Not implemented" << std::endl;
		return(1);

	} else if(strncmp(&argv[1][0], "concat", 6) == 0){
		return(concat(argc, argv));

	} else if(strncmp(&argv[1][0], "stats", 5) == 0){
		return(stats(argc, argv));

	} else if(strncmp(&argv[1][0], "--version", 9) == 0 || strncmp(&argv[1][0], "version", 7) == 0){
		programMessage(false);
		return(0);

	} else if(strncmp(&argv[1][0], "--help", 6) == 0 || strncmp(&argv[1][0], "help", 4) == 0){
		programMessage();
		programHelpDetailed();
		return(0);

	} else {
		programMessage();
		programHelpDetailed();
		std::cerr << Tomahawk::Helpers::timestamp("ERROR") << "Illegal command" << std::endl;
		return(1);
	}
	return(1);
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <thread>
#include <iostream>
#include <cassert>     /* assert */
#include <glm/ext.hpp>
#include <vtkIndent.h>
#include <vtkTable.h>
#include <vtkVariant.h>
#include <vtkUnstructuredGrid.h>
#include "persistence_curve_widget.h"

PersistenceCurveWidget::PersistenceCurveWidget(vtkSmartPointer<vtkXMLImageDataReader> input, unsigned int debug)
    : tree_type(ttk::TreeType::Split), debuglevel(debug)
{
    diagram = vtkSmartPointer<vtkPersistenceDiagram>::New();
    diagram->SetdebugLevel_(debuglevel);
    diagram->SetInputConnection(input->GetOutputPort());

    // Compute critical points
    critical_pairs = vtkSmartPointer<vtkThreshold>::New();
    critical_pairs->SetInputConnection(diagram->GetOutputPort());
    critical_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "PairIdentifier");
    critical_pairs->ThresholdBetween(-0.1, 999999);

    // Select the most persistent pairs
    persistent_pairs = vtkSmartPointer<vtkThreshold>::New();
    persistent_pairs->SetInputConnection(critical_pairs->GetOutputPort());
    persistent_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Persistence");
    // Start at a persistence above one so we filter out some junk
    threshold_range[0] = 4.f;
    persistent_pairs->ThresholdBetween(threshold_range[0], 999999);

    // Simplifying the input data to remove non-persistent pairs
    simplification = vtkSmartPointer<vtkTopologicalSimplification>::New();
    simplification->SetdebugLevel_(debuglevel);
    simplification->SetUseAllCores(true);
    simplification->SetThreadNumber(std::thread::hardware_concurrency());
    simplification->SetInputConnection(0, input->GetOutputPort());
    simplification->SetInputConnection(1, persistent_pairs->GetOutputPort());

    // We always show the full curve, without simplfication for the
    // selected tree type
    vtkcurve = vtkSmartPointer<vtkPersistenceCurve>::New();
    vtkcurve->SetdebugLevel_(debuglevel);
    vtkcurve->SetInputConnection(input->GetOutputPort());
    vtkcurve->SetComputeSaddleConnectors(false);
    vtkcurve->SetUseAllCores(true);
    vtkcurve->SetThreadNumber(std::thread::hardware_concurrency());
    vtkcurve->Update();
    update_persistence_curve();
    update_persistence_diagram();
}
vtkTopologicalSimplification* PersistenceCurveWidget::get_simplification() const {
    return simplification.Get();
}
void PersistenceCurveWidget::draw_ui() {
    if (ImGui::Begin("Persistence Plots"))
    {
	// we need to tell how large each plot is, so its better to plot sliders here
	ImGui::Text("Persistence Range [%.2f, %.2f]", persistence_range.x, persistence_range.y);
	ImGui::SliderFloat("Threshold", &threshold_range[0], persistence_range.x, persistence_range.y, "%.3f", glm::e<float>());
	// Keep values in range
	threshold_range[0] = glm::max(threshold_range[0], persistence_range.x);

	// If we changed our selection update the display in the other widgets
	if (ImGui::Button("Apply")) {
	    persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
	    simplification->Update();
	    update_persistence_diagram(); // update threshold
	}

	// draw plots
	float fullheight = ImGui::GetContentRegionAvail().y;
	draw_persistence_curve(fullheight * 0.5);
	draw_persistence_diagram(fullheight * 0.5);
    }
    ImGui::End();
}
void PersistenceCurveWidget::draw_persistence_curve(float ysize) {
    // Draw the persistence plot
    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
    ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
    ImGui::BeginChild("pers_curve", glm::vec2(0, ysize), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);

    const glm::vec2 padding(0.001f, 0.0f);
    const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
    const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
    const glm::vec2 axis_range = glm::log(glm::vec2(persistence_range.y, npairs_range.y));
    const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);

    ImDrawList *draw_list = ImGui::GetWindowDrawList();
    draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);

    // Draw curve
    for (size_t i = 0; !curve_points.empty() && i < curve_points.size() - 1; ++i) {
	const glm::vec2 a = glm::log(curve_points[i]);
	const glm::vec2 b = glm::log(curve_points[i + 1]);
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
    }

    // Draw threshold line
    {
	const float v = std::log(threshold_range.x) * view_scale.x + offset.x;
	const glm::vec2 a = glm::vec2(v, offset.y);
	const glm::vec2 b = glm::vec2(v, offset.y - canvas_size.y);
	draw_list->AddLine(a, b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.f);
    }

    draw_list->PopClipRect();

    ImGui::EndChild();
    ImGui::PopStyleColor();
    ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::draw_persistence_diagram(float ysize) {
    ImGui::Text("Persistence Diagram...");

    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
    ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
    ImGui::BeginChild("pers_diag", glm::vec2(0, ysize - 20.0f /* text y-offset */), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);

    // TODO: Persistence Diagram
    const glm::vec2 padding(0.005f, 0.02f);
    const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
    const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
    const glm::vec2 axis_range = glm::vec2(persistence_range.y);
    const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);

    ImDrawList *draw_list = ImGui::GetWindowDrawList();
    draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);

    // draw diagonal
    {
	const glm::vec2 a(0); // start from 0 for persistence diagram
	const glm::vec2 b(persistence_range.y);
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
    }
    // Draw threshold line
    {
	const glm::vec2 a = glm::vec2(0, threshold_range.x);
	const glm::vec2 b = glm::vec2(persistence_range.y - threshold_range.x, persistence_range.y);
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.0f);
    }
    // draw persistence lines
    for (size_t i = 0; i < static_cast<size_t>(diagram_lines.size()); ++i) {
	const glm::vec2 a = diagram_lines[i].ps;
	const glm::vec2 b = diagram_lines[i].pe;
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
    }

    draw_list->PopClipRect();
    ImGui::EndChild();
    ImGui::PopStyleColor();
    ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::set_tree_type(const ttk::TreeType &type) {
    if (tree_type != type) {
	tree_type = type;
	update_persistence_curve();
    }
}
void PersistenceCurveWidget::update_persistence_curve() {
    // Tree type mapping to persistence curve output index:
    // Join Tree: 0
    // Morse Smale Curve: 1
    // Split Tree: 2
    // Contour Tree: 3
    int tree = 0;
    switch (tree_type) {
    case ttk::TreeType::Contour: tree = 3; break;
    case ttk::TreeType::Split: tree = 2; break;
    case ttk::TreeType::Join: tree = 0; break;
    default: break;
    }
    vtkTable* table = dynamic_cast<vtkTable*>(vtkcurve->GetOutputInformation(tree)->Get(vtkDataObject::DATA_OBJECT()));
    vtkDataArray *persistence_col = dynamic_cast<vtkDataArray*>(table->GetColumn(0));
    vtkDataArray *npairs_col      = dynamic_cast<vtkDataArray*>(table->GetColumn(1));

    assert(persistence_col->GetSize() == npairs_col->GetSize());
    curve_points.clear();
    curve_points.reserve(persistence_col->GetSize());

    npairs_range = glm::vec2(std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity());
    persistence_range = glm::vec2(1.f, -std::numeric_limits<float>::infinity());
    std::map<float, size_t> pers_count;
    for (vtkIdType i = 0; i < persistence_col->GetSize(); ++i) {
	// It seems that often there are many entries with the same persistence value, count these up instead of making
	// a bunch of dot lines
	const float p = *persistence_col->GetTuple(i);
	if (p > 0.f) {
	    persistence_range.y = std::max(persistence_range.y, p);
	    const float n = *npairs_col->GetTuple(i);
	    npairs_range.x = std::min(npairs_range.x, static_cast<float>(n));
	    npairs_range.y = std::max(npairs_range.y, static_cast<float>(n));
	    curve_points.push_back(glm::vec2(p, n));
	}
    }
    threshold_range[1] = persistence_range.y;
    persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
    simplification->Update();
}
void PersistenceCurveWidget::update_persistence_diagram()
{
    diagram_lines.clear();
    vtkUnstructuredGrid* dcells = vtkUnstructuredGrid::SafeDownCast(diagram->GetOutput());

    if (debuglevel >= 1) {
	std::cout << "[DrawPersistenceDiagram] persistence range "
		  << persistence_range.x << " " << persistence_range.y << std::endl;
	dcells->GetPointData()->PrintSelf(std::cout, vtkIndent(0));
	dcells->GetCellData()->PrintSelf(std::cout, vtkIndent(0));
    }

    auto array_PairType       = dcells->GetCellData()->GetArray(1);  // might be useful for coloring
    auto array_Persistence    = dcells->GetCellData()->GetArray(2);  // threshold_range
    auto array_NodeType       = dcells->GetPointData()->GetArray(1); // might be useful for coloring

    assert(array_PairType->GetNumberOfTuples() == dcells->GetNumberOfCells());
    assert(array_Persistence->GetNumberOfTuples() == dcells->GetNumberOfCells());

    // yeah vtk wants to make everything more complicated ...
    vtkSmartPointer<vtkIdList> pointidx = vtkSmartPointer<vtkIdList>::New();

    for (vtkIdType i = 0; i < static_cast<vtkIdType>(dcells->GetNumberOfCells()); ++i) {
	double persistence = *array_Persistence->GetTuple(i);
	if (persistence >= threshold_range.x && persistence <= threshold_range.y) {
	    dcells->GetCellPoints(i, pointidx);
	    double pairtype = *array_PairType->GetTuple(i);
	    if (pairtype >= 0.0) { // it seems -1 type are all invalid points
		double pa[3], pb[3];
		dcells->GetPoint(pointidx->GetId(0), pa);
		dcells->GetPoint(pointidx->GetId(1), pb);
		double pat = *array_NodeType->GetTuple(pointidx->GetId(0));
		double pbt = *array_NodeType->GetTuple(pointidx->GetId(1));
		if (debuglevel >= 1) {
		    std::cout << "[DrawPersistenceDiagram] persistence " << persistence << std::endl;
		    std::cout << "[DrawPersistenceDiagram] -- start " << pa[0] << " " << pa[1] << std::endl;
		    std::cout << "[DrawPersistenceDiagram] -- end   " << pb[0] << " " << pb[1] << std::endl;
		}
		diagram_lines.emplace_back(pa, pb, pairtype, pat, pbt);
	    }
	}
    }
}
<commit_msg>Remove elipses on persistenc diag title<commit_after>#include <algorithm>
#include <thread>
#include <iostream>
#include <cassert>     /* assert */
#include <glm/ext.hpp>
#include <vtkIndent.h>
#include <vtkTable.h>
#include <vtkVariant.h>
#include <vtkUnstructuredGrid.h>
#include "persistence_curve_widget.h"

PersistenceCurveWidget::PersistenceCurveWidget(vtkSmartPointer<vtkXMLImageDataReader> input, unsigned int debug)
    : tree_type(ttk::TreeType::Split), debuglevel(debug)
{
    diagram = vtkSmartPointer<vtkPersistenceDiagram>::New();
    diagram->SetdebugLevel_(debuglevel);
    diagram->SetInputConnection(input->GetOutputPort());

    // Compute critical points
    critical_pairs = vtkSmartPointer<vtkThreshold>::New();
    critical_pairs->SetInputConnection(diagram->GetOutputPort());
    critical_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "PairIdentifier");
    critical_pairs->ThresholdBetween(-0.1, 999999);

    // Select the most persistent pairs
    persistent_pairs = vtkSmartPointer<vtkThreshold>::New();
    persistent_pairs->SetInputConnection(critical_pairs->GetOutputPort());
    persistent_pairs->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Persistence");
    // Start at a persistence above one so we filter out some junk
    threshold_range[0] = 4.f;
    persistent_pairs->ThresholdBetween(threshold_range[0], 999999);

    // Simplifying the input data to remove non-persistent pairs
    simplification = vtkSmartPointer<vtkTopologicalSimplification>::New();
    simplification->SetdebugLevel_(debuglevel);
    simplification->SetUseAllCores(true);
    simplification->SetThreadNumber(std::thread::hardware_concurrency());
    simplification->SetInputConnection(0, input->GetOutputPort());
    simplification->SetInputConnection(1, persistent_pairs->GetOutputPort());

    // We always show the full curve, without simplfication for the
    // selected tree type
    vtkcurve = vtkSmartPointer<vtkPersistenceCurve>::New();
    vtkcurve->SetdebugLevel_(debuglevel);
    vtkcurve->SetInputConnection(input->GetOutputPort());
    vtkcurve->SetComputeSaddleConnectors(false);
    vtkcurve->SetUseAllCores(true);
    vtkcurve->SetThreadNumber(std::thread::hardware_concurrency());
    vtkcurve->Update();
    update_persistence_curve();
    update_persistence_diagram();
}
vtkTopologicalSimplification* PersistenceCurveWidget::get_simplification() const {
    return simplification.Get();
}
void PersistenceCurveWidget::draw_ui() {
    if (ImGui::Begin("Persistence Plots"))
    {
	// we need to tell how large each plot is, so its better to plot sliders here
	ImGui::Text("Persistence Range [%.2f, %.2f]", persistence_range.x, persistence_range.y);
	ImGui::SliderFloat("Threshold", &threshold_range[0], persistence_range.x, persistence_range.y, "%.3f", glm::e<float>());
	// Keep values in range
	threshold_range[0] = glm::max(threshold_range[0], persistence_range.x);

	// If we changed our selection update the display in the other widgets
	if (ImGui::Button("Apply")) {
	    persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
	    simplification->Update();
	    update_persistence_diagram(); // update threshold
	}

	// draw plots
	float fullheight = ImGui::GetContentRegionAvail().y;
	draw_persistence_curve(fullheight * 0.5);
	draw_persistence_diagram(fullheight * 0.5);
    }
    ImGui::End();
}
void PersistenceCurveWidget::draw_persistence_curve(float ysize) {
    // Draw the persistence plot
    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
    ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
    ImGui::BeginChild("pers_curve", glm::vec2(0, ysize), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);

    const glm::vec2 padding(0.001f, 0.0f);
    const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
    const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
    const glm::vec2 axis_range = glm::log(glm::vec2(persistence_range.y, npairs_range.y));
    const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);

    ImDrawList *draw_list = ImGui::GetWindowDrawList();
    draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);

    // Draw curve
    for (size_t i = 0; !curve_points.empty() && i < curve_points.size() - 1; ++i) {
	const glm::vec2 a = glm::log(curve_points[i]);
	const glm::vec2 b = glm::log(curve_points[i + 1]);
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
    }

    // Draw threshold line
    {
	const float v = std::log(threshold_range.x) * view_scale.x + offset.x;
	const glm::vec2 a = glm::vec2(v, offset.y);
	const glm::vec2 b = glm::vec2(v, offset.y - canvas_size.y);
	draw_list->AddLine(a, b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.f);
    }

    draw_list->PopClipRect();

    ImGui::EndChild();
    ImGui::PopStyleColor();
    ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::draw_persistence_diagram(float ysize) {
    ImGui::Text("Persistence Diagram");

    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, glm::vec2(1));
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, glm::vec2(0));
    ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, ImColor(60, 60, 70, 200));
    ImGui::BeginChild("pers_diag", glm::vec2(0, ysize - 20.0f /* text y-offset */), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoMove);

    // TODO: Persistence Diagram
    const glm::vec2 padding(0.005f, 0.02f);
    const glm::vec2 canvas_size(ImGui::GetContentRegionAvail());
    const glm::vec2 offset = glm::vec2(ImGui::GetCursorScreenPos().x, ImGui::GetCursorScreenPos().y + canvas_size.y) + padding * glm::vec2(canvas_size.x, -canvas_size.y);
    const glm::vec2 axis_range = glm::vec2(persistence_range.y);
    const glm::vec2 view_scale = glm::vec2(canvas_size.x / axis_range.x, -canvas_size.y / axis_range.y) * (1.0f - 2.0f * padding);

    ImDrawList *draw_list = ImGui::GetWindowDrawList();
    draw_list->PushClipRect(ImGui::GetCursorScreenPos(), glm::vec2(ImGui::GetCursorScreenPos()) + canvas_size);

    // draw diagonal
    {
	const glm::vec2 a(0); // start from 0 for persistence diagram
	const glm::vec2 b(persistence_range.y);
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
    }
    // Draw threshold line
    {
	const glm::vec2 a = glm::vec2(0, threshold_range.x);
	const glm::vec2 b = glm::vec2(persistence_range.y - threshold_range.x, persistence_range.y);
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(0.8f, 0.8f, 0.2f, 1.f), 2.0f);
    }
    // draw persistence lines
    for (size_t i = 0; i < static_cast<size_t>(diagram_lines.size()); ++i) {
	const glm::vec2 a = diagram_lines[i].ps;
	const glm::vec2 b = diagram_lines[i].pe;
	draw_list->AddLine(offset + view_scale * a, offset + view_scale * b, ImColor(255, 255, 255), 2.0f);
    }

    draw_list->PopClipRect();
    ImGui::EndChild();
    ImGui::PopStyleColor();
    ImGui::PopStyleVar(2);
}
void PersistenceCurveWidget::set_tree_type(const ttk::TreeType &type) {
    if (tree_type != type) {
	tree_type = type;
	update_persistence_curve();
    }
}
void PersistenceCurveWidget::update_persistence_curve() {
    // Tree type mapping to persistence curve output index:
    // Join Tree: 0
    // Morse Smale Curve: 1
    // Split Tree: 2
    // Contour Tree: 3
    int tree = 0;
    switch (tree_type) {
    case ttk::TreeType::Contour: tree = 3; break;
    case ttk::TreeType::Split: tree = 2; break;
    case ttk::TreeType::Join: tree = 0; break;
    default: break;
    }
    vtkTable* table = dynamic_cast<vtkTable*>(vtkcurve->GetOutputInformation(tree)->Get(vtkDataObject::DATA_OBJECT()));
    vtkDataArray *persistence_col = dynamic_cast<vtkDataArray*>(table->GetColumn(0));
    vtkDataArray *npairs_col      = dynamic_cast<vtkDataArray*>(table->GetColumn(1));

    assert(persistence_col->GetSize() == npairs_col->GetSize());
    curve_points.clear();
    curve_points.reserve(persistence_col->GetSize());

    npairs_range = glm::vec2(std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity());
    persistence_range = glm::vec2(1.f, -std::numeric_limits<float>::infinity());
    std::map<float, size_t> pers_count;
    for (vtkIdType i = 0; i < persistence_col->GetSize(); ++i) {
	// It seems that often there are many entries with the same persistence value, count these up instead of making
	// a bunch of dot lines
	const float p = *persistence_col->GetTuple(i);
	if (p > 0.f) {
	    persistence_range.y = std::max(persistence_range.y, p);
	    const float n = *npairs_col->GetTuple(i);
	    npairs_range.x = std::min(npairs_range.x, static_cast<float>(n));
	    npairs_range.y = std::max(npairs_range.y, static_cast<float>(n));
	    curve_points.push_back(glm::vec2(p, n));
	}
    }
    threshold_range[1] = persistence_range.y;
    persistent_pairs->ThresholdBetween(threshold_range[0], threshold_range[1]);
    simplification->Update();
}
void PersistenceCurveWidget::update_persistence_diagram()
{
    diagram_lines.clear();
    vtkUnstructuredGrid* dcells = vtkUnstructuredGrid::SafeDownCast(diagram->GetOutput());

    if (debuglevel >= 1) {
	std::cout << "[DrawPersistenceDiagram] persistence range "
		  << persistence_range.x << " " << persistence_range.y << std::endl;
	dcells->GetPointData()->PrintSelf(std::cout, vtkIndent(0));
	dcells->GetCellData()->PrintSelf(std::cout, vtkIndent(0));
    }

    auto array_PairType       = dcells->GetCellData()->GetArray(1);  // might be useful for coloring
    auto array_Persistence    = dcells->GetCellData()->GetArray(2);  // threshold_range
    auto array_NodeType       = dcells->GetPointData()->GetArray(1); // might be useful for coloring

    assert(array_PairType->GetNumberOfTuples() == dcells->GetNumberOfCells());
    assert(array_Persistence->GetNumberOfTuples() == dcells->GetNumberOfCells());

    // yeah vtk wants to make everything more complicated ...
    vtkSmartPointer<vtkIdList> pointidx = vtkSmartPointer<vtkIdList>::New();

    for (vtkIdType i = 0; i < static_cast<vtkIdType>(dcells->GetNumberOfCells()); ++i) {
	double persistence = *array_Persistence->GetTuple(i);
	if (persistence >= threshold_range.x && persistence <= threshold_range.y) {
	    dcells->GetCellPoints(i, pointidx);
	    double pairtype = *array_PairType->GetTuple(i);
	    if (pairtype >= 0.0) { // it seems -1 type are all invalid points
		double pa[3], pb[3];
		dcells->GetPoint(pointidx->GetId(0), pa);
		dcells->GetPoint(pointidx->GetId(1), pb);
		double pat = *array_NodeType->GetTuple(pointidx->GetId(0));
		double pbt = *array_NodeType->GetTuple(pointidx->GetId(1));
		if (debuglevel >= 1) {
		    std::cout << "[DrawPersistenceDiagram] persistence " << persistence << std::endl;
		    std::cout << "[DrawPersistenceDiagram] -- start " << pa[0] << " " << pa[1] << std::endl;
		    std::cout << "[DrawPersistenceDiagram] -- end   " << pb[0] << " " << pb[1] << std::endl;
		}
		diagram_lines.emplace_back(pa, pb, pairtype, pat, pbt);
	    }
	}
    }
}
<|endoftext|>


<commit_before>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>

const float kPi = 4.0f * std::atan(1.0f);
const Uint32 kLagThreshold = 1000;
const Uint32 kFrameTime = 10;

const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f);
const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f);

const float kGridSpacing = 2.0f;
const int kGridSize = 8;

bool buttonLeft = false, buttonRight = false,
    buttonUp = false, buttonDown = false;
float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f;

struct gradient_point {
    float pos;
    unsigned char color[3];
};

const gradient_point sky[] = {
    { -0.50f, {   0,   0,  51 } },
    { -0.02f, {   0,   0,   0 } },
    {  0.00f, { 102, 204, 255 } },
    {  0.20f, {  51,   0, 255 } },
    {  0.70f, {   0,   0,   0 } }
};

void drawSky(void)
{
	int i;
    glPushAttrib(GL_CURRENT_BIT);
    glBegin(GL_TRIANGLE_STRIP);
    glColor3ubv(sky[0].color);
    glVertex3f(-2.0f, 1.0f, -1.0f);
    glVertex3f( 2.0f, 1.0f, -1.0f);
    for (i = 0; i < sizeof(sky) / sizeof(*sky); ++i) {
        glColor3ubv(sky[i].color);
        glVertex3f(-2.0f, 1.0f, sky[i].pos);
        glVertex3f( 2.0f, 1.0f, sky[i].pos);
    }
    glVertex3f(-2.0f, 0.0f, 1.0f);
    glVertex3f( 2.0f, 0.0f, 1.0f);
    glEnd();
    glPopAttrib();
}

void drawGround(void)
{
    int i;
    float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing;
    float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing;
    glPushMatrix();
    glTranslatef(px, py, 0.0f);
    glScalef(kGridSpacing, kGridSpacing, 1.0f);
    glColor3ub(51, 0, 255);
    glBegin(GL_LINES);
    for (i = -kGridSize; i <= kGridSize; ++i) {
        glVertex3f(i, -kGridSize, 0.0f);
        glVertex3f(i,  kGridSize, 0.0f);
        glVertex3f(-kGridSize, i, 0.0f);
        glVertex3f( kGridSize, i, 0.0f);
    }
    glEnd();
    glPopAttrib();
    glPopMatrix();
}

void drawScene(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
    glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
    drawSky();
    glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f);
    glTranslatef(-playerX, -playerY, -1.0f);
    glMatrixMode(GL_MODELVIEW);
    drawGround();
    SDL_GL_SwapBuffers();
}

void handleKey(SDL_keysym *key, bool state)
{
    switch (key->sym) {
    case SDLK_ESCAPE:
        if (state) {
            SDL_Quit();
            exit(0);
        }
        break;
    case SDLK_UP:
    case SDLK_w:
        buttonUp = state;
        break;
    case SDLK_DOWN:
    case SDLK_s:
        buttonDown = state;
        break;
    case SDLK_LEFT:
    case SDLK_a:
        buttonLeft = state;
        break;
    case SDLK_RIGHT:
    case SDLK_d:
        buttonRight = state;
        break;
    default:
        break;
    }
}

void advanceFrame(void)
{
    float forward = 0.0f, turn = 0.0f, face;
    if (buttonLeft)
        turn += kPlayerTurnSpeed;
    if (buttonRight)
        turn -= kPlayerTurnSpeed;
    if (buttonUp)
        forward += kPlayerForwardSpeed;
    if (buttonDown)
        forward -= kPlayerForwardSpeed;
    playerFace += turn;
    face = playerFace * (kPi / 180.0f);
    playerX += forward * std::cos(face);
    playerY += forward * std::sin(face);
}

int main(int argc, char *argv[])
{
    SDL_Surface *screen = NULL;
    bool done = false;
    SDL_Event event;
    int flags;
    Uint32 tickref = 0, tick;

    if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n",
                SDL_GetError());
        exit(1);
    }
    flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
    screen = SDL_SetVideoMode(640, 480, 32, flags);
    if (!screen) {
        fprintf(stderr, "Could not initialize video: %s\n",
                SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    printf(
        "Vendor: %s\n"
        "Renderer: %s\n"
        "Version: %s\n"
        "Extensions: %s\n",
        glGetString(GL_VENDOR), glGetString(GL_RENDERER),
        glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    while (!done) {
        tick = SDL_GetTicks();
        if (tick > tickref + kFrameTime) {
            do {
                advanceFrame();
                tickref += kFrameTime;
            } while (tick > tickref + kFrameTime);
        } else if (tick < tickref)
            tickref = tick;
        drawScene();
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                handleKey(&event.key.keysym, true);
                break;
            case SDL_KEYUP:
                handleKey(&event.key.keysym, false);
                break;
            case SDL_QUIT:
                done = true;
                break;
            }
        }
    }
    SDL_Quit();
    return 0;
}
<commit_msg>Minor cleanup of drawScene.<commit_after>#include "SDL.h"
#include "SDL_opengl.h"
#include <cmath>

const float kPi = 4.0f * std::atan(1.0f);
const Uint32 kLagThreshold = 1000;
const Uint32 kFrameTime = 10;

const float kPlayerForwardSpeed = 10.0f * (kFrameTime * 0.001f);
const float kPlayerTurnSpeed = 100.0f * (kFrameTime * 0.001f);

const float kGridSpacing = 2.0f;
const int kGridSize = 8;

bool buttonLeft = false, buttonRight = false,
    buttonUp = false, buttonDown = false;
float playerX = 0.0f, playerY = 0.0f, playerFace = 0.0f;

struct gradient_point {
    float pos;
    unsigned char color[3];
};

const gradient_point sky[] = {
    { -0.50f, {   0,   0,  51 } },
    { -0.02f, {   0,   0,   0 } },
    {  0.00f, { 102, 204, 255 } },
    {  0.20f, {  51,   0, 255 } },
    {  0.70f, {   0,   0,   0 } }
};

void drawSky(void)
{
	int i;
    glPushAttrib(GL_CURRENT_BIT);
    glBegin(GL_TRIANGLE_STRIP);
    glColor3ubv(sky[0].color);
    glVertex3f(-2.0f, 1.0f, -1.0f);
    glVertex3f( 2.0f, 1.0f, -1.0f);
    for (i = 0; i < sizeof(sky) / sizeof(*sky); ++i) {
        glColor3ubv(sky[i].color);
        glVertex3f(-2.0f, 1.0f, sky[i].pos);
        glVertex3f( 2.0f, 1.0f, sky[i].pos);
    }
    glVertex3f(-2.0f, 0.0f, 1.0f);
    glVertex3f( 2.0f, 0.0f, 1.0f);
    glEnd();
    glPopAttrib();
}

void drawGround(void)
{
    int i;
    float px = std::floor(playerX / kGridSpacing + 0.5f) * kGridSpacing;
    float py = std::floor(playerY / kGridSpacing + 0.5f) * kGridSpacing;
    glPushMatrix();
    glTranslatef(px, py, 0.0f);
    glScalef(kGridSpacing, kGridSpacing, 1.0f);
    glColor3ub(51, 0, 255);
    glBegin(GL_LINES);
    for (i = -kGridSize; i <= kGridSize; ++i) {
        glVertex3f(i, -kGridSize, 0.0f);
        glVertex3f(i,  kGridSize, 0.0f);
        glVertex3f(-kGridSize, i, 0.0f);
        glVertex3f( kGridSize, i, 0.0f);
    }
    glEnd();
    glPopAttrib();
    glPopMatrix();
}

void drawScene(void)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-0.1f, 0.1f, -0.075f, 0.075f, 0.1f, 100.0f);
    glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
    drawSky();
    glRotatef(90.0f - playerFace, 0.0f, 0.0f, 1.0f);
    glTranslatef(-playerX, -playerY, -1.0f);
    glMatrixMode(GL_MODELVIEW);

    drawGround();

    SDL_GL_SwapBuffers();
}

void handleKey(SDL_keysym *key, bool state)
{
    switch (key->sym) {
    case SDLK_ESCAPE:
        if (state) {
            SDL_Quit();
            exit(0);
        }
        break;
    case SDLK_UP:
    case SDLK_w:
        buttonUp = state;
        break;
    case SDLK_DOWN:
    case SDLK_s:
        buttonDown = state;
        break;
    case SDLK_LEFT:
    case SDLK_a:
        buttonLeft = state;
        break;
    case SDLK_RIGHT:
    case SDLK_d:
        buttonRight = state;
        break;
    default:
        break;
    }
}

void advanceFrame(void)
{
    float forward = 0.0f, turn = 0.0f, face;
    if (buttonLeft)
        turn += kPlayerTurnSpeed;
    if (buttonRight)
        turn -= kPlayerTurnSpeed;
    if (buttonUp)
        forward += kPlayerForwardSpeed;
    if (buttonDown)
        forward -= kPlayerForwardSpeed;
    playerFace += turn;
    face = playerFace * (kPi / 180.0f);
    playerX += forward * std::cos(face);
    playerY += forward * std::sin(face);
}

int main(int argc, char *argv[])
{
    SDL_Surface *screen = NULL;
    bool done = false;
    SDL_Event event;
    int flags;
    Uint32 tickref = 0, tick;

    if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Could not initialize SDL: %s\n",
                SDL_GetError());
        exit(1);
    }
    flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
    screen = SDL_SetVideoMode(640, 480, 32, flags);
    if (!screen) {
        fprintf(stderr, "Could not initialize video: %s\n",
                SDL_GetError());
        SDL_Quit();
        exit(1);
    }

    printf(
        "Vendor: %s\n"
        "Renderer: %s\n"
        "Version: %s\n"
        "Extensions: %s\n",
        glGetString(GL_VENDOR), glGetString(GL_RENDERER),
        glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    while (!done) {
        tick = SDL_GetTicks();
        if (tick > tickref + kFrameTime) {
            do {
                advanceFrame();
                tickref += kFrameTime;
            } while (tick > tickref + kFrameTime);
        } else if (tick < tickref)
            tickref = tick;
        drawScene();
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                handleKey(&event.key.keysym, true);
                break;
            case SDL_KEYUP:
                handleKey(&event.key.keysym, false);
                break;
            case SDL_QUIT:
                done = true;
                break;
            }
        }
    }
    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before>/* nobleNote, a note taking application
 * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
                      Fabian Deuchler <Taiko000@gmail.com>

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.

 * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
 */

#include "mainwindow.h"
#include <QApplication>
#include <QTranslator>
#include <QLibraryInfo>
#include <QSettings>
#include <QMessageBox>
#include <welcome.h>

int main (int argc, char *argv[]){
     QApplication app(argc, argv);
     app.setApplicationName("nobleNote");
     app.setOrganizationName("nobleNote");

     app.setFont(QFont("DejaVu Sans", 10)); // default font used in note editor

     //Qt translations
     QTranslator qtTranslator;
     qtTranslator.load("qt_" + QLocale::system().name(),
       QLibraryInfo::location(QLibraryInfo::TranslationsPath));
     app.installTranslator(&qtTranslator);

     //NobleNote translations
     QTranslator translator;
     QString tmp = "/usr/share/noblenote/translations/noblenote_";
     translator.load(tmp + QLocale::system().name());
     app.installTranslator(&translator);

     app.setQuitOnLastWindowClosed(false);

     //Configuration file
     QSettings settings; // ini format does save but in the executables directory, use native format
     if(!settings.isWritable()) // TODO QObject::tr does not work here because there is no Q_OBJECT macro in main
         QMessageBox::critical(0,"Settings not writable", QString("%1 settings not writable!").arg(app.applicationName()));
     if(!settings.value("import_path").isValid())
         settings.setValue("import_path", QDir::homePath());
     if(!settings.value("root_path").isValid())
     { // root path has not been set before
         QScopedPointer<Welcome> welcome(new Welcome);
         if(welcome->exec() == QDialog::Rejected) // welcome writes the root path
            return 0; // leave main if the user rejects the welcome dialog, else go on
     }

     MainWindow window;
     window.show();
     return app.exec();
}
<commit_msg>added translation file paths for windows in main.cpp<commit_after>/* nobleNote, a note taking application
 * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
                      Fabian Deuchler <Taiko000@gmail.com>

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.

 * nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
 */

#include "mainwindow.h"
#include <QApplication>
#include <QTranslator>
#include <QLibraryInfo>
#include <QSettings>
#include <QMessageBox>
#include <welcome.h>

int main (int argc, char *argv[]){
     QApplication app(argc, argv);
     app.setApplicationName("nobleNote");
     app.setOrganizationName("nobleNote");

     app.setFont(QFont("DejaVu Sans", 10)); // default font used in note editor

     //Qt translations
     QTranslator qtTranslator;
     qtTranslator.load("qt_" + QLocale::system().name(),
       QLibraryInfo::location(QLibraryInfo::TranslationsPath));
     app.installTranslator(&qtTranslator);

     //NobleNote translations
     QTranslator translator;
    #ifdef Q_OS_WIN32
     translator.load(":noblenote_" + QLocale::system().name());
    #else
     QString tmp = "/usr/share/noblenote/translations/noblenote_";
     translator.load(tmp + QLocale::system().name());
    #endif
     app.installTranslator(&translator);

     app.setQuitOnLastWindowClosed(false);

     //Configuration file
     QSettings settings; // ini format does save but in the executables directory, use native format
     if(!settings.isWritable()) // TODO QObject::tr does not work here because there is no Q_OBJECT macro in main
         QMessageBox::critical(0,"Settings not writable", QString("%1 settings not writable!").arg(app.applicationName()));
     if(!settings.value("import_path").isValid())
         settings.setValue("import_path", QDir::homePath());
     if(!settings.value("root_path").isValid())
     { // root path has not been set before
         QScopedPointer<Welcome> welcome(new Welcome);
         if(welcome->exec() == QDialog::Rejected) // welcome writes the root path
            return 0; // leave main if the user rejects the welcome dialog, else go on
     }

     MainWindow window;
     window.show();
     return app.exec();
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv)
{
  // hold a raw line of input
  std::string line;

  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  while (true)
  {
    // holds a single command and its arguments
    Command cmd;
    // holds multiple commands
    std::vector<Command> cmds;

    // print prompt and get a line of text (done in condition)
    printf("$ ");
    getline(std::cin, line);

    // look for comments
    if (line.find("#") != std::string::npos)
    {
      // remove them if necessary (they're useless)
      line = line.substr(0, line.find("#"));
    }

    // remove leading whitespace
    while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
    {
      line = line.substr(1, line.size() - 1);
    }

    if (std::cin.fail())
    {
      printf("\nGoodbye!\n");
      exit(0);
    }

    int mode = GETWORD;
    unsigned begin = 0;

    // temporary: show pre-processed input to know what's being dealt with
    printf("You entered: \"%s\"\n", line.c_str());

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i)
    {
      bool con   = isConn(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con))
      {
        // chunk the last term and throw it into the vector
        char* c = stocstr(line.substr(begin, i - begin));
        if (strlen(c) > 0)
        {
          cmd.args.push_back(c);
        }
        else
        {
          break;
        }

        if (space)
        {
          mode = TRIMSPACE;
        }
        else // it's a connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
      }
      else if (mode == TRIMSPACE && (!space && con))
      {
        if (con && cmd.args.empty())
        {
          se = true;
        }
        else if (con) // it's a valid connector connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
        else
        {
          mode = GETWORD;
        }
      }
    }

    // if there was a syntax error
    if (se)
    {
      printf("Syntax error detected\n");
      continue;
    }

    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      printf("Command %u:\n", i);
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        printf("\t\"%s\"\n", cmds[i].args[j]);
      }
      switch(cmds[i].connector)
      {
        case AND:
          printf("\t&&\n");
          break;
        case OR:
          printf("\t||\n");
          break;
        case SEMI:
          printf("\t;\n");
          break;
        case NONE:
          printf("\tNo connector\n");
          break;
        default:
          printf("\tERROR: no valid connector specified\n");
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        delete[] cmds[i].args[i];
      }
    }
  }
  return 0;
}

<commit_msg>Worked on fixing bugs<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv)
{
  // hold a raw line of input
  std::string line;

  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  while (true)
  {
    // holds a single command and its arguments
    Command cmd;
    // holds multiple commands
    std::vector<Command> cmds;

    // print prompt and get a line of text (done in condition)
    printf("$ ");
    getline(std::cin, line);

    // look for comments
    if (line.find("#") != std::string::npos)
    {
      // remove them if necessary (they're useless)
      line = line.substr(0, line.find("#"));
    }

    // remove leading whitespace
    while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
    {
      line = line.substr(1, line.size() - 1);
    }

    // adding a space to the end makes parsing easier
    line += ' ';

    if (std::cin.fail())
    {
      printf("\nGoodbye!\n");
      exit(0);
    }

    int mode = GETWORD;
    unsigned begin = 0;

    // temporary: show pre-processed input to know what's being dealt with
    printf("You entered: \"%s\"\n", line.c_str());

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    if (line.size() > 0 && isConn(line[0]))
    {
      se = true;
    }

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i)
    {
      bool con   = isConn(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con))
      {
        // chunk the last term and throw it into the vector
        char* c = stocstr(line.substr(begin, i - begin));
        if (strlen(c) > 0)
        {
          cmd.args.push_back(c);
        }
        else
        {
          printf("Oh no! Recieved a word with no length\n");
          break;
        }

        if (space)
        {
          mode = TRIMSPACE;
        }
        else // it's a connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
      }
      else if (mode == TRIMSPACE && (!space && con))
      {
        if (con && cmd.args.empty())
        {
          se = true;
        }
        else if (con)
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
        else
        {
          mode = GETWORD;
          begin = i;
        }
      }
    }

    // if there was a syntax error
    if (se)
    {
      printf("Syntax error detected\n");
      continue;
    }

    cmds.push_back(cmd);

    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      printf("Command %u:\n", i);
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        printf("\t\"%s\"\n", cmds[i].args[j]);
      }
      switch(cmds[i].connector)
      {
        case AND:
          printf("\t&&\n");
          break;
        case OR:
          printf("\t||\n");
          break;
        case SEMI:
          printf("\t;\n");
          break;
        case NONE:
          printf("\tNo connector\n");
          break;
        default:
          printf("\tERROR: no valid connector specified\n");
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        delete[] cmds[i].args[i];
      }
    }
  }
  return 0;
}

<|endoftext|>


<commit_before>
#include "Client.hpp"
#include <onions-common/Log.hpp>
#include <onions-common/Utils.hpp>
#include <botan/botan.h>
#include <popt.h>

// Botan::LibraryInitializer init("thread_safe");

int main(int argc, char** argv)
{
  char* logPath = NULL;
  bool license = false;
  ushort port = 9150;

  struct poptOption po[] = {
      {"output",
       'o',
       POPT_ARG_STRING,
       &logPath,
       0,
       "Specifies the filepath for event logging.",
       "<path>"},
      {"port",
       'p',
       POPT_ARG_SHORT,
       &port,
       0,
       "SOCKS port to use for Tor communication. The default is 9150.",
       "<port>"},
      {"license",
       'L',
       POPT_ARG_NONE,
       &license,
       0,
       "Print software license and exit.",
       NULL},
      POPT_AUTOHELP{NULL, 0, 0, NULL, 0, NULL, NULL}};

  if (!Utils::parse(
          poptGetContext(NULL, argc, const_cast<const char**>(argv), po, 0)))
  {
    std::cout << "Failed to parse command-line arguments. Aborting.\n";
    return EXIT_FAILURE;
  }

  if (license)
  {
    std::cout << "Modified/New BSD License" << std::endl;
    return EXIT_SUCCESS;
  }

  if (logPath && strcmp(logPath, "-") == 0)
    Log::setLogPath(std::string(logPath));

  Client::get().listenForDomains(port);

  return EXIT_SUCCESS;
}
<commit_msg>Fix #17<commit_after>
#include "Client.hpp"
#include <onions-common/Log.hpp>
#include <onions-common/Utils.hpp>
#include <botan/botan.h>
#include <popt.h>

// Botan::LibraryInitializer init("thread_safe");

int main(int argc, char** argv)
{
  char* logPath = NULL;
  bool license = false;
  ushort port = 9150;

  struct poptOption po[] = {
      {"output",
       'o',
       POPT_ARG_STRING,
       &logPath,
       0,
       "Specifies the filepath for event logging.",
       "<path>"},
      {"port",
       'p',
       POPT_ARG_SHORT,
       &port,
       0,
       "SOCKS port to use for Tor communication. The default is 9150.",
       "<port>"},
      {"license",
       'L',
       POPT_ARG_NONE,
       &license,
       0,
       "Print software license and exit.",
       NULL},
      POPT_AUTOHELP{NULL, 0, 0, NULL, 0, NULL, NULL}};

  if (!Utils::parse(
          poptGetContext(NULL, argc, const_cast<const char**>(argv), po, 0)))
  {
    std::cout << "Failed to parse command-line arguments. Aborting.\n";
    return EXIT_FAILURE;
  }

  if (license)
  {
    std::cout << "Modified/New BSD License" << std::endl;
    return EXIT_SUCCESS;
  }

  if (logPath && strcmp(logPath, "-") != 0)
    Log::setLogPath(std::string(logPath));

  Client::get().listenForDomains(port);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*! \mainpage Dwarf Therapist
*
* \section intro_sec Introduction
*
* Dwarf Therapist is written in C++ using Qt 5.1.1. It is meant to be used as
* an addon for the game Dwarf Fortress.
*
*/

#include "dwarftherapist.h"
#include "dfinstance.h"

int main(int argc, char *argv[]) {
    if(!DFInstance::authorize()){
        return 0;
    }
    DwarfTherapist d(argc, argv);
    return d.exec();
}
<commit_msg>Revert "remove invalid/duplicate setuid from main from #128", because it makes DT not run on Mac.<commit_after>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*! \mainpage Dwarf Therapist
*
* \section intro_sec Introduction
*
* Dwarf Therapist is written in C++ using Qt 5.1.1. It is meant to be used as
* an addon for the game Dwarf Fortress.
*
*/

#include "dwarftherapist.h"
#include "dfinstance.h"

int main(int argc, char *argv[]) {
    QCoreApplication::setSetuidAllowed(true);
    if(!DFInstance::authorize()){
        return 0;
    }
    DwarfTherapist d(argc, argv);
    return d.exec();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <cstring>
#include <string>
using namespace std;

void lsCom() {

}
bool isDependant = 0;
int main() {
    string str;
    pid_t pid;
    bool hasArg = 0, term = 0;
    int strSize = 0;
    int pos, arrPos;
    bool bexit = false;

    char *arg;
    char *comm;
    while(1) {
        cout << "$ ";
        getline(cin, str);
        string sarg, scomm;
        bool success = false;
        bool lastOR = false, lastAND = false;
        bool lastSuccess = false;

        pos = 0;
        strSize = str.size();
        //cout << strSize << endl;
        while(pos < strSize) {
            arg = (char*) malloc(256);
            comm = (char*) malloc(256);
            char* arr[30];
            string sarg, scomm;

            bool logOR = false, logAND = false;
            bool comment = false;
            arrPos = 0;
            hasArg = 0;
            term = false;
            hasArg = false;

            if(str.at(pos) == ' ') {
                while(pos < strSize && str.at(pos) == ' ') {
                    ++pos;
                }
                if(pos >= strSize) {
                    break;
                }
            }

            while(pos < strSize && str.at(pos) != ' ') {
                if(str.at(pos) == '#') {
                    comment = true;
                    break;
                }

                else if(str.at(pos) == ';') {
                    term = true;
                    ++pos;
                    break;
                }
                else if(str.at(pos) == '|') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '|') {
                        logOR = true;
                        ++pos;
                        break;
                    }
                }
                else if(str.at(pos) == '&') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '&') {
                        logAND = true;
                        ++pos;
                        break;
                    }
                }
                else {
                    scomm += str.at(pos);
                    ++pos;
                }
            }

            if(comment) {
                break;
            }

            strcpy(comm,scomm.c_str());
            //++pos; // This is to ommit the whitespace character following the command

            if(pos < strSize && str.at(pos) == ' ' && !(term)) {
                while(pos < strSize && str.at(pos) == ' ') {
                    ++pos;
                }
                if(pos >= strSize) {
                    break;
                }
            }

            arr[arrPos] = comm;
            ++arrPos;
            while(pos < strSize && !(term) && !(logOR) && !(logAND)) {
               if(str.at(pos) == '#') {
                   break;
               }
               else if(str.at(pos) == '-' && str.at(pos+1) == ' ') {
                   sarg += str.at(pos);
                   ++pos;
                   while(str.at(pos) == ' ') {
                       ++pos;
                   }
               }
               else if(str.at(pos) == ';') {
                   ++pos;
                   break;
               }
               else if(str.at(pos) == '|') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '|') {
                        logOR = true;
                        ++pos;
                        break;
                    }
                }
                else if(str.at(pos) == '&') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '&') {
                        logAND = true;
                        ++pos;
                        break;
                    }
                }
               else {
                   sarg += str.at(pos);
                   ++pos;
                   hasArg = true;
               }
            }

            if(hasArg) {
                unsigned int n = 0;
                string s;
                while(n < sarg.size()) {
                    if(sarg.at(n) == '-' && n != 0) {
                        strcpy(arg, s.c_str());
                        arr[arrPos] = arg;
                        ++arrPos;
                        s = "";
                    }
                    s += sarg.at(n);
                    ++n;
                }
                n = s.size() -1;
                while(s.at(n) == ' ') {
                    s.at(n) = '\0';
                    --n;
                }
                strcpy(arg, s.c_str());
                arr[arrPos] = arg;
                ++arrPos;
            }

            arr[arrPos] = NULL;

            /*for(int i = 0; i < 1; ++i) {
                cout << arr[i] << endl;
            }*/

            if(scomm != "exit") {
                pid = fork();

                if(pid == 0) {
                    if(lastSuccess == false) {
                        cout << "1" << endl;
                    }
                    if((!(lastOR) && !(lastAND)) || (lastSuccess == false && lastOR == true) ||
                        (lastSuccess == true && lastAND == true)) {
                        if(execvp(arr[0], arr) == -1) {
                            success = true;
                            perror("The command could not be executed!");
                            errno = 0;
                        }
                        _exit(0);
                    }
                }

                else {
                    wait(0);
                }
            }

            else {
                if((!lastOR && !lastAND) || (!lastSuccess && lastOR) || (lastSuccess && lastAND)) {
                    cout << "Good-bye!" << endl;
                    exit(0);
                }
            }

            lastOR = logOR;
            lastAND = logAND;
            lastSuccess = !(success);

            free(comm);
            free(arg);
        }
        if(bexit) {
            break;
        }
    }

    return 0;
}
<commit_msg>Forgot to take out test statement<commit_after>#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <cstring>
#include <string>
using namespace std;

void lsCom() {

}
bool isDependant = 0;
int main() {
    string str;
    pid_t pid;
    bool hasArg = 0, term = 0;
    int strSize = 0;
    int pos, arrPos;
    bool bexit = false;

    char *arg;
    char *comm;
    while(1) {
        cout << "$ ";
        getline(cin, str);
        string sarg, scomm;
        bool success = false;
        bool lastOR = false, lastAND = false;
        bool lastSuccess = false;

        pos = 0;
        strSize = str.size();
        //cout << strSize << endl;
        while(pos < strSize) {
            arg = (char*) malloc(256);
            comm = (char*) malloc(256);
            char* arr[30];
            string sarg, scomm;

            bool logOR = false, logAND = false;
            bool comment = false;
            arrPos = 0;
            hasArg = 0;
            term = false;
            hasArg = false;

            if(str.at(pos) == ' ') {
                while(pos < strSize && str.at(pos) == ' ') {
                    ++pos;
                }
                if(pos >= strSize) {
                    break;
                }
            }

            while(pos < strSize && str.at(pos) != ' ') {
                if(str.at(pos) == '#') {
                    comment = true;
                    break;
                }

                else if(str.at(pos) == ';') {
                    term = true;
                    ++pos;
                    break;
                }
                else if(str.at(pos) == '|') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '|') {
                        logOR = true;
                        ++pos;
                        break;
                    }
                }
                else if(str.at(pos) == '&') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '&') {
                        logAND = true;
                        ++pos;
                        break;
                    }
                }
                else {
                    scomm += str.at(pos);
                    ++pos;
                }
            }

            if(comment) {
                break;
            }

            strcpy(comm,scomm.c_str());
            //++pos; // This is to ommit the whitespace character following the command

            if(pos < strSize && str.at(pos) == ' ' && !(term)) {
                while(pos < strSize && str.at(pos) == ' ') {
                    ++pos;
                }
                if(pos >= strSize) {
                    break;
                }
            }

            arr[arrPos] = comm;
            ++arrPos;
            while(pos < strSize && !(term) && !(logOR) && !(logAND)) {
               if(str.at(pos) == '#') {
                   break;
               }
               else if(str.at(pos) == '-' && str.at(pos+1) == ' ') {
                   sarg += str.at(pos);
                   ++pos;
                   while(str.at(pos) == ' ') {
                       ++pos;
                   }
               }
               else if(str.at(pos) == ';') {
                   ++pos;
                   break;
               }
               else if(str.at(pos) == '|') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '|') {
                        logOR = true;
                        ++pos;
                        break;
                    }
                }
                else if(str.at(pos) == '&') {
                    ++pos;
                    if(pos < strSize && str.at(pos) == '&') {
                        logAND = true;
                        ++pos;
                        break;
                    }
                }
               else {
                   sarg += str.at(pos);
                   ++pos;
                   hasArg = true;
               }
            }

            if(hasArg) {
                unsigned int n = 0;
                string s;
                while(n < sarg.size()) {
                    if(sarg.at(n) == '-' && n != 0) {
                        strcpy(arg, s.c_str());
                        arr[arrPos] = arg;
                        ++arrPos;
                        s = "";
                    }
                    s += sarg.at(n);
                    ++n;
                }
                n = s.size() -1;
                while(s.at(n) == ' ') {
                    s.at(n) = '\0';
                    --n;
                }
                strcpy(arg, s.c_str());
                arr[arrPos] = arg;
                ++arrPos;
            }

            arr[arrPos] = NULL;

            /*for(int i = 0; i < 1; ++i) {
                cout << arr[i] << endl;
            }*/

            if(scomm != "exit") {
                pid = fork();

                if(pid == 0) {
                    if((!(lastOR) && !(lastAND)) || (lastSuccess == false && lastOR == true) ||
                        (lastSuccess == true && lastAND == true)) {
                        if(execvp(arr[0], arr) == -1) {
                            success = true;
                            perror("The command could not be executed!");
                            errno = 0;
                        }
                        _exit(0);
                    }
                }

                else {
                    wait(0);
                }
            }

            else {
                if((!lastOR && !lastAND) || (!lastSuccess && lastOR) || (lastSuccess && lastAND)) {
                    cout << "Good-bye!" << endl;
                    exit(0);
                }
            }

            lastOR = logOR;
            lastAND = logAND;
            lastSuccess = !(success);

            free(comm);
            free(arg);
        }
        if(bexit) {
            break;
        }
    }

    return 0;
}
<|endoftext|>