<commit_before>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include "qpp.h"

//#include "matlab.h" // support for MATLAB

// TODO: ip (inner product) function, make it general to return matrices
// TODO: use .data() raw pointer instead of looping
// TODO: optimize syspermute: ?Eigen::Map?
// TODO: IMPORTANT Rewrite partial trace without syspermute
// TODO: further parallelization

using namespace std;

using namespace qpp;
using namespace qpp::types;

int main()
{
	_init(); // ALWAYS call _init() at the beginning of main()
	cout << "Starting qpp..." << endl;

	// output format
	// cout << std::scientific;
	cout << std::fixed; // use fixed format for nice formatting
	cout << std::setprecision(4); // only for fixed or scientific modes

	// Bell state generator
	cout << endl << "Bell state generator: " << endl;
	cmat circuit;
	circuit = gt::CTRL(gt::X, { 0 }, { 1 }, 2) * expandout(gt::H, 0, { 2, 2 });
	cmat z0(2, 1);
	z0 << 1, 0;
	cmat z1(2, 1);
	z1 << 0, 1;
	cmat input = kron(z0, z0);
	cmat output = circuit * input;
	cout << "Circuit matrix representation: " << endl;
	displn(circuit);
	cout << endl << "Output (|Bell_0> state) of the circuit on |00>: " << endl;
	displn(output);

	// 3-qubit repetion code
	cout << endl << "3-qubit repetition code: " << endl;
	cmat rep;
	rep = gt::CTRL(gt::X, { 0 }, { 2 }, 3) * gt::CTRL(gt::X, { 0 }, { 1 }, 3);
	input = kronlist<cplx>( { z1, z0, z0 });
	output = rep * input;
	cout << "Circuit acting on |000> produces |111>. Check: " << endl;
	displn(output);

	// Gram-Schmidt
	cout << endl << "Gram-Schmidt on a random matrix:" << endl;
	cmat A = randn<cplx>(3, 3);
	displn(A);
	cmat Ags = grams(A);
	cout << endl << "Result:" << endl;
	displn(Ags);
	cout << endl << "Checking for unitarity:" << endl;
	displn((cmat) (Ags * adjoint(Ags)));

	// spectral decomposition test
	cout << endl << "Spectral decomposition tests." << endl;
	size_t D = 4;
	cmat rH = randH(D);
	cmat evalsH = hevals(rH);
	cmat evectsH = hevects(rH);
	cmat spec = cmat::Zero(D, D);
	for (size_t i = 0; i < D; i++)
		spec += evalsH(i) * proj((cmat) (evectsH.col(i)));
	cout << "Original matrix: " << endl;
	displn(rH);
	cout << endl << "Reconstructed from spectral decomposition: " << endl;
	displn(spec);
	cout << "Difference in norm: " << norm((cmat) (spec - rH)) << endl;

	// channel tests
	cout << endl << "Channel tests." << endl;
	size_t nk = 10, d = 2; // nk Kraus on d-dimensional system
	cout << "Generating a random channel with " << nk
			<< " Kraus operators on a " << d << " dimensional space..." << endl;
	std::vector<cmat> Ks = randKraus(nk, d);

	cmat rho_in = randrho(d); // input state
	cmat rho_out = channel(rho_in, Ks); // output state

	cout << "Computing its Choi matrix..." << endl;
	cmat choim = choi(Ks);
	cout << "Choi matrix:" << endl;
	displn(choim);
	cout << endl << "The eigenvalues of the Choi matrix are: " << endl;
	displn(transpose(hevals(choim)));
	cout << endl << "Their sum is: " << sum(hevals(choim)).real() << endl;
	std::vector<cmat> Kperps = choi2kraus(choim);
	cout << endl << "The Kraus rank of the channel is: " << Kperps.size()
			<< endl;
	cmat rho_out1 = channel(rho_in, Kperps);
	cout << endl << "Difference in norm on output states: "
			<< norm((cmat) (rho_out1 - rho_out)) << endl;
	cout << endl << "Superoperator matrix:" << endl;
	cmat smat = super(Ks);
	displn(smat);
	cout << endl << "The eigenvalues of the superoperator matrix are: " << endl;
	cmat evalsupop = evals(smat);
	displn(transpose(evalsupop));
	cout << endl << "Their absolute values are: " << endl;
	for (size_t i = 0; i < static_cast<size_t>(evalsupop.size()); i++)
		cout << std::abs(evalsupop(i)) << " ";
	cout << endl;

	// statistics tests
	cout << endl << "Statistics tests." << endl;
	std::vector<cplx> ampl = { 1. + ct::ii, 1. - ct::ii };
	cmat va(1, 4);
	va << 0.1, 1, 1. + ct::ii, 1. + 2. * ct::ii;
	stat::DiscreteDistributionFromComplex dc(va);
	cout << "The probabilities are: ";
	displn(dc.probabilities(), ", ", "{", "}");

	// other tests
	cout << endl << "Timing tests..." << endl;
	size_t n = 12; // number of qubits
	size_t N = std::pow(2, n);
	vector<size_t> dims; // local dimensions
	for (size_t i = 0; i < n; i++)
		dims.push_back(2);
	cout << "n = " << n << " qubits, matrix size " << N << " x " << N << "."
			<< endl;

	// TIMING
	Timer t, total;  // start the timer, automatic tic() in the constructor

	// matrix initialization
	cout << endl << "Matrix initialization timing." << endl;
	cmat randcmat = cmat::Random(N, N);
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// lazy matrix product
	cout << endl << "Lazy matrix product timing." << endl;
	t.tic();
	auto lazyprod = randcmat * randcmat; // lazyprod has type GenMatProduct
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// matrix product
	cout << endl << "Matrix product timing." << endl;
	t.tic(); // reset the chronometer
	cmat prodmat = randcmat * randcmat; // explicit cmat now
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// ptrace2 timing
	cout << endl << "ptrace2 timing." << endl;
	t.tic(); // reset the chronometer
	// trace away half of the qubits
	ptrace2(randcmat, { (size_t) std::sqrt(N), (size_t) std::sqrt(N) });
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// ptrace SLOW SLOW SLOW (because of syspermute, do it without)
	cout << endl << "ptrace timing." << endl;
	vector<size_t> subsys_ptrace = { 0 }; // trace away the first qubit
	cout << "Subsytem(s): ";
	displn(subsys_ptrace, ", ");
	t.tic();
	ptrace(randcmat, subsys_ptrace, dims);
	t.toc();
	cout << "Took " << t << " seconds." << endl;

	// ptranspose
	cout << endl << "ptranspose timing." << endl;
	vector<size_t> subsys_ptranspose; // partially transpose all subsystems
	for (size_t i = 0; i < n; i++)
		subsys_ptranspose.push_back(i);
	cout << "Subsytem(s): ";
	displn(subsys_ptranspose, ", ");
	t.tic();
	ptranspose(randcmat, subsys_ptranspose, dims);
	t.toc();
	cout << "Took " << t << " seconds." << endl;

	// syspermute SLOW SLOW SLOW
	cout << endl << "syspermute timing." << endl;
	vector<size_t> perm; // left-shift all subsystems by 1
	for (size_t i = 0; i < n; i++)
		perm.push_back((i + 1) % n);
	cout << "Subsytem(s): ";
	displn(perm, ", ");
	t.tic();
	syspermute(randcmat, perm, dims);
	t.toc();
	cout << "Took " << t << " seconds." << endl;

	// END TIMING
	total.toc(); // read the total running time
	cout << endl << "Total time: " << total.seconds() << " seconds.";

	cout << endl << "Exiting qpp..." << endl;
}
<commit_msg>commit<commit_after>/*
 * File:   main.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:38 PM
 */

#include "qpp.h"

//#include "matlab.h" // support for MATLAB

// TODO: ip (inner product) function, make it general to return matrices
// TODO: use .data() raw pointer instead of looping
// TODO: optimize syspermute: ?Eigen::Map?
// TODO: IMPORTANT Rewrite partial trace without syspermute
// TODO: further parallelization

using namespace std;

using namespace qpp;
using namespace qpp::types;

int main()
{
	_init(); // ALWAYS call _init() at the beginning of main()
	cout << "Starting qpp..." << endl;

	// output format
	// cout << std::scientific;
	cout << std::fixed; // use fixed format for nice formatting
	cout << std::setprecision(4); // only for fixed or scientific modes

	// Bell state generator
	cout << endl << "Bell state generator: " << endl;
	cmat circuit;
	circuit = gt::CTRL(gt::X, { 0 }, { 1 }, 2) * expandout(gt::H, 0, { 2, 2 });
	cmat z0(2, 1);
	z0 << 1, 0;
	cmat z1(2, 1);
	z1 << 0, 1;
	cmat input = kron(z0, z0);
	cmat output = circuit * input;
	cout << "Circuit matrix representation: " << endl;
	displn(circuit);
	cout << endl << "Output (|Bell_0> state) of the circuit on |00>: " << endl;
	displn(output);

	// 3-qubit repetion code
	cout << endl << "3-qubit repetition code: " << endl;
	cmat rep;
	rep = gt::CTRL(gt::X, { 0 }, { 2 }, 3) * gt::CTRL(gt::X, { 0 }, { 1 }, 3);
	input = kronlist<cplx>( { z1, z0, z0 });
	output = rep * input;
	cout << "Circuit acting on |000> produces |111>. Check: " << endl;
	displn(output);

	// Gram-Schmidt
	cout << endl << "Gram-Schmidt on a random matrix:" << endl;
	cmat A = randn<cplx>(3, 3);
	displn(A);
	cmat Ags = grams(A);
	cout << endl << "Result:" << endl;
	displn(Ags);
	cout << endl << "Checking for unitarity:" << endl;
	displn((cmat) (Ags * adjoint(Ags)));

	// spectral decomposition test
	cout << endl << "Spectral decomposition tests." << endl;
	size_t D = 4;
	cmat rH = randH(D);
	cmat evalsH = hevals(rH);
	cmat evectsH = hevects(rH);
	cmat spec = cmat::Zero(D, D);
	for (size_t i = 0; i < D; i++)
		spec += evalsH(i) * proj((cmat) (evectsH.col(i)));
	cout << "Original matrix: " << endl;
	displn(rH);
	cout << endl << "Reconstructed from spectral decomposition: " << endl;
	displn(spec);
	cout << "Difference in norm: " << norm((cmat) (spec - rH)) << endl;

	// channel tests
	cout << endl << "Channel tests." << endl;
	size_t nk = 10, d = 2; // nk Kraus on d-dimensional system
	cout << "Generating a random channel with " << nk
			<< " Kraus operators on a " << d << " dimensional space..." << endl;
	std::vector<cmat> Ks = randKraus(nk, d);

	cmat rho_in = randrho(d); // input state
	cmat rho_out = channel(rho_in, Ks); // output state

	cout << "Computing its Choi matrix..." << endl;
	cmat choim = choi(Ks);
	cout << "Choi matrix:" << endl;
	displn(choim);
	cout << endl << "The eigenvalues of the Choi matrix are: " << endl;
	displn(transpose(hevals(choim)));
	cout << endl << "Their sum is: " << sum(hevals(choim)).real() << endl;
	std::vector<cmat> Kperps = choi2kraus(choim);
	cout << endl << "The Kraus rank of the channel is: " << Kperps.size()
			<< endl;
	cmat rho_out1 = channel(rho_in, Kperps);
	cout << endl << "Difference in norm on output states: "
			<< norm((cmat) (rho_out1 - rho_out)) << endl;
	cout << endl << "Superoperator matrix:" << endl;
	cmat smat = super(Ks);
	displn(smat);
	cout << endl << "The eigenvalues of the superoperator matrix are: " << endl;
	cmat evalsupop = evals(smat);
	displn(transpose(evalsupop));
	cout << endl << "Their absolute values are: " << endl;
	for (size_t i = 0; i < static_cast<size_t>(evalsupop.size()); i++)
		cout << std::abs(evalsupop(i)) << " ";
	cout << endl << endl << "Diference in norm for superoperator action: ";
	cmat rho_out2 = transpose(
			reshape((cmat) (smat * reshape(transpose(rho_in), d * d, 1)), d,
					d));
	cout << norm((cmat) (rho_out - rho_out2)) << endl;

	// statistics tests
	cout << endl << "Statistics tests." << endl;
	std::vector<cplx> ampl = { 1. + ct::ii, 1. - ct::ii };
	cmat va(1, 4);
	va << 0.1, 1, 1. + ct::ii, 1. + 2. * ct::ii;
	stat::DiscreteDistributionFromComplex dc(va);
	cout << "The probabilities are: ";
	displn(dc.probabilities(), ", ", "{", "}");

	// other tests
	cout << endl << "Timing tests..." << endl;
	size_t n = 12; // number of qubits
	size_t N = std::pow(2, n);
	vector<size_t> dims; // local dimensions
	for (size_t i = 0; i < n; i++)
		dims.push_back(2);
	cout << "n = " << n << " qubits, matrix size " << N << " x " << N << "."
			<< endl;

	// TIMING
	Timer t, total;  // start the timer, automatic tic() in the constructor

	// matrix initialization
	cout << endl << "Matrix initialization timing." << endl;
	cmat randcmat = cmat::Random(N, N);
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// lazy matrix product
	cout << endl << "Lazy matrix product timing." << endl;
	t.tic();
	auto lazyprod = randcmat * randcmat; // lazyprod has type GenMatProduct
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// matrix product
	cout << endl << "Matrix product timing." << endl;
	t.tic(); // reset the chronometer
	cmat prodmat = randcmat * randcmat; // explicit cmat now
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// ptrace2 timing
	cout << endl << "ptrace2 timing." << endl;
	t.tic(); // reset the chronometer
	// trace away half of the qubits
	ptrace2(randcmat, { (size_t) std::sqrt(N), (size_t) std::sqrt(N) });
	t.toc(); // read the time
	cout << "Took " << t << " seconds." << endl;

	// ptrace SLOW SLOW SLOW (because of syspermute, do it without)
	cout << endl << "ptrace timing." << endl;
	vector<size_t> subsys_ptrace = { 0 }; // trace away the first qubit
	cout << "Subsytem(s): ";
	displn(subsys_ptrace, ", ");
	t.tic();
	ptrace(randcmat, subsys_ptrace, dims);
	t.toc();
	cout << "Took " << t << " seconds." << endl;

	// ptranspose
	cout << endl << "ptranspose timing." << endl;
	vector<size_t> subsys_ptranspose; // partially transpose all subsystems
	for (size_t i = 0; i < n; i++)
		subsys_ptranspose.push_back(i);
	cout << "Subsytem(s): ";
	displn(subsys_ptranspose, ", ");
	t.tic();
	ptranspose(randcmat, subsys_ptranspose, dims);
	t.toc();
	cout << "Took " << t << " seconds." << endl;

	// syspermute SLOW SLOW SLOW
	cout << endl << "syspermute timing." << endl;
	vector<size_t> perm; // left-shift all subsystems by 1
	for (size_t i = 0; i < n; i++)
		perm.push_back((i + 1) % n);
	cout << "Subsytem(s): ";
	displn(perm, ", ");
	t.tic();
	syspermute(randcmat, perm, dims);
	t.toc();
	cout << "Took " << t << " seconds." << endl;

	// END TIMING
	total.toc(); // read the total running time
	cout << endl << "Total time: " << total.seconds() << " seconds.";

	cout << endl << "Exiting qpp..." << endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <list>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <netdb.h>
#include <pwd.h>
#include <sys/socket.h>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost::algorithm;

class Base{
    public:
        Base(){};
        virtual bool evaluate() = 0;
};

class Command: public Base{
    private:
        vector<string> commandVec;
    public:
        Command(vector<string>s){
            commandVec = s;
        }

};

int main () {

    //take user input
    string initialCommand = "";
    while (true) {
        string login = getlogin();
        char hostname[100];
        gethostname(hostname, 100);
        cout << "[" << login << "@" << hostname << "] $ ";
        getline(cin, initialCommand);
        trim(initialCommand);

    }

    return 0;
}
<commit_msg>Added Comments<commit_after>#include <iostream>
#include <vector>
#include <list>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <netdb.h>
#include <pwd.h>
#include <sys/socket.h>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost::algorithm;

//Virtual Base Class
class Base{
    public:
        Base(){};
        //Function Inherited by each class
        virtual bool evaluate() = 0;
};

// Command Class that each command will inherit from
class Command: public Base{
    private:
    //Vector of commands
        vector<string> commandVec;
    public:
    //Contructor to take in vector and set it to commands vectors
        Command(vector<string>s){
            commandVec = s;
        }

};

int main () {

    //take user input
    string initialCommand = "";

    while (true) {
        string login = getlogin();
        char hostname[100];
        gethostname(hostname, 100);
        cout << "[" << login << "@" << hostname << "] $ ";
        getline(cin, initialCommand);
        trim(initialCommand);

    }

    return 0;
}
<|endoftext|>


<commit_before>#include <config.h>

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

#include <readline/readline.h>
#include <readline/history.h>
#include <tclap/CmdLine.h>

#include "bptree.h"
#include "locations.h"

enum Mode {
    MODE_ADJ = 0,
    MODE_NI = 1,
    MODE_DELTANI = 2
};

char const MODE_STR_ADJ[] = "adj";
char const MODE_STR_NI[] = "ni";
char const MODE_STR_DELTANI[] = "deltani";

std::vector<std::string> MODES = {MODE_STR_ADJ, MODE_STR_NI, MODE_STR_DELTANI};

int main(int argc, char** argv) {
    using namespace std;

    TCLAP::CmdLine args(PACKAGE_STRING);
    TCLAP::ValuesConstraint<std::string> modeConstraint(MODES);
    TCLAP::UnlabeledValueArg<std::string> modeArg(
        "mode",
        "Mode of execution",
        true,
        "",
        &modeConstraint
    );
    TCLAP::UnlabeledValueArg<std::string> locsArg(
        "locations",
        "Path to locations.tbl file",
        true,
        "",
        "file path"
    );
    TCLAP::UnlabeledValueArg<std::string> treeArg(
        "tree",
        "Path to mode specific tree data",
        true,
        "",
        "file path"
    );

    args.add(modeArg);
    args.add(locsArg);
    args.add(treeArg);

    args.parse(argc, argv);

    string strMode = modeArg.getValue();
    Mode mode;
    ModeInfo mode_info;
    if (strMode == MODE_STR_DELTANI) {
        mode = MODE_DELTANI;
        mode_info = deltaniModeInfo;
    } else if (strMode == MODE_STR_NI) {
        mode = MODE_NI;
        mode_info = niModeInfo;
    } else {
        mode = MODE_ADJ;
        mode_info = adjModeInfo;
    }

    if (mode != MODE_ADJ) {
        cerr << "Only \"adj\" mode is implemented!" << endl;
        return 1;
    }

    cout << "Running in \"" << strMode << "\" mode" << endl;

    ifstream locs_file(locsArg.getValue());
    if (locs_file.fail()) {
        cerr << "couldn't read locations file" << endl;
        return 1;
    }
    BPTree<Location> locs_tree;
    size_t num_locs;
    cout << "reading locations... ";
    cout.flush();
    num_locs = read_locations(locs_file, locs_tree);
    locs_file.close();
    if (num_locs == 0) {
        cerr << "error" << endl;
        return 1;
    }
    cout << "got " << num_locs << endl;

    ifstream tree_file(treeArg.getValue());
    if (tree_file.fail()) {
        cerr << "couldn't read tree data file" << endl;
        return 1;
    }
    ModeData mode_data;
    if (mode_info.init_mode != nullptr) {
        int ret = mode_info.init_mode(tree_file, mode_data);
        if (ret != 0) {
            return ret;
        }
    }
    tree_file.close();

    char *line;
    while(1) {
        line = readline("> ");
        if (line == nullptr) {
            cout << endl;
            break;
        }
        string input(line);
        if (input.empty()) {
            continue;
        }
        if (mode_info.run_input(locs_tree, mode_data, input) == 0) {
            add_history(line);
        }
    }
    if (mode_info.exit_mode != nullptr) {
        int ret = mode_info.exit_mode(locs_tree, mode_data);
        if (ret != 0) {
            return ret;
        }
    }

    return 0;
}
<commit_msg>Added quit command in console input<commit_after>#include <config.h>

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

#include <readline/readline.h>
#include <readline/history.h>
#include <tclap/CmdLine.h>

#include "bptree.h"
#include "locations.h"

enum Mode {
    MODE_ADJ = 0,
    MODE_NI = 1,
    MODE_DELTANI = 2
};

char const MODE_STR_ADJ[] = "adj";
char const MODE_STR_NI[] = "ni";
char const MODE_STR_DELTANI[] = "deltani";

std::vector<std::string> MODES = {MODE_STR_ADJ, MODE_STR_NI, MODE_STR_DELTANI};

int main(int argc, char** argv) {
    using namespace std;

    TCLAP::CmdLine args(PACKAGE_STRING);
    TCLAP::ValuesConstraint<std::string> modeConstraint(MODES);
    TCLAP::UnlabeledValueArg<std::string> modeArg(
        "mode",
        "Mode of execution",
        true,
        "",
        &modeConstraint
    );
    TCLAP::UnlabeledValueArg<std::string> locsArg(
        "locations",
        "Path to locations.tbl file",
        true,
        "",
        "file path"
    );
    TCLAP::UnlabeledValueArg<std::string> treeArg(
        "tree",
        "Path to mode specific tree data",
        true,
        "",
        "file path"
    );

    args.add(modeArg);
    args.add(locsArg);
    args.add(treeArg);

    args.parse(argc, argv);

    string strMode = modeArg.getValue();
    Mode mode;
    ModeInfo mode_info;
    if (strMode == MODE_STR_DELTANI) {
        mode = MODE_DELTANI;
        mode_info = deltaniModeInfo;
    } else if (strMode == MODE_STR_NI) {
        mode = MODE_NI;
        mode_info = niModeInfo;
    } else {
        mode = MODE_ADJ;
        mode_info = adjModeInfo;
    }

    if (mode != MODE_ADJ) {
        cerr << "Only \"adj\" mode is implemented!" << endl;
        return 1;
    }

    cout << "Running in \"" << strMode << "\" mode" << endl;

    ifstream locs_file(locsArg.getValue());
    if (locs_file.fail()) {
        cerr << "couldn't read locations file" << endl;
        return 1;
    }
    BPTree<Location> locs_tree;
    size_t num_locs;
    cout << "reading locations... ";
    cout.flush();
    num_locs = read_locations(locs_file, locs_tree);
    locs_file.close();
    if (num_locs == 0) {
        cerr << "error" << endl;
        return 1;
    }
    cout << "got " << num_locs << endl;

    ifstream tree_file(treeArg.getValue());
    if (tree_file.fail()) {
        cerr << "couldn't read tree data file" << endl;
        return 1;
    }
    ModeData mode_data;
    if (mode_info.init_mode != nullptr) {
        int ret = mode_info.init_mode(tree_file, mode_data);
        if (ret != 0) {
            return ret;
        }
    }
    tree_file.close();

    char *line;
    while(1) {
        line = readline("> ");
        if (line == nullptr) {
            cout << endl;
            break;
        }
        string input(line);
        if (input.empty()) {
            continue;
        } else if (input == "q" || input == "quit") {
            break;
        }
        if (mode_info.run_input(locs_tree, mode_data, input) == 0) {
            add_history(line);
        }
    }
    if (mode_info.exit_mode != nullptr) {
        int ret = mode_info.exit_mode(locs_tree, mode_data);
        if (ret != 0) {
            return ret;
        }
    }

    return 0;
}
<|endoftext|>


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

using namespace cv;

/// Global Variables
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;

/// Matrices to store images
Mat src1;
Mat src2;
Mat dst;

/**
 * @function on_trackbar
 * @brief Callback for trackbar
 */
void on_trackbar(int, void*) {
	alpha = (double) alpha_slider / alpha_slider_max;
	beta = (1.0 - alpha);

	addWeighted(src1, alpha, src2, beta, 0.0, dst);

	imshow("Linear Blend", dst);
}

int main(int argc, char** argv) {
	/// Read image ( same size, same type )
	src1 = imread("/home/sina/Pictures/img1.jpg");
	src2 = imread("/home/sina/Pictures/img2.jpg");

	if (!src1.data) {
		printf("Error loading src1 \n");
		return -1;
	}
	if (!src2.data) {
		printf("Error loading src2 \n");
		return -1;
	}

	/// Initialize values
	alpha_slider = 0;

	/// Create Windows
	namedWindow("Linear Blend", 1);

	/// Create Trackbars
	char TrackbarName[50];
	sprintf(TrackbarName, "Alpha x %d", alpha_slider_max);

	createTrackbar(TrackbarName, "Linear Blend", &alpha_slider,
			alpha_slider_max, on_trackbar);

	/// Show some stuff
	on_trackbar(alpha_slider, 0);

	/// Wait until user press some key
	waitKey(0);
	return 0;
}
<commit_msg>Implemented a simple program to capture one frame from the default camera and save it to a predefined location<commit_after>#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

int main(int argc, const char** argv)
{
	VideoCapture cap(0);
	Mat frame, frameCopy, image;

	if (!cap.isOpened())  // if not success, exit program
		cout << "No camera detected" << endl;

	double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
	double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the  video
	cout << "Frame size : " << dWidth << " x " << dHeight << endl;
	namedWindow("Camera Feed", CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"

	cout << "In capture ..." << endl;
	while (true)
	{
		Mat frame;
		bool bSuccess = cap.read(frame); // read a new frame from video
		if (!bSuccess) //if not success, break loop
		{
			cout << "Cannot read a frame from video file" << endl;
			break;
		}

		imshow("Camera Feed", frame); //show the frame in "MyVideo" window

		if (waitKey(30) == 32){ //27 is Esc
			cout << "Saving the image to /home/sina/Desktop/test.jpg" << endl;
			imwrite("/home/sina/Desktop/test.jpg", frame);

			break;
		}
	}

	waitKey(0);
	cvDestroyWindow("Camera Feed");

	return 0;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
#include <stdio.h>

#include "renderer.h"
#include "input.h"
#include "octree.h"
#include "player.h"
#include "terrain.h"

int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "MineCube");

    //App.UseVerticalSync(true);

    // Create player
    Player player(5.f, 0.f, 180.f, 5.f, 70.f, 30.f, "Foo");

    // Create a terrain and renderer
    Renderer renderer(Terrain(5, 0, 2,1,1, 50));

    // Create input handler
    InputHandler input_handler(&App, &player);

    // Set some stuff
    App.PreserveOpenGLStates(true);

    char buf[10];
    float Framerate;

    // Start game loop
    while (App.IsOpened())
    {
        Framerate = 1.f / App.GetFrameTime();

        if (App.GetInput().IsKeyDown(sf::Key::Space)) renderer.terrain.Regenerate();

        // Handle mouse and keyboard stuff
        input_handler.handleEvents();

        // Set the active window before using OpenGL commands
        // It's useless here because active window is always the same,
        // but don't forget it if you use multiple windows or controls
        //App.SetActive();

        // Draw entire scene
        renderer.render(player);

        // Draw FPS
        snprintf(buf, 10, "%.1f FPS", Framerate);
        sf::String Text;
        Text.SetText(buf);
        Text.SetFont(sf::Font::GetDefaultFont());
        App.Draw(Text);

        // Finally, display rendered frame on screen
        App.Display();
    }

    return EXIT_SUCCESS;
}

<commit_msg>Move the default spawn point so that gravity impls would actually do something.<commit_after>#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
#include <stdio.h>

#include "renderer.h"
#include "input.h"
#include "octree.h"
#include "player.h"
#include "terrain.h"

int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "MineCube");

    //App.UseVerticalSync(true);

    // Create player
    Player player(5.f, 0.f, 90.f, 5.f, 25.f, 60.f, "Foo");

    // Create a terrain and renderer
    Renderer renderer(Terrain(5, 0, 1,1,1, 50));

    // Create input handler
    InputHandler input_handler(&App, &player);

    // Set some stuff
    App.PreserveOpenGLStates(true);

    char buf[10];
    float Framerate;

    // Start game loop
    while (App.IsOpened())
    {
        Framerate = 1.f / App.GetFrameTime();

        if (App.GetInput().IsKeyDown(sf::Key::Space)) renderer.terrain.Regenerate();

        // Handle mouse and keyboard stuff
        input_handler.handleEvents();

        // Set the active window before using OpenGL commands
        // It's useless here because active window is always the same,
        // but don't forget it if you use multiple windows or controls
        //App.SetActive();

        // Draw entire scene
        renderer.render(player);

        // Draw FPS
        snprintf(buf, 10, "%.1f FPS", Framerate);
        sf::String Text;
        Text.SetText(buf);
        Text.SetFont(sf::Font::GetDefaultFont());
        App.Draw(Text);

        // Finally, display rendered frame on screen
        App.Display();
    }

    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include <iostream>
#include "components/command_line.hpp"

int
main(int argc, char *argv[])
{
    const command_line::options opts{
        command_line::option("-t", "--test", "A testing flag")
    };

    std::string progname = argv[0];
    std::vector<std::string> args(argv + 1, argv + argc);

    cliparser::make_type cli = cliparser::make(std::move(progname), std::move(opts));

    cli->process_input(args);

    if (cli->has("test"))
        std::cout << "We're testing, alright!" << std::endl;
    else
        cli->usage();

    return 0;
}
<commit_msg>add all flags from python/master<commit_after>#include <iostream>
#include <cstdint>
#include <exception>
#include "components/command_line.hpp"

using add_arg = command_line::option;

int
main(int argc, char *argv[])
{
    const command_line::options opts{
        add_arg("-h", "--help",      "Display this text and exit "),
        add_arg("-v", "--version",   "Print version information"),
        add_arg("-l", "--log",       "Set the logging verbosity (default: WARNING)", "LEVEL",
                {"error", "warning", "info", "trace"}),

        /* Exclusive arguments; cannot be combined with any other arguments. */
        add_arg("-d", "--ident",     "Specify an item identification (such as DOI, URL, etc.)"),

        /* Main arguments; at least one of these are required. */
        /* auto main = command_line::add_group( */
        /*     "main", "necessarily inclusive arguments; at least one required" */
        /* ); */
        add_arg("-a", "--author",    "Specify authors"),
        add_arg("-t", "--title",     "Specify title"),
        add_arg("-s", "--serie",     "Specify serie"),
        add_arg("-p", "--publisher", "Specify publisher"),

        /* Exact data arguments; all are optional. */
        add_arg("-y", "--year",      "Specify year of release"),
        add_arg("-L", "--language",  "Specify text language"),
        add_arg("-e", "--edition",   "Specify item edition"),
        add_arg("-E", "--extension", "Specify item extension", "EXT",
                {"epub", "pdf", "djvu"}),
        add_arg("-i", "--isbn",      "Specify item ISBN"),
    };

    uint8_t exit_code = EXIT_SUCCESS;

    try {
        /* Parse command line arguments */
        std::string progname = argv[0];
        std::vector<std::string> args(argv + 1, argv + argc);

        cliparser::make_type cli = cliparser::make(std::move(progname), std::move(opts));
        cli->process_input(args);

        if (cli->has("help")) {
            cli->usage();
            return EXIT_SUCCESS;
        } else if (cli->has("version")) {
            /*
             * TODO:
             * print_build_info(version_details(args));
             */
            return EXIT_SUCCESS;
        } else if (args.empty()) {
            cli->usage();
            return EXIT_FAILURE;
        }

    } catch(const std::exception &err) {
        std::cout << err.what() << std::endl;
        exit_code = EXIT_FAILURE;
    }

    return exit_code;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Jia Heng Eik
 *
 * 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 <vector>
#include <fstream>
#include <sstream>
#include <string>

#include "Sudoku.hpp"
#include "SudokuSolver.hpp"

int main(int argc, char* argv[]) {
	bool verbose { false };
	bool write { false };
	bool multi_thread { true };
	std::string input { };
	std::string output { };

	// handle arguments
	std::vector<std::string> args(argv, argv+argc);
	input = args[1];
	for (size_t i = 2; i < args.size(); ++i) {
		if (args[i] == "-v") verbose = true;
		if (args[i] == "-no_mt") multi_thread = false;
		else if (args[i] == "-o") {
			write = true;
			// if there is no other argument after -o
			if (i+1 == args.size()) {
				std::cout << "Please specify the output file name." << std::endl;
				return 0;
			}
			output = args[++i];
		}
	}
	verbose = verbose || !write;

	std::ifstream infile(input);
	if (!infile.good()) {
		std::cout << "File does not exists! Exiting program" << std::endl;
		return 0;
	}

	// reading 9x9 sudoku
	std::string line { };
	std::vector<Sudoku> puzzles { };
	while (std::getline(infile, line)) {
		// read file line by line
		std::istringstream iss(line);
		puzzles.push_back(Sudoku(line));
	}
	int index {0};
	unsigned int time {0};
	for (auto &sudoku: puzzles) {
		std::cout << "Solving 9x9 puzzle #" << ++index << "..." << std::endl;
		if (verbose)
			std::cout << sudoku.toString() << std::endl;
		SudokuSolver solver(sudoku);
		clock_t start = clock();
		Sudoku solution = solver.getSolution();
		clock_t end = clock();
		std::cout << "Done!!!" << std::endl;
		if (verbose)
			std::cout << "Solution: for puzzle #" << index << std::endl << solution.toString() << std::endl;
		time += static_cast<unsigned int>(end - start);
		if (write) {
			std::ofstream ofile (output);
			if (ofile.is_open()) {
				ofile << solution.toSimpleString();
				ofile.close();
			}
			else {
				std::cout << "Unable to open file";
				write = false;
			}
		}
	}
	std::cout << "it took " << time << "ticks, or "
				<< ((float)time)/CLOCKS_PER_SEC
				<< "seconds to solve all " << index << " 9x9 sudoku." << std::endl;
	return 0;
}
<commit_msg>remove multithread option<commit_after>/*
 * Copyright (c) 2015 Jia Heng Eik
 *
 * 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 <vector>
#include <fstream>
#include <sstream>
#include <string>

#include "Sudoku.hpp"
#include "SudokuSolver.hpp"

int main(int argc, char* argv[]) {
	bool verbose { false };
	bool write { false };
	std::string input { };
	std::string output { };

	// handle arguments
	std::vector<std::string> args(argv, argv+argc);
	input = args[1];
	for (size_t i = 2; i < args.size(); ++i) {
		if (args[i] == "-v") verbose = true;
		else if (args[i] == "-o") {
			write = true;
			// if there is no other argument after -o
			if (i+1 == args.size()) {
				std::cout << "Please specify the output file name." << std::endl;
				return 0;
			}
			output = args[++i];
		}
	}
	verbose = verbose || !write;

	std::ifstream infile(input);
	if (!infile.good()) {
		std::cout << "File does not exists! Exiting program" << std::endl;
		return 0;
	}

	// reading 9x9 sudoku
	std::string line { };
	std::vector<Sudoku> puzzles { };
	while (std::getline(infile, line)) {
		// read file line by line
		std::istringstream iss(line);
		puzzles.push_back(Sudoku(line));
	}
	int index {0};
	unsigned int time {0};
	for (auto &sudoku: puzzles) {
		std::cout << "Solving 9x9 puzzle #" << ++index << "..." << std::endl;
		if (verbose)
			std::cout << sudoku.toString() << std::endl;
		SudokuSolver solver(sudoku);
		clock_t start = clock();
		Sudoku solution = solver.getSolution();
		clock_t end = clock();
		std::cout << "Done!!!" << std::endl;
		if (verbose)
			std::cout << "Solution: for puzzle #" << index << std::endl << solution.toString() << std::endl;
		time += static_cast<unsigned int>(end - start);
		if (write) {
			std::ofstream ofile (output);
			if (ofile.is_open()) {
				ofile << solution.toSimpleString();
				ofile.close();
			}
			else {
				std::cout << "Unable to open file";
				write = false;
			}
		}
	}
	std::cout << "it took " << time << "ticks, or "
				<< ((float)time)/CLOCKS_PER_SEC
				<< "seconds to solve all " << index << " 9x9 sudoku." << std::endl;
	return 0;
}
<|endoftext|>


<commit_before>#include <argp.h>
#include <cstdlib>
#include <string>
#include <vector>

#include "capstats_server.h"

static char doc[] =
  "capstats -- an HTTP server exposing an API for tracking caps statistics.";

/* A description of the arguments we accept. */
static char args_doc[] = "";

static struct argp_option options[] = {
  {"database", 'd', "databasePath", 0, "Path to database file" },
  {"disableAPIKeys", 'r', 0, 0, "Disables API key checking for PUT/POST requests; for testing purposes only" },
  {"port", 'p', "port", 0, "Port number"},
  {"config", 'c', "configPath", 0, "Path to config file"},
  {"key", 'k', "key", 0, "Add the given API key to the keys database"},
  { 0 }
};

struct arguments
{
  uint16_t port;
  std::string databasePath;
  std::string configPath;
  bool checkAPIKeys;
  std::vector<DefaultUUID> defaultUUIDs;
};

  static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  struct arguments *arguments = (struct arguments*) state->input;

  int port;

  switch (key)
  {
    case 'd':
      arguments->databasePath = arg;
      break;

    case 'r':
      arguments->checkAPIKeys = false;
      break;

    case 'p':
      port = atoi(arg);
      if (port != 0) arguments->port = port;
      else argp_usage(state);
      break;

    case 'c':
      arguments->configPath = arg;
      break;

    case 'k':
      arguments->defaultUUIDs.push_back({ arg, "" });
      break;

    default:
      return ARGP_ERR_UNKNOWN;
  }

  return 0;
}

static struct argp argp = { options, parse_opt, args_doc, doc };

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

  // Default server settings.
  // TODO(gus): these should be defined within CapstatsServer itself. However,
  // I'm not sure on the best way to do this. I was thinking of using default
  // arguments in the constructor, but that becomes a pain in the ass to set
  // only a subset of the settings when constructing the server. Why doesn't
  // C++ have named args??

  struct arguments arguments;
  arguments.port = 23232;
  arguments.databasePath = ":memory:";
  arguments.checkAPIKeys = true;
  arguments.configPath = "";

  argp_parse (&argp, argc, argv, 0, 0, &arguments);

  // TODO(gus): preferably, we would load the config and then overwrite config
  // settings with command line settings. currently we're doing the opposite.

  // If a config file is specified, load it and get its data.
  if (!arguments.configPath.empty()) {
    JsonBox::Value config; config.loadFromFile(arguments.configPath);

    // Get the port value from the config if it exists; otherwise, use the
    // existing port setting.
    arguments.port = config["port"].tryGetInteger(arguments.port);

    arguments.databasePath = config["databasePath"].tryGetString(arguments.databasePath);

    JsonBox::Array defaultUUIDsJSON = config["default_uuids"].getArray();
    for (auto v = defaultUUIDsJSON.begin(); v != defaultUUIDsJSON.end(); ++v) {
      arguments.defaultUUIDs.push_back({
          (*v)["uuid"].getString(),
          // TODO(gus): this implicitly requires us to have a description.
          (*v)["description"].getString()
      });
    }
  }

  CapstatsServer server = CapstatsServer(arguments.port, arguments.databasePath, arguments.defaultUUIDs, arguments.checkAPIKeys);

  server.init();
  return server.run();
}
<commit_msg>initializes logging<commit_after>#include <argp.h>
#include <cstdlib>
#include <glog/logging.h>
#include <string>
#include <vector>

#include "capstats_server.h"

static char doc[] =
  "capstats -- an HTTP server exposing an API for tracking caps statistics.";

/* A description of the arguments we accept. */
static char args_doc[] = "";

static struct argp_option options[] = {
  {"database", 'd', "databasePath", 0, "Path to database file" },
  {"disableAPIKeys", 'r', 0, 0, "Disables API key checking for PUT/POST requests; for testing purposes only" },
  {"port", 'p', "port", 0, "Port number"},
  {"config", 'c', "configPath", 0, "Path to config file"},
  {"key", 'k', "key", 0, "Add the given API key to the keys database"},
  { 0 }
};

struct arguments
{
  uint16_t port;
  std::string databasePath;
  std::string configPath;
  bool checkAPIKeys;
  std::vector<DefaultUUID> defaultUUIDs;
};

  static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  struct arguments *arguments = (struct arguments*) state->input;

  int port;

  switch (key)
  {
    case 'd':
      arguments->databasePath = arg;
      break;

    case 'r':
      arguments->checkAPIKeys = false;
      break;

    case 'p':
      port = atoi(arg);
      if (port != 0) arguments->port = port;
      else argp_usage(state);
      break;

    case 'c':
      arguments->configPath = arg;
      break;

    case 'k':
      arguments->defaultUUIDs.push_back({ arg, "" });
      break;

    default:
      return ARGP_ERR_UNKNOWN;
  }

  return 0;
}

static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char** argv) {
   google::InitGoogleLogging(argv[0]);

  // Default server settings.
  // TODO(gus): these should be defined within CapstatsServer itself. However,
  // I'm not sure on the best way to do this. I was thinking of using default
  // arguments in the constructor, but that becomes a pain in the ass to set
  // only a subset of the settings when constructing the server. Why doesn't
  // C++ have named args??

  struct arguments arguments;
  arguments.port = 23232;
  arguments.databasePath = ":memory:";
  arguments.checkAPIKeys = true;
  arguments.configPath = "";

  argp_parse (&argp, argc, argv, 0, 0, &arguments);

  // TODO(gus): preferably, we would load the config and then overwrite config
  // settings with command line settings. currently we're doing the opposite.

  // If a config file is specified, load it and get its data.
  if (!arguments.configPath.empty()) {
    JsonBox::Value config; config.loadFromFile(arguments.configPath);

    // Get the port value from the config if it exists; otherwise, use the
    // existing port setting.
    arguments.port = config["port"].tryGetInteger(arguments.port);

    arguments.databasePath = config["databasePath"].tryGetString(arguments.databasePath);

    JsonBox::Array defaultUUIDsJSON = config["default_uuids"].getArray();
    for (auto v = defaultUUIDsJSON.begin(); v != defaultUUIDsJSON.end(); ++v) {
      arguments.defaultUUIDs.push_back({
          (*v)["uuid"].getString(),
          // TODO(gus): this implicitly requires us to have a description.
          (*v)["description"].getString()
      });
    }
  }

  CapstatsServer server = CapstatsServer(arguments.port, arguments.databasePath, arguments.defaultUUIDs, arguments.checkAPIKeys);

  server.init();
  return server.run();
}
<|endoftext|>


<commit_before>#include <GramsDisplay.h>
#include <HX711.h>
#include <SmoothingFilter.h>
#include <TimerDisplay.h>

// Pin connections
constexpr auto hx711_dt = A2;
constexpr auto hx711_sck = A1;
constexpr auto timer_display_clk = 2;
constexpr auto timer_display_dio = 3;
constexpr auto scale_display_clk = 8;
constexpr auto scale_display_dio = 9;

// Settings
constexpr auto hx711_scale_factor = 1874.f;
constexpr auto hx711_tare_samples = 10;
constexpr auto filter_size = 10;
constexpr auto hysteresis_size = 0.1f;

auto loadCell = HX711{};
auto timerDisplay = TimerDisplay{timer_display_clk, timer_display_dio};
auto weightDisplay = GramsDisplay{scale_display_clk, scale_display_dio};
auto filter = SmoothingFilter{filter_size, hysteresis_size};

void setup()
{
    Serial.begin(38400);

    loadCell.begin(hx711_dt, hx711_sck);
    loadCell.set_scale(hx711_scale_factor);
    loadCell.tare(hx711_tare_samples / 2);
    loadCell.tare(hx711_tare_samples / 2);
}

void loop()
{
    filter.addValue(loadCell.get_units());
    const auto weight_in_grams = filter.getValue();

    weightDisplay.display(weight_in_grams);

    if (weight_in_grams > 1.f)
        timerDisplay.start();

    timerDisplay.update();
}
<commit_msg>Remove unused serial begin<commit_after>#include <GramsDisplay.h>
#include <HX711.h>
#include <SmoothingFilter.h>
#include <TimerDisplay.h>

// Pin connections
constexpr auto hx711_dt = A2;
constexpr auto hx711_sck = A1;
constexpr auto timer_display_clk = 2;
constexpr auto timer_display_dio = 3;
constexpr auto scale_display_clk = 8;
constexpr auto scale_display_dio = 9;

// Settings
constexpr auto hx711_scale_factor = 1874.f;
constexpr auto hx711_tare_samples = 10;
constexpr auto filter_size = 10;
constexpr auto hysteresis_size = 0.1f;

auto loadCell = HX711{};
auto timerDisplay = TimerDisplay{timer_display_clk, timer_display_dio};
auto weightDisplay = GramsDisplay{scale_display_clk, scale_display_dio};
auto filter = SmoothingFilter{filter_size, hysteresis_size};

void setup()
{
    loadCell.begin(hx711_dt, hx711_sck);
    loadCell.set_scale(hx711_scale_factor);
    loadCell.tare(hx711_tare_samples / 2);
    loadCell.tare(hx711_tare_samples / 2);
}

void loop()
{
    filter.addValue(loadCell.get_units());
    const auto weight_in_grams = filter.getValue();

    weightDisplay.display(weight_in_grams);

    if (weight_in_grams > 1.f)
        timerDisplay.start();

    timerDisplay.update();
}
<|endoftext|>


<commit_before>#include <vulkan/vulkan.h>
#include <GLFW/glfw3.h>

#include <vector>
#include <iostream>

#include "debug/pretty_print.hpp"
#include "utils/demangle.hpp"

constexpr std::size_t QUEUE_COUNT = 8;

int main()
{
	if ( ! glfwInit()) {
		std::cout << "Failed to initialize GLFW!" << std::endl;
		return -1;
	}

	if ( ! glfwVulkanSupported()) {
		std::cout << "Vulkan is not supported on this system!" << std::endl;
		return -2;
	}

	// Initialize Vulkan

	VkApplicationInfo app_info = {};
	{
		app_info.sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO;
		app_info.pNext              = nullptr;
		app_info.pApplicationName   = "VkVoxels";
		app_info.applicationVersion = create_version(0, 0, 1);
		app_info.pEngineName        = "VkVoxels Engine";
		app_info.engineVersion      = create_version(0, 0, 1);
		app_info.apiVersion         = create_version(1, 0, 0);
	}

	VkInstanceCreateInfo instance_create_info = {};
	{
		int required_extension_count = 0;
		auto required_extension_names = glfwGetRequiredInstanceExtensions(&required_extension_count);
		if (required_extension_names != nullptr) {
			instance_create_info.sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
			instance_create_info.pNext                   = nullptr;
			instance_create_info.flags                   = 0;
			instance_create_info.pApplicationInfo        = &app_info;
			instance_create_info.enabledLayerCount       = 0;
			instance_create_info.ppEnabledLayerNames     = nullptr;
			instance_create_info.enabledExtensionCount   = required_extension_count;
			instance_create_info.ppEnabledExtensionNames = required_extension_names;
		} else {
			std::cout << "Error getting Vulkan extensions from GLFW!" << std::endl;
			return -3;
		}
	}

	VkInstance instance;
	if (vkCreateInstance(&instance_create_info, nullptr, &instance) != VK_SUCCESS) {
		std::cout << "Error creating Vulkan instance!" << std::endl;
		return -4;
	}

	std::vector<VkPhysicalDevice> phys_devices;
	// List available devices
	{
		// Get device count
		uint32_t phys_device_count = 0;
		vkEnumeratePhysicalDevices(instance, &phys_device_count, nullptr);

		// Get devices
		phys_devices.resize(phys_device_count);
		vkEnumeratePhysicalDevices(instance, &phys_device_count, phys_devices.data());

		// Iterate over devices
		for (const auto &phys_device : phys_devices) {
			std::cout << "Found physical device!" << std::endl;
			VkPhysicalDeviceProperties phys_device_props;
			vkGetPhysicalDeviceProperties(phys_device, &phys_device_props);
			std::cout << phys_device_props << std::endl;

			std::cout << "Device Queue Families:" << std::endl;

			// Get Queue count
			uint32_t queue_count = 0;
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, nullptr);

			// Get Queues
			std::vector<VkQueueFamilyProperties> queue_props(queue_count);
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, queue_props.data());

			auto queue_index = 0u;
			for (const auto &queue_prop : queue_props) {
				std::cout << "Queue Number " << queue_index++ << std::endl;
				std::cout << queue_prop << std::endl;
			}
		}
	}

	if (phys_devices.empty()) {
		std::cout << "Could not find any physical devices!" << std::endl;
		return -5;
	}

	VkPhysicalDevice *phys_dev = nullptr;
	for (auto &physical_device : phys_devices) {
		if (glfwGetPhysicalDevicePresentationSupport(instance, physical_device, 0) == GLFW_TRUE) {
			phys_dev = &physical_device;
		}
	}
	if (phys_dev == nullptr) {
		std::cout << "Could not find device capable of presenting images!" << std::endl;
		return -6;
	}

	// Create the logical Vulkan device
	VkDevice device;
	{
		const float queue_priorities[] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f};
		VkDeviceQueueCreateInfo queue_create_info = {};
		{
			queue_create_info.sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
			queue_create_info.pNext            = nullptr;
			queue_create_info.flags            = 0;
			queue_create_info.queueFamilyIndex = 0;
			queue_create_info.queueCount       = QUEUE_COUNT;
			queue_create_info.pQueuePriorities = queue_priorities;
		}

		VkPhysicalDeviceFeatures phys_device_features;
		vkGetPhysicalDeviceFeatures(phys_devices[0], &phys_device_features);

		VkDeviceCreateInfo device_create_info = {};
		{
			device_create_info.sType                   = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
			device_create_info.pNext                   = nullptr;
			device_create_info.flags                   = 0;
			device_create_info.queueCreateInfoCount    = 1;
			device_create_info.pQueueCreateInfos       = &queue_create_info;
			device_create_info.enabledLayerCount       = 0;
			device_create_info.ppEnabledLayerNames     = nullptr;
			device_create_info.enabledExtensionCount   = 0;
			device_create_info.ppEnabledExtensionNames = nullptr;
			device_create_info.pEnabledFeatures        = &phys_device_features;
		}

		if (vkCreateDevice(*phys_dev, &device_create_info, nullptr, &device) != VK_SUCCESS) {
			std::cout << "Failed to create logical device!" << std::endl;
			return -7;
		}
	}

	// Get logical device queues
	std::vector<VkQueue> queues(QUEUE_COUNT);
	{
		uint32_t queue_index = 0;
		for (auto &queue : queues) {
			vkGetDeviceQueue(device, 0, queue_index++, &queue);
		}
	}

	vkDestroyDevice(device, nullptr);
	vkDestroyInstance(instance, nullptr);
	glfwTerminate();
	return 0;
}
<commit_msg>[Windowing] Add window and Vulkan surface<commit_after>#include <vulkan/vulkan.h>
#include <GLFW/glfw3.h>

#include <vector>
#include <iostream>

#include "debug/pretty_print.hpp"
#include "utils/demangle.hpp"

constexpr std::size_t QUEUE_COUNT = 8;

int main()
{
	if ( ! glfwInit()) {
		std::cout << "Failed to initialize GLFW!" << std::endl;
		return -1;
	}

	glfwSetErrorCallback([](int, const char* msg){std::cout << msg << std::endl;});

	if ( ! glfwVulkanSupported()) {
		std::cout << "Vulkan is not supported on this system!" << std::endl;
		return -2;
	}

	// Initialize Vulkan

	VkApplicationInfo app_info = {};
	{
		app_info.sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO;
		app_info.pNext              = nullptr;
		app_info.pApplicationName   = "VkVoxels";
		app_info.applicationVersion = create_version(0, 0, 1);
		app_info.pEngineName        = "VkVoxels Engine";
		app_info.engineVersion      = create_version(0, 0, 1);
		app_info.apiVersion         = create_version(1, 0, 0);
	}

	VkInstanceCreateInfo instance_create_info = {};
	{
		int required_extension_count = 0;
		auto required_extension_names = glfwGetRequiredInstanceExtensions(&required_extension_count);
		if (required_extension_names != nullptr) {
			instance_create_info.sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
			instance_create_info.pNext                   = nullptr;
			instance_create_info.flags                   = 0;
			instance_create_info.pApplicationInfo        = &app_info;
			instance_create_info.enabledLayerCount       = 0;
			instance_create_info.ppEnabledLayerNames     = nullptr;
			instance_create_info.enabledExtensionCount   = required_extension_count;
			instance_create_info.ppEnabledExtensionNames = required_extension_names;
		} else {
			std::cout << "Error getting Vulkan extensions from GLFW!" << std::endl;
			return -3;
		}
	}

	VkInstance instance;
	if (vkCreateInstance(&instance_create_info, nullptr, &instance) != VK_SUCCESS) {
		std::cout << "Error creating Vulkan instance!" << std::endl;
		return -4;
	}

	std::vector<VkPhysicalDevice> phys_devices;
	// List available devices
	{
		// Get device count
		uint32_t phys_device_count = 0;
		vkEnumeratePhysicalDevices(instance, &phys_device_count, nullptr);

		// Get devices
		phys_devices.resize(phys_device_count);
		vkEnumeratePhysicalDevices(instance, &phys_device_count, phys_devices.data());

		// Iterate over devices
		for (const auto &phys_device : phys_devices) {
			std::cout << "Found physical device!" << std::endl;
			VkPhysicalDeviceProperties phys_device_props;
			vkGetPhysicalDeviceProperties(phys_device, &phys_device_props);
			std::cout << phys_device_props << std::endl;

			std::cout << "Device Queue Families:" << std::endl;

			// Get Queue count
			uint32_t queue_count = 0;
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, nullptr);

			// Get Queues
			std::vector<VkQueueFamilyProperties> queue_props(queue_count);
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, queue_props.data());

			auto queue_index = 0u;
			for (const auto &queue_prop : queue_props) {
				std::cout << "Queue Number " << queue_index++ << std::endl;
				std::cout << queue_prop << std::endl;
			}
		}
	}

	if (phys_devices.empty()) {
		std::cout << "Could not find any physical devices!" << std::endl;
		return -5;
	}

	VkPhysicalDevice *phys_dev = nullptr;
	for (auto &physical_device : phys_devices) {
		if (glfwGetPhysicalDevicePresentationSupport(instance, physical_device, 0) == GLFW_TRUE) {
			phys_dev = &physical_device;
		}
	}
	if (phys_dev == nullptr) {
		std::cout << "Could not find device capable of presenting images!" << std::endl;
		return -6;
	}

	// Create the logical Vulkan device
	VkDevice device;
	{
		const float queue_priorities[] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f};
		VkDeviceQueueCreateInfo queue_create_info = {};
		{
			queue_create_info.sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
			queue_create_info.pNext            = nullptr;
			queue_create_info.flags            = 0;
			queue_create_info.queueFamilyIndex = 0;
			queue_create_info.queueCount       = QUEUE_COUNT;
			queue_create_info.pQueuePriorities = queue_priorities;
		}

		VkPhysicalDeviceFeatures phys_device_features;
		vkGetPhysicalDeviceFeatures(phys_devices[0], &phys_device_features);

		VkDeviceCreateInfo device_create_info = {};
		{
			device_create_info.sType                   = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
			device_create_info.pNext                   = nullptr;
			device_create_info.flags                   = 0;
			device_create_info.queueCreateInfoCount    = 1;
			device_create_info.pQueueCreateInfos       = &queue_create_info;
			device_create_info.enabledLayerCount       = 0;
			device_create_info.ppEnabledLayerNames     = nullptr;
			device_create_info.enabledExtensionCount   = 0;
			device_create_info.ppEnabledExtensionNames = nullptr;
			device_create_info.pEnabledFeatures        = &phys_device_features;
		}

		if (vkCreateDevice(*phys_dev, &device_create_info, nullptr, &device) != VK_SUCCESS) {
			std::cout << "Failed to create logical device!" << std::endl;
			return -7;
		}
	}

	// Get logical device queues
	std::vector<VkQueue> queues(QUEUE_COUNT);
	{
		uint32_t queue_index = 0;
		for (auto &queue : queues) {
			vkGetDeviceQueue(device, 0, queue_index++, &queue);
		}
	}

	glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
	GLFWwindow *window = glfwCreateWindow(640, 480, "VkVoxels", nullptr, nullptr);
	if ( ! window) {
		std::cout << "Failed to create window!" << std::endl;
		return -8;
	}

	VkSurfaceKHR surface;
	if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
		std::cout << "Failed to create window surface!" << std::endl;
		return -9;
	}

	while ( ! glfwWindowShouldClose(window)) {
		glfwPollEvents();
	}

	vkDestroySurfaceKHR(instance, surface, nullptr);
	glfwDestroyWindow(window);
	vkDestroyDevice(device, nullptr);
	vkDestroyInstance(instance, nullptr);
	glfwTerminate();
	return 0;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML works!");
    sf::CircleShape shape(150.f);
    shape.setFillColor(sf::Color::Blue);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}<commit_msg>Changed the frame name or something??? :S<commit_after>#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Hackaton project FloFloL33tH4x0r");
    sf::CircleShape shape(150.f);
    shape.setFillColor(sf::Color::Blue);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}<|endoftext|>


<commit_before>#include <cstdio>
#include <cassert>
#include <iostream>     // std::cout
#include <algorithm>    // std::swap_ranges
#include <vector>       // std::vector
#include <time.h>
#include <stdlib.h>

#include "Chromosome.hpp"
#include "Manager.hpp"

/*
bool testChromosomeCreation() {

	Chromosome<int > population(100);
	population.set(0, 100);
	assert(population[0] == 100);
	std::cout << "Passed" << std::endl;
	return true;
}*/

/**
 * Test create chromosome of type int
 */
void testChromosomeCreation_uint() {

	unsigned int chromo_size = 8;
	unsigned int min_value = 0;
	unsigned int max_value = 7;
	std::vector<Chromosome<unsigned int > > children;
	std::vector<unsigned int > rand_chrom = {2,5,6,1,3,5,4,2};

	// Uses the default constructor to make all the ints.
	Chromosome<unsigned int> chromosome(chromo_size); // Creates {0,0,0,0,0,0,0,0,0,0}
	Chromosome<unsigned int> chromosome2(rand_chrom); // Creates {0,0,0,0,0,0,0,0,0,0}
	Chromosome<unsigned int>::initialize(chromo_size, min_value, max_value);
	chromosome.clonning(children);

	// Check that the child is actually in the children
	assert(children.size() == 1);
	std::cout << "Passed child size increased" << std::endl;

	// Check that the clone is equal to the parent
	assert(chromosome == children[0]);
	std::cout << "Passed parent equal to clone" << std::endl;

	chromosome.mutate(children);

	// Check that the child is actually in the children
	assert(children.size() == 2);
	std::cout << "Passed child size increased" << std::endl;

	// Check that the mutant is equal to the parent
	if(chromosome != children[1]) {
		std::cout << "Passed parent not equal to mutant" << std::endl;
	} else {
		// Note this does not necessary mean the mutate function isnt working.
		// (since it will pick a random number within the range, it my pick the same number and still be accurate).
		std::cout << "Failed parent equal to mutant" << std::endl;
	}
	for (unsigned int i = 0; i < 8; i++) {
		std::cout << children[1][i];
		if(i +1 < 8) {
			std::cout << ",";
		}
	}
	std::cout << '\n';

	chromosome.crossover(chromosome2, children);

	// Check that the child is actually in the children
	assert(children.size() == 4);
	std::cout << "Passed child size increased" << std::endl;

	// Check that the crossover1 is equal to the parent
	assert(chromosome != children[2]);
	std::cout << "Passed parent not equal to crossover1" << std::endl;

	for (unsigned int i = 0; i < 8; i++) {
		std::cout << children[2][i];
		if(i +1 < 8) {
			std::cout << ",";
		}

	}
	std::cout << '\n';

	// Check that the crossover2 is equal to the parent
	assert(chromosome != children[3]);
	std::cout << "Passed parent not equal to crossover2" << std::endl;

	for (unsigned int i = 0; i < 8; i++) {
		std::cout << children[3][i];
		if(i +1 < 8) {
			std::cout << ",";
		}
	}
	std::cout << '\n';

	unsigned int pop_size = 10;
	std::vector<Chromosome<int > > population;
	Chromosome<int >::initialize(chromo_size, min_value, max_value);
	Chromosome<int >::initPopulation(population, pop_size, chromo_size);

	// Check that the population is initialized to the correct size.
	assert(population.size() == pop_size);

	for (unsigned int i = 0; i < pop_size; i++) {
		for (unsigned int j = 0; j < chromo_size; j++) {
			std::cout << population[i][j];
			if(j +1 < chromo_size) {
				std::cout << ",";
			}
		}
		std::cout << '\n';

	}

	std::cout << "All Chromosome<int> Tests Passed" << std::endl;

}

void testManager_uint() {
	unsigned int pop_size = 10;
	unsigned int chromo_size = 8;
	unsigned int min_value = 0;
	unsigned int max_value = 7;

	unsigned int max_gen = 100;
	bool use_self_adaptive = true;
	double mutation_rate = 0.1;
	double mutation_change_rate = 0.1;
	double similarity_index = 0.1;
	double crossover_rate = 0.4;
	double clonning_rate = 0.5;

	Manager<unsigned int > manger(pop_size, 8, max_gen,
			max_value, min_value, use_self_adaptive,
			mutation_rate, mutation_change_rate, similarity_index,
			crossover_rate, clonning_rate);

	 //manager.
}

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

	//Skip program name if any
	argc -= (argc > 0);
	argv += (argc > 0);

	testChromosomeCreation_uint();

	return 0;
}
<commit_msg>ADDED: testing for roulette wheel<commit_after>#include <cstdio>
#include <cassert>
#include <iostream>     // std::cout
#include <algorithm>    // std::swap_ranges
#include <vector>       // std::vector
#include <time.h>
#include <stdlib.h>

#include "Chromosome.hpp"
#include "Manager.hpp"
#include "RouletteWheel.hpp"

/*
bool testChromosomeCreation() {

	Chromosome<int > population(100);
	population.set(0, 100);
	assert(population[0] == 100);
	std::cout << "Passed" << std::endl;
	return true;
}*/

/**
 * Test create chromosome of type int
 */
void testChromosomeCreation_uint() {

	unsigned int chromo_size = 8;
	unsigned int min_value = 0;
	unsigned int max_value = 7;
	std::vector<Chromosome<unsigned int > > children;
	std::vector<unsigned int > rand_chrom = {2,5,6,1,3,5,4,2};

	// Uses the default constructor to make all the ints.
	Chromosome<unsigned int> chromosome(chromo_size); // Creates {0,0,0,0,0,0,0,0,0,0}
	Chromosome<unsigned int> chromosome2(rand_chrom); // Creates {0,0,0,0,0,0,0,0,0,0}
	Chromosome<unsigned int>::initialize(chromo_size, min_value, max_value);
	chromosome.clonning(children);

	// Check that the child is actually in the children
	assert(children.size() == 1);
	std::cout << "Passed child size increased" << std::endl;

	// Check that the clone is equal to the parent
	assert(chromosome == children[0]);
	std::cout << "Passed parent equal to clone" << std::endl;

	chromosome.mutate(children);

	// Check that the child is actually in the children
	assert(children.size() == 2);
	std::cout << "Passed child size increased" << std::endl;

	// Check that the mutant is equal to the parent
	if(chromosome != children[1]) {
		std::cout << "Passed parent not equal to mutant" << std::endl;
	} else {
		// Note this does not necessary mean the mutate function isnt working.
		// (since it will pick a random number within the range, it my pick the same number and still be accurate).
		std::cout << "Failed parent equal to mutant" << std::endl;
	}
	for (unsigned int i = 0; i < 8; i++) {
		std::cout << children[1][i];
		if(i +1 < 8) {
			std::cout << ",";
		}
	}
	std::cout << '\n';

	chromosome.crossover(chromosome2, children);

	// Check that the child is actually in the children
	assert(children.size() == 4);
	std::cout << "Passed child size increased" << std::endl;

	// Check that the crossover1 is equal to the parent
	assert(chromosome != children[2]);
	std::cout << "Passed parent not equal to crossover1" << std::endl;

	for (unsigned int i = 0; i < 8; i++) {
		std::cout << children[2][i];
		if(i +1 < 8) {
			std::cout << ",";
		}

	}
	std::cout << '\n';

	// Check that the crossover2 is equal to the parent
	assert(chromosome != children[3]);
	std::cout << "Passed parent not equal to crossover2" << std::endl;

	for (unsigned int i = 0; i < 8; i++) {
		std::cout << children[3][i];
		if(i +1 < 8) {
			std::cout << ",";
		}
	}
	std::cout << '\n';

	unsigned int pop_size = 10;
	std::vector<Chromosome<int > > population;
	Chromosome<int >::initialize(chromo_size, min_value, max_value);
	Chromosome<int >::initPopulation(population, pop_size, chromo_size);

	// Check that the population is initialized to the correct size.
	assert(population.size() == pop_size);

	for (unsigned int i = 0; i < pop_size; i++) {
		for (unsigned int j = 0; j < chromo_size; j++) {
			std::cout << population[i][j];
			if(j +1 < chromo_size) {
				std::cout << ",";
			}
		}
		std::cout << '\n';

	}

	std::cout << "All Chromosome<int> Tests Passed" << std::endl;

}

void testManager_uint() {
	unsigned int pop_size = 10;
	unsigned int chromo_size = 8;
	unsigned int min_value = 0;
	unsigned int max_value = 7;

	unsigned int max_gen = 100;
	bool use_self_adaptive = true;
	double mutation_rate = 0.1;
	double mutation_change_rate = 0.1;
	double similarity_index = 0.1;
	double crossover_rate = 0.4;
	double clonning_rate = 0.5;

	Manager<unsigned int > manger(pop_size, chromo_size, max_gen,
			max_value, min_value, use_self_adaptive,
			mutation_rate, mutation_change_rate, similarity_index,
			crossover_rate, clonning_rate);

	// Create a test population of 10
	std::vector<Chromosome<unsigned int > > pop(10);

	// Init the chromosome operations
	Chromosome<unsigned int >::initialize(chromo_size, min_value, max_value);
	// Create a random chromosome population
	Chromosome<unsigned int >::initPopulation(pop, pop_size, chromo_size);

	std::cout << "Init pop = " << std::endl;
	for (unsigned int i = 0; i < pop_size; i++) {
		for (unsigned int j = 0; j < chromo_size; j++) {
			std::cout << pop[i][j];
			if(j +1 < chromo_size) {
				std::cout << ",";
			}
		}
		std::cout << '\n';

	}

	std::vector<std::pair<Chromosome<unsigned int >, double > > fitness(10);

	// Create a set of fitness values
	std::vector<double > fitness_values = { 0.1, 0.4, 0.2, 0.6, 0.7, 0.8, 0.5, 0.75, 0.92, 0.8 };

	for(unsigned int i = 0; i < fitness.size(); i++) {
		fitness[i] = std::pair<Chromosome<unsigned int >, double >(pop[i], fitness_values[i]);
	}

	RouletteWheel<unsigned int > rw;

	rw.init(fitness);

	unsigned int count = 0;
	while (count < pop_size) {
		Chromosome<unsigned int > cur = rw.next();
		std::cout << "Next Chromosome = ";
		for (unsigned int i = 0; i < chromo_size; i++) {
			std::cout << cur[i];
			if (i+1 < chromo_size) {
				std::cout << ",";
			}
		}
		std::cout << std::endl;
		count++;
	}

	 //manager.
}

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

	//Skip program name if any
	argc -= (argc > 0);
	argv += (argc > 0);

	testChromosomeCreation_uint();

	std::cout << std::endl;
	testManager_uint();

	return 0;
}
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Marianne Gagnon

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 <cstdlib>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <vector>
#include "Settings.h"

#include "Utils.h"
#include "DylibBundler.h"

/*
 TODO
 - what happens if a library is not remembered by full path but only name? (support improved, still not perfect)
 - could get mixed up if symlink and original are not in the same location (won't happen for UNIX prefixes like /usr/, but in random directories?)

 FIXME: why does it copy plugins i try to fix to the libs directory?

 */

const std::string VERSION = "git";

// FIXME - no memory management is done at all (anyway the program closes immediately so who cares?)

std::string installPath = "";

void showHelp()
{
    std::cout << "dylibbundler " << VERSION << std::endl;
    std::cout << "dylibbundler is a utility that helps bundle dynamic libraries inside mac OS X app bundles.\n" << std::endl;

    std::cout << "-x, --fix-file <file to fix (executable or app plug-in)>" << std::endl;
    std::cout << "-b, --bundle-deps" << std::endl;
    std::cout << "-d, --dest-dir <directory to send bundled libraries (relative to cwd)>" << std::endl;
    std::cout << "-p, --install-path <'inner' path of bundled libraries (usually relative to executable, by default '@executable_path/../libs/')>" << std::endl;
    std::cout << "-s, --search-path <directory to add to list of locations searched>" << std::endl;
    std::cout << "-of, --overwrite-files (allow overwriting files in output directory)" << std::endl;
    std::cout << "-od, --overwrite-dir (totally overwrite output directory if it already exists. implies --create-dir)" << std::endl;
    std::cout << "-cd, --create-dir (creates output directory if necessary)" << std::endl;
    std::cout << "-i, --ignore <location to ignore> (will ignore libraries in this directory)" << std::endl;
    std::cout << "-h, --help" << std::endl;
}

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

    // parse arguments
    for(int i=0; i<argc; i++)
    {
        if(strcmp(argv[i],"-x")==0 or strcmp(argv[i],"--fix-file")==0)
        {
            i++;
            Settings::addFileToFix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-b")==0 or strcmp(argv[i],"--bundle-deps")==0)
        {
            Settings::bundleLibs(true);
            continue;
        }
        else if(strcmp(argv[i],"-p")==0 or strcmp(argv[i],"--install-path")==0)
        {
            i++;
            Settings::inside_lib_path(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-i")==0 or strcmp(argv[i],"--ignore")==0)
        {
            i++;
            Settings::ignore_prefix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-d")==0 or strcmp(argv[i],"--dest-dir")==0)
        {
            i++;
            Settings::destFolder(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-of")==0 or strcmp(argv[i],"--overwrite-files")==0)
        {
            Settings::canOverwriteFiles(true);
            continue;
        }
        else if(strcmp(argv[i],"-od")==0 or strcmp(argv[i],"--overwrite-dir")==0)
        {
            Settings::canOverwriteDir(true);
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-cd")==0 or strcmp(argv[i],"--create-dir")==0)
        {
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-h")==0 or strcmp(argv[i],"--help")==0)
        {
            showHelp();
            exit(0);
        }
        if(strcmp(argv[i],"-s")==0 or strcmp(argv[i],"--search-path")==0)
        {
            i++;
            Settings::addSearchPath(argv[i]);
            continue;
        }
        else if(i>0)
        {
            // if we meet an unknown flag, abort
            // ignore first one cause it's usually the path to the executable
            std::cerr << "Unknown flag " << argv[i] << std::endl << std::endl;
            showHelp();
            exit(1);
        }
    }

    if(not Settings::bundleLibs() and Settings::fileToFixAmount()<1)
    {
        showHelp();
        exit(0);
    }

    std::cout << "* Collecting dependencies"; fflush(stdout);

    const int amount = Settings::fileToFixAmount();
    for(int n=0; n<amount; n++)
        collectDependencies(Settings::fileToFix(n));

    collectSubDependencies();
    doneWithDeps_go();

    return 0;
}
<commit_msg>Set version to 1.0.0<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Marianne Gagnon

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 <cstdlib>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <vector>
#include "Settings.h"

#include "Utils.h"
#include "DylibBundler.h"

/*
 TODO
 - what happens if a library is not remembered by full path but only name? (support improved, still not perfect)
 - could get mixed up if symlink and original are not in the same location (won't happen for UNIX prefixes like /usr/, but in random directories?)

 FIXME: why does it copy plugins i try to fix to the libs directory?

 */

const std::string VERSION = "1.0.0";

// FIXME - no memory management is done at all (anyway the program closes immediately so who cares?)

std::string installPath = "";

void showHelp()
{
    std::cout << "dylibbundler " << VERSION << std::endl;
    std::cout << "dylibbundler is a utility that helps bundle dynamic libraries inside mac OS X app bundles.\n" << std::endl;

    std::cout << "-x, --fix-file <file to fix (executable or app plug-in)>" << std::endl;
    std::cout << "-b, --bundle-deps" << std::endl;
    std::cout << "-d, --dest-dir <directory to send bundled libraries (relative to cwd)>" << std::endl;
    std::cout << "-p, --install-path <'inner' path of bundled libraries (usually relative to executable, by default '@executable_path/../libs/')>" << std::endl;
    std::cout << "-s, --search-path <directory to add to list of locations searched>" << std::endl;
    std::cout << "-of, --overwrite-files (allow overwriting files in output directory)" << std::endl;
    std::cout << "-od, --overwrite-dir (totally overwrite output directory if it already exists. implies --create-dir)" << std::endl;
    std::cout << "-cd, --create-dir (creates output directory if necessary)" << std::endl;
    std::cout << "-i, --ignore <location to ignore> (will ignore libraries in this directory)" << std::endl;
    std::cout << "-h, --help" << std::endl;
}

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

    // parse arguments
    for(int i=0; i<argc; i++)
    {
        if(strcmp(argv[i],"-x")==0 or strcmp(argv[i],"--fix-file")==0)
        {
            i++;
            Settings::addFileToFix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-b")==0 or strcmp(argv[i],"--bundle-deps")==0)
        {
            Settings::bundleLibs(true);
            continue;
        }
        else if(strcmp(argv[i],"-p")==0 or strcmp(argv[i],"--install-path")==0)
        {
            i++;
            Settings::inside_lib_path(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-i")==0 or strcmp(argv[i],"--ignore")==0)
        {
            i++;
            Settings::ignore_prefix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-d")==0 or strcmp(argv[i],"--dest-dir")==0)
        {
            i++;
            Settings::destFolder(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-of")==0 or strcmp(argv[i],"--overwrite-files")==0)
        {
            Settings::canOverwriteFiles(true);
            continue;
        }
        else if(strcmp(argv[i],"-od")==0 or strcmp(argv[i],"--overwrite-dir")==0)
        {
            Settings::canOverwriteDir(true);
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-cd")==0 or strcmp(argv[i],"--create-dir")==0)
        {
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-h")==0 or strcmp(argv[i],"--help")==0)
        {
            showHelp();
            exit(0);
        }
        if(strcmp(argv[i],"-s")==0 or strcmp(argv[i],"--search-path")==0)
        {
            i++;
            Settings::addSearchPath(argv[i]);
            continue;
        }
        else if(i>0)
        {
            // if we meet an unknown flag, abort
            // ignore first one cause it's usually the path to the executable
            std::cerr << "Unknown flag " << argv[i] << std::endl << std::endl;
            showHelp();
            exit(1);
        }
    }

    if(not Settings::bundleLibs() and Settings::fileToFixAmount()<1)
    {
        showHelp();
        exit(0);
    }

    std::cout << "* Collecting dependencies"; fflush(stdout);

    const int amount = Settings::fileToFixAmount();
    for(int n=0; n<amount; n++)
        collectDependencies(Settings::fileToFix(n));

    collectSubDependencies();
    doneWithDeps_go();

    return 0;
}
<|endoftext|>


<commit_before>#include <errno.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

string shell_prompt(); //prototype for prompt function
int cmd_interpreter(string); //prototype for command interpreter
void input_redir(vector<string>); //prototype for input redirection function
int input_helper(string, string);
void output_redir(vector<string>); //prototype for output redirection function
int output_helper(string, string);

int main (int argc, char** argv)
{
	while(true)
	{
		vector<string> inVector;
		string input;
		input = shell_prompt();
		//while (inVector.back() != "")
		if (input == "exit")
		{
			cout << "Exiting rshell." << endl;
			exit(0);
		}
		else
		{
			char_separator<char> sep(";", "|&#<>");
			string t;
			tokenizer< char_separator<char> > tokens(input, sep);
			BOOST_FOREACH(t, tokens)
			{
				//TODO do different things depending on delimiters in vector
				inVector.push_back(t);
			} //end BOOST_FOREACH

			bool comment_sentinel = true;
			bool pipe_sentinel = false;

			for (unsigned i = 0; i < inVector.size(); i++) //go through vector of commands - looking for comments
			{
				if(comment_sentinel)	//if a comment sign is not found, execute
				{
					string in = inVector.at(i);
			cerr << "[ " << in << " ]" << endl;
					if (in.at(0) == '#')
					{
						comment_sentinel = false;
					}

					else
					{
						for (unsigned k = 0; k < inVector.size(); k++)
						{

							if (inVector.at(k).at(0) == '&')
							{
								//TODO: remove later and fix
							}

							else if (inVector.at(k).at(0) == '|')
							{
								if (inVector.at(i + 1).at(0) == '|') //likely to go out of range if at end of command
								{
									pipe_sentinel = true;
								}
								if (pipe_sentinel)
								{
									//TODO: remove later and fix
								}

							}

							else if (inVector.at(k).at(0) == '<')
							{
								//input redirection
					//	cerr << "we indir i hope" << endl;
								input_redir(inVector);
								 //input_redir handles
								 break;
							}

							else if (inVector.at(k).at(0) == '>')
							{
								//output redirection
					//	cerr << "we outdir i hope" << endl;
								output_redir(inVector);
								 //output_redir function handles this
								 break;

							}
							else
							{
								; //nothing
							}
						}
						cmd_interpreter(in);
					}
				}

				//TODO: this is for connectors
				// check if the current in.at(0) character equals a connector
				// if it does, check if the next one equals a connector
				// if it does, run both commands
				// check return values of both commands
				// ????
				// profit
			}//endfor
		}//endif
	}//endwhile

	return 0;
}

void input_redir(vector<string> input)
{
	//handles all of input redirection
cerr << " we in now" << endl;
	for (unsigned i = 0; i < input.size(); i++)
	{
		if (input.at(i).at(0) == '<')
		{
//	cerr << "we input now" << endl;
			input_helper(input.at(i-1), input.at(i+1));
		}
	}
}

int input_helper(string one, string two)
{
	int pid = fork();
	if (pid == 0)
	{
		//child
		//open close dup
		if (open(two.c_str(), O_RDONLY) != -1)
		{
			if(close(0) != -1) //stdin
			{
				if(dup2(0, 0) != -1)
				{
					cmd_interpreter(one);
					return 1;
				}
				else
				{
					perror("dup2");
					exit(1);
				}
			}
			else
			{
				perror("close");
				exit(1);
			}
		}
		else
		{
			perror("open");
			exit(1);
		}
	}
	else
	{
		//parent
//		close(0);
		if (waitpid(-1, NULL, 0) == -1)
		{
			perror("waitpid");
			exit(1);
		}
		if(close(0) == -1)
		{
			perror("close");
			exit(1);
		}
	}

	return 0;
}

void output_redir(vector<string> input)
{
	//handles all output redirection
	for (unsigned i = 0; i < input.size(); i++)
	{
		//iterate through vector and finds redirection
		if (input.at(i).at(0) == '>')
		{
//		cerr << "we output now" << endl;
			output_helper(input.at(i-1), input.at(i+1));
		}
	}
}

int output_helper(string one, string two)
{
	int pid = fork();
	if (pid == 0)
	{
		//child
		//open close dup
		if (open(two.c_str(), O_WRONLY | O_CREAT) != -1)
		{
			if(close(1) != -1) //stdin
			{
				if(dup2(1, 1) != -1)
				{
					cmd_interpreter(one);
					return 1;
				}
				else
				{
					perror("dup2");
					exit(1);
				}
			}
			else
			{
				perror("close");
				exit(1);
			}
		}
		else
		{
			perror("open");
			exit(1);
		}
	}
	else
	{
		//parent
//		close(1);
		if (waitpid(-1, NULL, 0) == -1)
		{
			perror("waitpid");
			exit(1);
		}
		if (close(1) == -1)
		{
			perror("close");
			exit(1);
		}
	}

	return 0;
}

int cmd_interpreter(string input)//, char** argv)
{
	//parse command to seperate command and parameters

	//int len = input.length();

	vector<string> invector;
	string t;
	char_separator<char> sep(" ");
	tokenizer< char_separator<char> > tokens(input, sep);
	//int i = 0;
	BOOST_FOREACH(t, tokens)		//tokenize input string with flags to seperate items
	{
		invector.push_back(t);
	}
	unsigned len = invector.size();

	const char** cinput = new const char*[len+2];
	const char* program = invector.at(0).c_str();

	cinput[0] = program;

	for(unsigned i = 1; i < 1 + len; i++)
	{
		cinput[i] = invector[i].c_str();
	}
	cinput[len] = '\0';

//	int pipefd[
	int pid = fork();
	if(pid == 0)
	{
		if (execvp(program, (char**)cinput) == -1)
		{
			perror("execvp"); // throw an error
			exit(1);
		}
		else
		{
			return 1;
		}
	}
	else
	{
		//append stuff here

		//parent wait
		if (waitpid(-1, NULL, 0) == -1)
		{
			perror("waitpid");
			exit(1);
		}
	}

	return 0;
}

string shell_prompt()
{
	string in;
	//TODO - error checking for getlogin and gethostname
	//implement later
//	struct utsname name;
//	errno = 0;

//	uname(&name)
	/*
	char name[256];
	int maxlen = 64;
	if (!gethostname(name, maxlen))
	{
		string strname(name);
		cout << getlogin() << "@" << name  << "$ "; //custom prompt with hostname and login name
		cin >> in;
	}
	else
	{
		perror("gethostname"); //throw error if not found
	}
	*/
	cout << "rshell$ ";
	getline(cin, in);
	cin.clear();
	return in;
}
<commit_msg>redir with errors<commit_after>#include <errno.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <pwd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

string shell_prompt(); //prototype for prompt function
int cmd_interpreter(string); //prototype for command interpreter
void input_redir(vector<string>); //prototype for input redirection function
int input_helper(string, string);
void output_redir(vector<string>); //prototype for output redirection function
int output_helper(string, string);

int main (int argc, char** argv)
{
	while(true)
	{
		vector<string> inVector;
		string input;
		input = shell_prompt();
		//while (inVector.back() != "")
		if (input == "exit")
		{
			cout << "Exiting rshell." << endl;
			exit(0);
		}
		else
		{
			char_separator<char> sep(";", "|&#<>");
			string t;
			tokenizer< char_separator<char> > tokens(input, sep);
			BOOST_FOREACH(t, tokens)
			{
				//TODO do different things depending on delimiters in vector
				inVector.push_back(t);
			} //end BOOST_FOREACH

			bool comment_sentinel = true;
			bool pipe_sentinel = false;

			for (unsigned i = 0; i < inVector.size(); i++) //go through vector of commands - looking for comments
			{
				if(comment_sentinel)	//if a comment sign is not found, execute
				{
					string in = inVector.at(i);
			cerr << "[ " << in << " ]" << endl;
					if (in.at(0) == '#')
					{
						comment_sentinel = false;
					}

					else
					{
						for (unsigned k = 0; k < inVector.size(); k++)
						{

							if (inVector.at(k).at(0) == '&')
							{
								//TODO: remove later and fix
							}

							else if (inVector.at(k).at(0) == '|')
							{
								if (inVector.at(i + 1).at(0) == '|') //likely to go out of range if at end of command
								{
									pipe_sentinel = true;
								}
								if (pipe_sentinel)
								{
									//TODO: remove later and fix
								}

							}

							else if (inVector.at(k).at(0) == '<')
							{
								//input redirection
					//	cerr << "we indir i hope" << endl;
								input_redir(inVector);
								 //input_redir handles
								 break;
							}

							else if (inVector.at(k).at(0) == '>')
							{
								//output redirection
					//	cerr << "we outdir i hope" << endl;
								output_redir(inVector);
								 //output_redir function handles this
								 break;

							}
							else
							{
								; //nothing
							}
						}
						cmd_interpreter(in);
					}
				}

				//TODO: this is for connectors
				// check if the current in.at(0) character equals a connector
				// if it does, check if the next one equals a connector
				// if it does, run both commands
				// check return values of both commands
				// ????
				// profit
			}//endfor
		}//endif
	}//endwhile

	return 0;
}

void input_redir(vector<string> input)
{
	//handles all of input redirection
	for (unsigned i = 0; i < input.size(); i++)
	{
		if (input.at(i).at(0) == '<')
		{
//	cerr << "we input now" << endl;
			input_helper(input.at(i-1), input.at(i+1));
		}
	}
}

int input_helper(string one, string two)
{
	int pid = fork();
	if (pid == 0)
	{
		//child
		//open close dup
		if (open(two.c_str(), O_RDONLY) != -1)
		{
			if(close(0) != -1) //stdin
			{
				if(dup(0) != -1)
				{
		cerr << one << endl;
					cmd_interpreter(one);
					return 1;
				}
				else
				{
					perror("dup");
					exit(1);
				}
			}
			else
			{
				perror("close");
				exit(1);
			}
		}
		else
		{
			perror("open");
			exit(1);
		}
	}
	else
	{
		//parent
//		close(0);
		if (waitpid(-1, NULL, 0) == -1)
		{
			perror("waitpid");
			exit(1);
		}
		if(close(0) == -1)
		{
			perror("close");
			exit(1);
		}
	}

	return 0;
}

void output_redir(vector<string> input)
{
	//handles all output redirection
	for (unsigned i = 0; i < input.size(); i++)
	{
		//iterate through vector and finds redirection
		if (input.at(i).at(0) == '>')
		{
//		cerr << "we output now" << endl;
			output_helper(input.at(i-1), input.at(i+1));
		}
	}
}

int output_helper(string one, string two)
{
	int pid = fork();
	if (pid == 0)
	{
		//child
		//open close dup
		if (open(two.c_str(), O_WRONLY | O_CREAT) != -1)
		{
			if(close(1) != -1) //stdin
			{
				if(dup(1) != -1)
				{
					cmd_interpreter(one);
					return 1;
				}
				else
				{
					perror("dup");
					exit(1);
				}
			}
			else
			{
				perror("close");
				exit(1);
			}
		}
		else
		{
			perror("open");
			exit(1);
		}
	}
	else
	{
		//parent
//		close(1);
		if (waitpid(-1, NULL, 0) == -1)
		{
			perror("waitpid");
			exit(1);
		}
		if (close(1) == -1)
		{
			perror("close");
			exit(1);
		}
	}

	return 0;
}

int cmd_interpreter(string input)//, char** argv)
{
	//parse command to seperate command and parameters

	//int len = input.length();

	vector<string> invector;
	string t;
	char_separator<char> sep(" ");
	tokenizer< char_separator<char> > tokens(input, sep);
	//int i = 0;
	BOOST_FOREACH(t, tokens)		//tokenize input string with flags to seperate items
	{
		invector.push_back(t);
	}
	unsigned len = invector.size();

	const char** cinput = new const char*[len+2];
	const char* program = invector.at(0).c_str();

	cinput[0] = program;

	for(unsigned i = 1; i < 1 + len; i++)
	{
		cinput[i] = invector[i].c_str();
	}
	cinput[len] = '\0';

//	int pipefd[
	int pid = fork();
	if(pid == 0)
	{
		if (execvp(program, (char**)cinput) == -1)
		{
			perror("execvp"); // throw an error
			exit(1);
		}
		else
		{
			return 1;
		}
	}
	else
	{
		//append stuff here

		//parent wait
		if (waitpid(-1, NULL, 0) == -1)
		{
			perror("waitpid");
			exit(1);
		}
	}

	return 0;
}

string shell_prompt()
{
	string in;
	//TODO - error checking for getlogin and gethostname
	//implement later
//	struct utsname name;
//	errno = 0;

//	uname(&name)
	/*
	char name[256];
	int maxlen = 64;
	if (!gethostname(name, maxlen))
	{
		string strname(name);
		cout << getlogin() << "@" << name  << "$ "; //custom prompt with hostname and login name
		cin >> in;
	}
	else
	{
		perror("gethostname"); //throw error if not found
	}
	*/
	cout << "rshell$ ";
	getline(cin, in);
	cin.clear();
	return in;
}
<|endoftext|>


<commit_before>#include <QApplication>

#include "mainui.h"

#include "board.h"

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    MainUI* foo = new MainUI();
    foo->show();
    return app.exec();

}
<commit_msg>license header<commit_after>/*
explosive-c4
Copyright (C) 2014-2021 Salvo "LtWorf" Tomaselli

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
*/

#include <QApplication>

#include "mainui.h"

#include "board.h"

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    MainUI* foo = new MainUI();
    foo->show();
    return app.exec();

}
<|endoftext|>


<commit_before>#include <cassert>

#include <unistd.h>

#include "glload/gl_3_2.h"
#include "glload/gll.hpp"
#include <GL/glfw.h>

#include "render/shaderpipeline.hpp"
#include "heightmap/heightmapgenerator.hpp"

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

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 8);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	glfwOpenWindow(1024, 768, 8, 8, 8, 8, 24, 24, GLFW_WINDOW);
	glfwSetWindowTitle("OpenGL 3.2 Core profile test");

	//Load OpenGL functions
	if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) {
		return 1;
	}

	glViewport(0, 0, 1024, 768);

	//Set clear colour to black
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

	GLuint vaos[1];
	glGenVertexArrays(1, vaos);
	glBindVertexArray(vaos[0]);

	GLuint vbos[1];
	glGenBuffers(1, vbos);
	glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);

	HeightmapGenerator* hmgen = new HeightmapGenerator(1025, 0, 512);
	hmgen->fillMap();
	hmgen->convertMap();

	unsigned int vertexCount = hmgen->getVertexCount();

	glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(HMVertex), hmgen->getVertices(), GL_STATIC_DRAW);

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_TRUE, 0, 0);

	render::ShaderPipeLine shaderpipe("Vertex-Pass Y", "Fragment-Colour Height");

	shaderpipe.addShaderAttribute("vertex");

	shaderpipe.linkPipeLine();
	GLuint shaderProgram = shaderpipe.getShaderProgram();

	glUseProgram(shaderProgram);

	while(true) {
		usleep(500000);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexCount);

		glfwSwapBuffers();
	}

	glfwTerminate();
}
<commit_msg>Added more comments to blocks in main<commit_after>#include <cassert>

#include <unistd.h>

#include "glload/gl_3_2.h"
#include "glload/gll.hpp"
#include <GL/glfw.h>

#include "render/shaderpipeline.hpp"
#include "heightmap/heightmapgenerator.hpp"

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

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 8);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	glfwOpenWindow(1024, 768, 8, 8, 8, 8, 24, 24, GLFW_WINDOW);
	glfwSetWindowTitle("OpenGL 3.2 Core profile test");

	//Load OpenGL functions
	if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) {
		return 1;
	}

	glViewport(0, 0, 1024, 768);

	//Set clear colour to black
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

	//Create VAO and VBO
	GLuint vaos[1];
	glGenVertexArrays(1, vaos);
	glBindVertexArray(vaos[0]);

	GLuint vbos[1];
	glGenBuffers(1, vbos);
	glBindBuffer(GL_ARRAY_BUFFER, vbos[0]);

	//Generate heightmap
	HeightmapGenerator* hmgen = new HeightmapGenerator(1025, 0, 512);
	hmgen->fillMap();
	hmgen->convertMap();

	//Buffer heightmap-data to VBO
	unsigned int vertexCount = hmgen->getVertexCount();
	glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(HMVertex), hmgen->getVertices(), GL_STATIC_DRAW);

	//Set vertex attribute index 0 to current VBO
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_TRUE, 0, 0);

	//Create shader pipeline
	render::ShaderPipeLine shaderpipe("Vertex-Pass Y", "Fragment-Colour Height");

	shaderpipe.addShaderAttribute("vertex");

	shaderpipe.linkPipeLine();
	GLuint shaderProgram = shaderpipe.getShaderProgram();

	glUseProgram(shaderProgram);

	//Main render loop
	while(true) {
		usleep(500000);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexCount);

		glfwSwapBuffers();
	}

	glfwTerminate();
}
<|endoftext|>